blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af4cc04c4e9c1cad843d84e2f1521b83e1c00bd3 | 28fdb090792a29ef08b7fdef9492bd251daecdd2 | /2020041302/2020041302/Calculate.cpp | b22a7a75139e08e41028986e3dda9f566bfcd5e8 | [] | no_license | DeeBluee/VS | 48394c2508c294d317a34a766ac97e5299a12d83 | 3fd81e7e6e7117d89e0fb01c972d06365b4cbfda | refs/heads/master | 2021-03-25T23:39:33.151283 | 2020-06-13T12:54:47 | 2020-06-13T12:54:47 | 247,655,136 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,423 | cpp | // Calculate.cpp : 实现文件
//
#include "stdafx.h"
#include "2020041302.h"
#include "Calculate.h"
#include "afxdialogex.h"
// Calculate 对话框
IMPLEMENT_DYNAMIC(Calculate, CDialogEx)
Calculate::Calculate(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_DIALOG1, pParent)
, a(0)
, b(0)
, d(0)
, c(_T(""))
{
}
Calculate::~Calculate()
{
}
void Calculate::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, a);
DDX_Text(pDX, IDC_EDIT2, b);
DDX_Text(pDX, IDC_EDIT3, d);
DDX_Text(pDX, IDC_EDIT4, c);
DDX_Control(pDX, IDC_LIST1, ch);
}
BEGIN_MESSAGE_MAP(Calculate, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &Calculate::OnBnClickedButton1)
END_MESSAGE_MAP()
// Calculate 消息处理程序
BOOL Calculate::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
ch.AddString(_T("+"));
ch.AddString(_T("-"));
ch.AddString(_T("*"));
ch.AddString(_T("/"));
c = "=";
UpdateData(false);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void Calculate::OnBnClickedButton1()
{
UpdateData(true);
ch.GetText(ch.GetCurSel(), e);
if (e=='+') {
d = a + b;
}
if (e == '-') {
d = a - b;
}
if (e == '*') {
d = a * b;
}
if (e == '/'&&b!=0) {
d = a / b;
}
else if(b==0) d = -65536;
UpdateData(false);
// TODO: 在此添加控件通知处理程序代码
}
| [
"1285088540@qq.com"
] | 1285088540@qq.com |
0fe674ab8e7ce03ff9a3d6cdfd21785affe228a7 | 1d3adc676bc9bec6e86ed6378f3ebc73e4a8ab32 | /stereovision/framerate tests/grab then retrieve/main.cpp | 94630120d9d9f813d0a8bf32278fd74e818c1489 | [] | no_license | dviewai/table-tennis-computer-vision | 054b6ab79705d6bc31db4a01f41d20b7a7fb73d6 | 17f11f5d8a0525e3efa71f5d2a9dbfa34409d9c0 | refs/heads/master | 2022-04-10T23:22:11.431075 | 2020-03-31T23:06:02 | 2020-03-31T23:06:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,049 | cpp | #include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <chrono>
using namespace cv;
using namespace std;
void myGrab(int camNum, VideoCapture& captureCam);
void myRetrieve(int camNum, VideoCapture& captureCam, Mat& frameCam);
int main(int argc, char const *argv[])
{
// we open the webcam streams
VideoCapture captureCam1(1);
VideoCapture captureCam2(2);
if (!captureCam1.isOpened() || !captureCam2.isOpened()) {
cerr << "Error: can't access webcam stream" << endl;
exit(1);
}
Mat frameCam1, frameCam2;
auto start = chrono::high_resolution_clock::now();
float i = 0;
while(true) {
int duration;
chrono::high_resolution_clock::time_point start_time, end_time;
myGrab(1, captureCam1);
myGrab(2, captureCam2);
myRetrieve(1, captureCam1, frameCam1);
myRetrieve(2, captureCam2, frameCam2);
// uncomment to display the streams in a GUI
// start_time = chrono::high_resolution_clock::now();
// imshow("cam 1", frameCam1);
// imshow("cam 2", frameCam2);
// end_time = chrono::high_resolution_clock::now();
// duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
// cout << "imshow: " << std::setfill(' ') << std::setw(3) << duration << "ms ";
// uncomment to use waitKey (needed if displaying the streams)
// start_time = chrono::high_resolution_clock::now();
// char key = waitKey(1); // wait before next frame
// if (key == 'q')
// break;
// end_time = chrono::high_resolution_clock::now();
// duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
// cout << "waitKey: " << std::setfill(' ') << std::setw(3) << duration << "ms ";
cout << endl;
i++;
if (i > 200)
break;
}
auto end = chrono::high_resolution_clock::now();
cout << "\n\n" << i / chrono::duration_cast<chrono::milliseconds>(end - start).count()*1000 << " FPS" << endl;
return 0;
}
void myGrab(int camNum, VideoCapture& capture) {
auto start_time = chrono::high_resolution_clock::now();
bool grab = capture.grab();
auto end_time = chrono::high_resolution_clock::now();
int duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
cout << "g" << camNum << ": " << std::setfill(' ') << std::setw(3) << duration << "ms ";
if (! grab)
cout << endl << "GRAB FAILED cam number " << camNum << endl;
}
void myRetrieve(int camNum, VideoCapture& capture, Mat& frame) {
auto start_time = chrono::high_resolution_clock::now();
capture.retrieve(frame);
auto end_time = chrono::high_resolution_clock::now();
int duration = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
cout << "r" << camNum << ": " << std::setfill(' ') << std::setw(3) << duration << "ms ";
}
| [
"vincent.marquet1@free.fr"
] | vincent.marquet1@free.fr |
5d68ba3c832c75ff8da20172a3813545054d2de3 | 5cfd2e0c484c4a51d9f6bb4a95a8b64640ac6992 | /src/player.cpp | 6333485d226a40505e2939cb4a7ffdd03856b8d7 | [] | no_license | lzh9102/tx100 | 54c2da5ea33cdd7e1eb10b45a34cd755d92b26d1 | 79d112bf47b15fc7ae1e44a9c85ca21ac5175505 | refs/heads/master | 2021-01-10T19:37:47.846806 | 2013-10-07T10:28:18 | 2013-10-07T10:28:18 | 41,461,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,429 | cpp | /*
* Copyright (C) 2012 Timothy Lin
* This work is licensed under GPLv3 as published by the Free Software
* Foundation. Please see http://www.gnu.org/licenses/gpl.html for details.
*
* For more information, please visit the project homepage:
* http://code.google.com/p/tx100
*/
#define PLAYER_SPEED (float)130
#include "player.h"
#include "vectorhelper.h"
#include <cmath>
#define SQRT_2 1.414
struct Player::Private
{
sf::Image image;
sf::Sprite sprite;
sf::Vector2f pos; /* position */
sf::String label;
bool alive;
Private() : alive(false) { }
void render(sf::RenderWindow& w)
{
render(w, pos.x, pos.y);
}
void render(sf::RenderWindow& w, int x, int y)
{
const int width = sprite.GetSize().x, height = sprite.GetSize().y;
sprite.SetPosition(x - width / 2, y - height / 2);
w.Draw(sprite);
label.SetPosition(x + width, y - height);
w.Draw(label);
}
};
Player::Player() : p(new Private)
{
}
Player::~Player()
{
delete p;
}
void Player::start()
{
p->alive = true;
}
void Player::stop()
{
p->alive = false;
}
void Player::render(sf::RenderWindow& w)
{
if (p->alive)
p->render(w);
}
void Player::render(sf::RenderWindow& w, int x, int y)
{
if (p->alive)
p->render(w, x, y);
}
void Player::step(float t, const PlayerInput& input)
{
sf::Vector2f delta;
if (input.left)
delta.x -= 1;
if (input.right)
delta.x += 1;
if (input.up)
delta.y -= 1;
if (input.down)
delta.y += 1;
if (vector_length(delta) >= 0.5) // the player is moving
p->pos += vector_normalize(delta) * (t * PLAYER_SPEED);
}
void Player::step(float t, const std::list<Bullet>& bullet_list,
const sf::Vector2f& center)
{
sf::Vector2f v;
std::list<Bullet>::const_iterator it;
for (it=bullet_list.begin(); it!=bullet_list.end(); ++it) {
const Bullet& bullet = *it;
const sf::Vector2f difference = p->pos - bullet.pos;
const float distance = vector_length(difference);
sf::Vector2f normal = vector_normalize(sf::Vector2f(-bullet.vel.y, bullet.vel.x));
//if (distance > 10 * getWidth())
// normal = sf::Vector2f(0, 0);
normal /= (float)0.05 * distance;
if (distance < 2 * getWidth())
normal *= (float)500.0;
if (vector_dot(difference, normal) < 0)
normal = -normal;
//if (vector_length(v + normal) < 0.1)
//normal = -normal;
if (vector_dot(difference, bullet.vel) > 0) {
v += normal;
}
if (distance < 2 * getWidth())
v += (vector_normalize(difference) / distance * (float)1000.0);
}
sf::Vector2f deviation = center - p->pos;
if (vector_length(deviation) >= 100)
v += deviation * (float)0.01;
if (vector_length(v) >= t)
p->pos += vector_normalize(v) * PLAYER_SPEED * t;
}
float Player::getX() const
{
return p->pos.x;
}
float Player::getY() const
{
return p->pos.y;
}
int Player::getWidth() const
{
return p->sprite.GetSize().x;
}
int Player::getHeight() const
{
return p->sprite.GetSize().y;
}
sf::Vector2f Player::getPosition() const
{
return p->pos;
}
float Player::setX(float x)
{
return p->pos.x = x;
}
float Player::setY(float y)
{
return p->pos.y = y;
}
void Player::setPosition(float x, float y)
{
p->pos.x = x;
p->pos.y = y;
}
void Player::setLabel(const char *label)
{
p->label.SetText(label);
p->label.SetSize(15);
}
void Player::constraint(int w, int h)
{
const int player_width = getWidth(), player_height = getHeight();
const int top_limit = player_height/2, bottom_limit = h - player_height/2;
const int left_limit = player_width/2, right_limit = w - player_width/2;
const int x = p->pos.x, y = p->pos.y;
if (x < left_limit)
p->pos.x = left_limit;
else if (x >= right_limit)
p->pos.x = right_limit;
if (y < top_limit)
p->pos.y = top_limit;
else if (y >= bottom_limit)
p->pos.y = bottom_limit;
}
bool Player::isAlive() const
{
return p->alive;
}
bool Player::setImage(const char* filename)
{
if (!p->image.LoadFromFile(filename))
return false;
p->sprite.SetImage(p->image);
return true;
}
const sf::Sprite& Player::getSprite() const
{
return p->sprite;
}
| [
"lzh9102@gmail.com"
] | lzh9102@gmail.com |
8862d8446f5aa6432c91ff66ae1f76e0761b3ee9 | 18a3dcbc614ca10ea46892310044dd4427e3ddef | /二叉树/从上往下打印二叉树.cpp | ca5649f1f6f3827bd3a8832a242de15224d1c7b6 | [] | no_license | DeligientSloth/Coding-Interviews | d975bb65448f07b1ba0e493119bf6bd5b79b9645 | 9e594c03269b315931787caf22730dc655c91812 | refs/heads/master | 2021-09-02T04:04:58.868982 | 2017-12-30T06:51:03 | 2017-12-30T06:51:03 | 113,278,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*> Q;
vector<int> result;
if(root!=NULL) Q.push(root);
while(Q.empty()==false)
{
TreeNode* node=Q.front();
result.push_back(node->val);
Q.pop();
if(node->left!=NULL) Q.push(node->left);
if(node->right!=NULL) Q.push(node->right);
}
return result;
}
};
| [
"32997064+DeligientSloth@users.noreply.github.com"
] | 32997064+DeligientSloth@users.noreply.github.com |
36f53b93e5f58475b9a6cbf21dd702b28cfcc4bf | 7c02fd1bad09eb6ee8d736418a2ac899a00ad59d | /app/src/main/cpp/eventbus/EventBus.cpp | e860103010d5d45bb33f95a840738c60cef076b3 | [
"MIT"
] | permissive | simonppg/Break_it_all | 21f413af77fb5230deb1d4b8e3df0cb39d7841e2 | ac50ca1fb5e7d644fbc0c709330edd5ce1082477 | refs/heads/main | 2023-07-20T07:16:46.237997 | 2023-03-27T01:04:07 | 2023-03-27T01:04:07 | 109,542,884 | 0 | 2 | MIT | 2023-07-19T05:07:37 | 2017-11-05T01:24:20 | C++ | UTF-8 | C++ | false | false | 1,674 | cpp | #include "EventBus.hpp"
#include <iostream>
#include <utility>
using std::pair;
EventBus::EventBus() {
// subMap = new SubMap;
}
void EventBus::publish(Event *event) {
logEvent(event);
EventType eventType = event->type();
if (subMap.find(eventType) == subMap.end()) {
return;
}
for (auto subscriber : *subMap[eventType]) {
subscriber(event);
}
}
void EventBus::subcribe(EventType eventType, Subscriber subscriber) {
if (subMap.find(eventType) == subMap.end()) {
std::cout << "Not Found";
list<Subscriber> *aList = new list<Subscriber>;
aList->push_back(subscriber);
// subMap[eventType] = aList;
subMap.insert(pair<EventType, list<Subscriber> *>(eventType, aList));
} else {
std::cout << "Found";
list<Subscriber> *subscribers = subMap[eventType];
subscribers->push_back(subscriber);
}
}
void EventBus::logEvent(Event *event) {
EventType eventType = event->type();
if (eventType == EventType::SURFACE_CHANGED) {
// logger->logi("SURFACE_CHANGED");
std::cout << "SURFACE_CHANGED";
} else if (eventType == EventType::CURSOR_POSITION_CHANGED) {
// logger->logi("CURSOR_POSITION_CHANGED");
std::cout << "CURSOR_POSITION_CHANGED";
} else if (eventType == EventType::KEY_PRESSED) {
// logger->logi("KEY_PRESSED");
std::cout << "KEY_PRESSED";
} else if (eventType == EventType::SCREEN_TOUCHED) {
// logger->logi("SCREEN_TOUCHED");
std::cout << "SCREEN_TOUCHED";
} else if (eventType == EventType::SURFACE_CHANGED) {
// logger->logi("SURFACE_CHANGED");
std::cout << "SURFACE_CHANGED";
} else {
// logger->logi("UNKNOWN");
std::cout << "UNKNOWN";
}
}
| [
"simonppg@gmail.com"
] | simonppg@gmail.com |
423c6461affddc31b52ab2286986cc22096c86fc | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/c8/5bd8e1c0dcf1e5/main.cpp | db0b27a75e686cf35747018af9fb43bcfc713130 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | #include <iostream>
#include <string>
#include <vector>
class A
{
int _i;
int _j;
public:
A(int i, int j) : _i(i), _j(j) { std::cout << "cons" << std::endl; }
A(const A& other) { std::cout << "copy cons" << std::endl; }
private:
A& operator=(const A& other) { std::cout << "operator=" << std::endl; return *this; }
};
int main()
{
std::vector<A> as{
{ 1, 2 },
{ 1, 3 },
{ 7, 2 },
};
return 0;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
97f4ad03144ffb3fa17d5e168d9b43586c86b9bf | 3efc50ba20499cc9948473ee9ed2ccfce257d79a | /data/code-jam/files/2974486_chenhaifeng_5709773144064000_1_extracted_B.cpp | 8f262ced66a61a108cecf14a1b94d465629ada16 | [] | no_license | arthurherbout/crypto_code_detection | 7e10ed03238278690d2d9acaa90fab73e52bab86 | 3c9ff8a4b2e4d341a069956a6259bf9f731adfc0 | refs/heads/master | 2020-07-29T15:34:31.380731 | 2019-12-20T13:52:39 | 2019-12-20T13:52:39 | 209,857,592 | 9 | 4 | null | 2019-12-20T13:52:42 | 2019-09-20T18:35:35 | C | UTF-8 | C++ | false | false | 594 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int main() {
//freopen("B-large.in", "r", stdin);
//freopen("B-large.out", "w", stdout);
int t;
double c, f, x;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%lf%lf%lf", &c, &f, &x);
//printf("%lf %lf %lf\n", c, f, x);
double time = 0, t2, t3;
double speed = 2;
//int nFarm = 0;
while (1) {
t2 = x / speed;
t3 = c / speed + (x / (speed + f));
if (t2 < t3) {
time = time + t2;
break;
}
time += c / speed;
speed += f;
}
printf("Case #%d: %.7lf\n", i + 1, time);
}
return 0;
}
| [
"arthurherbout@gmail.com"
] | arthurherbout@gmail.com |
80a0081fb11890a864c6cd2c075a38a31ff2e81c | d550c5617c8f2fbf29e53a1e57afded9f9cdc642 | /environment/dump_env1.cpp | 8230185bd7eb998e7df3dfd3484d81b6d3d158e0 | [] | no_license | panchul/sb_cpp | b8c2d48263953080b619f44be8bee1d3a662820a | f50a2521f2bcd0788a3cf33e304ec0566dd26f62 | refs/heads/master | 2021-07-05T06:32:29.423397 | 2021-06-22T17:33:13 | 2021-06-22T17:33:13 | 65,116,417 | 0 | 0 | null | 2018-03-18T05:35:43 | 2016-08-07T04:56:46 | C++ | UTF-8 | C++ | false | false | 298 | cpp | // compile it with 'g++ dump_env.cpp
#include <stdio.h>
extern char **environ;
int main() {
printf("Using 'extern char **environ;'\n-------------\n");
char **ep = environ;
char *p;
while ((p = *ep++))
printf("%s\n", p);
printf("-------------\n");
return 0;
}
| [
"apanchul@hotmail.com"
] | apanchul@hotmail.com |
070b3611c8a20486f70529abbf7f0780a3898163 | e7fb9ffb95b83998fc5cae5446d10a6a46b729b6 | /ArduinoBasic/Problem14/P14.ino | 80bff8541fead924f82e46df506db1ca6ab65f84 | [] | no_license | dinhminhqaz/ArduinoBasic | 3002216caa1c55d4c9f4725d3930a968ff27d94b | 52ee50504fc1482b2bbfb6de543991fc7fba315b | refs/heads/main | 2023-06-30T18:44:05.253389 | 2021-08-07T19:24:21 | 2021-08-07T19:24:21 | 393,769,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | ino | int buzzPin=8;
int potPin=A3;
int potVal;
int toneVal;
void setup() {
// put your setup code here, to run once:
pinMode(buzzPin,OUTPUT);
pinMode(potPin,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
potVal=analogRead(potPin);
toneVal=(9940./1023.)*potVal+60;
digitalWrite(buzzPin,HIGH );
delayMicroseconds(toneVal);
digitalWrite(buzzPin,LOW);
delayMicroseconds(toneVal);
}
| [
"dinhminhqaz@gmail.com"
] | dinhminhqaz@gmail.com |
7e38dfee4662fd1accce05c53169049056d9f072 | 6821354f56b75d4192bd29c49a34077ff3b3a47b | /ThalesRemoteCppLibrary/thalesfileinterface.cpp | a708c4dbfae1f46cd7c6a59fe9b412f8824c8e93 | [
"MIT"
] | permissive | Zahner-elektrik/Thales-Remote-Cpp | 9e8641ef77da50c4383daf2c4dcd7b70def0ce91 | 0c912e6905329b6cdf230a7936aae4afd7a1b56b | refs/heads/main | 2023-08-17T04:14:46.874078 | 2023-08-09T08:23:05 | 2023-08-09T08:23:05 | 188,229,937 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,890 | cpp | /******************************************************************
* ____ __ __ __ __ _ __
* /_ / ___ _/ / ___ ___ ___________ / /__ / /__/ /_____(_) /__
* / /_/ _ `/ _ \/ _ \/ -_) __/___/ -_) / -_) '_/ __/ __/ / '_/
* /___/\_,_/_//_/_//_/\__/_/ \__/_/\__/_/\_\\__/_/ /_/_/\_\
*
* Copyright 2023 ZAHNER-elektrik I. Zahner-Schiller GmbH & Co. KG
*
* 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 "thalesfileinterface.h"
#include <iostream>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <regex>
ThalesFileInterface::ThalesFileInterface(std::string address, std::string connectionName)
{
this->connectionName = connectionName;
this->remoteConnection = new ZenniumConnection();
this->remoteConnection->connectToTerm(address, connectionName);
this->filesToSkip.push_back("lastshot.ism");
this->saveReceivedFilesToDisk = false;
this->keepReceivedFilesInObject = false;
this->receiving_worker_is_running = false;
}
ThalesFileInterface::ThalesFileInterface(ZenniumConnection* connection)
{
this->connectionName = connection->getConnectionName();
this->remoteConnection = connection;
this->filesToSkip.push_back("lastshot.ism");
this->saveReceivedFilesToDisk = false;
this->keepReceivedFilesInObject = false;
this->receiving_worker_is_running = false;
}
void ThalesFileInterface::close()
{
if(this->receiving_worker_is_running == true)
{
this->disableAutomaticFileExchange();
}
this->remoteConnection->disconnectFromTerm();
}
std::string ThalesFileInterface::enableAutomaticFileExchange(bool enable, std::string fileExtensions)
{
std::string retval;
if(enable == true)
{
retval = this->remoteConnection->sendStringAndWaitForReplyString(
"3," + this->connectionName + ",4,ON," + fileExtensions,
128,
std::chrono::duration<int, std::milli>::max(),
132
);
this->startWorker();
}
else
{
retval = this->remoteConnection->sendStringAndWaitForReplyString(
"3," + this->connectionName + ",4,OFF",
128,
std::chrono::duration<int, std::milli>::max(),
132
);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
this->stoppWorker();
}
return retval;
}
std::string ThalesFileInterface::disableAutomaticFileExchange()
{
return this->enableAutomaticFileExchange(false);
}
ThalesFileInterface::FileObject ThalesFileInterface::acquireFile(std::string filename)
{
FileObject retval;
retval.name = "";
if(receiving_worker_is_running == false)
{
this->remoteConnection->sendTelegram(
"3," + this->connectionName + ",1," + filename,
128);
retval = this->receiveFile(std::chrono::duration<int, std::milli>::max());
}
return retval;
}
void ThalesFileInterface::appendFilesToSkip(std::string filename)
{
this->filesToSkip.push_back(filename);
}
void ThalesFileInterface::setSavePath(std::string path)
{
this->pathToSave = path;
}
void ThalesFileInterface::enableSaveReceivedFilesToDisk(std::string path, bool enable)
{
this->saveReceivedFilesToDisk = enable;
this->setSavePath(path);
}
void ThalesFileInterface::disableSaveReceivedFilesToDisk()
{
this->saveReceivedFilesToDisk = false;
}
void ThalesFileInterface::enableKeepReceivedFilesInObject(bool enable)
{
keepReceivedFilesInObject = enable;
}
void ThalesFileInterface::disableKeepReceivedFilesInObject()
{
this->enableKeepReceivedFilesInObject(false);
}
const std::vector<ThalesFileInterface::FileObject>& ThalesFileInterface::getReceivedFiles()
{
return receivedFiles;
}
const ThalesFileInterface::FileObject &ThalesFileInterface::getLatestReceivedFile()
{
return receivedFiles.back();
}
void ThalesFileInterface::saveReceivedFile(FileObject file)
{
if(this->saveReceivedFilesToDisk == true)
{
std::filesystem::path dir(this->pathToSave);
std::filesystem::path fileName(file.name);
std::filesystem::path fileNameWithPath = dir / fileName;
std::ofstream fileStream(fileNameWithPath,std::ofstream::binary);
for(auto data : file.binary_data)
{
fileStream << data;
}
fileStream.close();
}
}
void ThalesFileInterface::deleteReceivedFiles()
{
this->receivedFiles.clear();
}
ThalesFileInterface::FileObject ThalesFileInterface::receiveFile(const std::chrono::duration<int, std::milli> timeout)
{
FileObject retval;
retval.name = "";
std::string filePath;
try {
filePath = this->remoteConnection->waitForStringTelegram(130,timeout);
} catch (...) {
return retval;
}
std::string fileLength = this->remoteConnection->waitForStringTelegram(129);
std::stringstream converterStream(fileLength);
int fileLengthBytes;
converterStream >> fileLengthBytes;
int bytesToReceive = fileLengthBytes;
std::vector<uint8_t> fileData;
while(bytesToReceive > 0)
{
auto readBytes = this->remoteConnection->waitForTelegram(131);
fileData.insert(fileData.end(),readBytes.begin(),readBytes.end());
bytesToReceive -= readBytes.size();
}
retval.binary_data = fileData;
retval.path = filePath;
retval.name = std::filesystem::path(filePath).filename().string();
return retval;
}
void ThalesFileInterface::startWorker()
{
if(this->receiving_worker_is_running == false)
{
this->receiving_worker_is_running = true;
this->receivingWorker = new std::thread(&ThalesFileInterface::fileReceiverJob, this);
}
}
void ThalesFileInterface::stoppWorker()
{
if(this->receiving_worker_is_running == true)
{
this->receiving_worker_is_running = false;
this->receivingWorker->join();
delete this->receivingWorker;
}
}
void ThalesFileInterface::fileReceiverJob()
{
while (this->receiving_worker_is_running == true)
{
try {
auto file = this->receiveFile(std::chrono::milliseconds(1000));
if(file.name != "")
{
if(std::find(filesToSkip.begin(),filesToSkip.end(),file.name) == filesToSkip.end())
{
if(saveReceivedFilesToDisk == true)
{
this->saveReceivedFile(file);
}
if(keepReceivedFilesInObject == true)
{
this->receivedFiles.push_back(file);
}
}
}
} catch (...) {
this->receiving_worker_is_running = false;
}
}
}
| [
"maximilian.krapp@zahner.de"
] | maximilian.krapp@zahner.de |
316252b53a4701428bfaf82d29bdebd257ba41c3 | 22f857842ea3db81144385941267b3cb4f0c57d5 | /Voice/BaseVoice.h | 43672de8803ac9a4e7ddf7d0028cf22468d9a794 | [] | no_license | eriser/eLibv2 | c1810c8e455a779a1211c20917daa39c751b91cd | ead21b62ba05216c2ed458017219c6340f3ca661 | refs/heads/master | 2021-01-17T08:15:15.534631 | 2015-12-27T09:38:20 | 2015-12-27T09:38:20 | 49,957,461 | 1 | 0 | null | 2016-01-19T14:19:03 | 2016-01-19T14:19:02 | null | UTF-8 | C++ | false | false | 3,258 | h | #ifndef MODBASEVOICE_H_
#define MODBASEVOICE_H_
// TODO: how to handle parameter-changes which will affect the modules within the voice?
namespace eLibV2
{
namespace Voice
{
/**
this module provides a base voice which can be used to produce polyphonic output
every note is used to create a single voice which maintains all processing itself
each voice is designed to be processed with in its own thread
*/
class BaseVoice
{
public:
enum eVoiceState
{
UNDEF = 0,
STARTED,
STOP_REQUESTED,
STOPPED
};
public:
BaseVoice()
{
m_eState = STOPPED;
}
virtual ~BaseVoice() {}
/**
start the voice and rendering
@param Note note to play
@param Velocity velocity to use
@param Mode additional information about how to play the note
@return true if voice has started
*/
virtual bool Start(UInt8 Note, UInt8 Velocity, UInt16 Mode)
{
bool bRes = false;
if (m_eState == STOPPED)
{
m_iNote = Note;
m_iVelocity = Velocity;
m_iMode = Mode;
m_eState = STARTED;
bRes = true;
}
return bRes;
}
/**
request the voice to stop. this will usually trigger the release phase of an envelope
*/
virtual void RequestStop(void) { m_eState = STOP_REQUESTED; }
/**
check if voice has stopped
@return true if voice has stopped
*/
virtual bool isStopped(void) { return (m_eState == STOPPED); }
UInt8 GetNote(void) const { return m_iNote; }
UInt8 GetVelocity(void) const { return m_iVelocity; }
virtual void ParameterChanged(UInt32 Index, double Value) = 0;
virtual void SetSamplerate(const double Samplerate) = 0;
/**
this method processes the voice and delivers the output to the main mix
- the outputs should be accumulated
- when the state reaches STOP_REQUESTED end the voice
- when the voice has ended, set state to STOPPED
@param inputs the inputs used to process external signals
@param outputs outputs receiving the data for the main mix
@param sampleFrames number of frames to process
*/
virtual void Render(float** inputs, float **outputs, SInt32 sampleFrames) = 0;
protected:
/**
stop the voice and signal the voicemanager it can be cleared
*/
virtual void Stop(void)
{
m_iNote = 0;
m_iVelocity = 0;
m_iMode = 0;
m_eState = STOP_REQUESTED;
}
protected:
UInt8 m_iNote;
UInt8 m_iVelocity;
UInt16 m_iMode;
eVoiceState m_eState;
};
}
}
#endif
| [
"sys@e-fope.de"
] | sys@e-fope.de |
6a9e6f92a44835426225b69f12e606580d8a7daa | e795ca60bd1cf3897531b5bd24323376cbc9e79d | /share/lab9/postlab/timer.cpp | f3cc85f58cb14684c5bdfd69be6918a63bee9ef4 | [] | no_license | luke-anglin/MITOCW | d337b5326121102154d20f3977ff6bd4d54422bf | 54412f30334fa7b5990f7f5ee7377f7d9ad76746 | refs/heads/main | 2023-03-28T06:42:18.467359 | 2021-03-25T14:35:23 | 2021-03-25T14:35:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | cpp | // NOTE: in order to compile this system on Linux (and most Unix
// systems) you will have to include the -lrt flag to your compiler.
/*Nicholas Mohammad
nm9ur
timer.cpp
10/19/2017
*/
#include <sstream>
#include <math.h>
#include <cstring>
#include "timer.h"
timer::timer(timer & t) : running(t.running) {
memcpy(&startVar, &(t.startVar), sizeof (timeval));
memcpy(&stopVar, &(t.stopVar), sizeof (timeval));
}
int timer::start() {
if (!running) {
running = true;
gettimeofday(&startVar,NULL);
return 0;
}
return 1;
}
int timer::stop() {
if (running) {
running = 0;
gettimeofday(&stopVar,NULL);
return 0;
}
return 1;
}
ostream & timer::print(ostream & out) {
return (out << toString());
}
double timer::getTime() {
time_t sec = stopVar.tv_sec - startVar.tv_sec;
long usec = stopVar.tv_usec - startVar.tv_usec;
return sec + usec/1000000.0;
}
string timer::toString() {
ostringstream out;
if (running)
out << "Timer still running\n";
else {
time_t sec = stopVar.tv_sec - startVar.tv_sec;
long usec = stopVar.tv_usec - startVar.tv_usec;
if ( usec < 0 ) {
sec--;
usec += 1000000;
}
out << sec << "."
<< ((usec<100000)?"0":"")
<< ((usec<10000)?"0":"")
<< ((usec<1000)?"0":"")
<< ((usec<100)?"0":"")
<< ((usec<10)?"0":"")
<< usec;
}
return out.str();
}
ostream & operator<<(ostream &out, timer &t) {
return t.print(out);
} | [
"lukeanglin@gmail.com"
] | lukeanglin@gmail.com |
9b4ad889cc2e3455a8be6b8d6c8ad1b15b325172 | 84b225d944bc0c079b43ce2a8ca5e542898398fa | /ViconUBXGPS/SerialWriter.h | 8dbed62fe92b6956d309495ab9e07a6cf3c4167a | [] | no_license | dwilson89/VivonToUBX | 89202004398aa31d190b9f4b3a44c7c6243c5b52 | 864e0a3181bb01cf0da961cee6662084fe04ec27 | refs/heads/master | 2020-06-12T09:12:07.402774 | 2014-08-31T08:25:28 | 2014-08-31T08:25:28 | 75,594,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #pragma once
using namespace System::IO::Ports;
using namespace System;
ref class SerialWriter
{
public:
SerialWriter(System::String^ portName, int baudRate);
void Open();
Boolean IsOpen();
void Close();
void Send(System::String^ payload);
System::String^ Read();
void Send(unsigned char* c,unsigned int byteCount);
private:
SerialPort^ _serialPort;
protected:
~SerialWriter();
};
| [
"rh4istl1n@hotmail.com"
] | rh4istl1n@hotmail.com |
9fc2c9ac7b1c073552e1798daf9fd9dcbcfc0677 | be8b9231c92e6c184f0692c92df9667be3770cb1 | /Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/ssd1351/ssd1351_indexedcolor.inl | a9cc87b89ccf6f94f3cc9319b98fc8e604167cb3 | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | Pocketart/typhoonclawvex | def0f4a607c90b1bafb180466dfa12ddd8a480c1 | eb4b523c13541b2b9136d32259bd0399b46a289e | refs/heads/master | 2021-09-15T07:26:07.218099 | 2018-05-07T02:20:15 | 2018-05-07T02:20:15 | 105,268,399 | 4 | 3 | MIT | 2018-05-04T17:30:49 | 2017-09-29T12:12:32 | C++ | UTF-8 | C++ | false | false | 1,044 | inl | // Specific implementations for high-color mode
// This gets included from inside the template definition in ssd1351.h, which is crazy, but it's the only way I know to make this compile.
MEMBER_REQUIRES(std::is_same<C, IndexedColor>::value)
void setColorDepth() {
// this is the same as high color mode for now.
// This is because indexed colours should ultimately be able to send any colour - just only 256 different ones.
// However, to make IndexedColor mode the fastest, I might make this use 2 bytes instead.
sendCommandAndContinue(CMD_REMAP);
sendDataAndContinue(0xB4);
};
MEMBER_REQUIRES(std::is_same<C, IndexedColor>::value)
void pushColor(const C &color, bool lastCommand=false) {
// Send color in indexed color mode - the data gets sent as three bytes,
// only using the low 6 bits for the color (for 18bit color in total)
sendDataAndContinue((color & 0xE0) >> 2);
sendDataAndContinue((color & 0x7C) << 1);
if (lastCommand) {
sendLastData((color & 0x3) << 4);
} else {
sendDataAndContinue((color & 0x3) << 4);
}
};
| [
"henry012007@gmail.com"
] | henry012007@gmail.com |
760060b881c92452ff455e244897db5c79057ec5 | e711039670ac74a8e8abd55874815794f5b812b0 | /src/CalculateMinimumHP.cpp | 500256e82d1c36c9aa07643ae928d166e43bac72 | [] | no_license | proudzhu/leetcode | 1e08ffd0a7197722f7b954c2884c3d8a824c0f9e | e0c9788e6b26f3cdc98f080f22217412d09ac7ee | refs/heads/master | 2022-09-24T02:40:23.405383 | 2022-09-05T12:22:45 | 2022-09-05T12:22:45 | 44,177,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | #include "CalculateMinimumHP.hpp"
#include <climits>
/*
* DP problem
*/
int calculateMinimumHP(std::vector<std::vector<int>>& dungeon)
{
int m = dungeon.size();
int n = dungeon[0].size();
std::vector<std::vector<int> > hp(m + 1, std::vector<int>(n + 1, INT_MAX));
hp[m][n - 1] = 1;
hp[m - 1][n] = 1;
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int need = std::min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j];
hp[i][j] = need <= 0 ? 1 : need;
}
}
return hp[0][0];
}
| [
"proudzhu.fdu@gmail.com"
] | proudzhu.fdu@gmail.com |
935e733d34009cc623138f8237fdd692417dd08b | 9b3affbcebf4c3f481f4b01d9737ee67dc7d54b0 | /Plot/Source/Plot/Private/PlotItem_PlayEffect.cpp | 05044bf7607f327ea9d6d0804b10d783ad4fefc1 | [] | no_license | 977908569/Plot | d9e7e6118b32735a7637f71df89b8c9cfe33ddbf | 940b5d19246c1f8346a86584214d57f5f1b68e81 | refs/heads/main | 2023-02-08T16:24:52.844132 | 2020-12-31T06:20:20 | 2020-12-31T06:20:20 | 325,729,532 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | cpp | #include "PlotItem_PlayEffect.h"
#include "Kismet/GameplayStatics.h"
#include "Particles/ParticleSystem.h"
UPlotItem_PlayEffect::UPlotItem_PlayEffect() {
bWait = false;
}
void UPlotItem_PlayEffect::Start()
{
if (auto MyPlot = GetPlot()) {
auto& PlotSpawnParticle = MyPlot->PlotSpawnParticle;
if (PlotSpawnParticle.Contains(EffectName)) {
ParticleSyetem = PlotSpawnParticle[EffectName];
if (ParticleSyetem.IsValid()) {
ParticleSyetem->SetVisibility(!bHide);
}
else {
PlotSpawnParticle.Remove(EffectName);
}
}
else {
if (Effect.IsValid()) {
UParticleSystem* LoadParticle = Cast<UParticleSystem>(Effect.TryLoad());
if (LoadParticle) {
const FTransform SpawnTransform(Rotator.Quaternion(), Position);
const auto NewParticle = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), LoadParticle, SpawnTransform);
if (NewParticle) {
ParticleSyetem = NewParticle;
PlotSpawnParticle.Add(EffectName, NewParticle);
}
}
}
}
}
Super::Start();
}
#if WITH_EDITOR
void UPlotItem_PlayEffect::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) {
Super::PostEditChangeProperty(PropertyChangedEvent);
if (ParticleSyetem.IsValid()) {
ParticleSyetem->SetWorldLocation(Position);
ParticleSyetem->SetWorldRotation(Rotator);
}
}
#endif
| [
"977908569@qq.com"
] | 977908569@qq.com |
86edb289db0411c71df51b39fed4edbdafc0de81 | 52e32d1228fe4179e96309c799f37763f2767ac6 | /include/Trigger.h | 847adc87cd9674226d02eb18cc97ba27c36c56c6 | [] | no_license | kylemartin120/Zork | bbfeb152e834c9160e2371d92c7e6e50e65c58f0 | a8ecf7b963b68e4fcca48121e879fcbdb18297ef | refs/heads/master | 2021-08-19T21:55:54.793815 | 2017-11-27T14:15:06 | 2017-11-27T14:15:06 | 109,631,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #ifndef TRIGGER_H_
#define TRIGGER_H_
#include "Condition.h"
#include "StatusCondition.h"
#include "HasCondition.h"
#include <iostream>
#include <string>
#include <vector>
#include "rapidxml.hpp"
using namespace std;
using namespace rapidxml;
class Condition;
class Trigger {
public:
vector<string> actions;
vector<string> prints;
vector<string> commands;
bool permanent;
bool used; // only matters if permanent is false
int last_used; // the last turn number it was used
vector<Condition*> conditions;
Trigger(vector<string> a, vector<string> ps, vector<string> co, bool p,
vector<Condition*> c);
Trigger(xml_node<>* node);
virtual ~Trigger();
vector<Condition*> getConditions();
vector<string> getPrints();
vector<string> getActions();
};
#endif
| [
"kmart120@hotmail.com"
] | kmart120@hotmail.com |
62b63292f29e5e45b3460f96f30ad42e044be4fc | 515eae03aa8892ce48e91b593f1d7057b4bf2cc2 | /CPP20/CONCEPT/concept_ordering4.cpp | 544b11cb5affc9e5d502dd969719f55def6831da | [] | no_license | et16kr/codenuri-clone | b7b759d85337009c40ee4b2d3e42e7c38a025c6d | d1178eec9db369d2cb94ceb44fd3a4982228f2eb | refs/heads/master | 2023-04-20T12:44:58.696043 | 2021-05-01T04:13:33 | 2021-05-01T04:13:33 | 363,316,531 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | #include <iostream>
template<typename T>
concept Concept1 = sizeof(T) > 1;
template<typename T>
concept Concept2 = sizeof(T) < 8;
template<typename T>
concept Concept3 = Concept1<T> && Concept2<T>;
template<typename T> requires Concept1<T>
void foo(T a) { std::cout << "1" << std::endl; }
template<typename T> requires Concept3<T>
void foo(T a) { std::cout << "2" << std::endl;}
int main()
{
foo(3);
}
| [
"et16kr@gmail.com"
] | et16kr@gmail.com |
c721d9137217f477a7b7c4a7caad17d6b347af43 | 0ed7f38691b880786bd4c8601d1a6f40ebd0c667 | /renderer.cpp | dea0c3196374f1f0e261b28bd0ee710f4d83420c | [] | no_license | Ernestynian/AI-Evolutionary-Images | 13d0e7f8e051c7df0083de31230975423052f1a6 | 18e8ea6dab6e6fe561f50eaed46d91d06fcd7496 | refs/heads/master | 2021-06-18T22:41:50.769362 | 2017-05-25T19:28:03 | 2017-05-25T19:28:03 | 91,721,747 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,421 | cpp | #include <cstdio>
#include <stdlib.h>
#include <malloc.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "renderer.h"
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glx.h>
#include <GL/glu.h>
typedef GLXContext(*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
typedef Bool(*glXMakeContextCurrentARBProc)(Display*, GLXDrawable, GLXDrawable, GLXContext);
static glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
static glXMakeContextCurrentARBProc glXMakeContextCurrentARB = 0;
Renderer::Renderer(Mat& original, int width, int height, bool isHardwareAccelerated):
width(width), height(height) {
this->original = &original;
columnAvgs = nullptr;
this->isHardwareAccelerated = isHardwareAccelerated;
if (isHardwareAccelerated) {
// source: https://sidvind.com/wiki/Opengl/windowless
static int visual_attribs[] = {
None
};
int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
None
};
Display* dpy = XOpenDisplay(0);
int fbcount = 0;
GLXFBConfig* fbc = NULL;
GLXContext ctx;
GLXPbuffer pbuf;
if(!(dpy = XOpenDisplay(0))) {
fprintf(stderr, "Failed to open display\n");
exit(1);
}
// get framebuffer configs, any is usable (might want to add proper attribs)
if(!(fbc = glXChooseFBConfig(dpy, DefaultScreen(dpy), visual_attribs, &fbcount))) {
fprintf(stderr, "Failed to get FBConfig\n");
exit(1);
}
// get the required extensions
glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte *)"glXCreateContextAttribsARB");
glXMakeContextCurrentARB = (glXMakeContextCurrentARBProc)glXGetProcAddressARB((const GLubyte *)"glXMakeContextCurrent");
if(!(glXCreateContextAttribsARB && glXMakeContextCurrentARB)) {
fprintf(stderr, "missing support for GLX_ARB_create_context\n");
XFree(fbc);
exit(1);
}
// create a context using glXCreateContextAttribsARB
if(!(ctx = glXCreateContextAttribsARB(dpy, fbc[0], 0, True, context_attribs))) {
fprintf(stderr, "Failed to create opengl context\n");
XFree(fbc);
exit(1);
}
// create temporary pbuffer
int pbuffer_attribs[] = {
GLX_PBUFFER_WIDTH, width,
GLX_PBUFFER_HEIGHT, height,
None
};
pbuf = glXCreatePbuffer(dpy, fbc[0], pbuffer_attribs);
XFree(fbc);
XSync(dpy, False);
// try to make it the current context
if(!glXMakeContextCurrent(dpy, pbuf, pbuf, ctx)) {
// some drivers does not support context without default framebuffer
// so fallback on using the default window.
if(!glXMakeContextCurrent(dpy, DefaultRootWindow(dpy), DefaultRootWindow(dpy), ctx)) {
fprintf(stderr, "failed to make current\n");
exit(1);
}
}
columnAvgs = new float[width];
prepareOpenGL();
createShaders();
}
}
Renderer::~Renderer() {
if (columnAvgs != nullptr)
delete[] columnAvgs;
if (isHardwareAccelerated) {
for (int i = 0; i < 3; ++i) {
glDeleteShader(fragShader[i]);
glDeleteProgram(p[i]);
}
}
}
void Renderer::prepareOpenGL() {
glewInit();
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(false);
glViewport(0, 0, width, height);
glClearColor(0, 0, 0, 0);
//glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glOrtho(0, width, 0, height, 0, 1);
/////////////////////////
Mat temp;
cv::flip(*original, temp, 0);
glGenTextures(1, &originalTexture);
glBindTexture(GL_TEXTURE_2D, originalTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_BGR, GL_UNSIGNED_BYTE, original->ptr());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
/////////////////////////
framebufferName = 0;
glGenFramebuffers(1, &framebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
//GLuint renderedTexture;
glGenTextures(1, &renderedTexture);
glBindTexture(GL_TEXTURE_2D, renderedTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderedTexture, 0);
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
/////////////////////////
framebuffer2Name = 0;
glGenFramebuffers(1, &framebuffer2Name);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer2Name);
//GLuint renderedTexture;
glGenTextures(1, &diffTexture);
glBindTexture(GL_TEXTURE_2D, diffTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, diffTexture, 0);
glDrawBuffers(1, DrawBuffers);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
}
void Renderer::createShaders() {
assert(GLEW_ARB_fragment_shader);
const char* fragmentShaderCode[] = {
textFileRead("render.frag"),
textFileRead("diff.frag"),
textFileRead("sum.frag")
};
for (int i = 0; i < 3; ++i) {
fragShader[i] = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragShader[i], 1, &fragmentShaderCode[i], nullptr);
glCompileShader(fragShader[i]);
printShaderInfoLog(fragmentShaderCode[i], fragShader[i]);
p[i] = glCreateProgram();
glAttachShader(p[i], fragShader[i]);
glLinkProgram(p[i]);
printProgramInfoLog(fragmentShaderCode[i], p[i]);
}
}
uint64 Renderer::render(Point2i** v, Scalar* c, int tris) {
if (isHardwareAccelerated)
return renderGPU(v, c, tris);
else
return renderCPU(v, c, tris);
}
void Renderer::renderImage(Point2i** v, Scalar* c, int tris, Mat& out) {
if (isHardwareAccelerated)
renderImageGPU(v, c, tris, out);
else
renderImageCPU(v, c, tris, out);
}
uint64 Renderer::renderGPU(Point2i** v, Scalar* c, int tris) {
///////// RENDER IMAGE TO TEXTURE /////////
glDisable(GL_TEXTURE_2D);
glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(p[0]);
glBegin(GL_TRIANGLES);
for(int j = 0; j < tris; j++) {
glColor4f(c[j][0], c[j][1], c[j][2], c[j][3]);
glVertex2i(v[j][0].x, v[j][0].y);
glVertex2i(v[j][1].x, v[j][1].y);
glVertex2i(v[j][2].x, v[j][2].y);
}
glEnd();
///////// CALCULATE PIXELS DIFFERENCE /////////
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer2Name);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(p[1]);
GLuint tex1ID = glGetUniformLocation(p[1], "render");
GLuint tex2ID = glGetUniformLocation(p[1], "orig");
glUniform1i(tex1ID, 0);
glUniform1i(tex2ID, 1);
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderedTexture);
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, originalTexture);
glBegin(GL_QUADS);
glTexCoord2i(0, 0); glVertex2i(0, 0);
glTexCoord2i(0, 1); glVertex2i(0, height);
glTexCoord2i(1, 1); glVertex2i(width, height);
glTexCoord2i(1, 0); glVertex2i(width, 0);
glEnd();
///////// CALCULATE SUMS OF COLUMNS /////////
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(p[2]);
GLuint texID = glGetUniformLocation(p[2], "diff");
GLuint imhID = glGetUniformLocation(p[2], "imageHeight");
glUniform1i(texID, 0);
glUniform1i(imhID, height);
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffTexture);
glBegin(GL_QUADS);
glTexCoord2i(0, 0); glVertex2i(0, 0);
glTexCoord2i(0, 1); glVertex2i(0, 1);
glTexCoord2i(1, 1); glVertex2i(width, 1);
glTexCoord2i(1, 0); glVertex2i(width, 0);
glEnd();
///////// CALCULATE FITNESS /////////
float sum = 0.0;
glReadPixels(0, 0, width, 1, GL_RED, GL_FLOAT, columnAvgs);
for (int i = 0; i < width; ++i)
sum += columnAvgs[i];
return uint64(sum * width * height * 2550);
}
void Renderer::renderImageGPU(Point2i** v, Scalar* c, int tris, Mat& out) {
// glScalef won't work - tested
// no need to flip matrix either
glDisable(GL_TEXTURE_2D);
glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(p[0]);
glBegin(GL_TRIANGLES);
for(int j = 0; j < tris; j++) {
glColor4f(c[j][0], c[j][1], c[j][2], c[j][3]);
glVertex2i(v[j][0].x, v[j][0].y);
glVertex2i(v[j][1].x, v[j][1].y);
glVertex2i(v[j][2].x, v[j][2].y);
}
glEnd();
glReadPixels(0, 0, out.cols, out.rows, GL_BGR, GL_UNSIGNED_BYTE, out.data);
}
uint64 Renderer::renderCPU(Point2i** v, Scalar* c, int tris) {
Mat out = Mat(height, width, CV_8UC3, Scalar(0, 0, 0));
Mat overlay = Mat(height, width, CV_8UC3, Scalar(0, 0, 0));
for(int i = 0; i < tris; i++) {
Point p[] = {
Point(v[i][0].x, v[i][0].y),
Point(v[i][1].x, v[i][1].y),
Point(v[i][2].x, v[i][2].y),
};
Scalar cf = Scalar(c[i][0] * 255.0, c[i][1] * 255.0, c[i][2] * 255.0);
fillConvexPoly(overlay, p, 3, cf);
float alpha = c[i][3];// * 0.1;
addWeighted(overlay, alpha, out, 1.0 - alpha, 0, out);
}
absdiff(out, *original, overlay);
overlay.convertTo(overlay, CV_16UC3); // should be made optional in some way
overlay = overlay.mul(overlay);
Scalar s = sum(overlay);
return s[0] + s[1] + s[2];
}
void Renderer::renderImageCPU(Point2i** v, Scalar* c, int tris, Mat& out) {
Mat overlay = Mat(height, width, CV_8UC3, Scalar(0, 0, 0));
for(int i = 0; i < tris; i++) {
Point p[] = {
Point(v[i][0].x, v[i][0].y),
Point(v[i][1].x, v[i][1].y),
Point(v[i][2].x, v[i][2].y),
};
Scalar cf = Scalar(c[i][0] * 255.0, c[i][1] * 255.0, c[i][2] * 255.0);
fillConvexPoly(overlay, p, 3, cf);
float alpha = c[i][3];// * 0.1;
addWeighted(overlay, alpha, out, 1.0 - alpha, 0, out);
}
}
void Renderer::printShaderInfoLog(const char* title, GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n%s\n", title, infoLog);
free(infoLog);
}
}
void Renderer::printProgramInfoLog(const char* title, GLuint obj) {
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0) {
infoLog = (char *)malloc(infologLength);
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("%s\n%s\n", title, infoLog);
free(infoLog);
}
}
char* Renderer::textFileRead(const char* fn) {
FILE *fp;
char *content = NULL;
int f,count;
f = open(fn, O_RDONLY);
count = lseek(f, 0, SEEK_END);
close(f);
if (fn != NULL) {
fp = fopen(fn,"rt");
if (fp != NULL) {
if (count > 0) {
content = (char *)malloc(sizeof(char) * (count+1));
count = fread(content,sizeof(char),count,fp);
content[count] = '\0';
}
fclose(fp);
}
}
return content;
}
| [
"rrocik@vp.pl"
] | rrocik@vp.pl |
0ab6e7586a9b9857e9485173af9ce5cef66ea418 | 52368d7ea35d80c95bee58b6fa0727894c98558a | /u411pgm1_panel/smu2_peaxism4.h | 357b4ead7bf691c4be698a74161ae2ff93ac2bdd | [] | no_license | catha32/u411pgm1 | f0aae78c4ac2962b4a96916f7b6f07789626e572 | 1033151dee336660483e4045aea9d12fdec4c059 | refs/heads/master | 2020-06-20T07:14:07.409115 | 2017-06-13T12:39:48 | 2017-06-13T12:39:48 | 94,197,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | h | #ifndef SMU2_PEAXISM4_H
#define SMU2_PEAXISM4_H
#include <QDialog>
namespace Ui {
class smu2_peaxism4;
}
class smu2_peaxism4 : public QDialog
{
Q_OBJECT
public:
explicit smu2_peaxism4(QWidget *parent = 0);
~smu2_peaxism4();
public slots:
bool init();
private:
Ui::smu2_peaxism4 *ui;
};
#endif // SMU2_PEAXISM4_H
| [
"catharina.haebel@helmholtz-berlin.de"
] | catharina.haebel@helmholtz-berlin.de |
88144e3f46f284fed7dad4d6d222e40241e9b764 | e095c6b8f3d7c8aeac9628ceb9f776f37811ea36 | /HandlerMC/DlgOutput.cpp | 452f7b361de04c6b17d27ba1ad6578cb50d0b51a | [] | no_license | dangquang95/Handler_MC_SS | 3dc16ba78ef594d16ca18a802db26ccffad201bd | c70a78878ecd102b3fb627cf156d9998eb04b21d | refs/heads/master | 2022-11-25T11:46:42.045391 | 2020-07-28T02:49:19 | 2020-07-28T02:49:19 | 283,078,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,167 | cpp | // DlgOutput.cpp : implementation file
//
#include "stdafx.h"
#include "HandlerMC.h"
#include "DlgOutput.h"
#include "afxdialogex.h"
// DlgOutput dialog
IMPLEMENT_DYNAMIC(DlgOutput, CDialogEx)
DlgOutput::DlgOutput(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_DLG_OUTPUT, pParent)
{
}
DlgOutput::~DlgOutput()
{
}
void DlgOutput::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
for (int i = 0; i < 32; i++)
{
DDX_Control(pDX, IDB_IO_0, m_Output[i]);
}
}
BEGIN_MESSAGE_MAP(DlgOutput, CDialogEx)
END_MESSAGE_MAP()
// DlgOutput message handlers
BEGIN_EVENTSINK_MAP(DlgOutput, CDialogEx)
ON_EVENT(DlgOutput, IDB_EXIT1, DISPID_CLICK, DlgOutput::ClickExit1, VTS_NONE)
END_EVENTSINK_MAP()
void DlgOutput::ClickExit1()
{
CDialog::OnCancel();
}
BOOL DlgOutput::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void DlgOutput::SetNameCaption()
{
CString m_Data;
for (int i = 0; i < 32; i++)
{
m_Data.Format("Output %d", i);
m_Output[i].SetCaption(m_Data);
}
} | [
"quang.ledang95@gmail.com"
] | quang.ledang95@gmail.com |
acb9ef9883a813559980d11d3a88e67090fee66a | 1103a717b305cc6d4aaac9e1d47cc6a1bb0afed4 | /SRC/RIA/Utility.cpp | cd54fd35e12020ce08426575e741388f8647e9cf | [] | no_license | rabbitjason/RIA | 3333942dd2acdaf7897ed74a565f905d337e5229 | af2befe41702a9e52913caac618facf3a4e27469 | refs/heads/master | 2021-04-25T14:04:31.560585 | 2018-05-14T06:22:23 | 2018-05-14T06:22:23 | 110,058,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,494 | cpp | #include "StdAfx.h"
#include "Utility.h"
CUtility::CUtility(void)
{
}
CUtility::~CUtility(void)
{
}
wstring CUtility::ANSIToUnicode(LPCSTR lpsContent)
{
int len = 0;
len = strlen(lpsContent);
int unicodeLen = ::MultiByteToWideChar( CP_ACP,
0,
lpsContent,
-1,
NULL,
0 );
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen+1];
memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
::MultiByteToWideChar( CP_ACP,
0,
lpsContent,
-1,
(LPWSTR)pUnicode,
unicodeLen );
wstring rt;
rt = ( wchar_t* )pUnicode;
delete pUnicode;
return rt;
}
wstring CUtility::ANSIToUnicode( const string& str )
{
return ANSIToUnicode(str.c_str());
}
string CUtility::UnicodeToANSI(LPCWSTR lpwsContent)
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte( CP_ACP,
0,
lpwsContent,
-1,
NULL,
0,
NULL,
NULL );
pElementText = new char[iTextLen + 1];
memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
::WideCharToMultiByte( CP_ACP,
0,
lpwsContent,
-1,
pElementText,
iTextLen,
NULL,
NULL );
string strText;
strText = pElementText;
delete[] pElementText;
return strText;
}
string CUtility::UnicodeToANSI( const wstring& str )
{
return UnicodeToANSI(str.c_str());
} | [
"ping_gao_jpi@sina.com"
] | ping_gao_jpi@sina.com |
8db2a701cbad767fb414eee4250c4dd2ee3f4c17 | aa42f1436b3c398def6251b424cdb130079e7d5e | /src/mapOptmization.cpp | 2394fb66f27c2398683a830f2f02bc4aed75d2f7 | [
"BSD-3-Clause"
] | permissive | liuxinren456852/LIO-SAM | 1dfac6f9631886990d2bf914c04779bedaccce9e | bc50671b4337c110787d07ec70d82977d56fcdf0 | refs/heads/master | 2022-11-18T16:52:29.745832 | 2020-07-08T02:26:32 | 2020-07-08T02:26:32 | 276,532,795 | 0 | 0 | BSD-3-Clause | 2020-07-08T02:26:33 | 2020-07-02T02:49:27 | null | UTF-8 | C++ | false | false | 61,561 | cpp | #include "utility.h"
#include "lio_sam/cloud_info.h"
#include <gtsam/geometry/Rot3.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/navigation/GPSFactor.h>
#include <gtsam/navigation/ImuFactor.h>
#include <gtsam/navigation/CombinedImuFactor.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/nonlinear/Marginals.h>
#include <gtsam/nonlinear/Values.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/nonlinear/ISAM2.h>
using namespace gtsam;
using symbol_shorthand::X; // Pose3 (x,y,z,r,p,y)
using symbol_shorthand::V; // Vel (xdot,ydot,zdot)
using symbol_shorthand::B; // Bias (ax,ay,az,gx,gy,gz)
using symbol_shorthand::G; // GPS pose
/*
* A point cloud type that has 6D pose info ([x,y,z,roll,pitch,yaw] intensity is time stamp)
*/
struct PointXYZIRPYT
{
PCL_ADD_POINT4D
PCL_ADD_INTENSITY; // preferred way of adding a XYZ+padding
float roll;
float pitch;
float yaw;
double time;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // make sure our new allocators are aligned
} EIGEN_ALIGN16; // enforce SSE padding for correct memory alignment
POINT_CLOUD_REGISTER_POINT_STRUCT (PointXYZIRPYT,
(float, x, x) (float, y, y)
(float, z, z) (float, intensity, intensity)
(float, roll, roll) (float, pitch, pitch) (float, yaw, yaw)
(double, time, time))
typedef PointXYZIRPYT PointTypePose;
class mapOptimization : public ParamServer
{
public:
// gtsam
NonlinearFactorGraph gtSAMgraph;
Values initialEstimate;
Values optimizedEstimate;
ISAM2 *isam;
Values isamCurrentEstimate;
Eigen::MatrixXd poseCovariance;
ros::Publisher pubLaserCloudSurround;
ros::Publisher pubOdomAftMappedROS;
ros::Publisher pubKeyPoses;
ros::Publisher pubPath;
ros::Publisher pubHistoryKeyFrames;
ros::Publisher pubIcpKeyFrames;
ros::Publisher pubRecentKeyFrames;
ros::Publisher pubRecentKeyFrame;
ros::Publisher pubCloudRegisteredRaw;
ros::Subscriber subLaserCloudInfo;
ros::Subscriber subGPS;
std::deque<nav_msgs::Odometry> gpsQueue;
lio_sam::cloud_info cloudInfo;
vector<pcl::PointCloud<PointType>::Ptr> cornerCloudKeyFrames;
vector<pcl::PointCloud<PointType>::Ptr> surfCloudKeyFrames;
pcl::PointCloud<PointType>::Ptr cloudKeyPoses3D;
pcl::PointCloud<PointTypePose>::Ptr cloudKeyPoses6D;
pcl::PointCloud<PointType>::Ptr laserCloudCornerLast; // corner feature set from odoOptimization
pcl::PointCloud<PointType>::Ptr laserCloudSurfLast; // surf feature set from odoOptimization
pcl::PointCloud<PointType>::Ptr laserCloudCornerLastDS; // downsampled corner featuer set from odoOptimization
pcl::PointCloud<PointType>::Ptr laserCloudSurfLastDS; // downsampled surf featuer set from odoOptimization
pcl::PointCloud<PointType>::Ptr laserCloudOri;
pcl::PointCloud<PointType>::Ptr coeffSel;
std::vector<PointType> laserCloudOriCornerVec; // corner point holder for parallel computation
std::vector<PointType> coeffSelCornerVec;
std::vector<bool> laserCloudOriCornerFlag;
std::vector<PointType> laserCloudOriSurfVec; // surf point holder for parallel computation
std::vector<PointType> coeffSelSurfVec;
std::vector<bool> laserCloudOriSurfFlag;
pcl::PointCloud<PointType>::Ptr laserCloudCornerFromMap;
pcl::PointCloud<PointType>::Ptr laserCloudSurfFromMap;
pcl::PointCloud<PointType>::Ptr laserCloudCornerFromMapDS;
pcl::PointCloud<PointType>::Ptr laserCloudSurfFromMapDS;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeCornerFromMap;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeSurfFromMap;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeSurroundingKeyPoses;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeHistoryKeyPoses;
pcl::PointCloud<PointType>::Ptr latestKeyFrameCloud;
pcl::PointCloud<PointType>::Ptr nearHistoryKeyFrameCloud;
pcl::VoxelGrid<PointType> downSizeFilterCorner;
pcl::VoxelGrid<PointType> downSizeFilterSurf;
pcl::VoxelGrid<PointType> downSizeFilterICP;
pcl::VoxelGrid<PointType> downSizeFilterSurroundingKeyPoses; // for surrounding key poses of scan-to-map optimization
ros::Time timeLaserInfoStamp;
double timeLaserCloudInfoLast;
float transformTobeMapped[6];
std::mutex mtx;
double timeLastProcessing = -1;
bool isDegenerate = false;
Eigen::Matrix<float, 6, 6> matP;
int laserCloudCornerFromMapDSNum = 0;
int laserCloudSurfFromMapDSNum = 0;
int laserCloudCornerLastDSNum = 0;
int laserCloudSurfLastDSNum = 0;
bool aLoopIsClosed = false;
int imuPreintegrationResetId = 0;
nav_msgs::Path globalPath;
Eigen::Affine3f transPointAssociateToMap;
mapOptimization()
{
ISAM2Params parameters;
parameters.relinearizeThreshold = 0.1;
parameters.relinearizeSkip = 1;
isam = new ISAM2(parameters);
pubKeyPoses = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/trajectory", 1);
pubLaserCloudSurround = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/map_global", 1);
pubOdomAftMappedROS = nh.advertise<nav_msgs::Odometry> ("lio_sam/mapping/odometry", 1);
pubPath = nh.advertise<nav_msgs::Path>("lio_sam/mapping/path", 1);
subLaserCloudInfo = nh.subscribe<lio_sam::cloud_info>("lio_sam/feature/cloud_info", 10, &mapOptimization::laserCloudInfoHandler, this, ros::TransportHints().tcpNoDelay());
subGPS = nh.subscribe<nav_msgs::Odometry> (gpsTopic, 200, &mapOptimization::gpsHandler, this, ros::TransportHints().tcpNoDelay());
pubHistoryKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/icp_loop_closure_history_cloud", 1);
pubIcpKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/icp_loop_closure_corrected_cloud", 1);
pubRecentKeyFrames = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/map_local", 1);
pubRecentKeyFrame = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/cloud_registered", 1);
pubCloudRegisteredRaw = nh.advertise<sensor_msgs::PointCloud2>("lio_sam/mapping/cloud_registered_raw", 1);
downSizeFilterCorner.setLeafSize(mappingCornerLeafSize, mappingCornerLeafSize, mappingCornerLeafSize);
downSizeFilterSurf.setLeafSize(mappingSurfLeafSize, mappingSurfLeafSize, mappingSurfLeafSize);
downSizeFilterICP.setLeafSize(mappingSurfLeafSize, mappingSurfLeafSize, mappingSurfLeafSize);
downSizeFilterSurroundingKeyPoses.setLeafSize(surroundingKeyframeDensity, surroundingKeyframeDensity, surroundingKeyframeDensity); // for surrounding key poses of scan-to-map optimization
allocateMemory();
}
void allocateMemory()
{
cloudKeyPoses3D.reset(new pcl::PointCloud<PointType>());
cloudKeyPoses6D.reset(new pcl::PointCloud<PointTypePose>());
kdtreeSurroundingKeyPoses.reset(new pcl::KdTreeFLANN<PointType>());
kdtreeHistoryKeyPoses.reset(new pcl::KdTreeFLANN<PointType>());
laserCloudCornerLast.reset(new pcl::PointCloud<PointType>()); // corner feature set from odoOptimization
laserCloudSurfLast.reset(new pcl::PointCloud<PointType>()); // surf feature set from odoOptimization
laserCloudCornerLastDS.reset(new pcl::PointCloud<PointType>()); // downsampled corner featuer set from odoOptimization
laserCloudSurfLastDS.reset(new pcl::PointCloud<PointType>()); // downsampled surf featuer set from odoOptimization
laserCloudOri.reset(new pcl::PointCloud<PointType>());
coeffSel.reset(new pcl::PointCloud<PointType>());
laserCloudOriCornerVec.resize(N_SCAN * Horizon_SCAN);
coeffSelCornerVec.resize(N_SCAN * Horizon_SCAN);
laserCloudOriCornerFlag.resize(N_SCAN * Horizon_SCAN);
laserCloudOriSurfVec.resize(N_SCAN * Horizon_SCAN);
coeffSelSurfVec.resize(N_SCAN * Horizon_SCAN);
laserCloudOriSurfFlag.resize(N_SCAN * Horizon_SCAN);
std::fill(laserCloudOriCornerFlag.begin(), laserCloudOriCornerFlag.end(), false);
std::fill(laserCloudOriSurfFlag.begin(), laserCloudOriSurfFlag.end(), false);
laserCloudCornerFromMap.reset(new pcl::PointCloud<PointType>());
laserCloudSurfFromMap.reset(new pcl::PointCloud<PointType>());
laserCloudCornerFromMapDS.reset(new pcl::PointCloud<PointType>());
laserCloudSurfFromMapDS.reset(new pcl::PointCloud<PointType>());
kdtreeCornerFromMap.reset(new pcl::KdTreeFLANN<PointType>());
kdtreeSurfFromMap.reset(new pcl::KdTreeFLANN<PointType>());
latestKeyFrameCloud.reset(new pcl::PointCloud<PointType>());
nearHistoryKeyFrameCloud.reset(new pcl::PointCloud<PointType>());
for (int i = 0; i < 6; ++i){
transformTobeMapped[i] = 0;
}
matP.setZero();
}
void laserCloudInfoHandler(const lio_sam::cloud_infoConstPtr& msgIn)
{
// extract time stamp
timeLaserInfoStamp = msgIn->header.stamp;
timeLaserCloudInfoLast = msgIn->header.stamp.toSec();
// extract info and feature cloud
cloudInfo = *msgIn;
pcl::fromROSMsg(msgIn->cloud_corner, *laserCloudCornerLast);
pcl::fromROSMsg(msgIn->cloud_surface, *laserCloudSurfLast);
std::lock_guard<std::mutex> lock(mtx);
if (timeLaserCloudInfoLast - timeLastProcessing >= mappingProcessInterval) {
timeLastProcessing = timeLaserCloudInfoLast;
updateInitialGuess();
extractSurroundingKeyFrames();
downsampleCurrentScan();
scan2MapOptimization();
saveKeyFramesAndFactor();
correctPoses();
publishOdometry();
publishFrames();
}
}
void gpsHandler(const nav_msgs::Odometry::ConstPtr& gpsMsg)
{
gpsQueue.push_back(*gpsMsg);
}
void pointAssociateToMap(PointType const * const pi, PointType * const po)
{
po->x = transPointAssociateToMap(0,0) * pi->x + transPointAssociateToMap(0,1) * pi->y + transPointAssociateToMap(0,2) * pi->z + transPointAssociateToMap(0,3);
po->y = transPointAssociateToMap(1,0) * pi->x + transPointAssociateToMap(1,1) * pi->y + transPointAssociateToMap(1,2) * pi->z + transPointAssociateToMap(1,3);
po->z = transPointAssociateToMap(2,0) * pi->x + transPointAssociateToMap(2,1) * pi->y + transPointAssociateToMap(2,2) * pi->z + transPointAssociateToMap(2,3);
po->intensity = pi->intensity;
}
pcl::PointCloud<PointType>::Ptr transformPointCloud(pcl::PointCloud<PointType>::Ptr cloudIn, PointTypePose* transformIn)
{
pcl::PointCloud<PointType>::Ptr cloudOut(new pcl::PointCloud<PointType>());
PointType *pointFrom;
int cloudSize = cloudIn->size();
cloudOut->resize(cloudSize);
Eigen::Affine3f transCur = pcl::getTransformation(transformIn->x, transformIn->y, transformIn->z, transformIn->roll, transformIn->pitch, transformIn->yaw);
for (int i = 0; i < cloudSize; ++i){
pointFrom = &cloudIn->points[i];
cloudOut->points[i].x = transCur(0,0) * pointFrom->x + transCur(0,1) * pointFrom->y + transCur(0,2) * pointFrom->z + transCur(0,3);
cloudOut->points[i].y = transCur(1,0) * pointFrom->x + transCur(1,1) * pointFrom->y + transCur(1,2) * pointFrom->z + transCur(1,3);
cloudOut->points[i].z = transCur(2,0) * pointFrom->x + transCur(2,1) * pointFrom->y + transCur(2,2) * pointFrom->z + transCur(2,3);
cloudOut->points[i].intensity = pointFrom->intensity;
}
return cloudOut;
}
gtsam::Pose3 pclPointTogtsamPose3(PointTypePose thisPoint)
{
return gtsam::Pose3(gtsam::Rot3::RzRyRx(double(thisPoint.roll), double(thisPoint.pitch), double(thisPoint.yaw)),
gtsam::Point3(double(thisPoint.x), double(thisPoint.y), double(thisPoint.z)));
}
gtsam::Pose3 trans2gtsamPose(float transformIn[])
{
return gtsam::Pose3(gtsam::Rot3::RzRyRx(transformIn[0], transformIn[1], transformIn[2]),
gtsam::Point3(transformIn[3], transformIn[4], transformIn[5]));
}
Eigen::Affine3f pclPointToAffine3f(PointTypePose thisPoint)
{
return pcl::getTransformation(thisPoint.x, thisPoint.y, thisPoint.z, thisPoint.roll, thisPoint.pitch, thisPoint.yaw);
}
Eigen::Affine3f trans2Affine3f(float transformIn[])
{
return pcl::getTransformation(transformIn[3], transformIn[4], transformIn[5], transformIn[0], transformIn[1], transformIn[2]);
}
PointTypePose trans2PointTypePose(float transformIn[])
{
PointTypePose thisPose6D;
thisPose6D.x = transformIn[3];
thisPose6D.y = transformIn[4];
thisPose6D.z = transformIn[5];
thisPose6D.roll = transformIn[0];
thisPose6D.pitch = transformIn[1];
thisPose6D.yaw = transformIn[2];
return thisPose6D;
}
void visualizeGlobalMapThread()
{
ros::Rate rate(0.2);
while (ros::ok()){
rate.sleep();
publishGlobalMap();
}
if (savePCD == false)
return;
cout << "****************************************************" << endl;
cout << "Saving map to pcd files ..." << endl;
// create directory and remove old files;
savePCDDirectory = std::getenv("HOME") + savePCDDirectory;
int unused = system((std::string("exec rm -r ") + savePCDDirectory).c_str());
unused = system((std::string("mkdir ") + savePCDDirectory).c_str());
// save key frame transformations
pcl::io::savePCDFileASCII(savePCDDirectory + "trajectory.pcd", *cloudKeyPoses3D);
pcl::io::savePCDFileASCII(savePCDDirectory + "transformations.pcd", *cloudKeyPoses6D);
// extract global point cloud map
pcl::PointCloud<PointType>::Ptr globalCornerCloud(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalCornerCloudDS(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalSurfCloud(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalSurfCloudDS(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalMapCloud(new pcl::PointCloud<PointType>());
for (int i = 0; i < (int)cloudKeyPoses3D->size(); i++) {
*globalCornerCloud += *transformPointCloud(cornerCloudKeyFrames[i], &cloudKeyPoses6D->points[i]);
*globalSurfCloud += *transformPointCloud(surfCloudKeyFrames[i], &cloudKeyPoses6D->points[i]);
cout << "\r" << std::flush << "Processing feature cloud " << i << " of " << cloudKeyPoses6D->size() << " ...";
}
// down-sample and save corner cloud
downSizeFilterCorner.setInputCloud(globalCornerCloud);
downSizeFilterCorner.filter(*globalCornerCloudDS);
pcl::io::savePCDFileASCII(savePCDDirectory + "cloudCorner.pcd", *globalCornerCloudDS);
// down-sample and save surf cloud
downSizeFilterSurf.setInputCloud(globalSurfCloud);
downSizeFilterSurf.filter(*globalSurfCloudDS);
pcl::io::savePCDFileASCII(savePCDDirectory + "cloudSurf.pcd", *globalSurfCloudDS);
// down-sample and save global point cloud map
*globalMapCloud += *globalCornerCloud;
*globalMapCloud += *globalSurfCloud;
pcl::io::savePCDFileASCII(savePCDDirectory + "cloudGlobal.pcd", *globalMapCloud);
cout << "****************************************************" << endl;
cout << "Saving map to pcd files completed" << endl;
}
void publishGlobalMap()
{
if (pubLaserCloudSurround.getNumSubscribers() == 0)
return;
if (cloudKeyPoses3D->points.empty() == true)
return;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeGlobalMap(new pcl::KdTreeFLANN<PointType>());;
pcl::PointCloud<PointType>::Ptr globalMapKeyPoses(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalMapKeyPosesDS(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalMapKeyFrames(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr globalMapKeyFramesDS(new pcl::PointCloud<PointType>());
// kd-tree to find near key frames to visualize
std::vector<int> pointSearchIndGlobalMap;
std::vector<float> pointSearchSqDisGlobalMap;
// search near key frames to visualize
mtx.lock();
kdtreeGlobalMap->setInputCloud(cloudKeyPoses3D);
kdtreeGlobalMap->radiusSearch(cloudKeyPoses3D->back(), globalMapVisualizationSearchRadius, pointSearchIndGlobalMap, pointSearchSqDisGlobalMap, 0);
mtx.unlock();
for (int i = 0; i < (int)pointSearchIndGlobalMap.size(); ++i)
globalMapKeyPoses->push_back(cloudKeyPoses3D->points[pointSearchIndGlobalMap[i]]);
// downsample near selected key frames
pcl::VoxelGrid<PointType> downSizeFilterGlobalMapKeyPoses; // for global map visualization
downSizeFilterGlobalMapKeyPoses.setLeafSize(globalMapVisualizationPoseDensity, globalMapVisualizationPoseDensity, globalMapVisualizationPoseDensity); // for global map visualization
downSizeFilterGlobalMapKeyPoses.setInputCloud(globalMapKeyPoses);
downSizeFilterGlobalMapKeyPoses.filter(*globalMapKeyPosesDS);
// extract visualized and downsampled key frames
for (int i = 0; i < (int)globalMapKeyPosesDS->size(); ++i){
if (pointDistance(globalMapKeyPosesDS->points[i], cloudKeyPoses3D->back()) > globalMapVisualizationSearchRadius)
continue;
int thisKeyInd = (int)globalMapKeyPosesDS->points[i].intensity;
*globalMapKeyFrames += *transformPointCloud(cornerCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
*globalMapKeyFrames += *transformPointCloud(surfCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
}
// downsample visualized points
pcl::VoxelGrid<PointType> downSizeFilterGlobalMapKeyFrames; // for global map visualization
downSizeFilterGlobalMapKeyFrames.setLeafSize(globalMapVisualizationLeafSize, globalMapVisualizationLeafSize, globalMapVisualizationLeafSize); // for global map visualization
downSizeFilterGlobalMapKeyFrames.setInputCloud(globalMapKeyFrames);
downSizeFilterGlobalMapKeyFrames.filter(*globalMapKeyFramesDS);
publishCloud(&pubLaserCloudSurround, globalMapKeyFramesDS, timeLaserInfoStamp, "odom");
}
void loopClosureThread()
{
if (loopClosureEnableFlag == false)
return;
ros::Rate rate(0.2);
while (ros::ok())
{
rate.sleep();
performLoopClosure();
}
}
bool detectLoopClosure(int *latestID, int *closestID)
{
int latestFrameIDLoopCloure;
int closestHistoryFrameID;
latestKeyFrameCloud->clear();
nearHistoryKeyFrameCloud->clear();
std::lock_guard<std::mutex> lock(mtx);
// find the closest history key frame
std::vector<int> pointSearchIndLoop;
std::vector<float> pointSearchSqDisLoop;
kdtreeHistoryKeyPoses->setInputCloud(cloudKeyPoses3D);
kdtreeHistoryKeyPoses->radiusSearch(cloudKeyPoses3D->back(), historyKeyframeSearchRadius, pointSearchIndLoop, pointSearchSqDisLoop, 0);
closestHistoryFrameID = -1;
for (int i = 0; i < (int)pointSearchIndLoop.size(); ++i)
{
int id = pointSearchIndLoop[i];
if (abs(cloudKeyPoses6D->points[id].time - timeLaserCloudInfoLast) > historyKeyframeSearchTimeDiff)
{
closestHistoryFrameID = id;
break;
}
}
if (closestHistoryFrameID == -1)
return false;
if ((int)cloudKeyPoses3D->size() - 1 == closestHistoryFrameID)
return false;
// save latest key frames
latestFrameIDLoopCloure = cloudKeyPoses3D->size() - 1;
*latestKeyFrameCloud += *transformPointCloud(cornerCloudKeyFrames[latestFrameIDLoopCloure], &cloudKeyPoses6D->points[latestFrameIDLoopCloure]);
*latestKeyFrameCloud += *transformPointCloud(surfCloudKeyFrames[latestFrameIDLoopCloure], &cloudKeyPoses6D->points[latestFrameIDLoopCloure]);
// save history near key frames
bool nearFrameAvailable = false;
for (int j = -historyKeyframeSearchNum; j <= historyKeyframeSearchNum; ++j)
{
if (closestHistoryFrameID + j < 0 || closestHistoryFrameID + j > latestFrameIDLoopCloure)
continue;
*nearHistoryKeyFrameCloud += *transformPointCloud(cornerCloudKeyFrames[closestHistoryFrameID+j], &cloudKeyPoses6D->points[closestHistoryFrameID+j]);
*nearHistoryKeyFrameCloud += *transformPointCloud(surfCloudKeyFrames[closestHistoryFrameID+j], &cloudKeyPoses6D->points[closestHistoryFrameID+j]);
nearFrameAvailable = true;
}
if (nearFrameAvailable == false)
return false;
*latestID = latestFrameIDLoopCloure;
*closestID = closestHistoryFrameID;
return true;
}
void performLoopClosure()
{
if (cloudKeyPoses3D->points.empty() == true)
return;
int latestFrameIDLoopCloure;
int closestHistoryFrameID;
if (detectLoopClosure(&latestFrameIDLoopCloure, &closestHistoryFrameID) == false)
return;
// ICP Settings
pcl::IterativeClosestPoint<PointType, PointType> icp;
icp.setMaxCorrespondenceDistance(100);
icp.setMaximumIterations(100);
icp.setTransformationEpsilon(1e-6);
icp.setEuclideanFitnessEpsilon(1e-6);
icp.setRANSACIterations(0);
// Downsample map cloud
pcl::PointCloud<PointType>::Ptr cloud_temp(new pcl::PointCloud<PointType>());
downSizeFilterICP.setInputCloud(nearHistoryKeyFrameCloud);
downSizeFilterICP.filter(*cloud_temp);
*nearHistoryKeyFrameCloud = *cloud_temp;
// publish history near key frames
publishCloud(&pubHistoryKeyFrames, nearHistoryKeyFrameCloud, timeLaserInfoStamp, "odom");
// Align clouds
icp.setInputSource(latestKeyFrameCloud);
icp.setInputTarget(nearHistoryKeyFrameCloud);
pcl::PointCloud<PointType>::Ptr unused_result(new pcl::PointCloud<PointType>());
icp.align(*unused_result);
// std::cout << "ICP converg flag:" << icp.hasConverged() << ". Fitness score: " << icp.getFitnessScore() << std::endl;
if (icp.hasConverged() == false || icp.getFitnessScore() > historyKeyframeFitnessScore)
return;
// publish corrected cloud
if (pubIcpKeyFrames.getNumSubscribers() != 0){
pcl::PointCloud<PointType>::Ptr closed_cloud(new pcl::PointCloud<PointType>());
pcl::transformPointCloud(*latestKeyFrameCloud, *closed_cloud, icp.getFinalTransformation());
publishCloud(&pubIcpKeyFrames, closed_cloud, timeLaserInfoStamp, "odom");
}
// Get pose transformation
float x, y, z, roll, pitch, yaw;
Eigen::Affine3f correctionLidarFrame;
correctionLidarFrame = icp.getFinalTransformation();
// transform from world origin to wrong pose
Eigen::Affine3f tWrong = pclPointToAffine3f(cloudKeyPoses6D->points[latestFrameIDLoopCloure]);
// transform from world origin to corrected pose
Eigen::Affine3f tCorrect = correctionLidarFrame * tWrong;// pre-multiplying -> successive rotation about a fixed frame
pcl::getTranslationAndEulerAngles (tCorrect, x, y, z, roll, pitch, yaw);
gtsam::Pose3 poseFrom = Pose3(Rot3::RzRyRx(roll, pitch, yaw), Point3(x, y, z));
gtsam::Pose3 poseTo = pclPointTogtsamPose3(cloudKeyPoses6D->points[closestHistoryFrameID]);
gtsam::Vector Vector6(6);
float noiseScore = icp.getFitnessScore();
Vector6 << noiseScore, noiseScore, noiseScore, noiseScore, noiseScore, noiseScore;
noiseModel::Diagonal::shared_ptr constraintNoise = noiseModel::Diagonal::Variances(Vector6);
// Add pose constraint
std::lock_guard<std::mutex> lock(mtx);
gtSAMgraph.add(BetweenFactor<Pose3>(latestFrameIDLoopCloure, closestHistoryFrameID, poseFrom.between(poseTo), constraintNoise));
isam->update(gtSAMgraph);
isam->update();
isam->update();
isam->update();
isam->update();
isam->update();
gtSAMgraph.resize(0);
isamCurrentEstimate = isam->calculateEstimate();
Pose3 latestEstimate = isamCurrentEstimate.at<Pose3>(isamCurrentEstimate.size()-1);
transformTobeMapped[0] = latestEstimate.rotation().roll();
transformTobeMapped[1] = latestEstimate.rotation().pitch();
transformTobeMapped[2] = latestEstimate.rotation().yaw();
transformTobeMapped[3] = latestEstimate.translation().x();
transformTobeMapped[4] = latestEstimate.translation().y();
transformTobeMapped[5] = latestEstimate.translation().z();
correctPoses();
aLoopIsClosed = true;
}
void updateInitialGuess()
{
static Eigen::Affine3f lastImuTransformation;
// initialization
if (cloudKeyPoses3D->points.empty())
{
transformTobeMapped[0] = cloudInfo.imuRollInit;
transformTobeMapped[1] = cloudInfo.imuPitchInit;
transformTobeMapped[2] = cloudInfo.imuYawInit;
if (!useImuHeadingInitialization)
transformTobeMapped[2] = 0;
lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit); // save imu before return;
return;
}
// use imu pre-integration estimation for pose guess
if (cloudInfo.odomAvailable == true && cloudInfo.imuPreintegrationResetId == imuPreintegrationResetId)
{
transformTobeMapped[0] = cloudInfo.initialGuessRoll;
transformTobeMapped[1] = cloudInfo.initialGuessPitch;
transformTobeMapped[2] = cloudInfo.initialGuessYaw;
transformTobeMapped[3] = cloudInfo.initialGuessX;
transformTobeMapped[4] = cloudInfo.initialGuessY;
transformTobeMapped[5] = cloudInfo.initialGuessZ;
lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit); // save imu before return;
return;
}
// use imu incremental estimation for pose guess (only rotation)
if (cloudInfo.imuAvailable == true)
{
Eigen::Affine3f transBack = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit);
Eigen::Affine3f transIncre = lastImuTransformation.inverse() * transBack;
Eigen::Affine3f transTobe = trans2Affine3f(transformTobeMapped);
Eigen::Affine3f transFinal = transTobe * transIncre;
pcl::getTranslationAndEulerAngles(transFinal, transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5],
transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit); // save imu before return;
return;
}
}
void extractForLoopClosure()
{
pcl::PointCloud<PointType>::Ptr cloudToExtract(new pcl::PointCloud<PointType>());
int numPoses = cloudKeyPoses3D->size();
for (int i = numPoses-1; i >= 0; --i)
{
if ((int)cloudToExtract->size() <= surroundingKeyframeSize)
cloudToExtract->push_back(cloudKeyPoses3D->points[i]);
else
break;
}
extractCloud(cloudToExtract);
}
void extractNearby()
{
pcl::PointCloud<PointType>::Ptr surroundingKeyPoses(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr surroundingKeyPosesDS(new pcl::PointCloud<PointType>());
std::vector<int> pointSearchInd;
std::vector<float> pointSearchSqDis;
// extract all the nearby key poses and downsample them
kdtreeSurroundingKeyPoses->setInputCloud(cloudKeyPoses3D); // create kd-tree
kdtreeSurroundingKeyPoses->radiusSearch(cloudKeyPoses3D->back(), (double)surroundingKeyframeSearchRadius, pointSearchInd, pointSearchSqDis);
for (int i = 0; i < (int)pointSearchInd.size(); ++i)
{
int id = pointSearchInd[i];
surroundingKeyPoses->push_back(cloudKeyPoses3D->points[id]);
}
downSizeFilterSurroundingKeyPoses.setInputCloud(surroundingKeyPoses);
downSizeFilterSurroundingKeyPoses.filter(*surroundingKeyPosesDS);
// also extract some latest key frames in case the robot rotates in one position
int numPoses = cloudKeyPoses3D->size();
for (int i = numPoses-1; i >= 0; --i)
{
if (timeLaserCloudInfoLast - cloudKeyPoses6D->points[i].time < 10.0)
surroundingKeyPosesDS->push_back(cloudKeyPoses3D->points[i]);
else
break;
}
extractCloud(surroundingKeyPosesDS);
}
void extractCloud(pcl::PointCloud<PointType>::Ptr cloudToExtract)
{
std::vector<pcl::PointCloud<PointType>> laserCloudCornerSurroundingVec;
std::vector<pcl::PointCloud<PointType>> laserCloudSurfSurroundingVec;
laserCloudCornerSurroundingVec.resize(cloudToExtract->size());
laserCloudSurfSurroundingVec.resize(cloudToExtract->size());
// extract surrounding map
#pragma omp parallel for num_threads(numberOfCores)
for (int i = 0; i < (int)cloudToExtract->size(); ++i)
{
if (pointDistance(cloudToExtract->points[i], cloudKeyPoses3D->back()) > surroundingKeyframeSearchRadius)
continue;
int thisKeyInd = (int)cloudToExtract->points[i].intensity;
laserCloudCornerSurroundingVec[i] = *transformPointCloud(cornerCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
laserCloudSurfSurroundingVec[i] = *transformPointCloud(surfCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
}
// fuse the map
laserCloudCornerFromMap->clear();
laserCloudSurfFromMap->clear();
for (int i = 0; i < (int)cloudToExtract->size(); ++i)
{
*laserCloudCornerFromMap += laserCloudCornerSurroundingVec[i];
*laserCloudSurfFromMap += laserCloudSurfSurroundingVec[i];
}
// Downsample the surrounding corner key frames (or map)
downSizeFilterCorner.setInputCloud(laserCloudCornerFromMap);
downSizeFilterCorner.filter(*laserCloudCornerFromMapDS);
laserCloudCornerFromMapDSNum = laserCloudCornerFromMapDS->size();
// Downsample the surrounding surf key frames (or map)
downSizeFilterSurf.setInputCloud(laserCloudSurfFromMap);
downSizeFilterSurf.filter(*laserCloudSurfFromMapDS);
laserCloudSurfFromMapDSNum = laserCloudSurfFromMapDS->size();
}
void extractSurroundingKeyFrames()
{
if (cloudKeyPoses3D->points.empty() == true)
return;
if (loopClosureEnableFlag == true)
{
extractForLoopClosure();
} else {
extractNearby();
}
}
void downsampleCurrentScan()
{
// Downsample cloud from current scan
laserCloudCornerLastDS->clear();
downSizeFilterCorner.setInputCloud(laserCloudCornerLast);
downSizeFilterCorner.filter(*laserCloudCornerLastDS);
laserCloudCornerLastDSNum = laserCloudCornerLastDS->size();
laserCloudSurfLastDS->clear();
downSizeFilterSurf.setInputCloud(laserCloudSurfLast);
downSizeFilterSurf.filter(*laserCloudSurfLastDS);
laserCloudSurfLastDSNum = laserCloudSurfLastDS->size();
}
void updatePointAssociateToMap()
{
transPointAssociateToMap = trans2Affine3f(transformTobeMapped);
}
void cornerOptimization()
{
updatePointAssociateToMap();
#pragma omp parallel for num_threads(numberOfCores)
for (int i = 0; i < laserCloudCornerLastDSNum; i++)
{
PointType pointOri, pointSel, coeff;
std::vector<int> pointSearchInd;
std::vector<float> pointSearchSqDis;
pointOri = laserCloudCornerLastDS->points[i];
pointAssociateToMap(&pointOri, &pointSel);
kdtreeCornerFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
cv::Mat matA1(3, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matD1(1, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matV1(3, 3, CV_32F, cv::Scalar::all(0));
if (pointSearchSqDis[4] < 1.0) {
float cx = 0, cy = 0, cz = 0;
for (int j = 0; j < 5; j++) {
cx += laserCloudCornerFromMapDS->points[pointSearchInd[j]].x;
cy += laserCloudCornerFromMapDS->points[pointSearchInd[j]].y;
cz += laserCloudCornerFromMapDS->points[pointSearchInd[j]].z;
}
cx /= 5; cy /= 5; cz /= 5;
float a11 = 0, a12 = 0, a13 = 0, a22 = 0, a23 = 0, a33 = 0;
for (int j = 0; j < 5; j++) {
float ax = laserCloudCornerFromMapDS->points[pointSearchInd[j]].x - cx;
float ay = laserCloudCornerFromMapDS->points[pointSearchInd[j]].y - cy;
float az = laserCloudCornerFromMapDS->points[pointSearchInd[j]].z - cz;
a11 += ax * ax; a12 += ax * ay; a13 += ax * az;
a22 += ay * ay; a23 += ay * az;
a33 += az * az;
}
a11 /= 5; a12 /= 5; a13 /= 5; a22 /= 5; a23 /= 5; a33 /= 5;
matA1.at<float>(0, 0) = a11; matA1.at<float>(0, 1) = a12; matA1.at<float>(0, 2) = a13;
matA1.at<float>(1, 0) = a12; matA1.at<float>(1, 1) = a22; matA1.at<float>(1, 2) = a23;
matA1.at<float>(2, 0) = a13; matA1.at<float>(2, 1) = a23; matA1.at<float>(2, 2) = a33;
cv::eigen(matA1, matD1, matV1);
if (matD1.at<float>(0, 0) > 3 * matD1.at<float>(0, 1)) {
float x0 = pointSel.x;
float y0 = pointSel.y;
float z0 = pointSel.z;
float x1 = cx + 0.1 * matV1.at<float>(0, 0);
float y1 = cy + 0.1 * matV1.at<float>(0, 1);
float z1 = cz + 0.1 * matV1.at<float>(0, 2);
float x2 = cx - 0.1 * matV1.at<float>(0, 0);
float y2 = cy - 0.1 * matV1.at<float>(0, 1);
float z2 = cz - 0.1 * matV1.at<float>(0, 2);
float a012 = sqrt(((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) * ((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
+ ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1)) * ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))
+ ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)) * ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)));
float l12 = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));
float la = ((y1 - y2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
+ (z1 - z2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))) / a012 / l12;
float lb = -((x1 - x2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
- (z1 - z2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;
float lc = -((x1 - x2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))
+ (y1 - y2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;
float ld2 = a012 / l12;
float s = 1 - 0.9 * fabs(ld2);
coeff.x = s * la;
coeff.y = s * lb;
coeff.z = s * lc;
coeff.intensity = s * ld2;
if (s > 0.1) {
laserCloudOriCornerVec[i] = pointOri;
coeffSelCornerVec[i] = coeff;
laserCloudOriCornerFlag[i] = true;
}
}
}
}
}
void surfOptimization()
{
updatePointAssociateToMap();
#pragma omp parallel for num_threads(numberOfCores)
for (int i = 0; i < laserCloudSurfLastDSNum; i++)
{
PointType pointOri, pointSel, coeff;
std::vector<int> pointSearchInd;
std::vector<float> pointSearchSqDis;
pointOri = laserCloudSurfLastDS->points[i];
pointAssociateToMap(&pointOri, &pointSel);
kdtreeSurfFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
Eigen::Matrix<float, 5, 3> matA0;
Eigen::Matrix<float, 5, 1> matB0;
Eigen::Vector3f matX0;
matA0.setZero();
matB0.fill(-1);
matX0.setZero();
if (pointSearchSqDis[4] < 1.0) {
for (int j = 0; j < 5; j++) {
matA0(j, 0) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].x;
matA0(j, 1) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].y;
matA0(j, 2) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].z;
}
matX0 = matA0.colPivHouseholderQr().solve(matB0);
float pa = matX0(0, 0);
float pb = matX0(1, 0);
float pc = matX0(2, 0);
float pd = 1;
float ps = sqrt(pa * pa + pb * pb + pc * pc);
pa /= ps; pb /= ps; pc /= ps; pd /= ps;
bool planeValid = true;
for (int j = 0; j < 5; j++) {
if (fabs(pa * laserCloudSurfFromMapDS->points[pointSearchInd[j]].x +
pb * laserCloudSurfFromMapDS->points[pointSearchInd[j]].y +
pc * laserCloudSurfFromMapDS->points[pointSearchInd[j]].z + pd) > 0.2) {
planeValid = false;
break;
}
}
if (planeValid) {
float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd;
float s = 1 - 0.9 * fabs(pd2) / sqrt(sqrt(pointSel.x * pointSel.x
+ pointSel.y * pointSel.y + pointSel.z * pointSel.z));
coeff.x = s * pa;
coeff.y = s * pb;
coeff.z = s * pc;
coeff.intensity = s * pd2;
if (s > 0.1) {
laserCloudOriSurfVec[i] = pointOri;
coeffSelSurfVec[i] = coeff;
laserCloudOriSurfFlag[i] = true;
}
}
}
}
}
void combineOptimizationCoeffs()
{
// combine corner coeffs
for (int i = 0; i < laserCloudCornerLastDSNum; ++i){
if (laserCloudOriCornerFlag[i] == true){
laserCloudOri->push_back(laserCloudOriCornerVec[i]);
coeffSel->push_back(coeffSelCornerVec[i]);
}
}
// combine surf coeffs
for (int i = 0; i < laserCloudSurfLastDSNum; ++i){
if (laserCloudOriSurfFlag[i] == true){
laserCloudOri->push_back(laserCloudOriSurfVec[i]);
coeffSel->push_back(coeffSelSurfVec[i]);
}
}
// reset flag for next iteration
std::fill(laserCloudOriCornerFlag.begin(), laserCloudOriCornerFlag.end(), false);
std::fill(laserCloudOriSurfFlag.begin(), laserCloudOriSurfFlag.end(), false);
}
bool LMOptimization(int iterCount)
{
// This optimization is from the original loam_velodyne by Ji Zhang, need to cope with coordinate transformation
// lidar <- camera --- camera <- lidar
// x = z --- x = y
// y = x --- y = z
// z = y --- z = x
// roll = yaw --- roll = pitch
// pitch = roll --- pitch = yaw
// yaw = pitch --- yaw = roll
// lidar -> camera
float srx = sin(transformTobeMapped[1]);
float crx = cos(transformTobeMapped[1]);
float sry = sin(transformTobeMapped[2]);
float cry = cos(transformTobeMapped[2]);
float srz = sin(transformTobeMapped[0]);
float crz = cos(transformTobeMapped[0]);
int laserCloudSelNum = laserCloudOri->size();
if (laserCloudSelNum < 50) {
return false;
}
cv::Mat matA(laserCloudSelNum, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matAt(6, laserCloudSelNum, CV_32F, cv::Scalar::all(0));
cv::Mat matAtA(6, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matB(laserCloudSelNum, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matAtB(6, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matX(6, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matP(6, 6, CV_32F, cv::Scalar::all(0));
PointType pointOri, coeff;
for (int i = 0; i < laserCloudSelNum; i++) {
// lidar -> camera
pointOri.x = laserCloudOri->points[i].y;
pointOri.y = laserCloudOri->points[i].z;
pointOri.z = laserCloudOri->points[i].x;
// lidar -> camera
coeff.x = coeffSel->points[i].y;
coeff.y = coeffSel->points[i].z;
coeff.z = coeffSel->points[i].x;
coeff.intensity = coeffSel->points[i].intensity;
// in camera
float arx = (crx*sry*srz*pointOri.x + crx*crz*sry*pointOri.y - srx*sry*pointOri.z) * coeff.x
+ (-srx*srz*pointOri.x - crz*srx*pointOri.y - crx*pointOri.z) * coeff.y
+ (crx*cry*srz*pointOri.x + crx*cry*crz*pointOri.y - cry*srx*pointOri.z) * coeff.z;
float ary = ((cry*srx*srz - crz*sry)*pointOri.x
+ (sry*srz + cry*crz*srx)*pointOri.y + crx*cry*pointOri.z) * coeff.x
+ ((-cry*crz - srx*sry*srz)*pointOri.x
+ (cry*srz - crz*srx*sry)*pointOri.y - crx*sry*pointOri.z) * coeff.z;
float arz = ((crz*srx*sry - cry*srz)*pointOri.x + (-cry*crz-srx*sry*srz)*pointOri.y)*coeff.x
+ (crx*crz*pointOri.x - crx*srz*pointOri.y) * coeff.y
+ ((sry*srz + cry*crz*srx)*pointOri.x + (crz*sry-cry*srx*srz)*pointOri.y)*coeff.z;
// lidar -> camera
matA.at<float>(i, 0) = arz;
matA.at<float>(i, 1) = arx;
matA.at<float>(i, 2) = ary;
matA.at<float>(i, 3) = coeff.z;
matA.at<float>(i, 4) = coeff.x;
matA.at<float>(i, 5) = coeff.y;
matB.at<float>(i, 0) = -coeff.intensity;
}
cv::transpose(matA, matAt);
matAtA = matAt * matA;
matAtB = matAt * matB;
cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR);
if (iterCount == 0) {
cv::Mat matE(1, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matV(6, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matV2(6, 6, CV_32F, cv::Scalar::all(0));
cv::eigen(matAtA, matE, matV);
matV.copyTo(matV2);
isDegenerate = false;
float eignThre[6] = {100, 100, 100, 100, 100, 100};
for (int i = 5; i >= 0; i--) {
if (matE.at<float>(0, i) < eignThre[i]) {
for (int j = 0; j < 6; j++) {
matV2.at<float>(i, j) = 0;
}
isDegenerate = true;
} else {
break;
}
}
matP = matV.inv() * matV2;
}
if (isDegenerate) {
cv::Mat matX2(6, 1, CV_32F, cv::Scalar::all(0));
matX.copyTo(matX2);
matX = matP * matX2;
}
transformTobeMapped[0] += matX.at<float>(0, 0);
transformTobeMapped[1] += matX.at<float>(1, 0);
transformTobeMapped[2] += matX.at<float>(2, 0);
transformTobeMapped[3] += matX.at<float>(3, 0);
transformTobeMapped[4] += matX.at<float>(4, 0);
transformTobeMapped[5] += matX.at<float>(5, 0);
float deltaR = sqrt(
pow(pcl::rad2deg(matX.at<float>(0, 0)), 2) +
pow(pcl::rad2deg(matX.at<float>(1, 0)), 2) +
pow(pcl::rad2deg(matX.at<float>(2, 0)), 2));
float deltaT = sqrt(
pow(matX.at<float>(3, 0) * 100, 2) +
pow(matX.at<float>(4, 0) * 100, 2) +
pow(matX.at<float>(5, 0) * 100, 2));
if (deltaR < 0.05 && deltaT < 0.05) {
return true; // converged
}
return false; // keep optimizing
}
void scan2MapOptimization()
{
if (cloudKeyPoses3D->points.empty())
return;
if (laserCloudCornerLastDSNum > edgeFeatureMinValidNum && laserCloudSurfLastDSNum > surfFeatureMinValidNum)
{
kdtreeCornerFromMap->setInputCloud(laserCloudCornerFromMapDS);
kdtreeSurfFromMap->setInputCloud(laserCloudSurfFromMapDS);
for (int iterCount = 0; iterCount < 30; iterCount++)
{
laserCloudOri->clear();
coeffSel->clear();
cornerOptimization();
surfOptimization();
combineOptimizationCoeffs();
if (LMOptimization(iterCount) == true)
break;
}
transformUpdate();
} else {
ROS_WARN("Not enough features! Only %d edge and %d planar features available.", laserCloudCornerLastDSNum, laserCloudSurfLastDSNum);
}
}
void transformUpdate()
{
if (cloudInfo.imuAvailable == true)
{
if (std::abs(cloudInfo.imuPitchInit) < 1.4)
{
double imuWeight = 0.05;
tf::Quaternion imuQuaternion;
tf::Quaternion transformQuaternion;
double rollMid, pitchMid, yawMid;
// slerp roll
transformQuaternion.setRPY(transformTobeMapped[0], 0, 0);
imuQuaternion.setRPY(cloudInfo.imuRollInit, 0, 0);
tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
transformTobeMapped[0] = rollMid;
// slerp pitch
transformQuaternion.setRPY(0, transformTobeMapped[1], 0);
imuQuaternion.setRPY(0, cloudInfo.imuPitchInit, 0);
tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
transformTobeMapped[1] = pitchMid;
}
}
transformTobeMapped[0] = constraintTransformation(transformTobeMapped[0], rotation_tollerance);
transformTobeMapped[1] = constraintTransformation(transformTobeMapped[1], rotation_tollerance);
transformTobeMapped[5] = constraintTransformation(transformTobeMapped[5], z_tollerance);
}
float constraintTransformation(float value, float limit)
{
if (value < -limit)
value = -limit;
if (value > limit)
value = limit;
return value;
}
bool saveFrame()
{
if (cloudKeyPoses3D->points.empty())
return true;
Eigen::Affine3f transStart = pclPointToAffine3f(cloudKeyPoses6D->back());
Eigen::Affine3f transFinal = pcl::getTransformation(transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5],
transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
Eigen::Affine3f transBetween = transStart.inverse() * transFinal;
float x, y, z, roll, pitch, yaw;
pcl::getTranslationAndEulerAngles(transBetween, x, y, z, roll, pitch, yaw);
if (abs(roll) < surroundingkeyframeAddingAngleThreshold &&
abs(pitch) < surroundingkeyframeAddingAngleThreshold &&
abs(yaw) < surroundingkeyframeAddingAngleThreshold &&
sqrt(x*x + y*y + z*z) < surroundingkeyframeAddingDistThreshold)
return false;
return true;
}
void addOdomFactor()
{
if (cloudKeyPoses3D->points.empty())
{
noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Variances((Vector(6) << 1e-2, 1e-2, M_PI*M_PI, 1e8, 1e8, 1e8).finished()); // rad*rad, meter*meter
gtSAMgraph.add(PriorFactor<Pose3>(0, trans2gtsamPose(transformTobeMapped), priorNoise));
initialEstimate.insert(0, trans2gtsamPose(transformTobeMapped));
}else{
noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Variances((Vector(6) << 1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4).finished());
gtsam::Pose3 poseFrom = pclPointTogtsamPose3(cloudKeyPoses6D->points.back());
gtsam::Pose3 poseTo = trans2gtsamPose(transformTobeMapped);
gtSAMgraph.add(BetweenFactor<Pose3>(cloudKeyPoses3D->size()-1, cloudKeyPoses3D->size(), poseFrom.between(poseTo), odometryNoise));
initialEstimate.insert(cloudKeyPoses3D->size(), poseTo);
}
}
void addGPSFactor()
{
if (gpsQueue.empty())
return;
// wait for system initialized and settles down
if (cloudKeyPoses3D->points.empty())
return;
else
{
if (pointDistance(cloudKeyPoses3D->front(), cloudKeyPoses3D->back()) < 5.0)
return;
}
// pose covariance small, no need to correct
if (poseCovariance(3,3) < poseCovThreshold && poseCovariance(4,4) < poseCovThreshold)
return;
// last gps position
static PointType lastGPSPoint;
while (!gpsQueue.empty())
{
if (gpsQueue.front().header.stamp.toSec() < timeLaserCloudInfoLast - 0.2)
{
// message too old
gpsQueue.pop_front();
}
else if (gpsQueue.front().header.stamp.toSec() > timeLaserCloudInfoLast + 0.2)
{
// message too new
break;
}
else
{
nav_msgs::Odometry thisGPS = gpsQueue.front();
gpsQueue.pop_front();
// GPS too noisy, skip
float noise_x = thisGPS.pose.covariance[0];
float noise_y = thisGPS.pose.covariance[7];
float noise_z = thisGPS.pose.covariance[14];
if (noise_x > gpsCovThreshold || noise_y > gpsCovThreshold)
continue;
float gps_x = thisGPS.pose.pose.position.x;
float gps_y = thisGPS.pose.pose.position.y;
float gps_z = thisGPS.pose.pose.position.z;
if (!useGpsElevation)
{
gps_z = transformTobeMapped[5];
noise_z = 0.01;
}
// GPS not properly initialized (0,0,0)
if (abs(gps_x) < 1e-6 && abs(gps_y) < 1e-6)
continue;
// Add GPS every a few meters
PointType curGPSPoint;
curGPSPoint.x = gps_x;
curGPSPoint.y = gps_y;
curGPSPoint.z = gps_z;
if (pointDistance(curGPSPoint, lastGPSPoint) < 5.0)
continue;
else
lastGPSPoint = curGPSPoint;
gtsam::Vector Vector3(3);
Vector3 << max(noise_x, 1.0f), max(noise_y, 1.0f), max(noise_z, 1.0f);
noiseModel::Diagonal::shared_ptr gps_noise = noiseModel::Diagonal::Variances(Vector3);
gtsam::GPSFactor gps_factor(cloudKeyPoses3D->size(), gtsam::Point3(gps_x, gps_y, gps_z), gps_noise);
gtSAMgraph.add(gps_factor);
aLoopIsClosed = true;
break;
}
}
}
void saveKeyFramesAndFactor()
{
if (saveFrame() == false)
return;
// odom factor
addOdomFactor();
// gps factor
addGPSFactor();
// cout << "****************************************************" << endl;
// gtSAMgraph.print("GTSAM Graph:\n");
// update iSAM
isam->update(gtSAMgraph, initialEstimate);
isam->update();
// update multiple-times till converge
if (aLoopIsClosed == true)
{
isam->update();
isam->update();
isam->update();
isam->update();
isam->update();
}
gtSAMgraph.resize(0);
initialEstimate.clear();
//save key poses
PointType thisPose3D;
PointTypePose thisPose6D;
Pose3 latestEstimate;
isamCurrentEstimate = isam->calculateEstimate();
latestEstimate = isamCurrentEstimate.at<Pose3>(isamCurrentEstimate.size()-1);
// cout << "****************************************************" << endl;
// isamCurrentEstimate.print("Current estimate: ");
thisPose3D.x = latestEstimate.translation().x();
thisPose3D.y = latestEstimate.translation().y();
thisPose3D.z = latestEstimate.translation().z();
thisPose3D.intensity = cloudKeyPoses3D->size(); // this can be used as index
cloudKeyPoses3D->push_back(thisPose3D);
thisPose6D.x = thisPose3D.x;
thisPose6D.y = thisPose3D.y;
thisPose6D.z = thisPose3D.z;
thisPose6D.intensity = thisPose3D.intensity ; // this can be used as index
thisPose6D.roll = latestEstimate.rotation().roll();
thisPose6D.pitch = latestEstimate.rotation().pitch();
thisPose6D.yaw = latestEstimate.rotation().yaw();
thisPose6D.time = timeLaserCloudInfoLast;
cloudKeyPoses6D->push_back(thisPose6D);
// cout << "****************************************************" << endl;
// cout << "Pose covariance:" << endl;
// cout << isam->marginalCovariance(isamCurrentEstimate.size()-1) << endl << endl;
poseCovariance = isam->marginalCovariance(isamCurrentEstimate.size()-1);
// save updated transform
transformTobeMapped[0] = latestEstimate.rotation().roll();
transformTobeMapped[1] = latestEstimate.rotation().pitch();
transformTobeMapped[2] = latestEstimate.rotation().yaw();
transformTobeMapped[3] = latestEstimate.translation().x();
transformTobeMapped[4] = latestEstimate.translation().y();
transformTobeMapped[5] = latestEstimate.translation().z();
// save all the received edge and surf points
pcl::PointCloud<PointType>::Ptr thisCornerKeyFrame(new pcl::PointCloud<PointType>());
pcl::PointCloud<PointType>::Ptr thisSurfKeyFrame(new pcl::PointCloud<PointType>());
pcl::copyPointCloud(*laserCloudCornerLastDS, *thisCornerKeyFrame);
pcl::copyPointCloud(*laserCloudSurfLastDS, *thisSurfKeyFrame);
// save key frame cloud
cornerCloudKeyFrames.push_back(thisCornerKeyFrame);
surfCloudKeyFrames.push_back(thisSurfKeyFrame);
// save path for visualization
updatePath(thisPose6D);
}
void correctPoses()
{
if (cloudKeyPoses3D->points.empty())
return;
if (aLoopIsClosed == true)
{
// clear path
globalPath.poses.clear();
// update key poses
int numPoses = isamCurrentEstimate.size();
for (int i = 0; i < numPoses; ++i)
{
cloudKeyPoses3D->points[i].x = isamCurrentEstimate.at<Pose3>(i).translation().x();
cloudKeyPoses3D->points[i].y = isamCurrentEstimate.at<Pose3>(i).translation().y();
cloudKeyPoses3D->points[i].z = isamCurrentEstimate.at<Pose3>(i).translation().z();
cloudKeyPoses6D->points[i].x = cloudKeyPoses3D->points[i].x;
cloudKeyPoses6D->points[i].y = cloudKeyPoses3D->points[i].y;
cloudKeyPoses6D->points[i].z = cloudKeyPoses3D->points[i].z;
cloudKeyPoses6D->points[i].roll = isamCurrentEstimate.at<Pose3>(i).rotation().roll();
cloudKeyPoses6D->points[i].pitch = isamCurrentEstimate.at<Pose3>(i).rotation().pitch();
cloudKeyPoses6D->points[i].yaw = isamCurrentEstimate.at<Pose3>(i).rotation().yaw();
updatePath(cloudKeyPoses6D->points[i]);
}
aLoopIsClosed = false;
// ID for reseting IMU pre-integration
++imuPreintegrationResetId;
}
}
void updatePath(const PointTypePose& pose_in)
{
geometry_msgs::PoseStamped pose_stamped;
pose_stamped.header.stamp = timeLaserInfoStamp;
pose_stamped.header.frame_id = "odom";
pose_stamped.pose.position.x = pose_in.x;
pose_stamped.pose.position.y = pose_in.y;
pose_stamped.pose.position.z = pose_in.z;
tf::Quaternion q = tf::createQuaternionFromRPY(pose_in.roll, pose_in.pitch, pose_in.yaw);
pose_stamped.pose.orientation.x = q.x();
pose_stamped.pose.orientation.y = q.y();
pose_stamped.pose.orientation.z = q.z();
pose_stamped.pose.orientation.w = q.w();
globalPath.poses.push_back(pose_stamped);
}
void publishOdometry()
{
// Publish odometry for ROS
nav_msgs::Odometry laserOdometryROS;
laserOdometryROS.header.stamp = timeLaserInfoStamp;
laserOdometryROS.header.frame_id = "odom";
laserOdometryROS.child_frame_id = "odom_mapping";
laserOdometryROS.pose.pose.position.x = transformTobeMapped[3];
laserOdometryROS.pose.pose.position.y = transformTobeMapped[4];
laserOdometryROS.pose.pose.position.z = transformTobeMapped[5];
laserOdometryROS.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
laserOdometryROS.pose.covariance[0] = double(imuPreintegrationResetId);
pubOdomAftMappedROS.publish(laserOdometryROS);
}
void publishFrames()
{
if (cloudKeyPoses3D->points.empty())
return;
// publish key poses
publishCloud(&pubKeyPoses, cloudKeyPoses3D, timeLaserInfoStamp, "odom");
// Publish surrounding key frames
publishCloud(&pubRecentKeyFrames, laserCloudSurfFromMapDS, timeLaserInfoStamp, "odom");
// publish registered key frame
if (pubRecentKeyFrame.getNumSubscribers() != 0)
{
pcl::PointCloud<PointType>::Ptr cloudOut(new pcl::PointCloud<PointType>());
PointTypePose thisPose6D = trans2PointTypePose(transformTobeMapped);
*cloudOut += *transformPointCloud(laserCloudCornerLastDS, &thisPose6D);
*cloudOut += *transformPointCloud(laserCloudSurfLastDS, &thisPose6D);
publishCloud(&pubRecentKeyFrame, cloudOut, timeLaserInfoStamp, "odom");
}
// publish registered high-res raw cloud
if (pubCloudRegisteredRaw.getNumSubscribers() != 0)
{
pcl::PointCloud<PointType>::Ptr cloudOut(new pcl::PointCloud<PointType>());
pcl::fromROSMsg(cloudInfo.cloud_deskewed, *cloudOut);
PointTypePose thisPose6D = trans2PointTypePose(transformTobeMapped);
*cloudOut = *transformPointCloud(cloudOut, &thisPose6D);
publishCloud(&pubCloudRegisteredRaw, cloudOut, timeLaserInfoStamp, "odom");
}
// publish path
if (pubPath.getNumSubscribers() != 0)
{
globalPath.header.stamp = timeLaserInfoStamp;
globalPath.header.frame_id = "odom";
pubPath.publish(globalPath);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "lio_sam");
mapOptimization MO;
ROS_INFO("\033[1;32m----> Map Optimization Started.\033[0m");
std::thread loopthread(&mapOptimization::loopClosureThread, &MO);
std::thread visualizeMapThread(&mapOptimization::visualizeGlobalMapThread, &MO);
ros::spin();
loopthread.join();
visualizeMapThread.join();
return 0;
} | [
"tixiao.shan@gmail.com"
] | tixiao.shan@gmail.com |
d501a3291b2f5cc2bd832f457c377c846258c4fb | f72de19d41937887d3e635fd2d76dc229c325d55 | /benchmarks/cache-thrash.cpp | 01d3bb4486cbe22e07a6dbc259e5a93f7c68fd3b | [] | no_license | rishabhkabra/6172-dynamic-memory-allocator | 10cd621a1fa30e4ccaa6deebbbe141811e99115e | cab44f514beab5151a02e9f2f6310bc0bc65caf9 | refs/heads/master | 2021-01-01T06:10:21.171986 | 2012-11-29T04:52:33 | 2012-11-29T04:52:33 | 12,188,883 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,313 | cpp | ///-*-C++-*-//////////////////////////////////////////////////////////////////
//
// Hoard: A Fast, Scalable, and Memory-Efficient Allocator
// for Shared-Memory Multiprocessors
// Contact author: Emery Berger, http://www.cs.umass.edu/~emery
//
// Copyright (c) 1998-2003, The University of Texas at Austin.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as
// published by the Free Software Foundation, http://www.fsf.org.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
//////////////////////////////////////////////////////////////////////////////
/**
* @file cache-thrash.cpp
* @brief cache-thrash is a benchmark that exercises a heap's cache-locality.
*
* Try the following (on a P-processor machine):
*
* cache-thrash 1 1000 1 1000000
* cache-thrash P 1000 1 1000000
*
* cache-thrash-hoard 1 1000 1 1000000
* cache-thrash-hoard P 1000 1 1000000
*
* The ideal is a P-fold speedup.
*
* Modified for Fall 2011 by 6.172 Staff
*/
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#include "cpuinfo.h"
#include "fred.h"
#include "timer.h"
#include "../wrapper.cpp"
// This class just holds arguments to each thread.
class workerArg {
public:
workerArg (size_t objSize, int repetitions, int iterations)
: _objSize (objSize),
_iterations (iterations),
_repetitions (repetitions)
{}
size_t _objSize;
int _iterations;
int _repetitions;
};
#if defined(_WIN32)
extern "C" void worker (void * arg)
#else
extern "C" void * worker (void * arg)
#endif
{
// Repeatedly do the following:
// malloc a given-sized object,
// repeatedly write on it,
// then free it.
workerArg * w = (workerArg *) arg;
for (int i = 0; i < w->_iterations; i++) {
// Allocate the object.
char * obj = (char *) CUSTOM_MALLOC(w->_objSize);
// Write into it a bunch of times.
for (int j = 0; j < w->_repetitions; j++) {
for (int k = 0; k < w->_objSize; k++) {
obj[k] = (char) k;
volatile char ch = obj[k];
ch++;
}
}
// Free the object.
CUSTOM_FREE(obj);
}
delete w;
end_thread();
#if !defined(_WIN32)
return NULL;
#endif
}
int main (int argc, char * argv[])
{
int nthreads;
int iterations;
int objSize;
int repetitions;
if (argc > 4) {
nthreads = atoi(argv[1]);
iterations = atoi(argv[2]);
objSize = atoi(argv[3]);
repetitions = atoi(argv[4]);
} else {
cerr << "Usage: " << argv[0] << " nthreads iterations objSize repetitions" << endl;
exit(1);
}
HL::Fred * threads = new HL::Fred[nthreads];
HL::Fred::setConcurrency (HL::CPUInfo::getNumProcessors());
int i;
HL::Timer t;
t.start();
for (i = 0; i < nthreads; i++) {
workerArg * w = new workerArg (objSize, repetitions / nthreads, iterations);
threads[i].create (&worker, (void *) w);
}
for (i = 0; i < nthreads; i++) {
threads[i].join();
}
t.stop();
delete [] threads;
cout << "Time elapsed = " << (double) t << " seconds." << endl;
end_program();
}
| [
"tfk@mit.edu"
] | tfk@mit.edu |
569df30e62c1ac91565cff538cfc711a3030467e | 1316bf69cb76ddde9e8cea19eb1aa5342bd309af | /CommonUtilities/Timer.hpp | 21c69903b2f8b9731ff1f94293941283c9cda715 | [] | no_license | proxxus/Common-utilities | 20f8ec1daaf0767dee64dde4ea963fd77ab8e3e9 | 19e47ae4a4809759cc0ed1c5e093cf93bdac562b | refs/heads/master | 2020-04-01T02:07:20.940247 | 2018-10-12T14:50:29 | 2018-10-12T14:50:29 | 152,765,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | hpp | #pragma once
#include <chrono>
class Timer
{
public:
Timer();
Timer(const Timer &aTimer) = delete;
Timer& operator=(const Timer &aTimer) = delete;
void Update();
float GetDeltaTime() const;
double GetTotalTime() const;
private:
float myDT;
std::chrono::high_resolution_clock myClock;
const std::chrono::high_resolution_clock::time_point myStartTime = myClock.now();
std::chrono::high_resolution_clock::time_point myLastFrame;
std::chrono::high_resolution_clock::time_point myCurrentFame;
}; | [
"elias.oh@learnet.se"
] | elias.oh@learnet.se |
0b8beb206615bb043982c32ca1d277529b994705 | 942cc84d8528eff11ecb49dc9c9cad5327f75016 | /UnitTests/DatabaseHandlerBenchmark/tst_databasehandlerbenchmark.cc | 0891c4b990b84ee1d4c31e3b05cd666368ee72dd | [
"MIT"
] | permissive | PerttuP/EventTimer | 5e681934bb20e804e3e8625c1fdcc5c61f9d60a2 | 99946052a6d3ac36f35798f69a938e1c45dd3a4c | refs/heads/master | 2021-01-01T05:17:41.634951 | 2016-10-30T19:07:21 | 2016-10-30T19:07:21 | 58,411,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,141 | cc | /**
* @file
* @brief Benchmarking tests for the DatabaseHandler class.
* @author Perttu Paarlahti 2016.
*/
#include <QString>
#include <QtTest>
#include <memory>
#include "databasehandler.hh"
/**
* @brief The DatabaseHandlerBenchmark clas
* implements benchmarking for the DatabaseHandler class.
*/
class DatabaseHandlerBenchmark : public QObject
{
Q_OBJECT
public:
DatabaseHandlerBenchmark();
private Q_SLOTS:
/**
* @brief Benchmark DatabaseHandler constructor.
*/
void constructorBenchmark();
void constructorBenchmark_data();
/**
* @brief Benchmark consequtive additions in an empty database.
*/
void addEventBenchmark();
void addEventBenchmark_data();
/**
* @brief Benchmark updating single event in the database.
*/
void updateSingleBenchmark();
void updateSingleBenchmark_data();
/**
* @brief Benchmark getting single event in the database.
*/
void getEventSingle();
void getEventSingle_data();
/**
* @brief Test getting next events in relatively small db (get 3 out of 20).
*/
void nextEventsBenchmark();
void nextEventsBenchmark_data();
/**
* @brief Benchmark adding, updating and removing single element.
*/
void addUpdateRemoveSingleEvent();
void addUpdateRemoveSingleEvent_data();
// Big data tests (1000 events):
// ------------------------------------------------------------------------
/**
* @brief Benchmark adding 1000 events into empty database.
*/
void addThousandEvents();
void addThousandEvents_data();
/**
* @brief Benchmark updating 1000 different events in the database.
*/
void updateThousandEvents();
void updateThousandEvents_data();
/**
* @brief Benchmark getting 1000 different events from the database.
*/
void getThousandEvents();
void getThousandEvents_data();
/**
* @brief Benchmark getting 500 expired events from the database.
*/
void get500ExpiredEvents();
void get500ExpiredEvents_data();
/**
* @brief Benchmark getting next event from db of 1000 events.
*/
void oneNextEventsFromThousandEvents();
void oneNextEventsFromThousandEvents_data();
/**
* @brief Benchmark getting 1000 next events from db of 1001 events.
*/
void thousandNextEvents();
void thousandNextEvents_data();
/**
* @brief Benchmark clearing 500 dynamic events.
*/
void clear500DynamicEvents();
void clear500DynamicEvents_data();
/**
* @brief Benchmark clearing remaining 500 events.
*/
void clear500Events();
void clear500Events_data();
/**
* @brief Benchmark removing 1000 events from the database one by one.
*/
void removeThousandEvents();
void removeThousandEvents_data();
private:
std::shared_ptr<EventTimerNS::DatabaseHandler>
initDB(QString dbType, QString dbName, QString tableName, QString dbHost, QString userName, QString password);
// Container for storing Events in big data tests.
std::vector<EventTimerNS::Event> events_;
QDateTime currentTime_;
};
DatabaseHandlerBenchmark::DatabaseHandlerBenchmark()
{
}
void DatabaseHandlerBenchmark::constructorBenchmark()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
EventTimerNS::DatabaseHandler::DbSetup setup;
setup.dbType = dbType;
setup.dbName = dbName;
setup.tableName = tableName;
setup.dbHostName = dbHost;
setup.userName = userName;
setup.password = password;
EventTimerNS::DatabaseHandler* h = nullptr;
QBENCHMARK {
h = new EventTimerNS::DatabaseHandler(setup);
}
delete h;
}
void DatabaseHandlerBenchmark::constructorBenchmark_data()
{
QTest::addColumn<QString>("dbType");
QTest::addColumn<QString>("dbName");
QTest::addColumn<QString>("tableName");
QTest::addColumn<QString>("dbHost");
QTest::addColumn<QString>("userName");
QTest::addColumn<QString>("password");
QTest::newRow("Local SQLite no authentication")
<< "QSQLITE" << "SQLiteTestDB" << "events" << QString() << QString() << QString();
}
void DatabaseHandlerBenchmark::addEventBenchmark()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
QBENCHMARK {
Event e("eventName", "2000-01-01 00:00:00:000", Event::STATIC, 1000, 123);
handler->addEvent(&e);
}
handler->clearAll();
}
void DatabaseHandlerBenchmark::addEventBenchmark_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::updateSingleBenchmark()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
Event original("original", "2000-01-01 00:00:00:000", Event::DYNAMIC, 0, 0);
Event updated("updated", "2016-05-13 17:11:00:000", Event::DYNAMIC, 10, 10);
handler->addEvent(&original);
QBENCHMARK {
handler->updateEvent(original.id(), updated);
}
handler->clearAll();
}
void DatabaseHandlerBenchmark::updateSingleBenchmark_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::getEventSingle()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
Event original("original", "2000-01-01 00:00:00:000", Event::DYNAMIC, 0, 0);
handler->addEvent(&original);
Event tmp;
QBENCHMARK {
tmp = handler->getEvent(original.id());
}
handler->clearAll();
}
void DatabaseHandlerBenchmark::getEventSingle_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::nextEventsBenchmark()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
// Add 17 past events
for (int i=1; i<=17; ++i){
Event e("past"+QString::number(i),
QDateTime::currentDateTime().addDays(-i).toString(Event::TIME_FORMAT),
Event::STATIC, 0, 0);
QVERIFY(handler->addEvent(&e) != Event::UNASSIGNED_ID);
}
// Add 3 future events
for (int i=0; i<3; ++i){
Event e("future"+QString::number(i),
QDateTime::currentDateTime().addDays(-i).toString(Event::TIME_FORMAT),
Event::STATIC, 0, 0);
QVERIFY(handler->addEvent(&e) != Event::UNASSIGNED_ID);
}
std::vector<Event> events;
QBENCHMARK {
events = handler->nextEvents(QDateTime::currentDateTime().toString(Event::TIME_FORMAT), 3u);
}
}
void DatabaseHandlerBenchmark::nextEventsBenchmark_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::addUpdateRemoveSingleEvent()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
QBENCHMARK {
Event original("original", "2000-01-01 00:00:00:000", Event::DYNAMIC, 0, 0);
Event updated("updated", "2016-05-13 17:11:00:000", Event::DYNAMIC, 10, 10);
handler->addEvent(&original);
handler->updateEvent(original.id(), updated);
handler->removeEvent(original.id());
}
handler->clearAll();
}
void DatabaseHandlerBenchmark::addUpdateRemoveSingleEvent_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::addThousandEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
handler->clearAll();
events_.clear();
// Create events.
currentTime_ = QDateTime::currentDateTime();
for (int i=1; i<=1000; ++i){
Event e;
if (i%2 == 0){
// Even id = Static expired.
e = Event("name" + QString::number(i), currentTime_.addDays(-i).toString(Event::TIME_FORMAT),
Event::STATIC, i*1000, Event::INFINITE_REPEAT);
}
else {
// Odd id = Dynamic future.
e = Event("name" + QString::number(i), currentTime_.addDays(i).toString(Event::TIME_FORMAT),
Event::DYNAMIC, i*1000, Event::INFINITE_REPEAT);
}
events_.push_back(e);
}
QVERIFY(events_.size() == 1000);
// Add events
QBENCHMARK_ONCE {
for (unsigned i=0; i<events_.size(); ++i) {
handler->addEvent(&(events_[i]));
}
}
// Check that events were added
for (Event e : events_){
QVERIFY(e.id() != Event::UNASSIGNED_ID);
}
}
void DatabaseHandlerBenchmark::addThousandEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::updateThousandEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
// Create updated events.
std::vector<Event> updated;
for (Event e : events_){
Event u;
if (e.id() % 2 == 0){
u = Event(e.name()+"_u",
QDateTime::fromString(e.timestamp(), Event::TIME_FORMAT).addDays(-1).toString(Event::TIME_FORMAT),
Event::DYNAMIC, e.interval()+1000, e.repeats()+1);
}
else {
u = Event(e.name()+"_u",
QDateTime::fromString(e.timestamp(), Event::TIME_FORMAT).addDays(1).toString(Event::TIME_FORMAT),
Event::STATIC, e.interval()+1000, e.repeats()+1);
}
updated.push_back(u);
}
QVERIFY(updated.size() == 1000);
// Update events
QBENCHMARK_ONCE {
for (unsigned i=0; i<events_.size(); ++i){
QVERIFY(handler->updateEvent(events_[i].id(), updated[i]));
}
}
}
void DatabaseHandlerBenchmark::updateThousandEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::getThousandEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
// Update events_ -container.
QBENCHMARK_ONCE {
for (unsigned i=0; i<events_.size(); ++i){
events_[i] = handler->getEvent(events_[i].id());
}
}
// Verify that all events are right.
for (Event e : events_) {
QVERIFY(e.id() != Event::UNASSIGNED_ID);
}
}
void DatabaseHandlerBenchmark::getThousandEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::get500ExpiredEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
// Get expired
std::vector<Event> expired;
QString timeStr = currentTime_.toString(Event::TIME_FORMAT);
QBENCHMARK_ONCE{
expired = handler->checkOccured(timeStr);
}
// Check that expired events are right.
QCOMPARE(expired.size(), std::vector<Event>::size_type(500));
for (Event e : expired){
QVERIFY(e.id() != Event::UNASSIGNED_ID);
QVERIFY(e.timestamp() < currentTime_.toString(Event::TIME_FORMAT));
Event original = events_[e.id()-1];
QCOMPARE(e.id(), original.id());
QCOMPARE(e.name(), original.name());
QCOMPARE(e.timestamp(), original.timestamp());
QCOMPARE(e.type(), original.type());
QCOMPARE(e.interval(), original.interval());
QCOMPARE(e.repeats(), original.repeats());
}
}
void DatabaseHandlerBenchmark::get500ExpiredEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::oneNextEventsFromThousandEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
QDateTime lastEventTime = QDateTime::fromString(handler->getEvent(999).timestamp(), Event::TIME_FORMAT);
Event e("name1001", lastEventTime.addDays(1).toString(Event::TIME_FORMAT),
Event::STATIC, 0, 0);
handler->addEvent(&e);
QString lastEventTimeStr = lastEventTime.toString(Event::TIME_FORMAT);
QBENCHMARK {
QCOMPARE(handler->nextEvents(lastEventTimeStr, 1).size(),
std::vector<Event>::size_type(1));
}
}
void DatabaseHandlerBenchmark::oneNextEventsFromThousandEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::thousandNextEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
QDateTime firstEventTime = QDateTime::fromString(handler->getEvent(1000).timestamp(), Event::TIME_FORMAT);
Event e("name1002", firstEventTime.addDays(1).toString(Event::TIME_FORMAT),
Event::STATIC, 0, 0);
handler->addEvent(&e);
QString firstEventTimeStr = firstEventTime.toString(Event::TIME_FORMAT);
QBENCHMARK {
QCOMPARE(handler->nextEvents(firstEventTimeStr, 1000).size(),
std::vector<Event>::size_type(1000));
}
}
void DatabaseHandlerBenchmark::thousandNextEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::clear500DynamicEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
QBENCHMARK_ONCE {
QVERIFY(handler->clearDynamic());
}
// Verify that dynamic events were removed
for (Event e : events_) {
if (e.type() == Event::DYNAMIC){
QCOMPARE(handler->getEvent(e.id()).id(), Event::UNASSIGNED_ID);
}
else {
QCOMPARE(handler->getEvent(e.id()).id(), e.id());
}
}
}
void DatabaseHandlerBenchmark::clear500DynamicEvents_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::clear500Events()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
QBENCHMARK_ONCE {
QVERIFY(handler->clearAll());
}
// Verify that all events are removed
for (Event e : events_) {
QCOMPARE(handler->getEvent(e.id()).id(), Event::UNASSIGNED_ID);
}
}
void DatabaseHandlerBenchmark::clear500Events_data()
{
constructorBenchmark_data();
}
void DatabaseHandlerBenchmark::removeThousandEvents()
{
QFETCH(QString, dbType);
QFETCH(QString, dbName);
QFETCH(QString, tableName);
QFETCH(QString, dbHost);
QFETCH(QString, userName);
QFETCH(QString, password);
QVERIFY(events_.size() == 1000);
using namespace EventTimerNS;
std::shared_ptr<DatabaseHandler> handler =
this->initDB(dbType, dbName, tableName, dbHost, userName, password);
// Re-populate database.
for (unsigned i=0; i<events_.size(); ++i){
QVERIFY(handler->getEvent(events_[i].id()).id() == Event::UNASSIGNED_ID);
Event e = events_[i].copy();
QVERIFY(handler->addEvent(&e) != Event::UNASSIGNED_ID);
QCOMPARE(e.id(), events_[i].id());
}
QBENCHMARK_ONCE {
for (Event e : events_){
QVERIFY(handler->removeEvent(e.id()));
}
}
}
void DatabaseHandlerBenchmark::removeThousandEvents_data()
{
constructorBenchmark_data();
}
std::shared_ptr<EventTimerNS::DatabaseHandler>
DatabaseHandlerBenchmark::initDB(QString dbType, QString dbName, QString tableName, QString dbHost, QString userName, QString password)
{
EventTimerNS::DatabaseHandler::DbSetup setup;
setup.dbType = dbType;
setup.dbName = dbName;
setup.tableName = tableName;
setup.dbHostName = dbHost;
setup.userName = userName;
setup.password = password;
std::shared_ptr<EventTimerNS::DatabaseHandler> h(new EventTimerNS::DatabaseHandler(setup));
return h;
}
QTEST_APPLESS_MAIN(DatabaseHandlerBenchmark)
#include "tst_databasehandlerbenchmark.moc"
| [
"perttu.paarlahti@gmail.com"
] | perttu.paarlahti@gmail.com |
3556671759030f8191e6e5e625118066e268aaa2 | 057b656e6e9f2b9ccaba78bfb62b8e3b21585b30 | /congig.cpp | 78ce660b68183f8938e6554c20497776b07d4cef | [
"MIT"
] | permissive | VegetablesMaster/qt_serial | fc7ebf9afe27f079e229b72317e965afc8796d8c | f0cd97fa3496ec7a2b0408d3f19d0ae2999927db | refs/heads/master | 2020-05-19T12:51:23.903501 | 2019-08-08T05:43:12 | 2019-08-08T05:43:12 | 185,023,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | cpp | #include "congig.h"
#include "ui_congig.h"
Congig::Congig(QWidget *parent) :
QDialog(parent),
ui(new Ui::Congig)
{
ui->setupUi(this);
}
Congig::~Congig()
{
delete ui;
}
| [
"42300161+VegetablesMaster@users.noreply.github.com"
] | 42300161+VegetablesMaster@users.noreply.github.com |
dea318563c5608efaae6c529e5b13e2097ef6160 | ca49e7235d40fa2acb63622a71a1339c85f6e5ea | /Karlos's code samples/Testing D3D11/Testing D3D11/ParticleSystem.h | e509c83cd8774786db8d467f544b215e154b1b86 | [] | no_license | xfac11/LitetSpel | c894f6075a1f64060b8eb2c037ce63e31b5acbfe | b14515cc8131f5fc0bb94f7b0b7f6d1a928568c5 | refs/heads/master | 2020-05-03T23:26:29.792671 | 2019-08-17T17:13:46 | 2019-08-17T17:13:46 | 178,865,742 | 4 | 2 | null | 2019-04-01T14:09:49 | 2019-04-01T13:09:10 | null | UTF-8 | C++ | false | false | 2,574 | h | #ifndef PARTICLESYSTEM
#define PARTICLESYSTEM
#include <d3d11.h>
#include <directxmath.h>
#include <string>
#include <vector>
#include "Texture.h"
#include "Vertex3D.h"
//#include "colorShader.h"
#include "DeferedShader.h"
class ParticleSystem
{
private:
struct ParticleType
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 rgb;
float velocity;
bool active;
};
//struct VertexType
//{
// DirectX::XMFLOAT3 position;
// DirectX::XMFLOAT2 texture;
// DirectX::XMFLOAT4 color;
//};
DirectX::XMFLOAT4X4 world;
DirectX::XMFLOAT4X4 Rotation;
DirectX::XMFLOAT4X4 Scale;
DirectX::XMFLOAT4X4 Translation;
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 particleDeviation;
float particleVelocity;
float particleVelocityVariation;
float particleSize;
float particlesPerSecond;
int maxParticles;
int currentParticleCount;
float accumulatedTime;
Texture theTexture;
Texture normal;
ParticleType* particleList;
int vertexCount;
int indexCount;
//Vertex3D* vertices;
std::vector<Vertex3D> body;
ID3D11Buffer *vertexBuffer;
ID3D11Buffer *indexBuffer;
ID3D11SamplerState* SamplerState;
bool LoadTexture(ID3D11Device*& device, ID3D11DeviceContext*& deviceContext, std::string filename, std::string normalFileName);
bool InitializeParticleSystem();
bool InitializeBuffers(ID3D11Device* device);
void EmitParticles(float frameTime);
void UpdateParticles(float frameTime);
void KillParticles();
bool UpdateBuffers(ID3D11DeviceContext* deviceContext);
void calculateModelVectors(); //NORMAL MAPS
void calculateTangentBinormal(NM_Vertex vertex1, NM_Vertex vertex2, NM_Vertex vertex3, DirectX::XMFLOAT3& tangent, DirectX::XMFLOAT3& binormal, DirectX::XMFLOAT3& normal);
void calculateNormal(DirectX::XMFLOAT3 tangent, DirectX::XMFLOAT3 binormal, DirectX::XMFLOAT3 & normal); //NORMAL MAPS
public:
ParticleSystem();
~ParticleSystem();
bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, std::string textureName, std::string normalFileName);
void Shutdown();
bool Frame(float frameTime, ID3D11DeviceContext* deviceContext);
//void Render(ColorShader & shader, ID3D11DeviceContext* deviceContext);
void draw(DeferedShader & shader, ID3D11DeviceContext* deviceContext);
//int GetIndexCount();
void setWorld();
DirectX::XMFLOAT4X4 getWorld();
void billboard( DirectX::XMFLOAT3 camPos);
void setPosition(float x, float y, float z );
void setSampler(ID3D11Device *& gDevice);
};
#endif // !PARTICLESYSTEM
| [
"noreply@github.com"
] | xfac11.noreply@github.com |
3a4e9d49295fa96770a9b88b9f7880800cb2d365 | b9b50107cae005e227eb4fbeb4831b3a63a8f5c4 | /src/physics/physics_generic_constraint.inl | 562b1dcd7ace0d72c6d0a027da931971a97f13cc | [
"MIT"
] | permissive | Shtille/scythe | 1d043a8fdd27442e97bfcea5c2055a69b8b579be | b5ddafa3a25d78af34cb6ff00f433988789023d9 | refs/heads/master | 2022-10-22T08:33:31.669363 | 2022-10-05T12:04:24 | 2022-10-05T12:04:24 | 145,037,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,307 | inl | #include "physics_generic_constraint.h"
#include "common/sc_assert.h"
namespace scythe {
inline const Quaternion& PhysicsGenericConstraint::GetRotationOffsetA() const
{
if (!rotation_offset_a_)
rotation_offset_a_ = new Quaternion();
SC_ASSERT(constraint_);
btQuaternion ro = static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetA().getRotation();
rotation_offset_a_->Set(ro.x(), ro.y(), ro.z(), ro.w());
return *rotation_offset_a_;
}
inline const Quaternion& PhysicsGenericConstraint::GetRotationOffsetB() const
{
if (!rotation_offset_b_)
rotation_offset_b_ = new Quaternion();
SC_ASSERT(constraint_);
btQuaternion ro = static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetB().getRotation();
rotation_offset_b_->Set(ro.x(), ro.y(), ro.z(), ro.w());
return *rotation_offset_b_;
}
inline const Vector3& PhysicsGenericConstraint::GetTranslationOffsetA() const
{
if (!translation_offset_a_)
translation_offset_a_ = new Vector3();
SC_ASSERT(constraint_);
btVector3 to = static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetA().getOrigin();
translation_offset_a_->Set(to.x(), to.y(), to.z());
return *translation_offset_a_;
}
inline const Vector3& PhysicsGenericConstraint::GetTranslationOffsetB() const
{
if (!translation_offset_b_)
translation_offset_b_ = new Vector3();
SC_ASSERT(constraint_);
btVector3 to = static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetB().getOrigin();
translation_offset_b_->Set(to.x(), to.y(), to.z());
return *translation_offset_b_;
}
inline void PhysicsGenericConstraint::SetAngularLowerLimit(const Vector3& limits)
{
SC_ASSERT(constraint_);
((btGeneric6DofConstraint*)constraint_)->setAngularLowerLimit(BV(limits));
}
inline void PhysicsGenericConstraint::SetAngularUpperLimit(const Vector3& limits)
{
SC_ASSERT(constraint_);
((btGeneric6DofConstraint*)constraint_)->setAngularUpperLimit(BV(limits));
}
inline void PhysicsGenericConstraint::SetLinearLowerLimit(const Vector3& limits)
{
SC_ASSERT(constraint_);
((btGeneric6DofConstraint*)constraint_)->setLinearLowerLimit(BV(limits));
}
inline void PhysicsGenericConstraint::SetLinearUpperLimit(const Vector3& limits)
{
SC_ASSERT(constraint_);
((btGeneric6DofConstraint*)constraint_)->setLinearUpperLimit(BV(limits));
}
inline void PhysicsGenericConstraint::SetRotationOffsetA(const Quaternion& rotationOffset)
{
SC_ASSERT(constraint_);
static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetA().setRotation(BQ(rotationOffset));
}
inline void PhysicsGenericConstraint::SetRotationOffsetB(const Quaternion& rotationOffset)
{
SC_ASSERT(constraint_);
static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetB().setRotation(BQ(rotationOffset));
}
inline void PhysicsGenericConstraint::SetTranslationOffsetA(const Vector3& translationOffset)
{
SC_ASSERT(constraint_);
static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetA().setOrigin(BV(translationOffset));
}
inline void PhysicsGenericConstraint::SetTranslationOffsetB(const Vector3& translationOffset)
{
SC_ASSERT(constraint_);
static_cast<btGeneric6DofConstraint*>(constraint_)->getFrameOffsetB().setOrigin(BV(translationOffset));
}
} // namespace scythe | [
"v.shtille@gmail.com"
] | v.shtille@gmail.com |
9732086ea91c2e5d107e1ee9e6e125af3418c884 | c3323e08d8dd5fad16ae2e5ca5e1e032d6462592 | /src/main.cpp | 11763ddd818c469da84c258945772a728116252b | [] | no_license | alexicon3000/MaterialsIntensity | bca4d089e211a5190e5c984dddeb6968a1d5ecfd | a7dd8b418f7bf89159b6531268aedd0858bd295c | refs/heads/master | 2016-09-06T03:45:19.672009 | 2014-04-26T21:37:44 | 2014-04-26T21:37:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | #include "ofMain.h"
#include "testApp.h"
//========================================================================
int main( ){
ofSetupOpenGL(1024,768, OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp( new testApp());
} | [
"alex.number2@gmail.com"
] | alex.number2@gmail.com |
dc02d31d3be2cb53c5f18e1d99ac022e09eaac07 | f5c3f2685798b2f6d49984364676700d7f789631 | /source_voxel_absorbed_dose/include/DetectorConstruction.hh | 42363bf9ab340d4b98c87a9683f453afeed09e5b | [] | no_license | llekiMnitsuJ/geant_voxel_s_values | ae4752245d26fc246ffadefac04e572035a0187d | 6e8fa7818be3761cd2f9870e64fe20311469daa8 | refs/heads/master | 2021-01-23T02:28:53.129676 | 2015-02-10T22:00:51 | 2015-02-10T22:00:51 | 30,207,852 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,361 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id$
//
/// \file VoxelSValuesDetectorConstruction.hh
/// \brief Definition of the VoxelSValuesDetectorConstruction class
#ifndef VoxelSValuesDetectorConstruction_h
#define VoxelSValuesDetectorConstruction_h 1
#include "G4VUserDetectorConstruction.hh"
#include "globals.hh"
class G4VPhysicalVolume;
/// Detector construction class to define materials and geometry.
class VoxelSValuesDetectorConstruction : public G4VUserDetectorConstruction
{
public:
VoxelSValuesDetectorConstruction();
virtual ~VoxelSValuesDetectorConstruction();
public:
virtual G4VPhysicalVolume* Construct();
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
| [
"justin.mikell@gmail.com"
] | justin.mikell@gmail.com |
2f4c0ea9c87414ca5048baf632be8a9982c0f74f | 8f2843049463d24888d9a4532b1fd5d283b131ad | /skia/third_party/externals/angle2/include/platform/FeaturesGL.h | b3c760e600d98287e0d6e89b87359205010c6f88 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Libpng",
"FTL",
"ICU",
"BSD-3-Clause",
"IJG",
"Zlib",
"NAIST-2003",
"MIT-Modern-Variant",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause"
] | permissive | openharmony/third_party_flutter | 90a413f139848ce36a6af11233f1cee101bdb1c1 | 3282d03b17ac498e90d993761296a53a4f89c546 | refs/heads/master | 2023-08-30T17:42:32.034443 | 2021-10-21T11:36:39 | 2021-10-21T11:36:39 | 400,092,174 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 20,079 | h | //
// Copyright 2015 The ANGLE 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.
//
// FeaturesGL.h: Features and workarounds for GL driver bugs and other issues.
#ifndef ANGLE_PLATFORM_FEATURESGL_H_
#define ANGLE_PLATFORM_FEATURESGL_H_
#include "platform/Feature.h"
namespace angle
{
struct FeaturesGL : FeatureSetBase
{
FeaturesGL();
~FeaturesGL();
// When writing a float to a normalized integer framebuffer, desktop OpenGL is allowed to write
// one of the two closest normalized integer representations (although round to nearest is
// preferred) (see section 2.3.5.2 of the GL 4.5 core specification). OpenGL ES requires that
// round-to-nearest is used (see "Conversion from Floating-Point to Framebuffer Fixed-Point" in
// section 2.1.2 of the OpenGL ES 2.0.25 spec). This issue only shows up on Intel and AMD
// drivers on framebuffer formats that have 1-bit alpha, work around this by using higher
// precision formats instead.
Feature avoid1BitAlphaTextureFormats = {
"avoid_1_bit_alpha_texture_formats", FeatureCategory::OpenGLWorkarounds,
"Issue on Intel and AMD drivers with 1-bit alpha framebuffer formats", &members};
// On some older Intel drivers, GL_RGBA4 is not color renderable, glCheckFramebufferStatus
// returns GL_FRAMEBUFFER_UNSUPPORTED. Work around this by using a known color-renderable
// format.
Feature rgba4IsNotSupportedForColorRendering = {
"rgba4_is_not_supported_for_color_rendering", FeatureCategory::OpenGLWorkarounds,
"Issue on older Intel drivers, GL_RGBA4 is not color renderable", &members};
// When clearing a framebuffer on Intel or AMD drivers, when GL_FRAMEBUFFER_SRGB is enabled, the
// driver clears to the linearized clear color despite the framebuffer not supporting SRGB
// blending. It only seems to do this when the framebuffer has only linear attachments, mixed
// attachments appear to get the correct clear color.
Feature doesSRGBClearsOnLinearFramebufferAttachments = {
"does_srgb_clears_on_linear_framebuffer_attachments", FeatureCategory::OpenGLWorkarounds,
"Issue clearing framebuffers with linear attachments on Intel or AMD "
"drivers when GL_FRAMEBUFFER_SRGB is enabled",
&members};
// On Mac some GLSL constructs involving do-while loops cause GPU hangs, such as the following:
// int i = 1;
// do {
// i --;
// continue;
// } while (i > 0)
// Work around this by rewriting the do-while to use another GLSL construct (block + while)
Feature doWhileGLSLCausesGPUHang = {
"do_while_glsl_causes_gpu_hang", FeatureCategory::OpenGLWorkarounds,
"On Mac, some GLSL constructs involving do-while loops cause GPU hangs", &members};
// Calling glFinish doesn't cause all queries to report that the result is available on some
// (NVIDIA) drivers. It was found that enabling GL_DEBUG_OUTPUT_SYNCHRONOUS before the finish
// causes it to fully finish.
Feature finishDoesNotCauseQueriesToBeAvailable = {
"finish_does_not_cause_queries_to_be_available", FeatureCategory::OpenGLWorkarounds,
"On some NVIDIA drivers, glFinish doesn't cause all queries to report available result",
&members};
// Always call useProgram after a successful link to avoid a driver bug.
// This workaround is meant to reproduce the use_current_program_after_successful_link
// workaround in Chromium (http://crbug.com/110263). It has been shown that this workaround is
// not necessary for MacOSX 10.9 and higher (http://crrev.com/39eb535b).
Feature alwaysCallUseProgramAfterLink = {
"always_call_use_program_after_link", FeatureCategory::OpenGLWorkarounds,
"Always call useProgram after a successful link to avoid a driver bug", &members};
// In the case of unpacking from a pixel unpack buffer, unpack overlapping rows row by row.
Feature unpackOverlappingRowsSeparatelyUnpackBuffer = {
"unpack_overlapping_rows_separately_unpack_buffer", FeatureCategory::OpenGLWorkarounds,
"In the case of unpacking from a pixel unpack buffer, unpack overlapping rows row by row",
&members};
// In the case of packing to a pixel pack buffer, pack overlapping rows row by row.
Feature packOverlappingRowsSeparatelyPackBuffer = {
"pack_overlapping_rows_separately_pack_buffer", FeatureCategory::OpenGLWorkarounds,
"In the case of packing to a pixel pack buffer, pack overlapping rows row by row",
&members};
// During initialization, assign the current vertex attributes to the spec-mandated defaults.
Feature initializeCurrentVertexAttributes = {
"initialize_current_vertex_attributes", FeatureCategory::OpenGLWorkarounds,
"During initialization, assign the current vertex attributes to the spec-mandated defaults",
&members};
// abs(i) where i is an integer returns unexpected result on Intel Mac.
// Emulate abs(i) with i * sign(i).
Feature emulateAbsIntFunction = {
"emulate_abs_int_function", FeatureCategory::OpenGLWorkarounds,
"On Intel Mac, abs(i) where i is an integer returns unexpected result", &members};
// On Intel Mac, calculation of loop conditions in for and while loop has bug.
// Add "&& true" to the end of the condition expression to work around the bug.
Feature addAndTrueToLoopCondition = {
"add_and_true_to_loop_condition", FeatureCategory::OpenGLWorkarounds,
"On Intel Mac, calculation of loop conditions in for and while loop has bug", &members};
// When uploading textures from an unpack buffer, some drivers count an extra row padding when
// checking if the pixel unpack buffer is big enough. Tracking bug: http://anglebug.com/1512
// For example considering the pixel buffer below where in memory, each row data (D) of the
// texture is followed by some unused data (the dots):
// +-------+--+
// |DDDDDDD|..|
// |DDDDDDD|..|
// |DDDDDDD|..|
// |DDDDDDD|..|
// +-------A--B
// The last pixel read will be A, but the driver will think it is B, causing it to generate an
// error when the pixel buffer is just big enough.
Feature unpackLastRowSeparatelyForPaddingInclusion = {
"unpack_last_row_separately_for_padding_inclusion", FeatureCategory::OpenGLWorkarounds,
"When uploading textures from an unpack buffer, some drivers count an extra row padding",
&members};
// Equivalent workaround when uploading data from a pixel pack buffer.
Feature packLastRowSeparatelyForPaddingInclusion = {
"pack_last_row_separately_for_padding_inclusion", FeatureCategory::OpenGLWorkarounds,
"When uploading textures from an pack buffer, some drivers count an extra row padding",
&members};
// On some Intel drivers, using isnan() on highp float will get wrong answer. To work around
// this bug, we use an expression to emulate function isnan().
// Tracking bug: http://crbug.com/650547
Feature emulateIsnanFloat = {
"emulate_isnan_float", FeatureCategory::OpenGLWorkarounds,
"On some Intel drivers, using isnan() on highp float will get wrong answer", &members};
// On Mac with OpenGL version 4.1, unused std140 or shared uniform blocks will be
// treated as inactive which is not consistent with WebGL2.0 spec. Reference all members in a
// unused std140 or shared uniform block at the beginning of main to work around it.
// Also used on Linux AMD.
Feature useUnusedBlocksWithStandardOrSharedLayout = {
"use_unused_blocks_with_standard_or_shared_layout", FeatureCategory::OpenGLWorkarounds,
"On Mac with OpenGL version 4.1 and Linux AMD, unused std140 or shared uniform blocks "
"will be treated as inactive",
&members};
// This flag is used to fix spec difference between GLSL 4.1 or lower and ESSL3.
Feature removeInvariantAndCentroidForESSL3 = {
"remove_invarient_and_centroid_for_essl3", FeatureCategory::OpenGLWorkarounds,
"Fix spec difference between GLSL 4.1 or lower and ESSL3", &members};
// On Intel Mac OSX 10.11 driver, using "-float" will get wrong answer. Use "0.0 - float" to
// replace "-float".
// Tracking bug: http://crbug.com/308366
Feature rewriteFloatUnaryMinusOperator = {
"rewrite_float_unary_minus_operator", FeatureCategory::OpenGLWorkarounds,
"On Intel Mac OSX 10.11 driver, using '-<float>' will get wrong answer", &members,
"http://crbug.com/308366"};
// On NVIDIA drivers, atan(y, x) may return a wrong answer.
// Tracking bug: http://crbug.com/672380
Feature emulateAtan2Float = {"emulate_atan_2_float", FeatureCategory::OpenGLWorkarounds,
"On NVIDIA drivers, atan(y, x) may return a wrong answer",
&members, "http://crbug.com/672380"};
// Some drivers seem to forget about UBO bindings when using program binaries. Work around
// this by re-applying the bindings after the program binary is loaded or saved.
// This only seems to affect AMD OpenGL drivers, and some Android devices.
// http://anglebug.com/1637
Feature reapplyUBOBindingsAfterUsingBinaryProgram = {
"reapply_ubo_bindings_after_using_binary_program", FeatureCategory::OpenGLWorkarounds,
"Some AMD OpenGL drivers and Android devices forget about UBO bindings "
"when using program binaries",
&members, "http://anglebug.com/1637"};
// Some OpenGL drivers return 0 when we query MAX_VERTEX_ATTRIB_STRIDE in an OpenGL 4.4 or
// higher context.
// This only seems to affect AMD OpenGL drivers.
// Tracking bug: http://anglebug.com/1936
Feature emulateMaxVertexAttribStride = {
"emulate_max_vertex_attrib_stride", FeatureCategory::OpenGLWorkarounds,
"Some AMD OpenGL >= 4.4 drivers return 0 when MAX_VERTEX_ATTRIB_STRIED queried", &members,
"http://anglebug.com/1936"};
// Initializing uninitialized locals caused odd behavior on Mac in a few WebGL 2 tests.
// Tracking bug: http://anglebug/2041
Feature dontInitializeUninitializedLocals = {
"dont_initialize_uninitialized_locals", FeatureCategory::OpenGLWorkarounds,
"On Mac initializing uninitialized locals caused odd behavior in a few WebGL 2 tests",
&members, "http://anglebug.com/2041"};
// On some NVIDIA drivers the point size range reported from the API is inconsistent with the
// actual behavior. Clamp the point size to the value from the API to fix this.
Feature clampPointSize = {
"clamp_point_size", FeatureCategory::OpenGLWorkarounds,
"On some NVIDIA drivers the point size range reported from the API is "
"inconsistent with the actual behavior",
&members};
// On some NVIDIA drivers certain types of GLSL arithmetic ops mixing vectors and scalars may be
// executed incorrectly. Change them in the shader translator. Tracking bug:
// http://crbug.com/772651
Feature rewriteVectorScalarArithmetic = {
"rewrite_vector_scalar_arithmetic", FeatureCategory::OpenGLWorkarounds,
"On some NVIDIA drivers certain types of GLSL arithmetic ops mixing "
"vectors and scalars may be executed incorrectly",
&members, "http://crbug.com/772651"};
// On some Android devices for loops used to initialize variables hit native GLSL compiler bugs.
Feature dontUseLoopsToInitializeVariables = {
"dont_use_loops_to_initialize_variables", FeatureCategory::OpenGLWorkarounds,
"On some Android devices for loops used to initialize variables hit "
"native GLSL compiler bugs",
&members};
// On some NVIDIA drivers gl_FragDepth is not clamped correctly when rendering to a floating
// point depth buffer. Clamp it in the translated shader to fix this.
Feature clampFragDepth = {"clamp_frag_depth", FeatureCategory::OpenGLWorkarounds,
"On some NVIDIA drivers gl_FragDepth is not clamped correctly when "
"rendering to a floating point depth buffer",
&members};
// On some NVIDIA drivers before version 397.31 repeated assignment to swizzled values inside a
// GLSL user-defined function have incorrect results. Rewrite this type of statements to fix
// this.
Feature rewriteRepeatedAssignToSwizzled = {
"rewrite_repeated_assign_to_swizzled", FeatureCategory::OpenGLWorkarounds,
"On some NVIDIA drivers < v397.31, repeated assignment to swizzled "
"values inside a GLSL user-defined function have incorrect results",
&members};
// On some AMD and Intel GL drivers ARB_blend_func_extended does not pass the tests.
// It might be possible to work around the Intel bug by rewriting *FragData to *FragColor
// instead of disabling the functionality entirely. The AMD bug looked like incorrect blending,
// not sure if a workaround is feasible. http://anglebug.com/1085
Feature disableBlendFuncExtended = {
"disable_blend_func_extended", FeatureCategory::OpenGLWorkarounds,
"On some AMD and Intel GL drivers ARB_blend_func_extended does not pass the tests",
&members, "http://anglebug.com/1085"};
// Qualcomm drivers returns raw sRGB values instead of linearized values when calling
// glReadPixels on unsized sRGB texture formats. http://crbug.com/550292 and
// http://crbug.com/565179
Feature unsizedsRGBReadPixelsDoesntTransform = {
"unsized_srgb_read_pixels_doesnt_transform", FeatureCategory::OpenGLWorkarounds,
"Qualcomm drivers returns raw sRGB values instead of linearized values "
"when calling glReadPixels on unsized sRGB texture formats",
&members, "http://crbug.com/565179"};
// Older Qualcomm drivers generate errors when querying the number of bits in timer queries, ex:
// GetQueryivEXT(GL_TIME_ELAPSED, GL_QUERY_COUNTER_BITS). http://anglebug.com/3027
Feature queryCounterBitsGeneratesErrors = {
"query_counter_bits_generates_errors", FeatureCategory::OpenGLWorkarounds,
"Older Qualcomm drivers generate errors when querying the number of bits in timer queries",
&members, "http://anglebug.com/3027"};
// Re-linking a program in parallel is buggy on some Intel Windows OpenGL drivers and Android
// platforms.
// http://anglebug.com/3045
Feature dontRelinkProgramsInParallel = {
"dont_relink_programs_in_parallel", FeatureCategory::OpenGLWorkarounds,
"On some Intel Windows OpenGL drivers and Android, relinking a program "
"in parallel is buggy",
&members, "http://anglebug.com/3045"};
// Some tests have been seen to fail using worker contexts, this switch allows worker contexts
// to be disabled for some platforms. http://crbug.com/849576
Feature disableWorkerContexts = {"disable_worker_contexts", FeatureCategory::OpenGLWorkarounds,
"Some tests have been seen to fail using worker contexts",
&members, "http://crbug.com/849576"};
// Most Android devices fail to allocate a texture that is larger than 4096. Limit the caps
// instead of generating GL_OUT_OF_MEMORY errors. Also causes system to hang on some older
// intel mesa drivers on Linux.
Feature limitMaxTextureSizeTo4096 = {"max_texture_size_limit_4096",
FeatureCategory::OpenGLWorkarounds,
"Limit max texture size to 4096 to avoid frequent "
"out-of-memory errors on Android or Intel Linux",
&members, "http://crbug.com/927470"};
// Prevent excessive MSAA allocations on Android devices, various rendering bugs have been
// observed and they tend to be high DPI anyways. http://crbug.com/797243
Feature limitMaxMSAASamplesTo4 = {
"max_msaa_sample_count_4", FeatureCategory::OpenGLWorkarounds,
"Various rendering bugs have been observed when using higher MSAA counts on Android",
&members, "http://crbug.com/797243"};
// Prefer to do the robust resource init clear using a glClear. Calls to TexSubImage2D on large
// textures can take hundreds of milliseconds because of slow uploads on macOS. Do this only on
// macOS because clears are buggy on other drivers.
// https://crbug.com/848952 (slow uploads on macOS)
// https://crbug.com/883276 (buggy clears on Android)
Feature allowClearForRobustResourceInit = {
"allow_clear_for_robust_resource_init", FeatureCategory::OpenGLWorkarounds,
"Using glClear for robust resource initialization is buggy on some drivers and leads to "
"texture corruption. Default to data uploads except on MacOS where it is very slow.",
&members, "http://crbug.com/883276"};
// Some drivers automatically handle out-of-bounds uniform array access but others need manual
// clamping to satisfy the WebGL requirements.
Feature clampArrayAccess = {"clamp_array_access", FeatureCategory::OpenGLWorkarounds,
"Clamp uniform array access to avoid reading invalid memory.",
&members, "http://anglebug.com/2978"};
// Reset glTexImage2D base level to workaround pixel comparison failure above Mac OS 10.12.4 on
// Intel Mac.
Feature resetTexImage2DBaseLevel = {"reset_teximage2d_base_level",
FeatureCategory::OpenGLWorkarounds,
"Reset texture base level before calling glTexImage2D to "
"work around pixel comparison failure.",
&members, "https://crbug.com/705865"};
// glClearColor does not always work on Intel 6xxx Mac drivers when the clear color made up of
// all zeros and ones.
Feature clearToZeroOrOneBroken = {
"clear_to_zero_or_one_broken", FeatureCategory::OpenGLWorkarounds,
"Clears when the clear color is all zeros or ones do not work.", &members,
"https://crbug.com/710443"};
// Some older Linux Intel mesa drivers will hang the system when allocating large textures. Fix
// this by capping the max texture size.
Feature limitMax3dArrayTextureSizeTo1024 = {
"max_3d_array_texture_size_1024", FeatureCategory::OpenGLWorkarounds,
"Limit max 3d texture size and max array texture layers to 1024 to avoid system hang on "
"older Intel Linux",
&members, "http://crbug.com/927470"};
// BlitFramebuffer has issues on some platforms with large source/dest texture sizes. This
// workaround adjusts the destination rectangle source and dest rectangle to fit within maximum
// twice the size of the framebuffer.
Feature adjustSrcDstRegionBlitFramebuffer = {
"adjust_src_dst_region_for_blitframebuffer", FeatureCategory::OpenGLWorkarounds,
"Many platforms have issues with blitFramebuffer when the parameters are large.", &members,
"http://crbug.com/830046"};
// BlitFramebuffer has issues on Mac when the source bounds aren't enclosed by the framebuffer.
// This workaround clips the source region and adjust the dest region proportionally.
Feature clipSrcRegionBlitFramebuffer = {
"clip_src_region_for_blitframebuffer", FeatureCategory::OpenGLWorkarounds,
"Mac has issues with blitFramebuffer when the parameters don't match the framebuffer size.",
&members, "http://crbug.com/830046"};
};
inline FeaturesGL::FeaturesGL() = default;
inline FeaturesGL::~FeaturesGL() = default;
} // namespace angle
#endif // ANGLE_PLATFORM_FEATURESGL_H_
| [
"mamingshuai1@huawei.com"
] | mamingshuai1@huawei.com |
ed3f7a07c57a0f48f6f9607d069d0a5da07374b1 | 75b5bb557253a780bd2795d1ffaeaa767af1a790 | /Lab10.cpp | 42f0ab0f9dc4918895d81c5ccce2973c65252531 | [] | no_license | xilara/CS271 | 85d246959bb60989e5c08b711a25f0c5698e04f2 | 91206d85bed2aaf6dbbe14a00999f9c9f7a9b840 | refs/heads/master | 2020-05-18T23:36:40.200467 | 2019-05-03T07:39:42 | 2019-05-03T07:39:42 | 184,716,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,454 | cpp | // CS 271
// Program Name: Lab10.cpp
// Author: Xiana Lara
// Date: 04/25/19
// Purpose: test cases for Package and TwoDayPackages
#include <iostream>
#include <iomanip>
#include "Package.h"
#include "TwoDayPackage.h"
using namespace std;
int main()
{
//Package Test
Package p1("First Name", "1111 Street St", "Las Cruces",
"NM", "88011", "F. Last", "2222 Avenue Ave", "Las Cruces", "NM",
"88001", 9.00, 1.00);
// print with 2 decimal places
cout << fixed << setprecision(2);
// Sender info
cout << endl;
cout << "Package Test\n" << endl;
cout << "Sender: \n" << right << p1.getSenderName() << endl;
cout << p1.getSenderAddress() << endl;
cout << p1.getSenderCity() << " " << p1.getSenderState() << " " << p1.getSenderZIP() << endl;
cout << "\n";
// Recipient info
cout << "Recipient: \n" << p1.getRecipientName() << endl;
cout << p1.getRecipientAddress() << endl;
cout << p1.getRecipientCity() << " " << p1.getRecipientState() << " " << p1.getRecipientZIP() << endl;
cout << "Shipping Cost $ " << p1.calculateCost() << endl;
//TwoDayPackage Test
TwoDayPackage tdp2("Second Test", "1234 Avenue Ave.", "Las Cruces",
"NM", "88011", "Recipient Name", "5678 Street st", "Las Cruces", "NM",
"88001", 15.50, 1.99, 1.03);
// print with 2 decimal places
cout << fixed << setprecision(2);
// Sender info
cout << "\n2 Day Test\n" << endl;
cout << "Sender: \n" << tdp2.getSenderName() << endl;
cout << tdp2.getSenderAddress() << endl;
cout << tdp2.getSenderCity() << " " << tdp2.getSenderState() << " " << tdp2.getSenderZIP() << endl;
cout << endl;
// Recipient info
cout << "Recipient: \n" << tdp2.getRecipientName() << endl;
cout << tdp2.getRecipientAddress() << endl;
cout << tdp2.getRecipientCity() << " " << tdp2.getRecipientState() << " " << tdp2.getRecipientZIP() << endl;
cout << "Shipping Cost $ " << tdp2.calculateCost() << endl;
cout << endl;
// TwoDayPackage Test Invalid Exception with negative cost
cout << "Invalid Argument Test: " << endl;
TwoDayPackage tdp3("NM SU", "1111 University Ave.", "Las Cruces",
"NM", "88001", "Student Whatever", "2222 Street St", "San Digeo", "CA",
"92111", -2.50, 0.25, 5.11);
} // of main
| [
"noreply@github.com"
] | xilara.noreply@github.com |
abea0af09f7d1cacb9e1d92eef7ee342515188db | 64a2b5b7db60e105fdcb48804fd2c13d0fc6de7b | /editor/mainwindow_tab/weapon_edit.h | 30808ce6f7c190a834f2d11e35b1ad1d0756e5a0 | [] | no_license | gameblabla/rockbot | d6d821b10c63d30a1758c7eab4d7e1affccac23f | c912f9728802cd9b3f0ca50bbfc5610c8f85674f | refs/heads/master | 2022-11-02T16:21:55.157178 | 2019-04-23T21:12:01 | 2019-04-23T21:12:01 | 273,803,404 | 2 | 0 | null | 2020-06-20T23:56:13 | 2020-06-20T23:56:12 | null | UTF-8 | C++ | false | false | 729 | h | #ifndef WEAPON_EDIT_H
#define WEAPON_EDIT_H
#include <QWidget>
#include "../file/format.h"
namespace Ui {
class weapon_edit;
}
class weapon_edit : public QWidget
{
Q_OBJECT
public:
explicit weapon_edit(QWidget *parent = 0);
~weapon_edit();
void reload();
private:
void reload_weapon_list();
private slots:
void on_weapon_select_combo_currentIndexChanged(int index);
void on_weapon_name_textChanged(const QString &arg1);
void on_weapon_projectile_type_currentIndexChanged(int index);
void on_weapon_damage_valueChanged(int arg1);
void on_weapon_charged_projectile_type_currentIndexChanged(int index);
private:
Ui::weapon_edit *ui;
short _selected_weapon;
bool _loaded;
};
#endif // WEAPON_EDIT_H
| [
"protoman@upperland.net"
] | protoman@upperland.net |
5f58fdb8e20253f5b42a17c9bf958a3310ec3615 | 430e2e0d4e69badbc7965873576c5188c7a08f80 | /src/profiles/Profile.h | b51fbf9c234b1ab3aecfe61bddc59cfa8f80f3a9 | [] | no_license | IgorMamushin/NetDrawer | adc674c00894e38833285954c75dff0a4734e394 | d56d35ea9a4af6c1e435ee3b354546bca91169ec | refs/heads/master | 2023-06-21T22:51:23.513608 | 2021-07-22T17:13:43 | 2021-07-22T17:13:43 | 387,471,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | #pragma once
#include <chrono>
#include <iostream>
#include <string>
class LogDuration {
public:
explicit LogDuration(const std::string& msg = "");
~LogDuration();
private:
std::string message;
std::chrono::steady_clock::time_point start;
};
#define UNIQ_ID_IMPL(lineno) _a_local_var_##lineno
#define UNIQ_ID(lineno) UNIQ_ID_IMPL(lineno)
#define LOG_DURATION(message) \
LogDuration UNIQ_ID(__LINE__){message};
| [
"imamushin@1worldsync.com"
] | imamushin@1worldsync.com |
5f77c0a6ef0cbce3c5f3f5907ade81199e81d6fb | 53a4002d40fae3936428e9d074c72e1e5f88b549 | /process.cpp | 6ccc70bf4c5f4759e4ca919f29c6116c9d8a2abf | [] | no_license | weeChanc/system | 1a1061b2debe2373c7affee579fd71ceb4ed0ea5 | 5fd823131ce93602cc7ba83c402d580c81283fa4 | refs/heads/master | 2020-04-11T13:05:32.681159 | 2018-12-28T03:22:18 | 2018-12-28T03:22:18 | 161,803,786 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include <iostream>
#include <string>
#include<ctime>
#include <algorithm>
#include <vector>
#include <windows.h>
#include <stdio.h>
#include "process.h"
using namespace std;
int main() {
ProcessSelectStrategy* SHORT_FIRST = new Strategy_SF();
ProcessSelectStrategy* HIGHT_RESPONSE_FIRST = new Strategy_HR();
ProcessSelectStrategy* ROTATE = new Strategy_RR();
ProcessSelectStrategy* BANK_STRATEGY = new Strategy_BANK();
ProcessManager::showBank(5, BANK_STRATEGY);
// ProcessManager::show(5, ROTATE);
// ProcessManager::show(5, SHORT_FIRST);
getchar();
return 0;
}
| [
"214652773@qq.com"
] | 214652773@qq.com |
31dd96b1cca59fc6206efcab917ecc88e0c3b356 | 92378ed3d736cd24be135c7a035180fe67c707c7 | /p6top6t/p6top6t.cpp | 230b96ff3f2e921d91035438f75f3c5f1f973bd4 | [] | no_license | eighttails/N6XBasicChecker | 7e25740bbe0ac3b6d44ad96bebaa1c22ce548fc7 | 094de269ba1837f4dbefad443106bcde15a37a4f | refs/heads/master | 2021-07-12T03:44:49.737201 | 2021-06-12T14:19:09 | 2021-06-12T14:19:09 | 42,002,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,598 | cpp | // ***************************************************
// P6toP6T Ver.2.3 *
// 2013.12.31 by Yumitaro *
// 2021.06.08 by eighttails *
// ***************************************************
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include "babelwrap.h"
#define VERSION 2.3
// P6T形式フォーマットVer.2
// 基本的には「ベタイメージ+フッタ+ベタイメージサイズ(4byte)」という構造
// フッタにはDATAブロック情報が含まれる。
// DATAブロックは無音部を区切りとして1と数える。
// BASICなど「ヘッダ+データ」という構造の場合,DATAブロックは2個となるが
// ID番号を同一にすることで関連付けて管理できる。
// ボーレートはとりあえず1200ボー固定
//
// [フッタ]
// header (2byte) : "P6"
// ver (1byte) : バージョン
// dbnum (1byte) : 含まれるDATAブロック数(255個まで)
// start (1byte) : オートスタートフラグ(0:無効 1:有効)
// basic (1byte) : BASICモード(PC-6001の場合は無意味)
// page (1byte) : ページ数
// askey (2byte) : オートスタートコマンド文字数
// ...コマンドがある場合はこの後にaskey分続く
// exhead (2byte) : 拡張情報サイズ(64KBまで)
// ...拡張情報がある場合はこの後にexhead分続く
//
// [DATAブロック]
// header (2byte) : "TI"
// id (1byte) : ID番号(DATAブロックを関連付ける)
// name (16byte) : データ名(15文字+'00H')
// baud (2byte) : ボーレート(600/1200)
// stime (2byte) : 無音部の時間(ms)
// ptime (2byte) : ぴー音の時間(ms)
// start (4byte) : ベタイメージ先頭からのオフセット
// size (4byte) : データサイズ
// DATAブロック情報構造体
typedef struct{
char header[3]; // 識別子 "TI"
uint8_t id; // ID番号
char name[16]; // データ名(15文字+'00H')
uint16_t baud; // ボーレート(600/1200)
uint16_t stime; // 無音部の時間(ms)
uint16_t ptime; // ぴー音の時間(ms)
uint32_t start; // ベタイメージ先頭からのオフセット
uint32_t size; // データサイズ
uint8_t *data; // データ領域へのポインタ(オンメモリで扱う場合)
} P6DATA;
// P6T情報構造体
typedef struct{
char header[3]; // 識別子 "P6"
uint8_t ver; // バージョン
uint8_t dbnum; // 含まれるDATAブロック数(255個まで)
uint8_t start; // オートスタートフラグ(0:無効 1:有効)
uint8_t basic; // BASICモード(PC-6001の場合は無意味)
uint8_t page; // ページ数
uint16_t askey; // オートスタートコマンドサイズ
uint16_t exhead; // 拡張情報サイズ(64KBまで)
char fname[260]; // P6T ファイル名
FILE *fp; // TAPE ファイルポインタ
uint8_t *exh; // 拡張情報格納領域へのポインタ
char *ask; // オートスタートコマンド格納領域へのポインタ
P6DATA *db; // DATAブロック情報へのポインタ
uint32_t beta; // ベタイメージサイズ
int mode; // OPENモード(TAPE_LOAD/TAPE_SAVE)
int dbsel; // 選択しているDATAブロック番号(0-254)
int seek; // 選択しているDATAブロックのシーク位置(データ領域先頭が0)
int swait; // 無音部の待ち回数
int pwait; // ぴー音の待ち回数
} P6CAS;
// テープの種類
const char *TapeType[] = {
"= QUIT =",
"ベタ",
"BASIC",
"I/Oモニタ",
"インテルHEX(MON)",
};
#define NumOfType 5
#define StdP 3400
#define IOP 3400
#define BAS 50
#define IOS 1000
#define StdBaud 1200
P6CAS *fout=NULL; // P6T情報ポインタ
P6DATA *fdb[255]; // DATAブロック情報ポインタ配列
FILE *infp = NULL; // 入力ファイルポインタ
uint32_t fsize = 0; // 入力ファイルのサイズ
uint8_t idnum = 0; // DATAブロックのID番号
FILE *inparam = stdin; // パラメータ入力元(デフォルトでは標準入力)
FILE *outparam = NULL; // パラメータ出力先
const char *paramfile = "p6tparams.txt"; // パラメータファイル名
// gets()代替関数
char* gets_f(char* s, int n, FILE *fp)
{
// バッファサイズが1に満たない場合はNULLを返す
if (n < 1) return NULL;
memset(s, 0, n);
// 1文字読み込み。EOFの場合はNULLを返す
int i = 0;
for(; i < n; i++) {
int ch = fgetc( fp );
// 自動入力の場合は標準出力に表示
if (inparam != stdin) putchar(ch);
if (ch == EOF || ch == '\n' || ch == '\0' ) {
break;
}
s[i] = ch;
}
// パラメータファイルに書き出し
if ( outparam ){
// 書き出す際は終端を改行にする
s[i] = '\n';
fwrite( s, i + 1, 1, outparam );
}
// 改行を終端記号に置換
s[i] = '\0';
return i > 0 ? s : NULL;
}
// getchar_f( inparam )代替関数
int getchar_f( FILE *fp )
{
int ch = fgetc( fp );
// 自動入力の場合は標準出力に表示
if (inparam != stdin) putchar(ch);
// パラメータファイルに書き出し
if ( ch != EOF && outparam ){
fputc( ch, outparam );
}
return ch;
}
// strcpy代替関数
// 1文字ずつコピーすることを保証するしてコピー元、コピー先が
// 重なる場合の未定義動作を防ぐ
char *strcpy_f(char *s1, const char *s2)
{
char *p = s1;
while( *s1++ = *s2++ );
return p;
}
// DATAブロック情報 領域確保 & 初期化
P6DATA *get_dbblock( P6CAS *ft )
{
if( !(fdb[ft->dbnum]=(P6DATA *)malloc( sizeof(P6DATA) )) ) exit( 1 );
memset( fdb[ft->dbnum], 0, sizeof(P6DATA) );
strncpy( fdb[ft->dbnum]->header, "TI", 2 );
return fdb[ft->dbnum++];
}
// データサイズ入力
// 空Enterの場合はmaxを返す
uint32_t input_datasize( uint32_t max )
{
uint32_t dsize=0;
char tmp[80]; // サイズ入力用バッファ
while( !dsize ){
if( gets_f( tmp, sizeof(tmp), inparam ) )
dsize = atol( tmp );
else
dsize = max;
if( !dsize ) printf_local("入力が正しくありません。\n> ");
}
return dsize;
}
// ベタ 読込み
void read_beta( P6CAS *ft, FILE *infp, FILE *outfp )
{
P6DATA *db;
uint32_t bsize=0;
int i;
// サイズ入力
printf_local( "サイズを入力して下さい。(全ての場合は何も入力せずにEnter)\n> " );
bsize = input_datasize( fsize - ftell( infp ) );
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// DATAブロック情報セット
db->id = idnum++; // ID番号
db->baud = StdBaud; // ボーレート
db->stime = StdP; // 無音部の時間(ms)
db->ptime = StdP; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = bsize; // データサイズ
// 実データセット
for( i=0; i<(int)bsize; i++ ) fputc( fgetc( infp ), outfp );
}
// BASIC 読込み
void read_basic( P6CAS *ft, FILE *infp, FILE *outfp )
{
P6DATA *db;
uint32_t bsize=0,fpnt;
int i,sum=0;
// *** まずはヘッダ部分 ***
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// ヘッダD3H読み飛ばし
while( fgetc( infp ) != 0xd3 ); // D3Hが見つかるまで空読み
while( fgetc( infp ) == 0xd3 ); // D3H以外が見つかるまで空読み
fseek( infp, -1, SEEK_CUR ); // 行き過ぎた分戻る
// DATAブロック情報セット
db->id = idnum; // ID番号
fread( db->name, 1, 6, infp ); // データ名(BASICのファイル名)
db->baud = StdBaud; // ボーレート
db->stime = StdP; // 無音部の時間(ms)
db->ptime = StdP; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = 16; // データサイズ
// 実データセット
for( i=0; i<10; i++ ) fputc( 0xd3, outfp ); // ヘッダD3H
fwrite( db->name, 6, 1, outfp ); // BASICのファイル名
// *** 次にデータ部分 ***
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// ブロックサイズを調べてデータ領域確保
fpnt = ftell( infp ); // 現在位置を保存
do{ // 00Hを10個検出するまで空読み
if( fgetc( infp ) == 0 ) sum++;
else sum = 0;
bsize++;
}while( sum < 10 );
fseek( infp, fpnt, SEEK_SET ); // 元の位置に戻る
// DATAブロック情報セット
db->id = idnum++; // ID番号
db->baud = StdBaud; // ボーレート
db->stime = 0; // 無音部の時間(ms)
db->ptime = BAS; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = bsize; // データサイズ
// db->size = bsize+2; // データサイズ(エンドマーク最後の2byteを含む)
// 実データセット
for( i=0; i<(int)bsize; i++ ) fputc( fgetc( infp ), outfp );
// エンドマークの00Hが残っている場合の処理
// if( fgetc( infp ) ) fseek( infp, -1, SEEK_CUR ); // 00Hでなければ戻る
// if( fgetc( infp ) ) fseek( infp, -1, SEEK_CUR ); // 00Hでなければ戻る
// fputc( 0, outfp ); // 00Hを出力
// fputc( 0, outfp ); // 00Hを出力
}
// I/Oモニタ形式 読込み
void read_iomon( P6CAS *ft, FILE *infp, FILE *outfp )
{
P6DATA *db;
uint32_t bsize=0;
int i;
// *** まずはヘッダ部分 ***
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// ヘッダ9CH読み飛ばし
while( fgetc( infp ) != 0x9c );
while( fgetc( infp ) != 0xaf );
// ヘッダAFH読み飛ばし
while( fgetc( infp ) == 0xaf );
fseek( infp, 1, SEEK_CUR );
bsize = ( getc(infp) | getc(infp)<<8 ) + 7; // データ部分の実データサイズ取得(ヘッダ9CH*6+1(?)を加算)
// DATAブロック情報セット
db->id = idnum; // ID番号
db->baud = StdBaud; // ボーレート
fgets( db->name, 3, infp ); // データ名(2文字のファイル名)
db->stime = StdP; // 無音部の時間(ms)
db->ptime = StdP; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = 17; // データサイズ
// 実データセット
for( i=0; i<6; i++ ) fputc( 0x9c, outfp ); // ヘッダ9CH
for( i=0; i<5; i++ ) fputc( 0xaf, outfp ); // ヘッダAFH
fseek( infp, -6, SEEK_CUR );
for( i=0; i<6; i++ ) fputc( fgetc( infp ), outfp ); // アドレス,サイズ,ファイル名
// *** 次にデータ部分 ***
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// DATAブロック情報セット
db->id = idnum++; // ID番号
db->baud = StdBaud; // ボーレート
db->stime = IOS; // 無音部の時間(ms)
db->ptime = IOP; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = bsize; // データサイズ
// 実データセット
for( i=0; i<(int)bsize; i++ ) fputc( fgetc( infp ), outfp );
}
// インテルHEX 読込み
void read_ihex( P6CAS *ft, FILE *infp, FILE *outfp )
{
P6DATA *db;
int i,sum=0;
uint32_t bsize=0,fpnt;
db = get_dbblock( ft ); // DATAブロック情報 領域確保 & 初期化
// ヘッダ9CH検出
while( fgetc( infp ) != 0x9c );
fseek( infp, -1, SEEK_CUR );
// ブロックサイズを調べる
fpnt = ftell( infp ); // 現在位置を保存
fseek( infp, 9, SEEK_CUR );
// 30Hを16個検出するまで空読み
do{
sum = 0;
for( i=0; i<16; i++ ){
if( fgetc( infp ) == 0x30 ) sum++;
else sum = 0;
}
if( sum==16 && (fgetc( infp )==0x1a) ) break;
else fseek( infp, 29, SEEK_CUR );
}while( 1 );
bsize = ftell( infp ) - fpnt;
fseek( infp, fpnt, SEEK_SET );
// DATAブロック情報セット
db->id = idnum++; // ID番号
db->baud = StdBaud; // ボーレート
db->stime = StdP; // 無音部の時間(ms)
db->ptime = StdP; // ぴー音の時間(ms)
db->start = ftell( outfp ); // ベタイメージ先頭からのオフセット
db->size = bsize; // データサイズ
// 実データセット
for( i=0; i<(int)bsize; i++ ) fputc( fgetc( infp ), outfp );
}
// P6T情報フッタ出力
void p6_footer( P6CAS *ft )
{
// "P6"
fputc( 'P', ft->fp );
fputc( '6', ft->fp );
// バージョン(2)
fputc( 2, ft->fp );
// 含まれるDATAブロック数
fputc( ft->dbnum, ft->fp );
// オートスタートフラグ(0:無効 1:有効)
fputc( ft->start, ft->fp );
// BASICモード(PC-6001の場合は無意味)
fputc( ft->basic, ft->fp );
// ページ数
fputc( ft->page, ft->fp );
// オートスタートコマンド文字数
fputc( ft->askey &0xff, ft->fp );
fputc( (ft->askey>>8)&0xff, ft->fp );
// オートスタートコマンド
if( ft->askey )
ft->ask[ft->askey-1] = 0x0d;
fwrite( ft->ask, ft->askey, 1, ft->fp );
// 拡張情報サイズ
fputc( ft->exhead &0xff, ft->fp );
fputc( (ft->exhead>>8)&0xff, ft->fp );
// 拡張情報
if( ft->exhead )
fwrite( ft->exh, ft->exhead, 1, ft->fp );
}
// DATAブロック情報出力
void db_info( P6DATA *db, FILE *fp )
{
// "TI"
fputc( 'T', fp );
fputc( 'I', fp );
// ID番号
fputc( db->id, fp );
// データ名
fwrite( db->name, 16, 1, fp );
// ボーレート
fputc( db->baud &0xff, fp );
fputc( (db->baud>>8)&0xff, fp );
// 無音部の時間
fputc( db->stime &0xff, fp );
fputc( (db->stime>>8)&0xff, fp );
// ぴー音の時間
fputc( db->ptime &0xff, fp );
fputc( (db->ptime>>8)&0xff, fp );
// ベタイメージ先頭からのオフセット
fputc( db->start &0xff, fp );
fputc( (db->start>>8) &0xff, fp );
fputc( (db->start>>16)&0xff, fp );
fputc( (db->start>>24)&0xff, fp );
// データサイズ
fputc( db->size &0xff, fp );
fputc( (db->size>>8) &0xff, fp );
fputc( (db->size>>16)&0xff, fp );
fputc( (db->size>>24)&0xff, fp );
printf_local( "ID番号 :%d\n", db->id );
printf_local( "データ名 :%s\n", db->name );
printf_local( "無音部の時間 :%d(%04X)\n", db->stime, db->stime );
printf_local( "ぴー音の時間 :%d(%04X)\n", db->ptime, db->ptime );
printf_local( "オフセット :%d(%08X)\n", db->start, db->start );
printf_local( "データサイズ :%d(%08X)\n", db->size, db->size );
}
int main( int argc, char **argv )
{
int i;
char *c;
uint8_t type; // テープの種類
uint32_t fpnt=0; // ファイルポインタ保存用
uint32_t totalsize=0; // ベタイメージのトータルサイズ
printf_local( "=== P6toP6T2 ===\n" );
po::options_description desc( "オプション", 200 );
desc.add_options()
( "help,h", "ヘルプを表示" )
( "version,v", "バージョンを表示" )
( "utf8,u", "出力をUTF-8でエンコード" )
( "store,s", "実行時の設定を保存" )
( "restore,r", "保存された設定で実行" )
;
po::options_description hidden( "不可視オプション" );
hidden.add_options()
( "input-file", po::value<std::vector<std::string> >(), "input file" )
;
// 無名のオプションはファイル名として処理される
po::positional_options_description p;
p.add( "input-file", -1 );
po::options_description cmdline_options;
cmdline_options.add( desc ).add( hidden );
po::variables_map vm;
// 構文エラー
bool argError = false;
try{
po::store( po::command_line_parser( argc, argv ).
options( cmdline_options ).positional( p ).run(), vm );
po::notify( vm );
} catch (...){
argError = true;
}
// 出力のエンコード設定
if ( vm.count( "utf8" ) ) {
utf8Output = true;
}
// バージョン情報
if ( vm.count( "version" ) ) {
std::cout << "p6top6t ver." << VERSION << std::endl
<< "Copyright 2012-2021 Yumitaro(@Yumitaro60), Tadahito Yao(@eighttails)" << std::endl
<< "http://eighttails.seesaa.net" << std::endl;
return 0;
}
// ヘルプオプションが指定、またはファイル名が指定されていない場合はヘルプを表示
if ( vm.count( "help" ) || !vm.count( "input-file" ) || argError ) {
std::cout << utf8_to_local( "Usage: p6top6t ファイル名 [オプション]" ) << std::endl;
std::stringstream s;
s << desc;
std::cout << utf8_to_local( s.str() );
return 0;
}
if ( vm.count( "store" ) ){
if ( vm.count( "restore" ) ){
printf_local( "--store と --restore オプションは同時に使用できません。\n" );
return -1;
}
outparam = fopen( paramfile, "w" );
if ( !outparam ) {
printf_local( "%s が作成できません。\n", paramfile );
return -1;
}
}
if ( vm.count( "restore" ) ){
inparam = fopen( paramfile, "r" );
if ( !inparam ) {
printf_local( "%s が見つかりません。\n", paramfile );
return -1;
}
}
std::vector<std::string> fileNames = vm["input-file"].as<std::vector<std::string> >();
if(fileNames.size() != 1){
printf_local( "ファイル名は1つのみ指定可能です。");
return -1;
}
std::string input_file = fileNames[0];
printf_local( "'%s'の変換を開始します。\n", input_file.c_str() );
// P6T情報 領域確保 & 初期化
if( !(fout=(P6CAS *)malloc( sizeof(P6CAS) ))) exit( 1 );
memset( fout, 0, sizeof(P6CAS) );
strncpy( fout->header, "P6", 2 );
// 出力ファイル名を設定
strcpy_f( fout->fname, input_file.c_str() );
strcpy_f( strrchr( fout->fname, '.' ), ".p6t" );
// DATAブロック情報ポインタ配列 初期化
for( i=0; i<255; i++ ) fdb[i] = NULL;
// オートスタート選択
do{
printf_local( "オートスタートを有効にしますか? (0:No 1:Yes)>" );
fout->start = getchar_f( inparam ) - '0';
getchar_f( inparam ); // Enter空読み
}while( fout->start > 1 );
if( fout->start ){
// BASICモード選択
do{
printf_local( "BASICモードを選んでください (1-6)>" );
fout->basic = getchar_f( inparam ) - '0';
getchar_f( inparam ); // Enter空読み
}while( fout->basic < 1 || fout->basic > 6 );
// ページ数選択
do{
printf_local( "ページ数を選んでください (1-4)>" );
fout->page = getchar_f( inparam ) - '0';
getchar_f( inparam ); // Enter空読み
}while( fout->page < 1 || fout->page > 4 );
// オートスタートコマンド入力
int asksize = sizeof(char)*512;
if( !(fout->ask=(char*)malloc( asksize )) ) exit( 1 ); // とりあえず512byteあれば十分か?
printf_local( "オートスタートコマンドを入力してください(改行は'\\n' LOAD終了待ちは'\\r' 末尾には不要)\n" );
printf_local( "'CLOAD\\rRUN' の場合は何も入力せずにEnter\n> " );
// 入力なければ"CLOAD RUN"
if( !gets_f( fout->ask, asksize, inparam ) ) strcpy_f( fout->ask, "CLOAD\\rRUN" );
// エスケープシーケンスの処理
do{
c = (char *)strchr( fout->ask, (int)'\\' );
if( c ){
switch( c[1] ){
case 'n': // 改行
c[0] = 0x0d;
strcpy_f( &c[1], &c[2] );
break;
case 'r': // テープリレー待ち
c[0] = 0x0a;
strcpy_f( &c[1], &c[2] );
break;
default:
printf_local( "!! '%c' 不正な制御文字です。", c[1] );
exit( 1 );
}
}
}while( c );
fout->askey = strlen( fout->ask ) + 1;
}
// 入力ファイルを開く
if( (infp=fopen(input_file.c_str(), "rb")) == NULL ){
fprintf_local( stderr, "p6top6t2: 入力ファイルが開けません '%s'\n", argv[1] );
exit( 1 );
}
// 入力ファイルサイズ取得
fseek( infp, 0, SEEK_END );
fsize = ftell( infp );
fseek( infp, 0, SEEK_SET );
// 出力ファイルを開く
if( (fout->fp=fopen( fout->fname, "wb")) == NULL ){
fprintf_local( stderr, "p6top6t2: 出力ファイルが開けません '%s'\n", fout->fname );
exit( 1 );
}
do{
printf_local("\n処理済 %d (/%d)\n\n", (int)fpnt, (int)fsize );
// テープの種類を選択
printf_local( "<< テープの種類を選んでください >>\n" );
for( i=0; i<NumOfType; i++ )
printf_local( "%d. %s\n", i, TapeType[i] );
type = getchar_f( inparam ) - '0';
getchar_f( inparam ); // Enter空読み
// データブロック出力
switch( type ){
case 0: // - QUIT -
fsize = 0;
break;
case 1: // BETA
read_beta( fout, infp, fout->fp );
break;
case 2: // BASIC
read_basic( fout, infp, fout->fp );
break;
case 3: // I/O
read_iomon( fout, infp, fout->fp );
break;
case 4: // インテルHEX
read_ihex( fout, infp, fout->fp );
break;
}
fpnt = ftell( infp );
}while( fpnt > 0 && fpnt < fsize );
fout->ver = 2; // P6T Ver.2
// P6T情報フッタ出力
p6_footer( fout );
// DATAブロック情報出力
for( i=0; i<fout->dbnum; i++ ){
printf_local( "<< Block No.%d >>\n", i );
db_info( fdb[i], fout->fp );
totalsize += fdb[i]->size;
}
// ベタイメージサイズ出力
fputc( totalsize &0xff, fout->fp );
fputc( (totalsize>>8) &0xff, fout->fp );
fputc( (totalsize>>16)&0xff, fout->fp );
fputc( (totalsize>>24)&0xff, fout->fp );
// 入力ファイルを閉じる
fclose( infp );
// 出力ファイルを閉じる
fclose( fout->fp );
// DATAブロック領域開放
for( i=0; i<fout->dbnum; i++ ) free( fdb[i] );
// P6T情報領域開放
free( fout->ask );
free( fout );
printf_local( "ファイルの変換が完了しました。\n" );
// パラメータファイルを閉じる
if ( inparam ) fclose( inparam );
if ( outparam ) fclose( outparam );
return 0;
}
| [
"eighttails@nifty.com"
] | eighttails@nifty.com |
56338857cbcb688692516ab293353d35ebc5490f | 0b2bb9df09731ccc8748b0b7bf66a7a427d4e416 | /src/compat/strnlen.cpp | c56709506324459ada68715a2bd770b2cfaef4c8 | [
"MIT"
] | permissive | tcilloni/cillocoin | aae0e5bbcb4808c489ac42d1db2725bfd4b42c5a | 1145e189b9f5f4fab414fc1751bf1fce189770c9 | refs/heads/master | 2022-06-09T23:58:47.924597 | 2019-05-03T15:25:48 | 2019-05-03T15:25:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | // Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/cillocoin-config.h>
#endif
#include <cstring>
#if HAVE_DECL_STRNLEN == 0
size_t strnlen( const char *start, size_t max_len)
{
const char *end = (const char *)memchr(start, '\0', max_len);
return end ? (size_t)(end - start) : max_len;
}
#endif // HAVE_DECL_STRNLEN
| [
"thomas.martin.cilloni@gmail.com"
] | thomas.martin.cilloni@gmail.com |
8ad8b904c380a8bbaca1716e2a1570068c6e8aa1 | 93333464cf0dbab7926519b529afd749cf6db77c | /HelloStorage/HelloStorage.cpp | 0263611c55080de1d563b834c7970831ad907969 | [] | no_license | RockNCode/blockchainTraining | f40c42e88888d74cd10116d95f8877c885154eef | 6f21fa21950ad7f7d09a7811ce638967810ddf13 | refs/heads/master | 2020-03-22T23:23:53.235277 | 2018-07-21T01:24:49 | 2018-07-21T01:24:49 | 140,807,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | #include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;
using std::string;
class HelloStorage : public eosio::contract {
public:
using contract::contract;
/// @abi action
void hello(const name username, const string& full_name) {
require_auth(username);
print("Hello, ",name(username));
addEntry(username,full_name);
}
private:
/// @abi table log i64
struct log {
uint64_t username;
string full_name;
uint64_t primary_key() const { return username; }
EOSLIB_SERIALIZE(log, (username)(full_name));
};
typedef multi_index<N(log), log> helloIndex;
void addEntry(const name username, const string& full_name) {
helloIndex entries(_self,_self);
auto iterator = entries.find(username);
eosio_assert(iterator == entries.end(), "Name already exists");
entries.emplace(username, [&](auto& logEntry)
{
logEntry.username = username;
logEntry.full_name = full_name;
});
}
};
EOSIO_ABI(HelloStorage,(hello));
| [
"alexgarcia2k@gmail.com"
] | alexgarcia2k@gmail.com |
ad778fdab104697b1ac4cf8f2d54c8968406cbfe | 7a49ef56fd4fd0dd961937f76155a520bd121dec | /searchAlgorithmsUsingClasses/LinearSearch.cpp | cec50ec7a63131dc79413c48c5139857425afe3d | [] | no_license | umairmustafa753/Algorithms | 503b089c6297c5805a7c11404f7cacc963d14f0b | cf41a5ee129835ddfd21addd9f7f8d1dfbcfc37c | refs/heads/master | 2022-03-19T11:12:04.810966 | 2019-11-29T14:00:30 | 2019-11-29T14:00:30 | 210,692,657 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include "LinearSearch.h"
LinearSearch::LinearSearch(){}
LinearSearch::~LinearSearch(){}
int LinearSearch::search( int array[], int sizeofArray, int key ){
//local variable.
int index = 0;
while( index < sizeofArray && array[index] != key ){
index++;
}
if( index > sizeofArray || array[ index ] != key ){
return -1;
}
return index;
}
| [
"umairhassaaan@gmail.com"
] | umairhassaaan@gmail.com |
961bc9f36ef5fd864afaf37a880bf3e63476eb81 | 7324879b19d76f9ea6984f876a9813653c08ec48 | /usage_example.cpp | 6b7976882b38cb8094a4881e266b0a0b745a3f08 | [] | no_license | koomisov/typelist | 8712d67a4b2e45f6e81b8369ec11c32850118417 | 90a65b6a0616d3c1e5e4536966a60756b3ff8f79 | refs/heads/master | 2020-09-22T10:08:30.050212 | 2019-12-01T13:10:30 | 2019-12-01T13:12:42 | 225,150,089 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include <iostream>
#include "lib/typelist.hpp"
template <typename T>
struct AddConst {
using type = const T;
};
int main() {
using list = lib::typelist<int, double, std::string>;
using list2 = lib::push_front_t<char, list>;
lib::nth_element_t<1, list2> var = 'c'; // char
lib::largest_type_t<list2> var2 = "its string";
std::cout << std::is_same_v<std::string, decltype(var2)> << std::endl;
using list3 = typename lib::reverse<list2>::type;
using list_accum = lib::accumulate_t<list, lib::push_front, lib::typelist<>>;
lib::nth_element_t<0, list_accum> s = "its string";
using pop_back_list = lib::pop_back_t<list2>;
lib::nth_element_t<2, pop_back_list> dd = 2.3; // double
using transformed_list = lib::transform_t<list, AddConst>;
std::cout << std::is_same_v<lib::nth_element_t<0, transformed_list>,
const int> << std::endl;
return 0;
}
| [
"you@example.com"
] | you@example.com |
4d5725d01fa6ce69b2dbfdd906d7a3346fc310c0 | 331cd47ae1d930df60cf6a5513c0a7d525b45a8c | /Source/Building_Escape/OpenDoor.cpp | 82417bc0c533202042d13b6b2944fc048411c9d9 | [] | no_license | AlanWisny/Building_Escape | e8999d90e11b7ba6a437ecdd3c44e9d42d8bd87a | 08662c25e651f69acc8a11edd168dd1a4f950969 | refs/heads/master | 2023-08-14T06:50:58.218606 | 2021-10-04T01:48:02 | 2021-10-04T01:48:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,572 | cpp | // Alan Thomasz Wisny 2021
#include "Components/AudioComponent.h"
#include "Components/PrimitiveComponent.h"
#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
#include "OpenDoor.h"
#include "GameFrameWork/Actor.h"
// Sets default values for this component's properties
UOpenDoor::UOpenDoor()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
}
// Called when the game starts
void UOpenDoor::BeginPlay()
{
Super::BeginPlay();
InitialYaw = GetOwner()->GetActorRotation().Yaw;
CurrentYaw = InitialYaw;
TargetYaw = TargetYaw + InitialYaw;
if (!PressurePlate)
{
UE_LOG(LogTemp, Error, TEXT("Bloody Hell! %s has the open door component on it, but no PressurePlate has been set."), *GetOwner()->GetName());
}
FindPressurePlate();
FindAudioCOmponent();
}
void UOpenDoor::FindAudioCOmponent()
{
AudioComponent = GetOwner()->FindComponentByClass<UAudioComponent>();
if (!AudioComponent)
{
UE_LOG(LogTemp, Error, TEXT("%s Missing audio component!"), *GetOwner()->GetName());
}
}
void UOpenDoor::FindPressurePlate()
{
if (!PressurePlate)
{
UE_LOG(LogTemp, Error, TEXT("%s has the open door component on it, but not PressurePlate set!"), *GetOwner()->GetName());
}
}
// Called every frame
void UOpenDoor::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (TotalMassOfActors() > MassToOpenDoors)
{
OpenDoor(DeltaTime);
DoorLastOpened = GetWorld()->GetTimeSeconds();
}
else
{
float CurrentTime = GetWorld()->GetTimeSeconds();
// if the door has been open longer than x seconds
if (CurrentTime - DoorLastOpened > DoorCloseDelay)
{
CloseDoor(DeltaTime);
}
}
}
void UOpenDoor::OpenDoor(float DeltaTime)
{
// UE_LOG(LogTemp, Warning, TEXT("%s"), *GetOwner()->GetActorRotation().ToString());
// UE_LOG(LogTemp, Warning, TEXT("Yaw is: %f"), GetOwner()->GetActorRotation().Yaw);
CurrentYaw = FMath::FInterpTo(CurrentYaw, TargetYaw, DeltaTime, DoorOpenSpeed);
FRotator DoorRotation = GetOwner()->GetActorRotation();
DoorRotation.Yaw = CurrentYaw;
GetOwner()->SetActorRotation(DoorRotation);
CloseDoorSound = false;
if (!AudioComponent)
{
return;
}
if (!OpenDoorSound)
{
AudioComponent->Play();
OpenDoorSound = true;
}
}
void UOpenDoor::CloseDoor(float DeltaTime)
{
// UE_LOG(LogTemp, Warning, TEXT("%s"), *GetOwner()->GetActorRotation().ToString());
// UE_LOG(LogTemp, Warning, TEXT("Yaw is: %f"), GetOwner()->GetActorRotation().Yaw);
CurrentYaw = FMath::FInterpTo(CurrentYaw, InitialYaw, DeltaTime, DoorCloseSpeed);
FRotator DoorRotation = GetOwner()->GetActorRotation();
DoorRotation.Yaw = CurrentYaw;
GetOwner()->SetActorRotation(DoorRotation);
OpenDoorSound = false;
if (!AudioComponent)
{
return;
}
if (!CloseDoorSound)
{
AudioComponent->Play();
CloseDoorSound = true;
}
}
float UOpenDoor::TotalMassOfActors() const
{
float TotalMass = 0.f;
// Find all Overlapping Actors
TArray<AActor *> OverLappingActors;
if (!PressurePlate)
{
return TotalMass;
}
PressurePlate->GetOverlappingActors(OUT OverLappingActors);
// Add up Their Masses
for (AActor *Actor : OverLappingActors)
{
TotalMass += Actor->FindComponentByClass<UPrimitiveComponent>()->GetMass();
// UE_LOG(LogTemp, Warning, TEXT("%s is on the PressurePlate."), *Actor->GetName());
}
return TotalMass;
}
| [
"AlanWisny@hotmail.com"
] | AlanWisny@hotmail.com |
f1ca79b8cd7c3468f4cbb4acbd24f5b1984c8d20 | 45a917690bba40638160fd8636bafb9c21b7f849 | /src.cpp | 234bc12d0ad393d8465cf8c3d3399571fc7fe815 | [] | no_license | FrozenAsh1337/Flash-Reader | 79cd39377ca66c29a2c74c8eaed889c00c58495c | b8eac6a095b2fa30d748a0e1c25995b895d658ae | refs/heads/main | 2023-08-23T17:26:55.671990 | 2021-10-14T12:19:11 | 2021-10-14T12:19:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,039 | cpp | #include <iostream>
#include <string>
#include <unistd.h>
#include <cstdlib>
#include <fstream>
#include <chrono>
#include <thread>
void help()
{
std::cout<<"-o open text file."<<std::endl;
std::cout<<"-s set speed of words in seconds. Default speed is 0.5 seconds per word."<<std::endl;
std::cout<<"-i index of where reading should start, default value will be starting or where last left for the same file."<<std::endl;
std::cout<<"If starting a new file while the previous one was left in the middle, run the new one with an option of \"-i 1\"."<<std::endl;
std::cout<<"-h display this help message."<<std::endl;
}
int main(int argc,char* argv[])
{
int index=1,counter=1;
float speed=0.5;
char ch;
bool started=false;
std::string line="",content="";
std::ifstream data;
//detecting if windows or not for clear command
#if defined(_WIN32)
#define CLEAR "cls"
#else
#define CLEAR "clear"
#endif
//checking if an index value is already set
std::string liner;
std::ifstream datar;
datar.open("index.txt");
while(datar>>line)
{
index=std::stoi(line);
break;
}
datar.close();
//taking command line arguments
while((ch=getopt(argc,argv,"o: s: i: h"))!=EOF)
{
started=true;
switch(ch)
{
case 'o':
content=optarg;
break;
case 's':
speed=atof(optarg);
break;
case 'i':
index=atoi(optarg);
break;
case 'h':
help();
return 0;
default:
return 1;
}
}
//preparring for display
data.open(content);
system(CLEAR);
while(data>>line)
{
if(index>counter)//ignoring already read lines
{
counter++;
continue;
}
started=true;
std::cout<<line<<std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(int(speed*1000)));
index++;
counter++;
//saving current index value
std::ofstream dataw;
dataw.open("index.txt");
dataw<<index;
dataw.close();
system(CLEAR);
}
data.close();
//resetting index
std::ofstream dataw;
dataw.open("index.txt");
dataw<<"1"<<std::endl;
dataw.close();
if(!started) help();
return 0;
}
| [
"noreply@github.com"
] | FrozenAsh1337.noreply@github.com |
cbbf2cac5468e38c3fe17b49fdacdeb77b9bffa1 | 6982cc32bb79d09b80a505c827a4f8d03e0ab99a | /llvm-pass/InstructionCombining.cpp | 3f375b80e5a30835544c1071240d1b3da6d2d7d0 | [
"Apache-2.0"
] | permissive | 4tXJ7f/alive | 96c1083174a9170885e5a25cc8e7c06f9b0fc511 | 138bdc3c366f090a19547b9286e58a4b2e0aeead | refs/heads/master | 2021-01-21T08:33:24.842563 | 2016-04-01T08:24:13 | 2016-04-01T08:24:13 | 47,609,081 | 7 | 0 | null | 2015-12-08T08:31:18 | 2015-12-08T08:31:18 | null | UTF-8 | C++ | false | false | 120,540 | cpp | //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// InstructionCombining - Combine instructions to form fewer, simple
// instructions. This pass does not modify the CFG. This pass is where
// algebraic simplification happens.
//
// This pass combines things like:
// %Y = add i32 %X, 1
// %Z = add i32 %Y, 1
// into:
// %Z = add i32 %X, 2
//
// This is a simple worklist driven algorithm.
//
// This pass guarantees that the following canonicalizations are performed on
// the program:
// 1. If a binary operator has a constant operand, it is moved to the RHS
// 2. Bitwise operators with constant operands are always grouped so that
// shifts are performed first, then or's, then and's, then xor's.
// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
// 4. All cmp instructions on boolean values are replaced with logical ops
// 5. add X, X is represented as (X*2) => (X << 1)
// 6. Multiplies with a power-of-two constant argument are transformed into
// shifts.
// ... etc.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "InstCombine.h"
#include "llvm-c/Initialization.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Transforms/Utils/Local.h"
#include <algorithm>
#include <climits>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "instcombine"
STATISTIC(NumCombined , "Number of insts combined");
STATISTIC(NumConstProp, "Number of constant folds");
STATISTIC(NumDeadInst , "Number of dead inst eliminated");
STATISTIC(NumSunkInst , "Number of instructions sunk");
STATISTIC(NumExpand, "Number of expansions");
STATISTIC(NumFactor , "Number of factorizations");
STATISTIC(NumReassoc , "Number of reassociations");
// Initialization Routines
void llvm::initializeInstCombine(PassRegistry &Registry) {
initializeInstCombinerPass(Registry);
}
void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
initializeInstCombine(*unwrap(R));
}
char InstCombiner::ID = 0;
INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
"Combine redundant instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(InstCombiner, "instcombine",
"Combine redundant instructions", false, false)
void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<TargetLibraryInfo>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
}
Value *InstCombiner::EmitGEPOffset(User *GEP) {
return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
}
/// ShouldChangeType - Return true if it is desirable to convert a computation
/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
/// type for example, or from a smaller to a larger illegal type.
bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
assert(From->isIntegerTy() && To->isIntegerTy());
// If we don't have DL, we don't know if the source/dest are legal.
if (!DL) return false;
unsigned FromWidth = From->getPrimitiveSizeInBits();
unsigned ToWidth = To->getPrimitiveSizeInBits();
bool FromLegal = DL->isLegalInteger(FromWidth);
bool ToLegal = DL->isLegalInteger(ToWidth);
// If this is a legal integer from type, and the result would be an illegal
// type, don't do the transformation.
if (FromLegal && !ToLegal)
return false;
// Otherwise, if both are illegal, do not increase the size of the result. We
// do allow things like i160 -> i64, but not i64 -> i160.
if (!FromLegal && !ToLegal && ToWidth > FromWidth)
return false;
return true;
}
// Return true, if No Signed Wrap should be maintained for I.
// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
// where both B and C should be ConstantInts, results in a constant that does
// not overflow. This function only handles the Add and Sub opcodes. For
// all other opcodes, the function conservatively returns false.
static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
if (!OBO || !OBO->hasNoSignedWrap()) {
return false;
}
// We reason about Add and Sub Only.
Instruction::BinaryOps Opcode = I.getOpcode();
if (Opcode != Instruction::Add &&
Opcode != Instruction::Sub) {
return false;
}
ConstantInt *CB = dyn_cast<ConstantInt>(B);
ConstantInt *CC = dyn_cast<ConstantInt>(C);
if (!CB || !CC) {
return false;
}
const APInt &BVal = CB->getValue();
const APInt &CVal = CC->getValue();
bool Overflow = false;
if (Opcode == Instruction::Add) {
BVal.sadd_ov(CVal, Overflow);
} else {
BVal.ssub_ov(CVal, Overflow);
}
return !Overflow;
}
/// Conservatively clears subclassOptionalData after a reassociation or
/// commutation. We preserve fast-math flags when applicable as they can be
/// preserved.
static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
if (!FPMO) {
I.clearSubclassOptionalData();
return;
}
FastMathFlags FMF = I.getFastMathFlags();
I.clearSubclassOptionalData();
I.setFastMathFlags(FMF);
}
/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
/// operators which are associative or commutative:
//
// Commutative operators:
//
// 1. Order operands such that they are listed from right (least complex) to
// left (most complex). This puts constants before unary operators before
// binary operators.
//
// Associative operators:
//
// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
//
// Associative and commutative operators:
//
// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
// if C1 and C2 are constants.
//
bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Instruction::BinaryOps Opcode = I.getOpcode();
bool Changed = false;
do {
// Order operands such that they are listed from right (least complex) to
// left (most complex). This puts constants before unary operators before
// binary operators.
if (I.isCommutative() && getComplexity(I.getOperand(0)) <
getComplexity(I.getOperand(1)))
Changed = !I.swapOperands();
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
if (I.isAssociative()) {
// Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
if (Op0 && Op0->getOpcode() == Opcode) {
Value *A = Op0->getOperand(0);
Value *B = Op0->getOperand(1);
Value *C = I.getOperand(1);
// Does "B op C" simplify?
if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
// It simplifies to V. Form "A op V".
I.setOperand(0, A);
I.setOperand(1, V);
// Conservatively clear the optional flags, since they may not be
// preserved by the reassociation.
if (MaintainNoSignedWrap(I, B, C) &&
(!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
// Note: this is only valid because SimplifyBinOp doesn't look at
// the operands to Op0.
I.clearSubclassOptionalData();
I.setHasNoSignedWrap(true);
} else {
ClearSubclassDataAfterReassociation(I);
}
Changed = true;
++NumReassoc;
continue;
}
}
// Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
if (Op1 && Op1->getOpcode() == Opcode) {
Value *A = I.getOperand(0);
Value *B = Op1->getOperand(0);
Value *C = Op1->getOperand(1);
// Does "A op B" simplify?
if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
// It simplifies to V. Form "V op C".
I.setOperand(0, V);
I.setOperand(1, C);
// Conservatively clear the optional flags, since they may not be
// preserved by the reassociation.
ClearSubclassDataAfterReassociation(I);
Changed = true;
++NumReassoc;
continue;
}
}
}
if (I.isAssociative() && I.isCommutative()) {
// Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
if (Op0 && Op0->getOpcode() == Opcode) {
Value *A = Op0->getOperand(0);
Value *B = Op0->getOperand(1);
Value *C = I.getOperand(1);
// Does "C op A" simplify?
if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
// It simplifies to V. Form "V op B".
I.setOperand(0, V);
I.setOperand(1, B);
// Conservatively clear the optional flags, since they may not be
// preserved by the reassociation.
ClearSubclassDataAfterReassociation(I);
Changed = true;
++NumReassoc;
continue;
}
}
// Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
if (Op1 && Op1->getOpcode() == Opcode) {
Value *A = I.getOperand(0);
Value *B = Op1->getOperand(0);
Value *C = Op1->getOperand(1);
// Does "C op A" simplify?
if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
// It simplifies to V. Form "B op V".
I.setOperand(0, B);
I.setOperand(1, V);
// Conservatively clear the optional flags, since they may not be
// preserved by the reassociation.
ClearSubclassDataAfterReassociation(I);
Changed = true;
++NumReassoc;
continue;
}
}
// Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
// if C1 and C2 are constants.
if (Op0 && Op1 &&
Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
isa<Constant>(Op0->getOperand(1)) &&
isa<Constant>(Op1->getOperand(1)) &&
Op0->hasOneUse() && Op1->hasOneUse()) {
Value *A = Op0->getOperand(0);
Constant *C1 = cast<Constant>(Op0->getOperand(1));
Value *B = Op1->getOperand(0);
Constant *C2 = cast<Constant>(Op1->getOperand(1));
Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
if (isa<FPMathOperator>(New)) {
FastMathFlags Flags = I.getFastMathFlags();
Flags &= Op0->getFastMathFlags();
Flags &= Op1->getFastMathFlags();
New->setFastMathFlags(Flags);
}
InsertNewInstWith(New, I);
New->takeName(Op1);
I.setOperand(0, New);
I.setOperand(1, Folded);
// Conservatively clear the optional flags, since they may not be
// preserved by the reassociation.
ClearSubclassDataAfterReassociation(I);
Changed = true;
continue;
}
}
// No further simplifications.
return Changed;
} while (1);
}
/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
/// "(X LOp Y) ROp (X LOp Z)".
static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
Instruction::BinaryOps ROp) {
switch (LOp) {
default:
return false;
case Instruction::And:
// And distributes over Or and Xor.
switch (ROp) {
default:
return false;
case Instruction::Or:
case Instruction::Xor:
return true;
}
case Instruction::Mul:
// Multiplication distributes over addition and subtraction.
switch (ROp) {
default:
return false;
case Instruction::Add:
case Instruction::Sub:
return true;
}
case Instruction::Or:
// Or distributes over And.
switch (ROp) {
default:
return false;
case Instruction::And:
return true;
}
}
}
/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
/// "(X ROp Z) LOp (Y ROp Z)".
static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
Instruction::BinaryOps ROp) {
if (Instruction::isCommutative(ROp))
return LeftDistributesOverRight(ROp, LOp);
switch (LOp) {
default:
return false;
// (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
// (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
// (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
switch (ROp) {
default:
return false;
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
return true;
}
}
// TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
// but this requires knowing that the addition does not overflow and other
// such subtleties.
return false;
}
/// This function returns identity value for given opcode, which can be used to
/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
if (isa<Constant>(V))
return nullptr;
if (OpCode == Instruction::Mul)
return ConstantInt::get(V->getType(), 1);
// TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
return nullptr;
}
/// This function factors binary ops which can be combined using distributive
/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
/// RHS to 4.
static Instruction::BinaryOps
getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
BinaryOperator *Op, Value *&LHS, Value *&RHS) {
if (!Op)
return Instruction::BinaryOpsEnd;
LHS = Op->getOperand(0);
RHS = Op->getOperand(1);
switch (TopLevelOpcode) {
default:
return Op->getOpcode();
case Instruction::Add:
case Instruction::Sub:
if (Op->getOpcode() == Instruction::Shl) {
if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
// The multiplier is really 1 << CST.
RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
return Instruction::Mul;
}
}
return Op->getOpcode();
}
// TODO: We can add other conversions e.g. shr => div etc.
}
/// This tries to simplify binary operations by factorizing out common terms
/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
const DataLayout *DL, BinaryOperator &I,
Instruction::BinaryOps InnerOpcode, Value *A,
Value *B, Value *C, Value *D) {
// If any of A, B, C, D are null, we can not factor I, return early.
// Checking A and C should be enough.
if (!A || !C || !B || !D)
return nullptr;
Value *SimplifiedInst = nullptr;
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
// Does "X op' Y" always equal "Y op' X"?
bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
// Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
// Does the instruction have the form "(A op' B) op (A op' D)" or, in the
// commutative case, "(A op' B) op (C op' A)"?
if (A == C || (InnerCommutative && A == D)) {
if (A != C)
std::swap(C, D);
// Consider forming "A op' (B op D)".
// If "B op D" simplifies then it can be formed with no cost.
Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
// If "B op D" doesn't simplify then only go on if both of the existing
// operations "A op' B" and "C op' D" will be zapped as no longer used.
if (!V && LHS->hasOneUse() && RHS->hasOneUse())
V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
if (V) {
SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
}
}
// Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
// Does the instruction have the form "(A op' B) op (C op' B)" or, in the
// commutative case, "(A op' B) op (B op' D)"?
if (B == D || (InnerCommutative && B == C)) {
if (B != D)
std::swap(C, D);
// Consider forming "(A op C) op' B".
// If "A op C" simplifies then it can be formed with no cost.
Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
// If "A op C" doesn't simplify then only go on if both of the existing
// operations "A op' B" and "C op' D" will be zapped as no longer used.
if (!V && LHS->hasOneUse() && RHS->hasOneUse())
V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
if (V) {
SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
}
}
if (SimplifiedInst) {
++NumFactor;
SimplifiedInst->takeName(&I);
// Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
// TODO: Check for NUW.
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
bool HasNSW = false;
if (isa<OverflowingBinaryOperator>(&I))
HasNSW = I.hasNoSignedWrap();
if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
if (isa<OverflowingBinaryOperator>(Op0))
HasNSW &= Op0->hasNoSignedWrap();
if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
if (isa<OverflowingBinaryOperator>(Op1))
HasNSW &= Op1->hasNoSignedWrap();
BO->setHasNoSignedWrap(HasNSW);
}
}
}
return SimplifiedInst;
}
/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
/// which some other binary operation distributes over either by factorizing
/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
/// a win). Returns the simplified value, or null if it didn't simplify.
Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
// Factorization.
Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
auto TopLevelOpcode = I.getOpcode();
auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
// The instruction has the form "(A op' B) op (C op' D)". Try to factorize
// a common term.
if (LHSOpcode == RHSOpcode) {
if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
return V;
}
// The instruction has the form "(A op' B) op (C)". Try to factorize common
// term.
if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
getIdentityValue(LHSOpcode, RHS)))
return V;
// The instruction has the form "(B) op (C op' D)". Try to factorize common
// term.
if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
getIdentityValue(RHSOpcode, LHS), C, D))
return V;
// Expansion.
if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
// The instruction has the form "(A op' B) op C". See if expanding it out
// to "(A op C) op' (B op C)" results in simplifications.
Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
// Do "A op C" and "B op C" both simplify?
if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
// They do! Return "L op' R".
++NumExpand;
// If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
if ((L == A && R == B) ||
(Instruction::isCommutative(InnerOpcode) && L == B && R == A))
return Op0;
// Otherwise return "L op' R" if it simplifies.
if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
return V;
// Otherwise, create a new instruction.
C = Builder->CreateBinOp(InnerOpcode, L, R);
C->takeName(&I);
return C;
}
}
if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
// The instruction has the form "A op (B op' C)". See if expanding it out
// to "(A op B) op' (A op C)" results in simplifications.
Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
// Do "A op B" and "A op C" both simplify?
if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
// They do! Return "L op' R".
++NumExpand;
// If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
if ((L == B && R == C) ||
(Instruction::isCommutative(InnerOpcode) && L == C && R == B))
return Op1;
// Otherwise return "L op' R" if it simplifies.
if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
return V;
// Otherwise, create a new instruction.
A = Builder->CreateBinOp(InnerOpcode, L, R);
A->takeName(&I);
return A;
}
}
return nullptr;
}
// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
// if the LHS is a constant zero (which is the 'negate' form).
//
Value *InstCombiner::dyn_castNegVal(Value *V) const {
if (BinaryOperator::isNeg(V))
return BinaryOperator::getNegArgument(V);
// Constants can be considered to be negated values if they can be folded.
if (ConstantInt *C = dyn_cast<ConstantInt>(V))
return ConstantExpr::getNeg(C);
if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
if (C->getType()->getElementType()->isIntegerTy())
return ConstantExpr::getNeg(C);
return nullptr;
}
// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
// instruction if the LHS is a constant negative zero (which is the 'negate'
// form).
//
Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
return BinaryOperator::getFNegArgument(V);
// Constants can be considered to be negated values if they can be folded.
if (ConstantFP *C = dyn_cast<ConstantFP>(V))
return ConstantExpr::getFNeg(C);
if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
if (C->getType()->getElementType()->isFloatingPointTy())
return ConstantExpr::getFNeg(C);
return nullptr;
}
static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
InstCombiner *IC) {
if (CastInst *CI = dyn_cast<CastInst>(&I)) {
return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
}
// Figure out if the constant is the left or the right argument.
bool ConstIsRHS = isa<Constant>(I.getOperand(1));
Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
if (Constant *SOC = dyn_cast<Constant>(SO)) {
if (ConstIsRHS)
return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
}
Value *Op0 = SO, *Op1 = ConstOperand;
if (!ConstIsRHS)
std::swap(Op0, Op1);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
SO->getName()+".op");
Instruction *FPInst = dyn_cast<Instruction>(RI);
if (FPInst && isa<FPMathOperator>(FPInst))
FPInst->copyFastMathFlags(BO);
return RI;
}
if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
SO->getName()+".cmp");
if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
SO->getName()+".cmp");
llvm_unreachable("Unknown binary instruction type!");
}
// FoldOpIntoSelect - Given an instruction with a select as one operand and a
// constant as the other operand, try to fold the binary operator into the
// select arguments. This also works for Cast instructions, which obviously do
// not have a second operand.
Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
// Don't modify shared select instructions
if (!SI->hasOneUse()) return nullptr;
Value *TV = SI->getOperand(1);
Value *FV = SI->getOperand(2);
if (isa<Constant>(TV) || isa<Constant>(FV)) {
// Bool selects with constant operands can be folded to logical ops.
if (SI->getType()->isIntegerTy(1)) return nullptr;
// If it's a bitcast involving vectors, make sure it has the same number of
// elements on both sides.
if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
// Verify that either both or neither are vectors.
if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
// If vectors, verify that they have the same number of elements.
if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
return nullptr;
}
Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
return SelectInst::Create(SI->getCondition(),
SelectTrueVal, SelectFalseVal);
}
return nullptr;
}
/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
/// has a PHI node as operand #0, see if we can fold the instruction into the
/// PHI (which is only possible if all operands to the PHI are constants).
///
Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
PHINode *PN = cast<PHINode>(I.getOperand(0));
unsigned NumPHIValues = PN->getNumIncomingValues();
if (NumPHIValues == 0)
return nullptr;
// We normally only transform phis with a single use. However, if a PHI has
// multiple uses and they are all the same operation, we can fold *all* of the
// uses into the PHI.
if (!PN->hasOneUse()) {
// Walk the use list for the instruction, comparing them to I.
for (User *U : PN->users()) {
Instruction *UI = cast<Instruction>(U);
if (UI != &I && !I.isIdenticalTo(UI))
return nullptr;
}
// Otherwise, we can replace *all* users with the new PHI we form.
}
// Check to see if all of the operands of the PHI are simple constants
// (constantint/constantfp/undef). If there is one non-constant value,
// remember the BB it is in. If there is more than one or if *it* is a PHI,
// bail out. We don't do arbitrary constant expressions here because moving
// their computation can be expensive without a cost model.
BasicBlock *NonConstBB = nullptr;
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InVal = PN->getIncomingValue(i);
if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
continue;
if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
if (NonConstBB) return nullptr; // More than one non-const value.
NonConstBB = PN->getIncomingBlock(i);
// If the InVal is an invoke at the end of the pred block, then we can't
// insert a computation after it without breaking the edge.
if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
if (II->getParent() == NonConstBB)
return nullptr;
// If the incoming non-constant value is in I's block, we will remove one
// instruction, but insert another equivalent one, leading to infinite
// instcombine.
if (isPotentiallyReachable(I.getParent(), NonConstBB, DT,
getAnalysisIfAvailable<LoopInfo>()))
return nullptr;
}
// If there is exactly one non-constant value, we can insert a copy of the
// operation in that block. However, if this is a critical edge, we would be
// inserting the computation on some other paths (e.g. inside a loop). Only
// do this if the pred block is unconditionally branching into the phi block.
if (NonConstBB != nullptr) {
BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
if (!BI || !BI->isUnconditional()) return nullptr;
}
// Okay, we can do the transformation: create the new PHI node.
PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
InsertNewInstBefore(NewPN, *PN);
NewPN->takeName(PN);
// If we are going to have to insert a new computation, do so right before the
// predecessors terminator.
if (NonConstBB)
Builder->SetInsertPoint(NonConstBB->getTerminator());
// Next, add all of the operands to the PHI.
if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
// We only currently try to fold the condition of a select when it is a phi,
// not the true/false values.
Value *TrueV = SI->getTrueValue();
Value *FalseV = SI->getFalseValue();
BasicBlock *PhiTransBB = PN->getParent();
for (unsigned i = 0; i != NumPHIValues; ++i) {
BasicBlock *ThisBB = PN->getIncomingBlock(i);
Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Value *InV = nullptr;
// Beware of ConstantExpr: it may eventually evaluate to getNullValue,
// even if currently isNullValue gives false.
Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
if (InC && !isa<ConstantExpr>(InC))
InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
else
InV = Builder->CreateSelect(PN->getIncomingValue(i),
TrueVInPred, FalseVInPred, "phitmp");
NewPN->addIncoming(InV, ThisBB);
}
} else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
Constant *C = cast<Constant>(I.getOperand(1));
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InV = nullptr;
if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
else if (isa<ICmpInst>(CI))
InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
C, "phitmp");
else
InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
C, "phitmp");
NewPN->addIncoming(InV, PN->getIncomingBlock(i));
}
} else if (I.getNumOperands() == 2) {
Constant *C = cast<Constant>(I.getOperand(1));
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InV = nullptr;
if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
InV = ConstantExpr::get(I.getOpcode(), InC, C);
else
InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
PN->getIncomingValue(i), C, "phitmp");
NewPN->addIncoming(InV, PN->getIncomingBlock(i));
}
} else {
CastInst *CI = cast<CastInst>(&I);
Type *RetTy = CI->getType();
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InV;
if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
else
InV = Builder->CreateCast(CI->getOpcode(),
PN->getIncomingValue(i), I.getType(), "phitmp");
NewPN->addIncoming(InV, PN->getIncomingBlock(i));
}
}
for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Instruction *User = cast<Instruction>(*UI++);
if (User == &I) continue;
ReplaceInstUsesWith(*User, NewPN);
EraseInstFromFunction(*User);
}
return ReplaceInstUsesWith(I, NewPN);
}
/// FindElementAtOffset - Given a pointer type and a constant offset, determine
/// whether or not there is a sequence of GEP indices into the pointed type that
/// will land us at the specified offset. If so, fill them into NewIndices and
/// return the resultant element type, otherwise return null.
Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
SmallVectorImpl<Value*> &NewIndices) {
assert(PtrTy->isPtrOrPtrVectorTy());
if (!DL)
return nullptr;
Type *Ty = PtrTy->getPointerElementType();
if (!Ty->isSized())
return nullptr;
// Start with the index over the outer type. Note that the type size
// might be zero (even if the offset isn't zero) if the indexed type
// is something like [0 x {int, int}]
Type *IntPtrTy = DL->getIntPtrType(PtrTy);
int64_t FirstIdx = 0;
if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
FirstIdx = Offset/TySize;
Offset -= FirstIdx*TySize;
// Handle hosts where % returns negative instead of values [0..TySize).
if (Offset < 0) {
--FirstIdx;
Offset += TySize;
assert(Offset >= 0);
}
assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
}
NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
// Index into the types. If we fail, set OrigBase to null.
while (Offset) {
// Indexing into tail padding between struct/array elements.
if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
return nullptr;
if (StructType *STy = dyn_cast<StructType>(Ty)) {
const StructLayout *SL = DL->getStructLayout(STy);
assert(Offset < (int64_t)SL->getSizeInBytes() &&
"Offset must stay within the indexed type");
unsigned Elt = SL->getElementContainingOffset(Offset);
NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
Elt));
Offset -= SL->getElementOffset(Elt);
Ty = STy->getElementType(Elt);
} else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
assert(EltSize && "Cannot index into a zero-sized array");
NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Offset %= EltSize;
Ty = AT->getElementType();
} else {
// Otherwise, we can't index into the middle of this atomic type, bail.
return nullptr;
}
}
return Ty;
}
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
// If this GEP has only 0 indices, it is the same pointer as
// Src. If Src is not a trivial GEP too, don't combine
// the indices.
if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
!Src.hasOneUse())
return false;
return true;
}
/// Descale - Return a value X such that Val = X * Scale, or null if none. If
/// the multiplication is known not to overflow then NoSignedWrap is set.
Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
Scale.getBitWidth() && "Scale not compatible with value!");
// If Val is zero or Scale is one then Val = Val * Scale.
if (match(Val, m_Zero()) || Scale == 1) {
NoSignedWrap = true;
return Val;
}
// If Scale is zero then it does not divide Val.
if (Scale.isMinValue())
return nullptr;
// Look through chains of multiplications, searching for a constant that is
// divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
// will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
// a factor of 4 will produce X*(Y*2). The principle of operation is to bore
// down from Val:
//
// Val = M1 * X || Analysis starts here and works down
// M1 = M2 * Y || Doesn't descend into terms with more
// M2 = Z * 4 \/ than one use
//
// Then to modify a term at the bottom:
//
// Val = M1 * X
// M1 = Z * Y || Replaced M2 with Z
//
// Then to work back up correcting nsw flags.
// Op - the term we are currently analyzing. Starts at Val then drills down.
// Replaced with its descaled value before exiting from the drill down loop.
Value *Op = Val;
// Parent - initially null, but after drilling down notes where Op came from.
// In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
// 0'th operand of Val.
std::pair<Instruction*, unsigned> Parent;
// RequireNoSignedWrap - Set if the transform requires a descaling at deeper
// levels that doesn't overflow.
bool RequireNoSignedWrap = false;
// logScale - log base 2 of the scale. Negative if not a power of 2.
int32_t logScale = Scale.exactLogBase2();
for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
// If Op is a constant divisible by Scale then descale to the quotient.
APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
if (!Remainder.isMinValue())
// Not divisible by Scale.
return nullptr;
// Replace with the quotient in the parent.
Op = ConstantInt::get(CI->getType(), Quotient);
NoSignedWrap = true;
break;
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
if (BO->getOpcode() == Instruction::Mul) {
// Multiplication.
NoSignedWrap = BO->hasNoSignedWrap();
if (RequireNoSignedWrap && !NoSignedWrap)
return nullptr;
// There are three cases for multiplication: multiplication by exactly
// the scale, multiplication by a constant different to the scale, and
// multiplication by something else.
Value *LHS = BO->getOperand(0);
Value *RHS = BO->getOperand(1);
if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
// Multiplication by a constant.
if (CI->getValue() == Scale) {
// Multiplication by exactly the scale, replace the multiplication
// by its left-hand side in the parent.
Op = LHS;
break;
}
// Otherwise drill down into the constant.
if (!Op->hasOneUse())
return nullptr;
Parent = std::make_pair(BO, 1);
continue;
}
// Multiplication by something else. Drill down into the left-hand side
// since that's where the reassociate pass puts the good stuff.
if (!Op->hasOneUse())
return nullptr;
Parent = std::make_pair(BO, 0);
continue;
}
if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
isa<ConstantInt>(BO->getOperand(1))) {
// Multiplication by a power of 2.
NoSignedWrap = BO->hasNoSignedWrap();
if (RequireNoSignedWrap && !NoSignedWrap)
return nullptr;
Value *LHS = BO->getOperand(0);
int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
getLimitedValue(Scale.getBitWidth());
// Op = LHS << Amt.
if (Amt == logScale) {
// Multiplication by exactly the scale, replace the multiplication
// by its left-hand side in the parent.
Op = LHS;
break;
}
if (Amt < logScale || !Op->hasOneUse())
return nullptr;
// Multiplication by more than the scale. Reduce the multiplying amount
// by the scale in the parent.
Parent = std::make_pair(BO, 1);
Op = ConstantInt::get(BO->getType(), Amt - logScale);
break;
}
}
if (!Op->hasOneUse())
return nullptr;
if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
if (Cast->getOpcode() == Instruction::SExt) {
// Op is sign-extended from a smaller type, descale in the smaller type.
unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
APInt SmallScale = Scale.trunc(SmallSize);
// Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
// descale Op as (sext Y) * Scale. In order to have
// sext (Y * SmallScale) = (sext Y) * Scale
// some conditions need to hold however: SmallScale must sign-extend to
// Scale and the multiplication Y * SmallScale should not overflow.
if (SmallScale.sext(Scale.getBitWidth()) != Scale)
// SmallScale does not sign-extend to Scale.
return nullptr;
assert(SmallScale.exactLogBase2() == logScale);
// Require that Y * SmallScale must not overflow.
RequireNoSignedWrap = true;
// Drill down through the cast.
Parent = std::make_pair(Cast, 0);
Scale = SmallScale;
continue;
}
if (Cast->getOpcode() == Instruction::Trunc) {
// Op is truncated from a larger type, descale in the larger type.
// Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
// trunc (Y * sext Scale) = (trunc Y) * Scale
// always holds. However (trunc Y) * Scale may overflow even if
// trunc (Y * sext Scale) does not, so nsw flags need to be cleared
// from this point up in the expression (see later).
if (RequireNoSignedWrap)
return nullptr;
// Drill down through the cast.
unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
Parent = std::make_pair(Cast, 0);
Scale = Scale.sext(LargeSize);
if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
logScale = -1;
assert(Scale.exactLogBase2() == logScale);
continue;
}
}
// Unsupported expression, bail out.
return nullptr;
}
// If Op is zero then Val = Op * Scale.
if (match(Op, m_Zero())) {
NoSignedWrap = true;
return Op;
}
// We know that we can successfully descale, so from here on we can safely
// modify the IR. Op holds the descaled version of the deepest term in the
// expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
// not to overflow.
if (!Parent.first)
// The expression only had one term.
return Op;
// Rewrite the parent using the descaled version of its operand.
assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
assert(Op != Parent.first->getOperand(Parent.second) &&
"Descaling was a no-op?");
Parent.first->setOperand(Parent.second, Op);
Worklist.Add(Parent.first);
// Now work back up the expression correcting nsw flags. The logic is based
// on the following observation: if X * Y is known not to overflow as a signed
// multiplication, and Y is replaced by a value Z with smaller absolute value,
// then X * Z will not overflow as a signed multiplication either. As we work
// our way up, having NoSignedWrap 'true' means that the descaled value at the
// current level has strictly smaller absolute value than the original.
Instruction *Ancestor = Parent.first;
do {
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
// If the multiplication wasn't nsw then we can't say anything about the
// value of the descaled multiplication, and we have to clear nsw flags
// from this point on up.
bool OpNoSignedWrap = BO->hasNoSignedWrap();
NoSignedWrap &= OpNoSignedWrap;
if (NoSignedWrap != OpNoSignedWrap) {
BO->setHasNoSignedWrap(NoSignedWrap);
Worklist.Add(Ancestor);
}
} else if (Ancestor->getOpcode() == Instruction::Trunc) {
// The fact that the descaled input to the trunc has smaller absolute
// value than the original input doesn't tell us anything useful about
// the absolute values of the truncations.
NoSignedWrap = false;
}
assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
"Failed to keep proper track of nsw flags while drilling down?");
if (Ancestor == Val)
// Got to the top, all done!
return Val;
// Move up one level in the expression.
assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Ancestor = Ancestor->user_back();
} while (1);
}
/// \brief Creates node of binary operation with the same attributes as the
/// specified one but with other operands.
static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
InstCombiner::BuilderTy *B) {
Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
if (isa<OverflowingBinaryOperator>(NewBO)) {
NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
}
if (isa<PossiblyExactOperator>(NewBO))
NewBO->setIsExact(Inst.isExact());
}
return BORes;
}
/// \brief Makes transformation of binary operation specific for vector types.
/// \param Inst 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::SimplifyVectorOp(BinaryOperator &Inst) {
if (!Inst.getType()->isVectorTy()) return nullptr;
// It may not be safe to reorder shuffles and things like div, urem, etc.
// because we may trap when executing those ops on unknown vector elements.
// See PR20059.
if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
// If both arguments of binary operation are shuffles, which use the same
// mask and shuffle within a single vector, it is worthwhile to move the
// shuffle after binary operation:
// Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
if (isa<UndefValue>(LShuf->getOperand(1)) &&
isa<UndefValue>(RShuf->getOperand(1)) &&
LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
LShuf->getMask() == RShuf->getMask()) {
Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
RShuf->getOperand(0), Builder);
Value *Res = Builder->CreateShuffleVector(NewBO,
UndefValue::get(NewBO->getType()), LShuf->getMask());
return Res;
}
}
// If one argument is a shuffle within one vector, the other is a constant,
// try moving the shuffle after the binary operation.
ShuffleVectorInst *Shuffle = nullptr;
Constant *C1 = nullptr;
if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
if (Shuffle && C1 &&
(isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
isa<UndefValue>(Shuffle->getOperand(1)) &&
Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
// Find constant C2 that has property:
// shuffle(C2, ShMask) = C1
// If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
// reorder is not possible.
SmallVector<Constant*, 16> C2M(VWidth,
UndefValue::get(C1->getType()->getScalarType()));
bool MayChange = true;
for (unsigned I = 0; I < VWidth; ++I) {
if (ShMask[I] >= 0) {
assert(ShMask[I] < (int)VWidth);
if (!isa<UndefValue>(C2M[ShMask[I]])) {
MayChange = false;
break;
}
C2M[ShMask[I]] = C1->getAggregateElement(I);
}
}
if (MayChange) {
Constant *C2 = ConstantVector::get(C2M);
Value *NewLHS, *NewRHS;
if (isa<Constant>(LHS)) {
NewLHS = C2;
NewRHS = Shuffle->getOperand(0);
} else {
NewLHS = Shuffle->getOperand(0);
NewRHS = C2;
}
Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Value *Res = Builder->CreateShuffleVector(NewBO,
UndefValue::get(Inst.getType()), Shuffle->getMask());
return Res;
}
}
return nullptr;
}
Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
return ReplaceInstUsesWith(GEP, V);
Value *PtrOp = GEP.getOperand(0);
// Eliminate unneeded casts for indices, and replace indices which displace
// by multiples of a zero size type with zero.
if (DL) {
bool MadeChange = false;
Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
gep_type_iterator GTI = gep_type_begin(GEP);
for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
I != E; ++I, ++GTI) {
// Skip indices into struct types.
SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
if (!SeqTy) continue;
// If the element type has zero size then any index over it is equivalent
// to an index of zero, so replace it with zero if it is not zero already.
if (SeqTy->getElementType()->isSized() &&
DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
*I = Constant::getNullValue(IntPtrTy);
MadeChange = true;
}
Type *IndexTy = (*I)->getType();
if (IndexTy != IntPtrTy) {
// If we are using a wider index than needed for this platform, shrink
// it to what we need. If narrower, sign-extend it to what we need.
// This explicit cast can make subsequent optimizations more obvious.
*I = Builder->CreateIntCast(*I, IntPtrTy, true);
MadeChange = true;
}
}
if (MadeChange) return &GEP;
}
// Check to see if the inputs to the PHI node are getelementptr instructions.
if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
if (!Op1)
return nullptr;
signed DI = -1;
for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
return nullptr;
// Keep track of the type as we walk the GEP.
Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
return nullptr;
if (Op1->getOperand(J) != Op2->getOperand(J)) {
if (DI == -1) {
// We have not seen any differences yet in the GEPs feeding the
// PHI yet, so we record this one if it is allowed to be a
// variable.
// The first two arguments can vary for any GEP, the rest have to be
// static for struct slots
if (J > 1 && CurTy->isStructTy())
return nullptr;
DI = J;
} else {
// The GEP is different by more than one input. While this could be
// extended to support GEPs that vary by more than one variable it
// doesn't make sense since it greatly increases the complexity and
// would result in an R+R+R addressing mode which no backend
// directly supports and would need to be broken into several
// simpler instructions anyway.
return nullptr;
}
}
// Sink down a layer of the type for the next iteration.
if (J > 0) {
if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
} else {
CurTy = nullptr;
}
}
}
}
GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
if (DI == -1) {
// All the GEPs feeding the PHI are identical. Clone one down into our
// BB so that it can be merged with the current GEP.
GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
NewGEP);
} else {
// All the GEPs feeding the PHI differ at a single offset. Clone a GEP
// into the current block so it can be merged, and create a new PHI to
// set that index.
Instruction *InsertPt = Builder->GetInsertPoint();
Builder->SetInsertPoint(PN);
PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
PN->getNumOperands());
Builder->SetInsertPoint(InsertPt);
for (auto &I : PN->operands())
NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
PN->getIncomingBlock(I));
NewGEP->setOperand(DI, NewPN);
GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
NewGEP);
NewGEP->setOperand(DI, NewPN);
}
GEP.setOperand(0, NewGEP);
PtrOp = NewGEP;
}
// Combine Indices - If the source pointer to this getelementptr instruction
// is a getelementptr instruction, combine the indices of the two
// getelementptr instructions into a single instruction.
//
if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
return nullptr;
// Note that if our source is a gep chain itself then we wait for that
// chain to be resolved before we perform this transformation. This
// avoids us creating a TON of code in some cases.
if (GEPOperator *SrcGEP =
dyn_cast<GEPOperator>(Src->getOperand(0)))
if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
return nullptr; // Wait until our source is folded to completion.
SmallVector<Value*, 8> Indices;
// Find out whether the last index in the source GEP is a sequential idx.
bool EndsWithSequential = false;
for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
I != E; ++I)
EndsWithSequential = !(*I)->isStructTy();
// Can we combine the two pointer arithmetics offsets?
if (EndsWithSequential) {
// Replace: gep (gep %P, long B), long A, ...
// With: T = long A+B; gep %P, T, ...
//
Value *Sum;
Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
Value *GO1 = GEP.getOperand(1);
if (SO1 == Constant::getNullValue(SO1->getType())) {
Sum = GO1;
} else if (GO1 == Constant::getNullValue(GO1->getType())) {
Sum = SO1;
} else {
// If they aren't the same type, then the input hasn't been processed
// by the loop above yet (which canonicalizes sequential index types to
// intptr_t). Just avoid transforming this until the input has been
// normalized.
if (SO1->getType() != GO1->getType())
return nullptr;
Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
}
// Update the GEP in place if possible.
if (Src->getNumOperands() == 2) {
GEP.setOperand(0, Src->getOperand(0));
GEP.setOperand(1, Sum);
return &GEP;
}
Indices.append(Src->op_begin()+1, Src->op_end()-1);
Indices.push_back(Sum);
Indices.append(GEP.op_begin()+2, GEP.op_end());
} else if (isa<Constant>(*GEP.idx_begin()) &&
cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Src->getNumOperands() != 1) {
// Otherwise we can do the fold if the first index of the GEP is a zero
Indices.append(Src->op_begin()+1, Src->op_end());
Indices.append(GEP.idx_begin()+1, GEP.idx_end());
}
if (!Indices.empty())
return (GEP.isInBounds() && Src->isInBounds()) ?
GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
GEP.getName()) :
GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
}
if (DL && GEP.getNumIndices() == 1) {
unsigned AS = GEP.getPointerAddressSpace();
if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
DL->getPointerSizeInBits(AS)) {
Type *PtrTy = GEP.getPointerOperandType();
Type *Ty = PtrTy->getPointerElementType();
uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
bool Matched = false;
uint64_t C;
Value *V = nullptr;
if (TyAllocSize == 1) {
V = GEP.getOperand(1);
Matched = true;
} else if (match(GEP.getOperand(1),
m_AShr(m_Value(V), m_ConstantInt(C)))) {
if (TyAllocSize == 1ULL << C)
Matched = true;
} else if (match(GEP.getOperand(1),
m_SDiv(m_Value(V), m_ConstantInt(C)))) {
if (TyAllocSize == C)
Matched = true;
}
if (Matched) {
// Canonicalize (gep i8* X, -(ptrtoint Y))
// to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
// The GEP pattern is emitted by the SCEV expander for certain kinds of
// pointer arithmetic.
if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
Operator *Index = cast<Operator>(V);
Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
}
// Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
// to (bitcast Y)
Value *Y;
if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
GEP.getType());
}
}
}
}
// Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Value *StrippedPtr = PtrOp->stripPointerCasts();
PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
// We do not handle pointer-vector geps here.
if (!StrippedPtrTy)
return nullptr;
if (StrippedPtr != PtrOp) {
bool HasZeroPointerIndex = false;
if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
HasZeroPointerIndex = C->isZero();
// Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
// into : GEP [10 x i8]* X, i32 0, ...
//
// Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
// into : GEP i8* X, ...
//
// This occurs when the program declares an array extern like "int X[];"
if (HasZeroPointerIndex) {
PointerType *CPTy = cast<PointerType>(PtrOp->getType());
if (ArrayType *CATy =
dyn_cast<ArrayType>(CPTy->getElementType())) {
// GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
// -> GEP i8* X, ...
SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
GetElementPtrInst *Res =
GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Res->setIsInBounds(GEP.isInBounds());
if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
return Res;
// Insert Res, and create an addrspacecast.
// e.g.,
// GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
// ->
// %0 = GEP i8 addrspace(1)* X, ...
// addrspacecast i8 addrspace(1)* %0 to i8*
return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
}
if (ArrayType *XATy =
dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
// GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
if (CATy->getElementType() == XATy->getElementType()) {
// -> GEP [10 x i8]* X, i32 0, ...
// At this point, we know that the cast source type is a pointer
// to an array of the same type as the destination pointer
// array. Because the array type is never stepped over (there
// is a leading zero) we can fold the cast into this GEP.
if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
GEP.setOperand(0, StrippedPtr);
return &GEP;
}
// Cannot replace the base pointer directly because StrippedPtr's
// address space is different. Instead, create a new GEP followed by
// an addrspacecast.
// e.g.,
// GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
// i32 0, ...
// ->
// %0 = GEP [10 x i8] addrspace(1)* X, ...
// addrspacecast i8 addrspace(1)* %0 to i8*
SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
Value *NewGEP = GEP.isInBounds() ?
Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
return new AddrSpaceCastInst(NewGEP, GEP.getType());
}
}
}
} else if (GEP.getNumOperands() == 2) {
// Transform things like:
// %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
// into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Type *SrcElTy = StrippedPtrTy->getElementType();
Type *ResElTy = PtrOp->getType()->getPointerElementType();
if (DL && SrcElTy->isArrayTy() &&
DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
DL->getTypeAllocSize(ResElTy)) {
Type *IdxType = DL->getIntPtrType(GEP.getType());
Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
Value *NewGEP = GEP.isInBounds() ?
Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
// V and GEP are both pointer types --> BitCast
return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
GEP.getType());
}
// Transform things like:
// %V = mul i64 %N, 4
// %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
// into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
// Check that changing the type amounts to dividing the index by a scale
// factor.
uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
if (ResSize && SrcSize % ResSize == 0) {
Value *Idx = GEP.getOperand(1);
unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
uint64_t Scale = SrcSize / ResSize;
// Earlier transforms ensure that the index has type IntPtrType, which
// considerably simplifies the logic by eliminating implicit casts.
assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
"Index not cast to pointer width?");
bool NSW;
if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
// Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
// If the multiplication NewIdx * Scale may overflow then the new
// GEP may not be "inbounds".
Value *NewGEP = GEP.isInBounds() && NSW ?
Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
// The NewGEP must be pointer typed, so must the old one -> BitCast
return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
GEP.getType());
}
}
}
// Similarly, transform things like:
// getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
// (where tmp = 8*tmp2) into:
// getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
SrcElTy->isArrayTy()) {
// Check that changing to the array element type amounts to dividing the
// index by a scale factor.
uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
uint64_t ArrayEltSize
= DL->getTypeAllocSize(SrcElTy->getArrayElementType());
if (ResSize && ArrayEltSize % ResSize == 0) {
Value *Idx = GEP.getOperand(1);
unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
uint64_t Scale = ArrayEltSize / ResSize;
// Earlier transforms ensure that the index has type IntPtrType, which
// considerably simplifies the logic by eliminating implicit casts.
assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
"Index not cast to pointer width?");
bool NSW;
if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
// Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
// If the multiplication NewIdx * Scale may overflow then the new
// GEP may not be "inbounds".
Value *Off[2] = {
Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
NewIdx
};
Value *NewGEP = GEP.isInBounds() && NSW ?
Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
// The NewGEP must be pointer typed, so must the old one -> BitCast
return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
GEP.getType());
}
}
}
}
}
if (!DL)
return nullptr;
// addrspacecast between types is canonicalized as a bitcast, then an
// addrspacecast. To take advantage of the below bitcast + struct GEP, look
// through the addrspacecast.
if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
// X = bitcast A addrspace(1)* to B addrspace(1)*
// Y = addrspacecast A addrspace(1)* to B addrspace(2)*
// Z = gep Y, <...constant indices...>
// Into an addrspacecasted GEP of the struct.
if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
PtrOp = BC;
}
/// See if we can simplify:
/// X = bitcast A* to B*
/// Y = gep X, <...constant indices...>
/// into a gep of the original struct. This is important for SROA and alias
/// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Value *Operand = BCI->getOperand(0);
PointerType *OpType = cast<PointerType>(Operand->getType());
unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
APInt Offset(OffsetBits, 0);
if (!isa<BitCastInst>(Operand) &&
GEP.accumulateConstantOffset(*DL, Offset)) {
// If this GEP instruction doesn't move the pointer, just replace the GEP
// with a bitcast of the real input to the dest type.
if (!Offset) {
// If the bitcast is of an allocation, and the allocation will be
// converted to match the type of the cast, don't touch this.
if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
// See if the bitcast simplifies, if so, don't nuke this GEP yet.
if (Instruction *I = visitBitCast(*BCI)) {
if (I != BCI) {
I->takeName(BCI);
BCI->getParent()->getInstList().insert(BCI, I);
ReplaceInstUsesWith(*BCI, I);
}
return &GEP;
}
}
if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
return new AddrSpaceCastInst(Operand, GEP.getType());
return new BitCastInst(Operand, GEP.getType());
}
// Otherwise, if the offset is non-zero, we need to find out if there is a
// field at Offset in 'A's type. If so, we can pull the cast through the
// GEP.
SmallVector<Value*, 8> NewIndices;
if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
Value *NGEP = GEP.isInBounds() ?
Builder->CreateInBoundsGEP(Operand, NewIndices) :
Builder->CreateGEP(Operand, NewIndices);
if (NGEP->getType() == GEP.getType())
return ReplaceInstUsesWith(GEP, NGEP);
NGEP->takeName(&GEP);
if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
return new AddrSpaceCastInst(NGEP, GEP.getType());
return new BitCastInst(NGEP, GEP.getType());
}
}
}
return nullptr;
}
static bool
isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
const TargetLibraryInfo *TLI) {
SmallVector<Instruction*, 4> Worklist;
Worklist.push_back(AI);
do {
Instruction *PI = Worklist.pop_back_val();
for (User *U : PI->users()) {
Instruction *I = cast<Instruction>(U);
switch (I->getOpcode()) {
default:
// Give up the moment we see something we can't handle.
return false;
case Instruction::BitCast:
case Instruction::GetElementPtr:
Users.push_back(I);
Worklist.push_back(I);
continue;
case Instruction::ICmp: {
ICmpInst *ICI = cast<ICmpInst>(I);
// We can fold eq/ne comparisons with null to false/true, respectively.
if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
return false;
Users.push_back(I);
continue;
}
case Instruction::Call:
// Ignore no-op and store intrinsics.
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
switch (II->getIntrinsicID()) {
default:
return false;
case Intrinsic::memmove:
case Intrinsic::memcpy:
case Intrinsic::memset: {
MemIntrinsic *MI = cast<MemIntrinsic>(II);
if (MI->isVolatile() || MI->getRawDest() != PI)
return false;
}
// fall through
case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
case Intrinsic::invariant_start:
case Intrinsic::invariant_end:
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::objectsize:
Users.push_back(I);
continue;
}
}
if (isFreeCall(I, TLI)) {
Users.push_back(I);
continue;
}
return false;
case Instruction::Store: {
StoreInst *SI = cast<StoreInst>(I);
if (SI->isVolatile() || SI->getPointerOperand() != PI)
return false;
Users.push_back(I);
continue;
}
}
llvm_unreachable("missing a return?");
}
} while (!Worklist.empty());
return true;
}
Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
// If we have a malloc call which is only used in any amount of comparisons
// to null and free calls, delete the calls and replace the comparisons with
// true or false as appropriate.
SmallVector<WeakVH, 64> Users;
if (isAllocSiteRemovable(&MI, Users, TLI)) {
for (unsigned i = 0, e = Users.size(); i != e; ++i) {
Instruction *I = cast_or_null<Instruction>(&*Users[i]);
if (!I) continue;
if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
ReplaceInstUsesWith(*C,
ConstantInt::get(Type::getInt1Ty(C->getContext()),
C->isFalseWhenEqual()));
} else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
} else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
if (II->getIntrinsicID() == Intrinsic::objectsize) {
ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
}
}
EraseInstFromFunction(*I);
}
if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
// Replace invoke with a NOP intrinsic to maintain the original CFG
Module *M = II->getParent()->getParent()->getParent();
Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
None, "", II->getParent());
}
return EraseInstFromFunction(MI);
}
return nullptr;
}
/// \brief Move the call to free before a NULL test.
///
/// Check if this free is accessed after its argument has been test
/// against NULL (property 0).
/// If yes, it is legal to move this call in its predecessor block.
///
/// The move is performed only if the block containing the call to free
/// will be removed, i.e.:
/// 1. it has only one predecessor P, and P has two successors
/// 2. it contains the call and an unconditional branch
/// 3. its successor is the same as its predecessor's successor
///
/// The profitability is out-of concern here and this function should
/// be called only if the caller knows this transformation would be
/// profitable (e.g., for code size).
static Instruction *
tryToMoveFreeBeforeNullTest(CallInst &FI) {
Value *Op = FI.getArgOperand(0);
BasicBlock *FreeInstrBB = FI.getParent();
BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
// Validate part of constraint #1: Only one predecessor
// FIXME: We can extend the number of predecessor, but in that case, we
// would duplicate the call to free in each predecessor and it may
// not be profitable even for code size.
if (!PredBB)
return nullptr;
// Validate constraint #2: Does this block contains only the call to
// free and an unconditional branch?
// FIXME: We could check if we can speculate everything in the
// predecessor block
if (FreeInstrBB->size() != 2)
return nullptr;
BasicBlock *SuccBB;
if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
return nullptr;
// Validate the rest of constraint #1 by matching on the pred branch.
TerminatorInst *TI = PredBB->getTerminator();
BasicBlock *TrueBB, *FalseBB;
ICmpInst::Predicate Pred;
if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
return nullptr;
if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
return nullptr;
// Validate constraint #3: Ensure the null case just falls through.
if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
return nullptr;
assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
"Broken CFG: missing edge from predecessor to successor");
FI.moveBefore(TI);
return &FI;
}
Instruction *InstCombiner::visitFree(CallInst &FI) {
Value *Op = FI.getArgOperand(0);
// free undef -> unreachable.
if (isa<UndefValue>(Op)) {
// Insert a new store to null because we cannot modify the CFG here.
Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
return EraseInstFromFunction(FI);
}
// If we have 'free null' delete the instruction. This can happen in stl code
// when lots of inlining happens.
if (isa<ConstantPointerNull>(Op))
return EraseInstFromFunction(FI);
// If we optimize for code size, try to move the call to free before the null
// test so that simplify cfg can remove the empty block and dead code
// elimination the branch. I.e., helps to turn something like:
// if (foo) free(foo);
// into
// free(foo);
if (MinimizeSize)
if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
return I;
return nullptr;
}
Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
if (RI.getNumOperands() == 0) // ret void
return nullptr;
Value *ResultOp = RI.getOperand(0);
Type *VTy = ResultOp->getType();
if (!VTy->isIntegerTy())
return nullptr;
// There might be assume intrinsics dominating this return that completely
// determine the value. If so, constant fold it.
unsigned BitWidth = VTy->getPrimitiveSizeInBits();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
if ((KnownZero|KnownOne).isAllOnesValue())
RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
return nullptr;
}
Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
// Change br (not X), label True, label False to: br X, label False, True
Value *X = nullptr;
BasicBlock *TrueDest;
BasicBlock *FalseDest;
if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
!isa<Constant>(X)) {
// Swap Destinations and condition...
BI.setCondition(X);
BI.swapSuccessors();
return &BI;
}
// Canonicalize fcmp_one -> fcmp_oeq
FCmpInst::Predicate FPred; Value *Y;
if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
TrueDest, FalseDest)) &&
BI.getCondition()->hasOneUse())
if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
FPred == FCmpInst::FCMP_OGE) {
FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
// Swap Destinations and condition.
BI.swapSuccessors();
Worklist.Add(Cond);
return &BI;
}
// Canonicalize icmp_ne -> icmp_eq
ICmpInst::Predicate IPred;
if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
TrueDest, FalseDest)) &&
BI.getCondition()->hasOneUse())
if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
IPred == ICmpInst::ICMP_SGE) {
ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
// Swap Destinations and condition.
BI.swapSuccessors();
Worklist.Add(Cond);
return &BI;
}
return nullptr;
}
Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
Value *Cond = SI.getCondition();
unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
computeKnownBits(Cond, KnownZero, KnownOne);
unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
// Compute the number of leading bits we can ignore.
for (auto &C : SI.cases()) {
LeadingKnownZeros = std::min(
LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
LeadingKnownOnes = std::min(
LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
}
unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
// Truncate the condition operand if the new type is equal to or larger than
// the largest legal integer type. We need to be conservative here since
// x86 generates redundant zero-extenstion instructions if the operand is
// truncated to i8 or i16.
bool TruncCond = false;
if (DL && BitWidth > NewWidth &&
NewWidth >= DL->getLargestLegalIntTypeSize()) {
TruncCond = true;
IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
Builder->SetInsertPoint(&SI);
Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
SI.setCondition(NewCond);
for (auto &C : SI.cases())
static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
}
if (Instruction *I = dyn_cast<Instruction>(Cond)) {
if (I->getOpcode() == Instruction::Add)
if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
// change 'switch (X+4) case 1:' into 'switch (X) case -3'
// Skip the first item since that's the default case.
for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
i != e; ++i) {
ConstantInt* CaseVal = i.getCaseValue();
Constant *LHS = CaseVal;
if (TruncCond)
LHS = LeadingKnownZeros
? ConstantExpr::getZExt(CaseVal, Cond->getType())
: ConstantExpr::getSExt(CaseVal, Cond->getType());
Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
assert(isa<ConstantInt>(NewCaseVal) &&
"Result of expression should be constant");
i.setValue(cast<ConstantInt>(NewCaseVal));
}
SI.setCondition(I->getOperand(0));
Worklist.Add(I);
return &SI;
}
}
return TruncCond ? &SI : nullptr;
}
Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Value *Agg = EV.getAggregateOperand();
if (!EV.hasIndices())
return ReplaceInstUsesWith(EV, Agg);
if (Constant *C = dyn_cast<Constant>(Agg)) {
if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
if (EV.getNumIndices() == 0)
return ReplaceInstUsesWith(EV, C2);
// Extract the remaining indices out of the constant indexed by the
// first index
return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
}
return nullptr; // Can't handle other constants
}
if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
// We're extracting from an insertvalue instruction, compare the indices
const unsigned *exti, *exte, *insi, *inse;
for (exti = EV.idx_begin(), insi = IV->idx_begin(),
exte = EV.idx_end(), inse = IV->idx_end();
exti != exte && insi != inse;
++exti, ++insi) {
if (*insi != *exti)
// The insert and extract both reference distinctly different elements.
// This means the extract is not influenced by the insert, and we can
// replace the aggregate operand of the extract with the aggregate
// operand of the insert. i.e., replace
// %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
// %E = extractvalue { i32, { i32 } } %I, 0
// with
// %E = extractvalue { i32, { i32 } } %A, 0
return ExtractValueInst::Create(IV->getAggregateOperand(),
EV.getIndices());
}
if (exti == exte && insi == inse)
// Both iterators are at the end: Index lists are identical. Replace
// %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
// %C = extractvalue { i32, { i32 } } %B, 1, 0
// with "i32 42"
return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
if (exti == exte) {
// The extract list is a prefix of the insert list. i.e. replace
// %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
// %E = extractvalue { i32, { i32 } } %I, 1
// with
// %X = extractvalue { i32, { i32 } } %A, 1
// %E = insertvalue { i32 } %X, i32 42, 0
// by switching the order of the insert and extract (though the
// insertvalue should be left in, since it may have other uses).
Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
EV.getIndices());
return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
makeArrayRef(insi, inse));
}
if (insi == inse)
// The insert list is a prefix of the extract list
// We can simply remove the common indices from the extract and make it
// operate on the inserted value instead of the insertvalue result.
// i.e., replace
// %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
// %E = extractvalue { i32, { i32 } } %I, 1, 0
// with
// %E extractvalue { i32 } { i32 42 }, 0
return ExtractValueInst::Create(IV->getInsertedValueOperand(),
makeArrayRef(exti, exte));
}
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
// We're extracting from an intrinsic, see if we're the only user, which
// allows us to simplify multiple result intrinsics to simpler things that
// just get one value.
if (II->hasOneUse()) {
// Check if we're grabbing the overflow bit or the result of a 'with
// overflow' intrinsic. If it's the latter we can remove the intrinsic
// and replace it with a traditional binary instruction.
switch (II->getIntrinsicID()) {
case Intrinsic::uadd_with_overflow:
case Intrinsic::sadd_with_overflow:
if (*EV.idx_begin() == 0) { // Normal result.
Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
EraseInstFromFunction(*II);
return BinaryOperator::CreateAdd(LHS, RHS);
}
// If the normal result of the add is dead, and the RHS is a constant,
// we can transform this into a range comparison.
// overflow = uadd a, -4 --> overflow = icmp ugt a, 3
if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
ConstantExpr::getNot(CI));
break;
case Intrinsic::usub_with_overflow:
case Intrinsic::ssub_with_overflow:
if (*EV.idx_begin() == 0) { // Normal result.
Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
EraseInstFromFunction(*II);
return BinaryOperator::CreateSub(LHS, RHS);
}
break;
case Intrinsic::umul_with_overflow:
case Intrinsic::smul_with_overflow:
if (*EV.idx_begin() == 0) { // Normal result.
Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
EraseInstFromFunction(*II);
return BinaryOperator::CreateMul(LHS, RHS);
}
break;
default:
break;
}
}
}
if (LoadInst *L = dyn_cast<LoadInst>(Agg))
// If the (non-volatile) load only has one use, we can rewrite this to a
// load from a GEP. This reduces the size of the load.
// FIXME: If a load is used only by extractvalue instructions then this
// could be done regardless of having multiple uses.
if (L->isSimple() && L->hasOneUse()) {
// extractvalue has integer indices, getelementptr has Value*s. Convert.
SmallVector<Value*, 4> Indices;
// Prefix an i32 0 since we need the first element.
Indices.push_back(Builder->getInt32(0));
for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
I != E; ++I)
Indices.push_back(Builder->getInt32(*I));
// We need to insert these at the location of the old load, not at that of
// the extractvalue.
Builder->SetInsertPoint(L->getParent(), L);
Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
// Returning the load directly will cause the main loop to insert it in
// the wrong spot, so use ReplaceInstUsesWith().
return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
}
// We could simplify extracts from other values. Note that nested extracts may
// already be simplified implicitly by the above: extract (extract (insert) )
// will be translated into extract ( insert ( extract ) ) first and then just
// the value inserted, if appropriate. Similarly for extracts from single-use
// loads: extract (extract (load)) will be translated to extract (load (gep))
// and if again single-use then via load (gep (gep)) to load (gep).
// However, double extracts from e.g. function arguments or return values
// aren't handled yet.
return nullptr;
}
enum Personality_Type {
Unknown_Personality,
GNU_Ada_Personality,
GNU_CXX_Personality,
GNU_ObjC_Personality
};
/// RecognizePersonality - See if the given exception handling personality
/// function is one that we understand. If so, return a description of it;
/// otherwise return Unknown_Personality.
static Personality_Type RecognizePersonality(Value *Pers) {
Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
if (!F)
return Unknown_Personality;
return StringSwitch<Personality_Type>(F->getName())
.Case("__gnat_eh_personality", GNU_Ada_Personality)
.Case("__gxx_personality_v0", GNU_CXX_Personality)
.Case("__objc_personality_v0", GNU_ObjC_Personality)
.Default(Unknown_Personality);
}
/// isCatchAll - Return 'true' if the given typeinfo will match anything.
static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
switch (Personality) {
case Unknown_Personality:
return false;
case GNU_Ada_Personality:
// While __gnat_all_others_value will match any Ada exception, it doesn't
// match foreign exceptions (or didn't, before gcc-4.7).
return false;
case GNU_CXX_Personality:
case GNU_ObjC_Personality:
return TypeInfo->isNullValue();
}
llvm_unreachable("Unknown personality!");
}
static bool shorter_filter(const Value *LHS, const Value *RHS) {
return
cast<ArrayType>(LHS->getType())->getNumElements()
<
cast<ArrayType>(RHS->getType())->getNumElements();
}
Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
// The logic here should be correct for any real-world personality function.
// However if that turns out not to be true, the offending logic can always
// be conditioned on the personality function, like the catch-all logic is.
Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
// Simplify the list of clauses, eg by removing repeated catch clauses
// (these are often created by inlining).
bool MakeNewInstruction = false; // If true, recreate using the following:
SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
bool isLastClause = i + 1 == e;
if (LI.isCatch(i)) {
// A catch clause.
Constant *CatchClause = LI.getClause(i);
Constant *TypeInfo = CatchClause->stripPointerCasts();
// If we already saw this clause, there is no point in having a second
// copy of it.
if (AlreadyCaught.insert(TypeInfo).second) {
// This catch clause was not already seen.
NewClauses.push_back(CatchClause);
} else {
// Repeated catch clause - drop the redundant copy.
MakeNewInstruction = true;
}
// If this is a catch-all then there is no point in keeping any following
// clauses or marking the landingpad as having a cleanup.
if (isCatchAll(Personality, TypeInfo)) {
if (!isLastClause)
MakeNewInstruction = true;
CleanupFlag = false;
break;
}
} else {
// A filter clause. If any of the filter elements were already caught
// then they can be dropped from the filter. It is tempting to try to
// exploit the filter further by saying that any typeinfo that does not
// occur in the filter can't be caught later (and thus can be dropped).
// However this would be wrong, since typeinfos can match without being
// equal (for example if one represents a C++ class, and the other some
// class derived from it).
assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Constant *FilterClause = LI.getClause(i);
ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
unsigned NumTypeInfos = FilterType->getNumElements();
// An empty filter catches everything, so there is no point in keeping any
// following clauses or marking the landingpad as having a cleanup. By
// dealing with this case here the following code is made a bit simpler.
if (!NumTypeInfos) {
NewClauses.push_back(FilterClause);
if (!isLastClause)
MakeNewInstruction = true;
CleanupFlag = false;
break;
}
bool MakeNewFilter = false; // If true, make a new filter.
SmallVector<Constant *, 16> NewFilterElts; // New elements.
if (isa<ConstantAggregateZero>(FilterClause)) {
// Not an empty filter - it contains at least one null typeinfo.
assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
Constant *TypeInfo =
Constant::getNullValue(FilterType->getElementType());
// If this typeinfo is a catch-all then the filter can never match.
if (isCatchAll(Personality, TypeInfo)) {
// Throw the filter away.
MakeNewInstruction = true;
continue;
}
// There is no point in having multiple copies of this typeinfo, so
// discard all but the first copy if there is more than one.
NewFilterElts.push_back(TypeInfo);
if (NumTypeInfos > 1)
MakeNewFilter = true;
} else {
ConstantArray *Filter = cast<ConstantArray>(FilterClause);
SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
NewFilterElts.reserve(NumTypeInfos);
// Remove any filter elements that were already caught or that already
// occurred in the filter. While there, see if any of the elements are
// catch-alls. If so, the filter can be discarded.
bool SawCatchAll = false;
for (unsigned j = 0; j != NumTypeInfos; ++j) {
Constant *Elt = Filter->getOperand(j);
Constant *TypeInfo = Elt->stripPointerCasts();
if (isCatchAll(Personality, TypeInfo)) {
// This element is a catch-all. Bail out, noting this fact.
SawCatchAll = true;
break;
}
if (AlreadyCaught.count(TypeInfo))
// Already caught by an earlier clause, so having it in the filter
// is pointless.
continue;
// There is no point in having multiple copies of the same typeinfo in
// a filter, so only add it if we didn't already.
if (SeenInFilter.insert(TypeInfo).second)
NewFilterElts.push_back(cast<Constant>(Elt));
}
// A filter containing a catch-all cannot match anything by definition.
if (SawCatchAll) {
// Throw the filter away.
MakeNewInstruction = true;
continue;
}
// If we dropped something from the filter, make a new one.
if (NewFilterElts.size() < NumTypeInfos)
MakeNewFilter = true;
}
if (MakeNewFilter) {
FilterType = ArrayType::get(FilterType->getElementType(),
NewFilterElts.size());
FilterClause = ConstantArray::get(FilterType, NewFilterElts);
MakeNewInstruction = true;
}
NewClauses.push_back(FilterClause);
// If the new filter is empty then it will catch everything so there is
// no point in keeping any following clauses or marking the landingpad
// as having a cleanup. The case of the original filter being empty was
// already handled above.
if (MakeNewFilter && !NewFilterElts.size()) {
assert(MakeNewInstruction && "New filter but not a new instruction!");
CleanupFlag = false;
break;
}
}
}
// If several filters occur in a row then reorder them so that the shortest
// filters come first (those with the smallest number of elements). This is
// advantageous because shorter filters are more likely to match, speeding up
// unwinding, but mostly because it increases the effectiveness of the other
// filter optimizations below.
for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
unsigned j;
// Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
for (j = i; j != e; ++j)
if (!isa<ArrayType>(NewClauses[j]->getType()))
break;
// Check whether the filters are already sorted by length. We need to know
// if sorting them is actually going to do anything so that we only make a
// new landingpad instruction if it does.
for (unsigned k = i; k + 1 < j; ++k)
if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
// Not sorted, so sort the filters now. Doing an unstable sort would be
// correct too but reordering filters pointlessly might confuse users.
std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
shorter_filter);
MakeNewInstruction = true;
break;
}
// Look for the next batch of filters.
i = j + 1;
}
// If typeinfos matched if and only if equal, then the elements of a filter L
// that occurs later than a filter F could be replaced by the intersection of
// the elements of F and L. In reality two typeinfos can match without being
// equal (for example if one represents a C++ class, and the other some class
// derived from it) so it would be wrong to perform this transform in general.
// However the transform is correct and useful if F is a subset of L. In that
// case L can be replaced by F, and thus removed altogether since repeating a
// filter is pointless. So here we look at all pairs of filters F and L where
// L follows F in the list of clauses, and remove L if every element of F is
// an element of L. This can occur when inlining C++ functions with exception
// specifications.
for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
// Examine each filter in turn.
Value *Filter = NewClauses[i];
ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
if (!FTy)
// Not a filter - skip it.
continue;
unsigned FElts = FTy->getNumElements();
// Examine each filter following this one. Doing this backwards means that
// we don't have to worry about filters disappearing under us when removed.
for (unsigned j = NewClauses.size() - 1; j != i; --j) {
Value *LFilter = NewClauses[j];
ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
if (!LTy)
// Not a filter - skip it.
continue;
// If Filter is a subset of LFilter, i.e. every element of Filter is also
// an element of LFilter, then discard LFilter.
SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
// If Filter is empty then it is a subset of LFilter.
if (!FElts) {
// Discard LFilter.
NewClauses.erase(J);
MakeNewInstruction = true;
// Move on to the next filter.
continue;
}
unsigned LElts = LTy->getNumElements();
// If Filter is longer than LFilter then it cannot be a subset of it.
if (FElts > LElts)
// Move on to the next filter.
continue;
// At this point we know that LFilter has at least one element.
if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
// Filter is a subset of LFilter iff Filter contains only zeros (as we
// already know that Filter is not longer than LFilter).
if (isa<ConstantAggregateZero>(Filter)) {
assert(FElts <= LElts && "Should have handled this case earlier!");
// Discard LFilter.
NewClauses.erase(J);
MakeNewInstruction = true;
}
// Move on to the next filter.
continue;
}
ConstantArray *LArray = cast<ConstantArray>(LFilter);
if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
// Since Filter is non-empty and contains only zeros, it is a subset of
// LFilter iff LFilter contains a zero.
assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
for (unsigned l = 0; l != LElts; ++l)
if (LArray->getOperand(l)->isNullValue()) {
// LFilter contains a zero - discard it.
NewClauses.erase(J);
MakeNewInstruction = true;
break;
}
// Move on to the next filter.
continue;
}
// At this point we know that both filters are ConstantArrays. Loop over
// operands to see whether every element of Filter is also an element of
// LFilter. Since filters tend to be short this is probably faster than
// using a method that scales nicely.
ConstantArray *FArray = cast<ConstantArray>(Filter);
bool AllFound = true;
for (unsigned f = 0; f != FElts; ++f) {
Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
AllFound = false;
for (unsigned l = 0; l != LElts; ++l) {
Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
if (LTypeInfo == FTypeInfo) {
AllFound = true;
break;
}
}
if (!AllFound)
break;
}
if (AllFound) {
// Discard LFilter.
NewClauses.erase(J);
MakeNewInstruction = true;
}
// Move on to the next filter.
}
}
// If we changed any of the clauses, replace the old landingpad instruction
// with a new one.
if (MakeNewInstruction) {
LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
LI.getPersonalityFn(),
NewClauses.size());
for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
NLI->addClause(NewClauses[i]);
// A landing pad with no clauses must have the cleanup flag set. It is
// theoretically possible, though highly unlikely, that we eliminated all
// clauses. If so, force the cleanup flag to true.
if (NewClauses.empty())
CleanupFlag = true;
NLI->setCleanup(CleanupFlag);
return NLI;
}
// Even if none of the clauses changed, we may nonetheless have understood
// that the cleanup flag is pointless. Clear it if so.
if (LI.isCleanup() != CleanupFlag) {
assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
LI.setCleanup(CleanupFlag);
return &LI;
}
return nullptr;
}
/// TryToSinkInstruction - Try to move the specified instruction from its
/// current block into the beginning of DestBlock, which can only happen if it's
/// safe to move the instruction past all of the instructions between it and the
/// end of its block.
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
assert(I->hasOneUse() && "Invariants didn't hold!");
// Cannot move control-flow-involving, volatile loads, vaarg, etc.
if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
isa<TerminatorInst>(I))
return false;
// Do not sink alloca instructions out of the entry block.
if (isa<AllocaInst>(I) && I->getParent() ==
&DestBlock->getParent()->getEntryBlock())
return false;
// We can only sink load instructions if there is nothing between the load and
// the end of block that could change the value.
if (I->mayReadFromMemory()) {
for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Scan != E; ++Scan)
if (Scan->mayWriteToMemory())
return false;
}
BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
I->moveBefore(InsertPos);
++NumSunkInst;
return true;
}
/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we constant fold and DCE instructions as we go, to avoid adding
/// them to the worklist (this significantly speeds up instcombine on code where
/// many instructions are dead or constant). Additionally, if we find a branch
/// whose condition is a known constant, we only visit the reachable successors.
///
static bool AddReachableCodeToWorklist(BasicBlock *BB,
SmallPtrSetImpl<BasicBlock*> &Visited,
InstCombiner &IC,
const DataLayout *DL,
const TargetLibraryInfo *TLI) {
bool MadeIRChange = false;
SmallVector<BasicBlock*, 256> Worklist;
Worklist.push_back(BB);
SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
DenseMap<ConstantExpr*, Constant*> FoldedConstants;
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second)
continue;
for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Instruction *Inst = BBI++;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst, TLI)) {
++NumDeadInst;
DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
Inst->eraseFromParent();
continue;
}
// ConstantProp instruction if trivially constant.
if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
<< *Inst << '\n');
Inst->replaceAllUsesWith(C);
++NumConstProp;
Inst->eraseFromParent();
continue;
}
if (DL) {
// See if we can constant fold its operands.
for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
i != e; ++i) {
ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
if (CE == nullptr) continue;
Constant*& FoldRes = FoldedConstants[CE];
if (!FoldRes)
FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
if (!FoldRes)
FoldRes = CE;
if (FoldRes != CE) {
*i = FoldRes;
MadeIRChange = true;
}
}
}
InstrsForInstCombineWorklist.push_back(Inst);
}
// Recursively visit successors. If this is a branch or switch on a
// constant, only visit the reachable successor.
TerminatorInst *TI = BB->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Worklist.push_back(ReachableBB);
continue;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
// See if this is an explicit destination.
for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
i != e; ++i)
if (i.getCaseValue() == Cond) {
BasicBlock *ReachableBB = i.getCaseSuccessor();
Worklist.push_back(ReachableBB);
continue;
}
// Otherwise it is the default destination.
Worklist.push_back(SI->getDefaultDest());
continue;
}
}
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Worklist.push_back(TI->getSuccessor(i));
} while (!Worklist.empty());
// Once we've found all of the instructions to add to instcombine's worklist,
// add them in reverse order. This way instcombine will visit from the top
// of the function down. This jives well with the way that it adds all uses
// of instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
InstrsForInstCombineWorklist.size());
return MadeIRChange;
}
bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
MadeIRChange = false;
DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
{
// Do a depth-first traversal of the function, populate the worklist with
// the reachable instructions. Ignore blocks that are not reachable. Keep
// track of which blocks we visit.
SmallPtrSet<BasicBlock*, 64> Visited;
MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
TLI);
// Do a quick scan over the function. If we find any blocks that are
// unreachable, remove any instructions inside of them. This prevents
// the instcombine code from having to deal with some bad special cases.
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
if (Visited.count(BB)) continue;
// Delete the instructions backwards, as it has a reduced likelihood of
// having to update as many def-use and use-def chains.
Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
while (EndInst != BB->begin()) {
// Delete the next to last instruction.
BasicBlock::iterator I = EndInst;
Instruction *Inst = --I;
if (!Inst->use_empty())
Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
if (isa<LandingPadInst>(Inst)) {
EndInst = Inst;
continue;
}
if (!isa<DbgInfoIntrinsic>(Inst)) {
++NumDeadInst;
MadeIRChange = true;
}
Inst->eraseFromParent();
}
}
}
while (!Worklist.isEmpty()) {
Instruction *I = Worklist.RemoveOne();
if (I == nullptr) continue; // skip null values.
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I, TLI)) {
DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
EraseInstFromFunction(*I);
++NumDeadInst;
MadeIRChange = true;
continue;
}
// Instruction isn't dead, see if we can constant propagate it.
if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
// Add operands to the worklist.
ReplaceInstUsesWith(*I, C);
++NumConstProp;
EraseInstFromFunction(*I);
MadeIRChange = true;
continue;
}
// See if we can trivially sink this instruction to a successor basic block.
if (I->hasOneUse()) {
BasicBlock *BB = I->getParent();
Instruction *UserInst = cast<Instruction>(*I->user_begin());
BasicBlock *UserParent;
// Get the block the use occurs in.
if (PHINode *PN = dyn_cast<PHINode>(UserInst))
UserParent = PN->getIncomingBlock(*I->use_begin());
else
UserParent = UserInst->getParent();
if (UserParent != BB) {
bool UserIsSuccessor = false;
// See if the user is one of our successors.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
if (*SI == UserParent) {
UserIsSuccessor = true;
break;
}
// If the user is one of our immediate successors, and if that successor
// only has us as a predecessors (we'd have to split the critical edge
// otherwise), we can keep going.
if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
// Okay, the CFG is simple enough, try to sink this instruction.
if (TryToSinkInstruction(I, UserParent)) {
MadeIRChange = true;
// We'll add uses of the sunk instruction below, but since sinking
// can expose opportunities for it's *operands* add them to the
// worklist
for (Use &U : I->operands())
if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
Worklist.Add(OpI);
}
}
}
}
// Now that we have an instruction, try combining it to simplify it.
Builder->SetInsertPoint(I->getParent(), I);
Builder->SetCurrentDebugLocation(I->getDebugLoc());
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
if (Instruction *Result = runOnInstruction(I)) {
//if (Instruction *Result = visit(*I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
DEBUG(dbgs() << "IC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
if (!I->getDebugLoc().isUnknown())
Result->setDebugLoc(I->getDebugLoc());
// Everything uses the new instruction now.
I->replaceAllUsesWith(Result);
// Move the name to the new instruction first.
Result->takeName(I);
// Push the new instruction and any users onto the worklist.
Worklist.Add(Result);
Worklist.AddUsersToWorkList(*Result);
// Insert the new instruction into the basic block...
BasicBlock *InstParent = I->getParent();
BasicBlock::iterator InsertPos = I;
// If we replace a PHI with something that isn't a PHI, fix up the
// insertion point.
if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
InsertPos = InstParent->getFirstInsertionPt();
InstParent->getInstList().insert(InsertPos, Result);
EraseInstFromFunction(*I);
} else {
#ifndef NDEBUG
DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
#endif
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I, TLI)) {
EraseInstFromFunction(*I);
} else {
Worklist.Add(I);
Worklist.AddUsersToWorkList(*I);
}
}
MadeIRChange = true;
}
}
Worklist.Zap();
return MadeIRChange;
}
namespace {
class InstCombinerLibCallSimplifier final : public LibCallSimplifier {
InstCombiner *IC;
public:
InstCombinerLibCallSimplifier(const DataLayout *DL,
const TargetLibraryInfo *TLI,
InstCombiner *IC)
: LibCallSimplifier(DL, TLI) {
this->IC = IC;
}
/// replaceAllUsesWith - override so that instruction replacement
/// can be defined in terms of the instruction combiner framework.
void replaceAllUsesWith(Instruction *I, Value *With) const override {
IC->ReplaceInstUsesWith(*I, With);
}
};
}
bool hasNoSignedWrap(Value *I) {
if (OverflowingBinaryOperator *op = dyn_cast<OverflowingBinaryOperator>(I)) {
return op->hasNoSignedWrap();
}
return false;
}
bool hasNoUnsignedWrap(Value *I) {
if (OverflowingBinaryOperator *op = dyn_cast<OverflowingBinaryOperator>(I)) {
return op->hasNoUnsignedWrap();
}
return false;
}
bool isExact(Value *I) {
if (PossiblyExactOperator *op = dyn_cast<PossiblyExactOperator>(I)) {
return op->isExact();
}
return false;
}
/*
bool WillNotOverflowSignedMul(const APInt &x, const APInt &y) {
bool Overflow;
APInt z = x.smul_ov(y, Overflow);
return !Overflow;
}
*/
bool WillNotOverflowUnsignedMul(const APInt &x, const APInt &y) {
bool Overflow;
APInt z = x.umul_ov(y, Overflow);
return !Overflow;
}
bool WillNotOverflowUnsignedShl(const APInt &x, const APInt &y) {
bool Overflow;
APInt z = x.ushl_ov(y, Overflow);
return !Overflow;
}
APInt InstCombiner::computeKnownZeroBits(Value *V) {
unsigned BitWidth = V->getType()->getScalarSizeInBits();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
computeKnownBits(V, KnownZero, KnownOne);
return KnownZero;
}
APInt InstCombiner::computeKnownOneBits(Value *V) {
unsigned BitWidth = V->getType()->getScalarSizeInBits();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
computeKnownBits(V, KnownZero, KnownOne);
return KnownOne;
}
// ----------------------------
// Insert InstCombiner::runOnInstruction here
// ----------------------------
#include "alive.inc"
bool InstCombiner::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DL = DLP ? &DLP->getDataLayout() : nullptr;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
TLI = &getAnalysis<TargetLibraryInfo>();
// Minimizing size?
MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::MinSize);
/// Builder - This is an IRBuilder that automatically inserts new
/// instructions into the worklist when they are created.
IRBuilder<true, TargetFolder, InstCombineIRInserter> TheBuilder(
F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, AC));
Builder = &TheBuilder;
InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
Simplifier = &TheSimplifier;
bool EverMadeChange = false;
// Lower dbg.declare intrinsics otherwise their value may be clobbered
// by instcombiner.
EverMadeChange = LowerDbgDeclare(F);
// Iterate while there is work to do.
unsigned Iteration = 0;
while (DoOneIteration(F, Iteration++))
EverMadeChange = true;
Builder = nullptr;
return EverMadeChange;
}
FunctionPass *llvm::createInstructionCombiningPass() {
return new InstCombiner();
}
| [
"davemm@cs.rutgers.edu"
] | davemm@cs.rutgers.edu |
ac5941793ce65341f496757aff066b30b8d4ecfe | e19c6e8f6fc43451055a59e2ee98a64c77de877e | /breath/cpu/example/cpu.cpp | bd62f7c619fdbee0c622139aa718b386be431ec7 | [
"BSD-3-Clause"
] | permissive | erez-o/breath | 606a5e445ca2516c9131ca7e28fa37c12c525015 | adf197b4e959beffce11e090c5e806d2ff4df38a | refs/heads/master | 2023-01-11T20:24:16.573636 | 2020-11-01T03:06:57 | 2020-11-01T03:06:57 | 299,582,899 | 0 | 0 | NOASSERTION | 2020-09-29T10:29:39 | 2020-09-29T10:29:38 | null | UTF-8 | C++ | false | false | 2,953 | cpp | // ===========================================================================
// This is an open source non-commercial project.
// Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java:
// http://www.viva64.com
// ===========================================================================
// Copyright 2016 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
//
// Reference:
// Intel(R) 64 and IA-32 Architectures Developer's Manual: Vol. 2A.
// ---------------------------------------------------------------------------
#include "breath/cpu/get_cpuid_info.hpp"
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <ostream>
#include <string>
namespace {
bool
has_processor_brand_string()
{
std::uint32_t const mask = 0x8000'0000 ;
cpuid_result const r = get_cpuid_info( mask, 0 ) ;
return (r.eax & mask) != 0 &&
r.eax >= (mask + 4) ;
}
std::string
processor_brand_string()
{
std::uint32_t const from = 0x8000'0002 ;
std::uint32_t const to = 0x8000'0004 ;
std::size_t const len = 16 * ( to - from + 1 ) ;
char brand_string[ len ] ;
for ( std::uint32_t i = from ; i <= to ; ++ i ) {
cpuid_result const info = get_cpuid_info( i, 0 ) ;
char * const p = brand_string + 16 * ( i - from ) ;
std::memcpy( p, &info.eax, sizeof( info.eax ) ) ;
std::memcpy( p + 4, &info.ebx, sizeof( info.ebx ) ) ;
std::memcpy( p + 8, &info.ecx, sizeof( info.ecx ) ) ;
std::memcpy( p + 12, &info.edx, sizeof( info.edx ) ) ;
}
return std::string( brand_string ) ;
}
std::string
cpu_vendor_id_string()
{
cpuid_result const info = get_cpuid_info( 0, 0 ) ;
int const len = 12 ;
char id_string[ len ] ;
std::memcpy( id_string, &info.ebx, sizeof( info.ebx ) ) ;
std::memcpy( id_string + 4, &info.edx, sizeof( info.edx ) ) ;
std::memcpy( id_string + 8, &info.ecx, sizeof( info.ecx ) ) ;
return std::string( id_string, len ) ;
}
}
int
main()
{
std::cout << "CPU vendor ID string: " <<
cpu_vendor_id_string() << std::endl ;
std::cout << "Processor brand string: " << ( has_processor_brand_string()
? processor_brand_string()
: "<not available>" )
<< std::endl ;
}
// Local Variables:
// mode: c++
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim: set ft=cpp et sts=4 sw=4:
| [
"gennaro.prota+github@gmail.com"
] | gennaro.prota+github@gmail.com |
d802ba345ed93836162ed5271e71aac24d88b491 | e8adb71ab57b24eb0f9fdacea5d51e6cef5a244e | /src/Plugins/VerilatorPlugin/VerilatorIntegrationLibrary/src/peripherals/fastvdma.h | 592c77716238904e73da248b7eb7c4eccb3aecd5 | [
"MIT"
] | permissive | mtrzas/renode | 97a895329e01a40ec8cf08dd46e9de0a9a9ad937 | 4c843c143771b0e005613149f1f22f7719e3d187 | refs/heads/master | 2023-07-31T21:59:58.766572 | 2021-09-06T11:10:48 | 2021-09-08T15:09:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | h | //
// Copyright (c) 2010-2021 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
#include "../renode_bus.h"
#include "../buses/bus.h"
struct FASTVDMA : RenodeAgent
{
public:
FASTVDMA(BaseBus* bus, uint8_t* irq_reader=nullptr, uint8_t* irq_writer=nullptr);
void eval();
uint8_t* irq_reader;
uint8_t* irq_writer;
uint8_t prev_irq_reader;
uint8_t prev_irq_writer;
const uint8_t writer_addr = 0;
const uint8_t reader_addr = 1;
};
| [
"wkuna@internships.antmicro.com"
] | wkuna@internships.antmicro.com |
2f2a211f565241e1afb2d83de0fce3c4589d55bc | dd7f94de72394e48fdbef4214808fb568c3c1ffe | /calc.cpp | 33fc1fc5dc309c606f81f69b1387b11b9dc96eeb | [] | no_license | Jaishree-Gharde/esdl-jaishree-gharde | a88ae27d8a0d5edcc21eb216a11bf1a4b2673af5 | bc2d68bb9e786755e53d0bbd4bf33cdddff197f2 | refs/heads/master | 2021-01-01T17:46:57.520998 | 2014-07-30T03:20:25 | 2014-07-30T03:20:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include<iostream.h>
using namespace std;
int main()
{
cout<<"Jaishree";
return 0;
}
| [
"jaishree.gharde@cumminscollege.in"
] | jaishree.gharde@cumminscollege.in |
a8a9ef5dadeabb9b4e88cc58b1b133e2e3c4b3be | 9ab2f13980526e713a41a1451481f978873756f5 | /prj.sandbox/markup/src/mainframe.h | c202270f8128423fe2664a0b19789e8dbab2ad3b | [] | no_license | vokintsop/visiworld | c77f37efce7a7035da4d88bc1546a88a0b7a0ff6 | 94a7b563dc79ba761611cdf9b774506b8aff2e90 | refs/heads/master | 2021-01-19T03:02:04.427416 | 2016-07-25T12:15:26 | 2016-07-25T12:15:26 | 45,334,758 | 0 | 2 | null | 2016-01-18T08:26:01 | 2015-11-01T09:32:55 | C++ | UTF-8 | C++ | false | false | 346 | h | #ifndef __MAINFRAME_H
#define __MAINFRAME_H
#include "geomap/geomapeditor.h"
#include "markup/markupeditor.h"
#include "maptorealworld.h"
class MarkupMainFrame
{
public:
Ptr< GeoMapEditor > pGeoMapEditor; // singleton
Ptr< MarkupEditor > pMarkupEditor;
Ptr< Camera2DPoseEstimator> pCamPoseEst;
};
#endif // __MAINFRAME_H | [
"Vassili.Postnikov@gmail.com"
] | Vassili.Postnikov@gmail.com |
6eea2fb4af4bd2f0b59fb14a53a0e54a03fb76f7 | e0735384c3fb5948c0d42cdf7ec8f7ef8d90ed32 | /Курсовой проект Новик Виктории — оригинал/NVA_2020/Rules.h | a74405b2bc8c21bf24488dee287962be1b6c2ba4 | [] | no_license | vnvika/NVA_2020 | 8e1ee3a8c0f956e9a6af5486b84a35006c465049 | 4628f30b28e84d222cbc6b782d2216df46136147 | refs/heads/main | 2023-02-18T20:16:52.884877 | 2021-01-21T13:28:15 | 2021-01-21T13:28:15 | 331,633,699 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 8,641 | h | #pragma once
#include "GRB.h"
namespace GRB
{
Greibach greibach(NS('S'), TS('$'), 20,
Rule(NS('S'), GRB_ERROR_SERIES, 3, // Неверная структура программы
Rule::Chain(6, TS('t'), TS('f'), TS('i'), NS('P'), NS('T'), NS('S')),
Rule::Chain(6, TS('g'), TS('f'), TS('i'), NS('P'), NS('G'), NS('S')),
Rule::Chain(4, TS('m'), TS('{'), NS('K'), TS('}'))
),
Rule(NS('T'), GRB_ERROR_SERIES + 2, 2, // Ошибка в теле функции
Rule::Chain(3, TS('{'), NS('Q'), TS('}')),
Rule::Chain(4, TS('{'), NS('K'), NS('Q'), TS('}'))
),
Rule(NS('P'), GRB_ERROR_SERIES + 1, 2, // Не найден список параметров функции
Rule::Chain(3, TS('('), NS('E'), TS(')')),
Rule::Chain(2, TS('('), TS(')'))
),
Rule(NS('E'), GRB_ERROR_SERIES + 3, 2, // Ошибка в списке параметров функции
Rule::Chain(4, TS('t'), TS('i'), TS(','), NS('E')),
Rule::Chain(2, TS('t'), TS('i'))
),
Rule(NS('F'), GRB_ERROR_SERIES + 4, 2, // Ошибка в вызове функции
Rule::Chain(3, TS('('), NS('N'), TS(')')),
Rule::Chain(2, TS('('), TS(')'))
),
Rule(NS('N'), GRB_ERROR_SERIES + 5, 4, // Ошибка в списке параметров функции
Rule::Chain(1, TS('i')),
Rule::Chain(1, TS('l')),
Rule::Chain(3, TS('i'), TS(','), NS('N')),
Rule::Chain(3, TS('l'), TS(','), NS('N'))
),
Rule(NS('R'), GRB_ERROR_SERIES + 6, 4, // Ошибка при констуировании условного выражения
Rule::Chain(2, TS('r'), NS('Y')),
Rule::Chain(2, TS('w'), NS('Y')),
Rule::Chain(4, TS('r'), NS('Y'), TS('w'), NS('Y')),
Rule::Chain(4, TS('w'), NS('Y'), TS('r'), NS('Y'))
),
Rule(NS('Z'), GRB_ERROR_SERIES + 8, 4, // Ошибка в условии цикла/условного выражения
Rule::Chain(3, TS('i'), NS('L'), TS('i')),
Rule::Chain(3, TS('i'), NS('L'), TS('l')),
Rule::Chain(3, TS('l'), NS('L'), TS('l')),
Rule::Chain(3, TS('l'), NS('L'), TS('i'))
),
Rule(NS('L'), GRB_ERROR_SERIES + 9, 4, // Неверный условный оператор
Rule::Chain(1, TS('<')),
Rule::Chain(1, TS('>')),
Rule::Chain(1, TS('&')),
Rule::Chain(1, TS('!'))
),
Rule(NS('A'), GRB_ERROR_SERIES + 10, 5, // Неверный арифметический оператор
Rule::Chain(1, TS('+')),
Rule::Chain(1, TS('-')),
Rule::Chain(1, TS('*')),
Rule::Chain(1, TS('%')),
Rule::Chain(1, TS('/'))
),
Rule(NS('W'), GRB_ERROR_SERIES + 11, 12, // Ошибка в арифметичском выражении
Rule::Chain(1, TS('i')),
Rule::Chain(1, TS('l')),
Rule::Chain(3, TS('('), NS('W'), TS(')')),
Rule::Chain(4, TS('('), TS('-'), TS('i'), TS(')')),
Rule::Chain(6, TS('('), TS('-'), TS('i'), TS(')'), NS('A'), NS('W')),
Rule::Chain(5, TS('('), NS('W'), TS(')'), NS('A'), NS('W')),
Rule::Chain(2, TS('i'), NS('F')),
Rule::Chain(2, TS('p'), NS('F')),
Rule::Chain(3, TS('i'), NS('A'), NS('W')),
Rule::Chain(3, TS('l'), NS('A'), NS('W')),
Rule::Chain(4, TS('i'), NS('F'), NS('A'), NS('W')),
Rule::Chain(4, TS('p'), NS('F'), NS('A'), NS('W'))
),
Rule(NS('K'), GRB_ERROR_SERIES + 12, 22, // Недопустимая синтаксическая конструкция
Rule::Chain(4, TS('?'), NS('Z'), NS('R'), NS('K')), // is
Rule::Chain(5, TS('c'), NS('Z'), TS('d'), NS('H'), NS('K')), // while
Rule::Chain(3, TS('?'), NS('Z'), NS('R')), // is
Rule::Chain(4, TS('c'), NS('Z'), TS('d'), NS('H')), // while
Rule::Chain(7, TS('n'), TS('t'), TS('i'), TS('='), NS('V'), TS(';'), NS('K')), // декларация + присваивание
Rule::Chain(7, TS('n'), TS('t'), TS('i'), TS('='), NS('W'), TS(';'), NS('K')), // декларация + присваивание
Rule::Chain(5, TS('n'), TS('t'), TS('i'), TS(';'), NS('K')), // декларация
Rule::Chain(5, TS('i'), TS('='), NS('W'), TS(';'), NS('K')), // присваивание
Rule::Chain(5, TS('i'), TS(':'), NS('V'), TS(';'), NS('K')), // присваивание
Rule::Chain(4, TS('o'), NS('V'), TS(';'), NS('K')), // вывод
Rule::Chain(4, TS('^'), NS('V'), TS(';'), NS('K')), // перевод строки
Rule::Chain(6, TS('i'), TS('='), TS('U'), NS('F'), TS(';'), NS('K')), // присваивание c помощью вызова функции
Rule::Chain(4, TS('i'), NS('F'), TS(';'), NS('K')), // вызов функции
Rule::Chain(6, TS('n'), TS('t'), TS('i'), TS('='), NS('V'), TS(';')), // декларация + присваивание
Rule::Chain(6, TS('n'), TS('t'), TS('i'), TS('='), NS('W'), TS(';')), // декларация + присваивание
Rule::Chain(4, TS('i'), TS('='), NS('W'), TS(';')), // присваивание
Rule::Chain(4, TS('i'), TS(':'), NS('V'), TS(';')), // присваивание
Rule::Chain(4, TS('n'), TS('t'), TS('i'), TS(';')), // декларация
Rule::Chain(3, TS('o'), NS('V'), TS(';')), // вывод
Rule::Chain(3, TS('^'), NS('V'), TS(';')), // перевод строки
Rule::Chain(5, TS('i'), TS('='), TS('U'), NS('F'), TS(';')), // присваивание c помощью вызова функции
Rule::Chain(3, TS('i'), NS('F'), TS(';')) // вызов функции
),
Rule(NS('X'), GRB_ERROR_SERIES + 13, 12, // Недопустимая синтаксическая конструкция в теле цикла/условного выражения
Rule::Chain(5, TS('i'), TS('='), NS('W'), TS(';'), NS('X')), // присваивание
Rule::Chain(5, TS('i'), TS(':'), NS('V'), TS(';'), NS('X')), // присваивание
Rule::Chain(4, TS('o'), NS('V'), TS(';'), NS('X')), // вывод
Rule::Chain(4, TS('^'), NS('V'), TS(';'), NS('X')), // перевод строки
Rule::Chain(6, TS('i'), TS('='), TS('U'), NS('F'), TS(';'), NS('K')), // присваивание c помощью вызова функции
Rule::Chain(4, TS('i'), NS('F'), TS(';'), NS('K')), // вызов функции
Rule::Chain(4, TS('i'), TS('='), NS('W'), TS(';')), // присваивание
Rule::Chain(3, TS('o'), NS('V'), TS(';')), // вывод
Rule::Chain(3, TS('^'), NS('V'), TS(';')), // перевод строки
Rule::Chain(4, TS('i'), TS(':'), NS('V'), TS(';')), // присваивание
Rule::Chain(5, TS('i'), TS('='), TS('U'), NS('F'), TS(';')), // присваивание c помощью вызова функции
Rule::Chain(3, TS('i'), NS('F'), TS(';')) // вызов функции
),
Rule(NS('Q'), GRB_ERROR_SERIES + 7, 4, // Ошибка при конструировании return
Rule::Chain(3, TS('e'), NS('V'), TS(';')),
Rule::Chain(6, TS('e'), TS('('), TS('-'), TS('i'), TS(')'), TS(';')),
Rule::Chain(2, TS('e'), TS(';')),
Rule::Chain(5, TS('e'), TS('('), TS('l'), TS(')'), TS(';'))
),
Rule(NS('B'), GRB_ERROR_SERIES + 14, 4, // Ошибка при конструировании условного выражения в цикле
Rule::Chain(3, TS('?'), NS('Z'), NS('R')),
Rule::Chain(4, TS('?'), NS('Z'), NS('R'), NS('X')),
Rule::Chain(5, TS('?'), NS('Z'), NS('R'), NS('X'), NS('B')),
Rule::Chain(4, TS('?'), NS('Z'), NS('R'), NS('B'))
),
Rule(NS('Y'), GRB_ERROR_SERIES + 16, 3, // Ошибка в теле условного выражения
Rule::Chain(4, TS('['), NS('X'), NS('Q'), TS(']')),
Rule::Chain(3, TS('['), NS('X'), TS(']')),
Rule::Chain(3, TS('['), NS('Q'), TS(']'))
),
Rule(NS('H'), GRB_ERROR_SERIES + 17, 3, // ошибка в теле цикла
Rule::Chain(4, TS('['), NS('X'), NS('B'), TS(']')),
Rule::Chain(3, TS('['), NS('B'), TS(']')),
Rule::Chain(3, TS('['), NS('X'), TS(']'))
),
Rule(NS('V'), GRB_ERROR_SERIES + 15, 2, // Правила для идентификаторов или литералов
Rule::Chain(1, TS('i')),
Rule::Chain(1, TS('l'))
),
Rule(NS('U'), GRB_ERROR_SERIES + 3, 2, // Правила для идентификатора функции
Rule::Chain(1, TS('i')),
Rule::Chain(1, TS('p'))
),
Rule(NS('G'), GRB_ERROR_SERIES + 2, 2, // ошибка в теле процедуры
Rule::Chain(4, TS('{'), TS('e'), TS(';'), TS('}')),
Rule::Chain(5, TS('{'), NS('K'), TS('e'), TS(';'), TS('}'))
)
);
} | [
"vnvika@icloud.com"
] | vnvika@icloud.com |
5008e690cf6edded8185a35eab0411dca3313ea7 | be2f96849070360cc71fb4f441760c2ad5cfeb34 | /lprdemo/lprdemo.cpp | 3b809c1666236f3b09a428038c553c8ca3dc831c | [] | no_license | HwangKC/HyperLPR_lib | 956e27a127d1e8f9fdfe79f06cf5c9254cc3eb34 | e0a253da81737fea60f979bc02d8818daa52b9bd | refs/heads/master | 2021-09-09T07:40:03.055408 | 2018-03-14T09:13:24 | 2018-03-14T09:13:24 | 125,017,644 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,059 | cpp | #include "stdafx.h"
#include <sys/stat.h>
#include <algorithm>
#include <functional>
#include <lprlib.h>
#define DEFAULT_DISPLAY_WIDTH (800)
#define DEFAULT_DISPLAT_HEIGHT (600)
std::vector<std::string> CH_PLATE_CODE{ "京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂",
"琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
"B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z","港","学","使","警","澳","挂","军","北","南","广","沈","兰","成","济","海","民","航","空" };
using namespace std;
template<class T>
static unsigned int levenshtein_distance(const T &s1, const T &s2)
{
const size_t len1 = s1.size(), len2 = s2.size();
std::vector<unsigned int> col(len2 + 1), prevCol(len2 + 1);
for (unsigned int i = 0; i < prevCol.size(); i++) prevCol[i] = i;
for (unsigned int i = 0; i < len1; i++)
{
col[0] = i + 1;
for (unsigned int j = 0; j < len2; j++)
col[j + 1] = min(
min(prevCol[1 + j] + 1, col[j] + 1),
prevCol[j] + (s1[i] == s2[j] ? 0 : 1));
col.swap(prevCol);
}
return prevCol[len2];
}
bool compare(const pr::PlateInfo & m1, const pr::PlateInfo & m2)
{
return m1.confidence > m2.confidence;
}
void TEST_ACC()
{
pr::PipelinePR prc("model/cascade.xml",
"model/HorizonalFinemapping.prototxt",
"model/HorizonalFinemapping.caffemodel",
"model/Segmentation.prototxt",
"model/Segmentation.caffemodel",
"model/CharacterRecognization.prototxt",
"model/CharacterRecognization.caffemodel",
"model/SegmentationFree.prototxt",
"model/SegmentationFree.caffemodel"
);
ifstream file;
string imagename;
int n = 0, correct = 0, j = 0, sum = 0;
char filename[] = "E:\\general_test\\1.txt";
string pathh = "E:\\general_test\\";
file.open(filename, ios::in);
// cout << filename << endl;
while (!file.eof())
{
file >> imagename;
string imgpath = pathh + imagename;
// cout << imgpath << endl;
std::cout << "------------------------------------------------" << endl;
cout << "图片名:" << imagename << endl;
cv::Mat image = cv::imread(imgpath);
// cv::imshow("image", image);
// cv::waitKey(0);
std::vector<pr::PlateInfo> res = prc.RunPiplineAsImage(image, pr::SEGMENTATION_FREE_METHOD);
float conf = 0;
vector<float> con;
vector<string> name;
for (auto st : res)
{
if (st.confidence > 0.1)
{
//std::cout << st.getPlateName() << " " << st.confidence << std::endl;
con.push_back(st.confidence);
name.push_back(st.getPlateName());
//conf += st.confidence;
}
else
cout << "no string" << endl;
}
// std::cout << conf << std::endl;
int num = con.size();
float max = 0;
string platestr, chpr, ch;
int diff = 0, dif = 0;
for (int i = 0; i < num; i++)
{
if (con.at(i) > max)
{
max = con.at(i);
platestr = name.at(i);
}
}
// cout << "max:"<<max << endl;
cout << "string:" << platestr << endl;
chpr = platestr.substr(0, 2);
ch = imagename.substr(0, 2);
diff = levenshtein_distance(imagename, platestr);
dif = diff - 4;
cout << "差距:" << dif << endl;
sum += dif;
if (ch != chpr) n++;
if (diff == 0) correct++;
j++;
}
float cha = 1 - float(n) / float(j);
std::cout << "------------------------------------------------" << endl;
cout << "车牌总数:" << j << endl;
cout << "汉字识别准确率:" << cha << endl;
float chaccuracy = 1 - float(sum - n * 2) / float(j * 8);
cout << "字符识别准确率:" << chaccuracy << endl;
cv::waitKey(0);
}
void TEST_PIPELINE(char* pszImagePath, int default_width)
{
if (pszImagePath == NULL)
{
std::cout << "NULL plate image!" << std::endl;
return;
}
struct _stat fileStat;
int ret = _stat(pszImagePath, &fileStat);
if (ret != 0) //文件不存在
{
std::cout << "Image " << pszImagePath << " do not exist!" << std::endl;
return;
}
//计时,计算处理一幅图片需要的时间
CWatchTimer wt;
wt.start();
pr::PipelinePR prc(
"model/cascade.xml",
"model/HorizonalFinemapping.prototxt",
"model/HorizonalFinemapping.caffemodel",
"model/Segmentation.prototxt",
"model/Segmentation.caffemodel",
"model/CharacterRecognization.prototxt",
"model/CharacterRecognization.caffemodel",
"model/SegmentationFree.prototxt",
"model/SegmentationFree.caffemodel"
);
std::cout << "PipelinePR initialze elapsed (us):" << wt.elapsed()*1e6 << std::endl;
std::cout << "Processing " << pszImagePath << std::endl;
wt.start();
cv::Mat image = cv::imread(pszImagePath);
std::cout << "reading image elapsed (us):" << wt.elapsed()*1e6 << std::endl;
std::cout << "Source Image size (w*h): " << image.cols << " * " << image.rows << std::endl;
cv::Mat image2;
bool bScaled = false;
if (image.cols > image.rows) //w>h
{
if (image.cols > DEFAULT_DISPLAY_WIDTH)
{
cv::resize(image, image2, cv::Size(DEFAULT_DISPLAY_WIDTH, image.rows * DEFAULT_DISPLAY_WIDTH / image.cols), cv::INTER_LINEAR);
bScaled = true;
}
}
else
{
if (image.rows > DEFAULT_DISPLAT_HEIGHT)
{
cv::resize(image, image2, cv::Size(image.cols * DEFAULT_DISPLAT_HEIGHT / image.rows, DEFAULT_DISPLAT_HEIGHT), cv::INTER_LINEAR);
bScaled = true;
}
}
//是否需要降低分辨率进行识别
if (default_width != 0)
{
if (image.cols > image.rows) //w>h
{
if (image.cols > default_width)
cv::resize(image, image, cv::Size(default_width, image.rows * default_width / image.cols), cv::INTER_LINEAR);
}
else
{
if (image.rows > default_width)
cv::resize(image, image, cv::Size(image.cols * default_width / image.rows, default_width), cv::INTER_LINEAR);
}
std::cout << "Scaled image size (w*h): " << image.cols << " * " << image.rows << std::endl;
}
wt.start();
//std::vector<pr::PlateInfo> res = prc.RunPiplineAsImage(image, pr::SEGMENTATION_BASED_METHOD/*pr::SEGMENTATION_FREE_METHOD*/);
std::vector<pr::PlateInfo> res = prc.RunPiplineAsImage(image, pr::SEGMENTATION_FREE_METHOD);
//获得识别需要的的时间,单位为秒,精度为微秒
double elapsed = wt.elapsed() * 1000;
std::cout << "Total Elapsed (ms):" << elapsed << std::endl;
//按置信度进行从大到小排序输出
std::sort(res.begin(), res.end(), compare);
for (auto st : res)
{
if (st.confidence > 0.75)
{
std::cout << "Plate: " << st.getPlateName() << "\tconfidence: " << st.confidence << std::endl;
cv::Rect region = st.getPlateRect();
cv::rectangle(image, cv::Point(region.x, region.y), cv::Point(region.x + region.width, region.y + region.height), cv::Scalar(255, 255, 0), 2);
}
}
if (bScaled)
cv::imshow("image", image2);
else
cv::imshow("image", image);
cv::waitKey(0);
}
void TEST_CAM(char* pszImagePath)
{
if (pszImagePath == NULL)
{
std::cout << "NULL plate video file path name!" << std::endl;
return;
}
struct _stat fileStat;
int ret = _stat(pszImagePath, &fileStat);
if (ret != 0) //文件不存在
{
std::cout << "Video " << pszImagePath << " do not exist!" << std::endl;
return;
}
cv::VideoCapture capture(pszImagePath);
cv::Mat frame;
pr::PipelinePR prc(
"model/cascade.xml",
"model/HorizonalFinemapping.prototxt",
"model/HorizonalFinemapping.caffemodel",
"model/Segmentation.prototxt",
"model/Segmentation.caffemodel",
"model/CharacterRecognization.prototxt",
"model/CharacterRecognization.caffemodel",
"model/SegmentationFree.prototxt",
"model/SegmentationFree.caffemodel"
);
while (1)
{
//读取下一帧
if (!capture.read(frame))
{
std::cout << "读取视频失败" << std::endl;
exit(1);
}
//
// cv::transpose(frame,frame);
// cv::flip(frame,frame,2);
// cv::resize(frame,frame,cv::Size(frame.cols/2,frame.rows/2));
std::vector<pr::PlateInfo> res = prc.RunPiplineAsImage(frame, pr::SEGMENTATION_FREE_METHOD);
for (auto st : res)
{
if (st.confidence > 0.75)
{
std::cout << st.getPlateName() << " " << st.confidence << std::endl;
cv::Rect region = st.getPlateRect();
cv::rectangle(frame, cv::Point(region.x, region.y), cv::Point(region.x + region.width, region.y + region.height), cv::Scalar(255, 255, 0), 2);
}
}
cv::imshow("image", frame);
cv::waitKey(1);
}
}
int main(int argc, char** argv)
{
if (argc < 2 || argc > 3)
{
std::cout << "Usage:" << argv[0] << " plate_image_path [SCALE_MAX_IMAGE_WIDTH|0]" << std::endl;
return 1;
}
int default_width = 0;
if (argc == 3)
default_width = atoi(argv[2]);
TEST_PIPELINE(argv[1], default_width);
return 0;
} | [
"huang.kechao@ronghechina.com"
] | huang.kechao@ronghechina.com |
0cbea18593cd279ddecc6fb2e672d802c21d6d7f | 13dafbe0e33771bd24496637a761c4703fb0beb4 | /Codeforces/CutAndPaste.cpp | ecee803397d8f427b9d0070c5353aa64cb27475c | [] | no_license | Owmicron/CPStuff | 121d498b2418141fa45d27fcbfa0a1fd851a4293 | 436f3234ed2f2930b13169f30428ded5da557b75 | refs/heads/master | 2022-12-30T06:43:18.425735 | 2020-10-20T12:21:59 | 2020-10-20T12:21:59 | 258,448,760 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,704 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#pragma comment(linker, "/stack:200000000")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef string str;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
typedef map <str,int> mapsi;
typedef map <str,int> :: iterator mapsitr;
typedef map <int , int> mint;
typedef map <ll , ll> mll;
typedef set <int> si;
typedef set <ll> sll;
typedef si :: iterator sitr;
typedef si :: reverse_iterator rsitr;
typedef sll :: iterator sltr;
typedef sll :: reverse_iterator rsltr;
#define mset multiset
typedef mset <int> msi;
typedef mset <ll> msll;
typedef msi :: iterator msitr;
typedef msi :: reverse_iterator msritr;
typedef msll :: iterator msltr;
typedef msll :: reverse_iterator mslritr;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define mp make_pair
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define fi first
#define se second
#define fs first.second
#define ss second.second
#define ff first.first
#define sf second.first
#define newl '\n'
#define fbo find_by_order
#define ook order_of_key
char to_upper (char x){
if( 97 <= int(x) && int(x) <= 122)return char(x-32);
else if( 65 <= int(x) && int(x) <= 90)return x;
}
char to_lower (char x){
if( 97 <= int(x) && int(x) <= 122)return x;
else if( 65 <= int(x) && int(x) <= 90)return char(x+32);
}
int numerize (char x){
if(48 <= int(x) && int(x) <= 57)return int(x-'0');
else if( 97 <= int(x) && int(x) <= 122)return int(x-96);
else if( 65 <= int(x) && int(x) <= 90)return int(x-64);
}
bool isect (int l1, int r1, int l2, int r2){
pii p1,p2;
p1 = mp(l1,r1); p2 = mp(l2,r2);
if(p1>p2)swap(p1,p2);
if(p2.fi <= p1.se)return true;
else return false;
}
ll quickpow (ll num1, ll num2, ll MOD){
if(num2==0)return 1;
else if(num2==1)return num1;
else{
ll temp = quickpow (num1,num2/2,MOD); ll res = ((temp%MOD) * (temp%MOD))%MOD;
if(num2%2==1) res = ((res%MOD)*(num1%MOD))%MOD; return res;
}
}
ll invmod (ll num, ll MOD){return quickpow (num,MOD-2,MOD);}
ll gcd (ll num1, ll num2){
if(num1 < num2) swap(num1,num2); ll num3 = num1 % num2 ;
while(num3 > 0){ num1 = num2; num2 = num3; num3 = num1 % num2;}
return num2;
}
ll lcm (ll num1 , ll num2){return (ll) (num1/__gcd(num1,num2))*num2;}
// end of Template
int t,sz,x,a[1000010];
str s;
ll md = 1e9+7;
void solve(){
int idx = 1;
while(sz < x){
int l = idx+1;
int r = sz;
for(int i=1;i<=a[idx]-1;i++){
for(int j=l;j<=r;j++){
sz ++;
a[sz] = a[j];
if(sz >= x) break;
}
if(sz>=x)break;
}
idx++;
}
ll len = s.size();
for(int i=1;i<=x;i++){
ll y = (len - i);
if(len < 0) len = md + len;
ll tmp = ((a[i]-1)*y) % md;
len = ((len%md) + (tmp%md)) % md;
}
cout<<len<<newl;
}
int main(){
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>t;
for(int cases=1;cases<=t;cases++){
cin>>x; cin>>s;
sz = s.size();
for(int i=0;i<s.size();i++) a[i+1] = numerize(s[i]);
solve();
}
}
| [
"owenultima@gmail.com"
] | owenultima@gmail.com |
b7fa8c79b2c3628880a701ec879ea865c5eb5cb1 | 1121785445c29515a68f2e31022ff33315518d68 | /OJ/HDU_CODE/33061.cpp | 44252001b4e14cad0a9bebf218ff9c9589eb9320 | [] | no_license | cpsa3/backup | 5406c4c14772c1789353c2cfe2a73e86677c392a | 64ca598b5c15352c623b290d5e93fa815df3489f | refs/heads/master | 2016-08-11T14:58:35.300203 | 2016-03-02T11:39:35 | 2016-03-02T11:39:35 | 45,887,997 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,826 | cpp | ////////////////////System Comment////////////////////
////Welcome to Hangzhou Dianzi University Online Judge
////http://acm.hdu.edu.cn
//////////////////////////////////////////////////////
////Username: 096040179JY
////Nickname: ___简言
////Run ID:
////Submit time: 2010-12-05 00:28:34
////Compiler: Visual C++
//////////////////////////////////////////////////////
////Problem ID: 3306
////Problem Title:
////Run result: Accept
////Run time:515MS
////Run memory:248KB
//////////////////System Comment End//////////////////
#include <iostream>
#define MOD 10007
struct mat
{
__int64 v[4][4];
};
int N,X,Y;
mat e,ans;//转换矩阵
mat matrix_mul(mat p1,mat p2)//矩阵相乘
{
int i,j,k;
mat t;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
t.v[i][j]=0;
for(k=0;k<4;k++)
t.v[i][j]=(t.v[i][j]+p1.v[i][k]*p2.v[k][j])%MOD;
}
return t;
}
mat matrix_mi(mat p1,int k)//矩阵求幂
{
if(k==1)
return p1;
if(k&1)
return matrix_mul(matrix_mi(p1,k-1),p1);
else
{
mat t=matrix_mi(p1,k>>1);
return matrix_mul(t,t);
}
}
int main()
{
int i,j;
while(scanf("%d%d%d",&N,&X,&Y)!=EOF)
{
//memset(e.v,0,sizeof(e.v));
if(!N)
{printf("1\n");continue;}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
e.v[i][j]=0;
X=X%MOD;Y=Y%MOD;
e.v[0][0]=1;//输入转换矩阵
e.v[1][0]=1;
e.v[1][1]=X*X%MOD;
e.v[1][2]=X%MOD;
e.v[1][3]=1;
e.v[2][1]=2*X*Y%MOD;
e.v[2][2]=Y%MOD;
e.v[3][1]=Y*Y%MOD;
ans=matrix_mi(e,N);
/*
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%I64d ",ans.v[i][j]);
printf("\n");
}
*/
//__int64 ANS=(ans.v[0][0]+ans.v[1][0]+ans.v[2][0]+ans.v[3][0])%MOD;
__int64 ANS=0;
for(i=0;i<4;i++)
ANS=(ANS+ans.v[i][0])%MOD;
printf("%I64d\n",ANS);
}
return 0;
} | [
"1090303279@qq.com"
] | 1090303279@qq.com |
687c92312a6fef127b1645537da0209fa8cb135b | d82a39614b0d838147e72cdd2a2860911105d5cd | /objectDetector/GetHOGFeature.cpp | 6d7850669fe0ffa8ab5b59c7013d828ec047eb46 | [] | no_license | j0x7c4/GestureRecognition | eb1a839e7a7b52661782852fd72139571af181ab | a1d77193f0d7a139489769944a7152565359d5d8 | refs/heads/master | 2021-01-13T01:36:29.485474 | 2012-11-20T09:07:53 | 2012-11-20T09:07:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | cpp | #include <cv.h>
#include <highgui.h>
#include <ml.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace cv;
using namespace std;
void saveFeature ( int cat, vector<float>& feature, string filename );
int main(int argc, char** argv)
{
vector<string> img_path;
vector<int> img_catg;
int nLine = 0;
string buf;
ifstream svm_data( "E:/source/gestureRecognition/objectDetector/bottle_svm_data" );
Mat src;
Mat trainImg(cvSize(64,64),8,3);
while( svm_data )
{
if( getline( svm_data, buf ) )
{
if( nLine % 2 == 0 )
{
img_catg.push_back( atoi( buf.c_str() ) );
}
else
{
img_path.push_back( buf );
}
nLine ++;
}
}
svm_data.close();
for( string::size_type i = 0; i != img_path.size(); i++ )
{
try {
src=imread(img_path[i],1);
}
catch ( Exception e ) {
cout<<e.what()<<endl;
continue;
}
cout<<" processing "<<img_path[i].c_str()<<endl;
resize(src,trainImg,cvSize(64,64));
HOGDescriptor hog(cvSize(64,64),cvSize(16,16),cvSize(8,8),cvSize(8,8),9);
vector<float>hog_features;
hog.compute(trainImg, hog_features,Size(1,1), Size(0,0));
cout<<"HOG dims: "<<hog_features.size()<<endl;
saveFeature(img_catg[i],hog_features,"train_data.txt");
cout<<" end processing "<<img_path[i].c_str()<<" "<<img_catg[i]<<endl;
}
return 0;
}
void saveFeature ( int cat, vector<float>& feature, string filename ) {
fstream saveStream(filename,fstream::out | fstream::app);
saveStream<<cat;
for ( int i=0 ; i<feature.size() ; i++ ) {
saveStream<<" "<<i<<":"<<feature[i];
}
saveStream<<endl;
} | [
"china.eli@gmail.com"
] | china.eli@gmail.com |
0ebf694ea2ecda717ccfbd69162f9801c4907327 | b10543704745b1bb9641519bc648d8f7394953d9 | /src/SimpleGui/guiTextLine.hpp | 56d54b126572658bf805f3cb0ca058a56ae0ef61 | [] | no_license | scaryspacebat/SimpleUI | 339a19a2845cb3b906a9912a5af713ee5c18a7e0 | c6d2af1b10b03718bf25af8af11a16edece6e75f | refs/heads/master | 2020-03-10T22:13:29.821044 | 2018-06-08T00:15:41 | 2018-06-08T00:15:41 | 129,614,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | hpp | #ifndef GUI_TEXT_H
#define GUI_TEXT_H
#include "GuiHasAdjustablePosXY.h"
#include <string>
class GuiTextLine : public GuiHasAdjustablePosXY {
public:
GuiTextLine( std::string t="" );
virtual ~GuiTextLine();
virtual void init();
virtual void render();
void setText( std::string t );
void setFontSize( int s );
protected:
private:
std::string text;
GLuint f8_id;
GLuint f16_id;
int i_font_size;
};
#endif // GUI_TEXT_H
| [
"38399058+scaryspacebat@users.noreply.github.com"
] | 38399058+scaryspacebat@users.noreply.github.com |
34889b04f0b715cf986c7e409124c23f80cede80 | 11588f23bb087199d2dd11b1c4111db6405ab1db | /source/server/config/stats/dog_statsd.cc | f7b94360881165557204d98c58a534c16f0fcfed | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ofek/envoy | 44d6b655cfde2664d5f8f5ddc1bae8707608e4ac | 8f30f67262d6db0762e3014e57e3bdfab96c0dfc | refs/heads/master | 2021-04-27T20:25:17.622262 | 2018-02-22T17:21:29 | 2018-02-22T17:21:29 | 122,378,235 | 1 | 0 | Apache-2.0 | 2018-02-21T18:48:36 | 2018-02-21T18:48:35 | null | UTF-8 | C++ | false | false | 1,527 | cc | #include "server/config/stats/dog_statsd.h"
#include <string>
#include "envoy/config/metrics/v2/stats.pb.h"
#include "envoy/config/metrics/v2/stats.pb.validate.h"
#include "envoy/registry/registry.h"
#include "common/config/well_known_names.h"
#include "common/network/resolver_impl.h"
#include "common/stats/statsd.h"
namespace Envoy {
namespace Server {
namespace Configuration {
Stats::SinkPtr DogStatsdSinkFactory::createStatsSink(const Protobuf::Message& config,
Server::Instance& server) {
const auto& sink_config =
MessageUtil::downcastAndValidate<const envoy::config::metrics::v2::DogStatsdSink&>(config);
Network::Address::InstanceConstSharedPtr address =
Network::Address::resolveProtoAddress(sink_config.address());
ENVOY_LOG(debug, "dog_statsd UDP ip address: {}", address->asString());
return Stats::SinkPtr(
new Stats::Statsd::UdpStatsdSink(server.threadLocal(), std::move(address), true));
}
ProtobufTypes::MessagePtr DogStatsdSinkFactory::createEmptyConfigProto() {
return std::unique_ptr<envoy::config::metrics::v2::DogStatsdSink>(
new envoy::config::metrics::v2::DogStatsdSink());
}
std::string DogStatsdSinkFactory::name() { return Config::StatsSinkNames::get().DOG_STATSD; }
/**
* Static registration for the this sink factory. @see RegisterFactory.
*/
static Registry::RegisterFactory<DogStatsdSinkFactory, StatsSinkFactory> register_;
} // namespace Configuration
} // namespace Server
} // namespace Envoy
| [
"mklein@lyft.com"
] | mklein@lyft.com |
9bb9dbac0c0e2b356c7a849368fea72fd06775c4 | 69d600ca5471224974b32a9ade1a09a158f07f44 | /opengl/imgui/imgui.h | 788f74c9c7974ec37e15072033e02531b13626a1 | [
"MIT"
] | permissive | ASTex-ICube/aa_real_time_glint | 2d18c25785ec9848acdf5ae0d17c4567f8363d5b | f5ac25dd10d791a3d695f30329f598e7342c7228 | refs/heads/main | 2023-03-23T20:18:42.505993 | 2021-03-02T16:44:58 | 2021-03-02T16:44:58 | 342,246,525 | 14 | 4 | MIT | 2021-03-02T16:44:59 | 2021-02-25T13:03:15 | null | UTF-8 | C++ | false | false | 224,324 | h | // dear imgui, v1.77 WIP
// (headers)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
// Read imgui.cpp for details, links and comments.
// Resources:
// - FAQ http://dearimgui.org/faq
// - Homepage & latest https://github.com/ocornut/imgui
// - Releases & changelog https://github.com/ocornut/imgui/releases
// - Gallery https://github.com/ocornut/imgui/issues/3075 (please post your screenshots/video there!)
// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
// - Wiki https://github.com/ocornut/imgui/wiki
// - Issues & support https://github.com/ocornut/imgui/issues
/*
Index of this file:
// Header mess
// Forward declarations and basic types
// ImGui API (Dear ImGui end-user API)
// Flags & Enumerations
// Memory allocations macros
// ImVector<>
// ImGuiStyle
// ImGuiIO
// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload)
// Obsolete functions
// Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)
// Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
// Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont)
*/
#pragma once
// Configuration file with compile-time options (edit imconfig.h or #define IMGUI_USER_CONFIG to your own filename)
#ifdef IMGUI_USER_CONFIG
#include IMGUI_USER_CONFIG
#endif
#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H)
#include "imconfig.h"
#endif
#ifndef IMGUI_DISABLE
//-----------------------------------------------------------------------------
// Header mess
//-----------------------------------------------------------------------------
// Includes
#include <float.h> // FLT_MIN, FLT_MAX
#include <stdarg.h> // va_list, va_start, va_end
#include <stddef.h> // ptrdiff_t, NULL
#include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp
// Version
// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens)
#define IMGUI_VERSION "1.77 WIP"
#define IMGUI_VERSION_NUM 17601
#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx))
// Define attributes of all API symbols declarations (e.g. for DLL under Windows)
// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h)
// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API)
#ifndef IMGUI_API
#define IMGUI_API
#endif
#ifndef IMGUI_IMPL_API
#define IMGUI_IMPL_API IMGUI_API
#endif
// Helper Macros
#ifndef IM_ASSERT
#include <assert.h>
#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h
#endif
#if !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__))
#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // To apply printf-style warnings to our functions.
#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
#else
#define IM_FMTARGS(FMT)
#define IM_FMTLIST(FMT)
#endif
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers!
#define IM_UNUSED(_VAR) ((void)_VAR) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds.
#if (__cplusplus >= 201100)
#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11
#else
#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Old style macro.
#endif
// Warnings
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-----------------------------------------------------------------------------
// Forward declarations and basic types
//-----------------------------------------------------------------------------
// Forward declarations
struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit()
struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback)
struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix.
struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder)
struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself)
struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back.
struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)
struct ImFont; // Runtime data for a single font within a parent ImFontAtlas
struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader
struct ImFontConfig; // Configuration data when adding a font or merging fonts
struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset)
struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data
struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using)
struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h)
struct ImGuiIO; // Main configuration and I/O between your application and ImGui
struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use)
struct ImGuiListClipper; // Helper to manually clip large list of items
struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro
struct ImGuiPayload; // User data payload for drag and drop operations
struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use)
struct ImGuiStorage; // Helper for key->value storage
struct ImGuiStyle; // Runtime data for styling/colors
struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder)
struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]")
// Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file)
// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!
// In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling
typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions
typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type
typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction
typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum)
typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation
typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle)
typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier
typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling
typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc.
typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList
typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas
typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags
typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc.
typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags
typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo()
typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload()
typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused()
typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc.
typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline()
typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super)
typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()
typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar()
typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem()
typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader()
typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild()
// Other types
#ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx']
typedef void* ImTextureID; // User data for rendering back-end to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details.
#endif
typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string.
typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data);
typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);
// Decoded character types
// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display)
typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings.
typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.
#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16]
typedef ImWchar32 ImWchar;
#else
typedef ImWchar16 ImWchar;
#endif
// Basic scalar data types
typedef signed char ImS8; // 8-bit signed integer
typedef unsigned char ImU8; // 8-bit unsigned integer
typedef signed short ImS16; // 16-bit signed integer
typedef unsigned short ImU16; // 16-bit unsigned integer
typedef signed int ImS32; // 32-bit signed integer == int
typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors)
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 ImS64; // 64-bit signed integer (pre and post C++11 with Visual Studio)
typedef unsigned __int64 ImU64; // 64-bit unsigned integer (pre and post C++11 with Visual Studio)
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t ImS64; // 64-bit signed integer (pre C++11)
typedef uint64_t ImU64; // 64-bit unsigned integer (pre C++11)
#else
typedef signed long long ImS64; // 64-bit signed integer (post C++11)
typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11)
#endif
// 2D vector (often used to store positions or sizes)
struct ImVec2
{
float x, y;
ImVec2() { x = y = 0.0f; }
ImVec2(float _x, float _y) { x = _x; y = _y; }
float operator[] (size_t idx) const { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine.
float& operator[] (size_t idx) { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine.
#ifdef IM_VEC2_CLASS_EXTRA
IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2.
#endif
};
// 4D vector (often used to store floating-point colors)
struct ImVec4
{
float x, y, z, w;
ImVec4() { x = y = z = w = 0.0f; }
ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
#ifdef IM_VEC4_CLASS_EXTRA
IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4.
#endif
};
//-----------------------------------------------------------------------------
// ImGui: Dear ImGui end-user API
// (This is a namespace. You can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!)
//-----------------------------------------------------------------------------
namespace ImGui
{
// Context creation and access
// Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts.
// None of those functions is reliant on the current context.
IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);
IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
IMGUI_API ImGuiContext* GetCurrentContext();
IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
// Main
IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!
IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame().
IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!
IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can get call GetDrawData() to obtain it and run your rendering function (up to v1.60, this used to call io.RenderDrawListsFn(). Nowadays, we allow and prefer calling your render function yourself.)
IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render.
// Demo, Debug, Information
IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information.
IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Debug/Metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc.
IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles.
IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts.
IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23" (essentially the compiled value for IMGUI_VERSION)
// Styles
IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default)
IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font
// Windows
// - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
// - You may append multiple times to the same window during the same frame.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// - Note that the bottom of window stack always contains a window called "Debug".
IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
IMGUI_API void End();
// Child Windows
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
// Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().]
IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API void EndChild();
// Windows Utilities
// - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.
IMGUI_API bool IsWindowAppearing();
IMGUI_API bool IsWindowCollapsed();
IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.
IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives
IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
IMGUI_API ImVec2 GetWindowSize(); // get current window size
IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x)
IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y)
// Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.
IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()
IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin()
IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus().
IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().
IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus.
// Content region
// - Those functions are bound to be redesigned soon (they are confusing, incomplete and return values in local window coordinates which increases confusion)
IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
IMGUI_API float GetWindowContentRegionWidth(); //
// Windows Scrolling
IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()]
IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()]
IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X
IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y
IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()]
IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()]
IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
// Parameters stacks (shared)
IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
IMGUI_API void PopFont();
IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col);
IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
IMGUI_API void PopStyleColor(int count = 1);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);
IMGUI_API void PopStyleVar(int count = 1);
IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.
IMGUI_API ImFont* GetFont(); // get current font
IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier
IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied
IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied
// Parameters stacks (current window)
IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side). 0.0f = default to ~2/3 of windows width,
IMGUI_API void PopItemWidth();
IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
IMGUI_API void PopTextWrapPos();
IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
IMGUI_API void PopAllowKeyboardFocus();
IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
IMGUI_API void PopButtonRepeat();
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
// - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
// - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
// Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
// Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.
IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates.
IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context.
IMGUI_API void Spacing(); // add vertical spacing.
IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0
IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0
IMGUI_API void BeginGroup(); // lock horizontal starting position
IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position)
IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList::
IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system.
IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
IMGUI_API void SetCursorPosY(float local_y); //
IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates
IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
IMGUI_API float GetTextLineHeight(); // ~ FontSize
IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
// ID stack/scopes
// - Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most
// likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
// - The resulting ID are hashes of the entire stack.
// - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
// - In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID,
// whereas "str_id" denote a string that is only used as an ID and not normally displayed.
IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string).
IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string).
IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer).
IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer).
IMGUI_API void PopID(); // pop from the ID stack.
IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
IMGUI_API ImGuiID GetID(const void* ptr_id);
// Widgets: Text
IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text
IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
// - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button
IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape
IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));
IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
IMGUI_API bool Checkbox(const char* label, bool* v);
IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer
IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
// Widgets: Combo Box
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
// - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);
// Widgets: Drags
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
// - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits.
// - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
// - Use v_min > v_max to lock edits.
IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound
IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f);
IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound
IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL);
IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f);
IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f);
// Widgets: Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders
IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg");
IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d");
IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f);
// Widgets: Input with Keyboard
// - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
// - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.
IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
// Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible.
// - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed.
IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
// Widgets: Trees
// - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.
IMGUI_API bool TreeNode(const char* label);
IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired.
IMGUI_API void TreePush(const void* ptr_id = NULL); // "
IMGUI_API void TreePop(); // ~ Unindent()+PopId()
IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header
IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper.
// Widgets: List Boxes
// - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them.
IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);
IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.
IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // "
IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true!
// Widgets: Data Plotting
IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
// Widgets: Value() Helpers.
// - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
IMGUI_API void Value(const char* prefix, bool b);
IMGUI_API void Value(const char* prefix, int v);
IMGUI_API void Value(const char* prefix, unsigned int v);
IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL);
// Widgets: Menus
// - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
// - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
// - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true!
IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
// Tooltips
// - Tooltip are windows following the mouse which do not take focus away.
IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
IMGUI_API void EndTooltip();
IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip().
IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
// Popups, Modals
// The properties of popups windows are:
// - They block normal mouse hovering detection outside them. (*1)
// - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// Because hovering detection is disabled outside the popup, when clicking outside the click will not be seen by underlying widgets! (*1)
// - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls.
// User can manipulate the visibility state by calling OpenPopup(), CloseCurrentPopup() etc.
// - We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions.
// Those three properties are connected: we need to retain popup visibility state in the library because popups may be closed as any time.
// (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup.
// To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
// This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click.
IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true!
IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window.
IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows).
IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside)
IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened.
IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack.
IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
// Columns
// - You can also use SameLine(pos_x) to mimic simplified columns.
// - The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!)
// - There is a maximum of 64 columns.
// - Currently working on new 'Tables' api which will replace columns around Q2 2020 (see GitHub #2957).
IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
IMGUI_API int GetColumnIndex(); // get current column index
IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
IMGUI_API int GetColumnsCount();
// Tab Bars, Tabs
IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar
IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true!
IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected.
IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true!
IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout)
IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file
IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard
IMGUI_API void LogFinish(); // stop logging (close file, etc.)
IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard
IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
// Drag and Drop
// - [BETA API] API may evolve!
// - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement)
IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true!
IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.
// Clipping
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
IMGUI_API void PopClipRect();
// Focus, Activation
// - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window.
IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
// Item/Widgets Utilities
// - Most of the functions are referring to the last/previous item we submitted.
// - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)
IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation?
IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()
IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling)
IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive).
IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.
IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode().
IMGUI_API bool IsAnyItemHovered(); // is any item hovered?
IMGUI_API bool IsAnyItemActive(); // is any item active?
IMGUI_API bool IsAnyItemFocused(); // is any item focused?
IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space)
IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space)
IMGUI_API ImVec2 GetItemRectSize(); // get size of last item
IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
// Miscellaneous Utilities
IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame.
IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame.
IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances.
IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.).
IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
IMGUI_API ImGuiStorage* GetStateStorage();
IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
// Text Utilities
IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
// Color Utilities
IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
// Inputs Utilities: Keyboard
// - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[].
// - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index.
IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index].
IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)?
IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
IMGUI_API void CaptureKeyboardFromApp(bool want_capture_keyboard_value = true); // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call.
// Inputs Utilities: Mouse
// - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
// - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
// - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held?
IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down)
IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down)
IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.
IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.
IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available
IMGUI_API bool IsAnyMouseDown(); // is any mouse button held?
IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)
IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); //
IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired cursor type
IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call.
// Clipboard Utilities
// - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
IMGUI_API const char* GetClipboardText();
IMGUI_API void SetClipboardText(const char* text);
// Settings/.Ini Utilities
// - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
// - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).
IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.
IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).
IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
// Debug Utilities
IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro.
// Memory Allocators
// - All those functions are not reliant on the current context.
// - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again because we use global storage for those.
IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL);
IMGUI_API void* MemAlloc(size_t size);
IMGUI_API void MemFree(void* ptr);
} // namespace ImGui
//-----------------------------------------------------------------------------
// Flags & Enumerations
//-----------------------------------------------------------------------------
// Flags for ImGui::Begin()
enum ImGuiWindowFlags_
{
ImGuiWindowFlags_None = 0,
ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar
ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip
ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window
ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically)
ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it
ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame
ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through.
ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar
ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state
ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y)
ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window
ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
// [Internal]
ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal()
ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu()
// [Obsolete]
//ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f or style.WindowBorderSize=1.0f to enable borders around items or windows.
//ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)
};
// Flags for ImGui::InputText()
enum ImGuiInputTextFlags_
{
ImGuiInputTextFlags_None = 0,
ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/
ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef
ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z
ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs
ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus
ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function.
ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling)
ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling)
ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer.
ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field
ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).
ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally
ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode
ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode
ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*'
ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input)
ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)
// [Internal]
ImGuiInputTextFlags_Multiline = 1 << 20, // For internal use by InputTextMultiline()
ImGuiInputTextFlags_NoMarkEdited = 1 << 21 // For internal use by functions using InputText() before reformatting data
};
// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*()
enum ImGuiTreeNodeFlags_
{
ImGuiTreeNodeFlags_None = 0,
ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected
ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open
ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node
ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.
ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes).
ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow
ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default.
ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area).
ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
//ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog
};
// Flags for ImGui::Selectable()
enum ImGuiSelectableFlags_
{
ImGuiSelectableFlags_None = 0,
ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window
ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column)
ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too
ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text
ImGuiSelectableFlags_AllowItemOverlap = 1 << 4 // (WIP) Hit testing to allow subsequent widgets to overlap this one
};
// Flags for ImGui::BeginCombo()
enum ImGuiComboFlags_
{
ImGuiComboFlags_None = 0,
ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default
ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()
ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default)
ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible
ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible
ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button
ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button
ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest
};
// Flags for ImGui::BeginTabBar()
enum ImGuiTabBarFlags_
{
ImGuiTabBarFlags_None = 0,
ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list
ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear
ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup
ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll)
ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab
ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit
ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit
ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll,
ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown
};
// Flags for ImGui::BeginTabItem()
enum ImGuiTabItemFlags_
{
ImGuiTabItemFlags_None = 0,
ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker.
ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem()
ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
};
// Flags for ImGui::IsWindowFocused()
enum ImGuiFocusedFlags_
{
ImGuiFocusedFlags_None = 0,
ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused
ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy)
ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ!
ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows
};
// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()
// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ!
// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls.
enum ImGuiHoveredFlags_
{
ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered
ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered
ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window
//ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is obstructed or overlapped by another window
ImGuiHoveredFlags_AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled
ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,
ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows
};
// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()
enum ImGuiDragDropFlags_
{
ImGuiDragDropFlags_None = 0,
// BeginDragDropSource() flags
ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged)
// AcceptDragDropPayload() flags
ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site.
ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery.
};
// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui.
#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type.
#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type.
// A primary data type
enum ImGuiDataType_
{
ImGuiDataType_S8, // signed char / char (with sensible compilers)
ImGuiDataType_U8, // unsigned char
ImGuiDataType_S16, // short
ImGuiDataType_U16, // unsigned short
ImGuiDataType_S32, // int
ImGuiDataType_U32, // unsigned int
ImGuiDataType_S64, // long long / __int64
ImGuiDataType_U64, // unsigned long long / unsigned __int64
ImGuiDataType_Float, // float
ImGuiDataType_Double, // double
ImGuiDataType_COUNT
};
// A cardinal direction
enum ImGuiDir_
{
ImGuiDir_None = -1,
ImGuiDir_Left = 0,
ImGuiDir_Right = 1,
ImGuiDir_Up = 2,
ImGuiDir_Down = 3,
ImGuiDir_COUNT
};
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
enum ImGuiKey_
{
ImGuiKey_Tab,
ImGuiKey_LeftArrow,
ImGuiKey_RightArrow,
ImGuiKey_UpArrow,
ImGuiKey_DownArrow,
ImGuiKey_PageUp,
ImGuiKey_PageDown,
ImGuiKey_Home,
ImGuiKey_End,
ImGuiKey_Insert,
ImGuiKey_Delete,
ImGuiKey_Backspace,
ImGuiKey_Space,
ImGuiKey_Enter,
ImGuiKey_Escape,
ImGuiKey_KeyPadEnter,
ImGuiKey_A, // for text edit CTRL+A: select all
ImGuiKey_C, // for text edit CTRL+C: copy
ImGuiKey_V, // for text edit CTRL+V: paste
ImGuiKey_X, // for text edit CTRL+X: cut
ImGuiKey_Y, // for text edit CTRL+Y: redo
ImGuiKey_Z, // for text edit CTRL+Z: undo
ImGuiKey_COUNT
};
// To test io.KeyMods (which is a combination of individual fields io.KeyCtrl, io.KeyShift, io.KeyAlt set by user/back-end)
enum ImGuiKeyModFlags_
{
ImGuiKeyModFlags_None = 0,
ImGuiKeyModFlags_Ctrl = 1 << 0,
ImGuiKeyModFlags_Shift = 1 << 1,
ImGuiKeyModFlags_Alt = 1 << 2,
ImGuiKeyModFlags_Super = 1 << 3
};
// Gamepad/Keyboard navigation
// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
// Read instructions in imgui.cpp for more details. Download PNG/PSD at http://goo.gl/9LgVZW.
enum ImGuiNavInput_
{
// Gamepad Mapping
ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard)
ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard)
ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard)
ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard)
ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard)
ImGuiNavInput_DpadRight, //
ImGuiNavInput_DpadUp, //
ImGuiNavInput_DpadDown, //
ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down
ImGuiNavInput_LStickRight, //
ImGuiNavInput_LStickUp, //
ImGuiNavInput_LStickDown, //
ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
// [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them.
// Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeysDown[] instead of io.NavInputs[].
ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt
ImGuiNavInput_KeyLeft_, // move left // = Arrow keys
ImGuiNavInput_KeyRight_, // move right
ImGuiNavInput_KeyUp_, // move up
ImGuiNavInput_KeyDown_, // move down
ImGuiNavInput_COUNT,
ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_
};
// Configuration flags stored in io.ConfigFlags. Set by user/application.
enum ImGuiConfigFlags_
{
ImGuiConfigFlags_None = 0,
ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[].
ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad.
ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth.
ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set.
ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end.
ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.
// User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear ImGui)
ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware.
ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse.
};
// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end.
enum ImGuiBackendFlags_
{
ImGuiBackendFlags_None = 0,
ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end Platform supports gamepad and currently has one connected.
ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end Platform supports honoring GetMouseCursor() value to change the OS cursor shape.
ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Back-end Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3 // Back-end Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices.
};
// Enumeration for PushStyleColor() / PopStyleColor()
enum ImGuiCol_
{
ImGuiCol_Text,
ImGuiCol_TextDisabled,
ImGuiCol_WindowBg, // Background of normal windows
ImGuiCol_ChildBg, // Background of child windows
ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows
ImGuiCol_Border,
ImGuiCol_BorderShadow,
ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input
ImGuiCol_FrameBgHovered,
ImGuiCol_FrameBgActive,
ImGuiCol_TitleBg,
ImGuiCol_TitleBgActive,
ImGuiCol_TitleBgCollapsed,
ImGuiCol_MenuBarBg,
ImGuiCol_ScrollbarBg,
ImGuiCol_ScrollbarGrab,
ImGuiCol_ScrollbarGrabHovered,
ImGuiCol_ScrollbarGrabActive,
ImGuiCol_CheckMark,
ImGuiCol_SliderGrab,
ImGuiCol_SliderGrabActive,
ImGuiCol_Button,
ImGuiCol_ButtonHovered,
ImGuiCol_ButtonActive,
ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem
ImGuiCol_HeaderHovered,
ImGuiCol_HeaderActive,
ImGuiCol_Separator,
ImGuiCol_SeparatorHovered,
ImGuiCol_SeparatorActive,
ImGuiCol_ResizeGrip,
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
ImGuiCol_Tab,
ImGuiCol_TabHovered,
ImGuiCol_TabActive,
ImGuiCol_TabUnfocused,
ImGuiCol_TabUnfocusedActive,
ImGuiCol_PlotLines,
ImGuiCol_PlotLinesHovered,
ImGuiCol_PlotHistogram,
ImGuiCol_PlotHistogramHovered,
ImGuiCol_TextSelectedBg,
ImGuiCol_DragDropTarget,
ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item
ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
ImGuiCol_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg // [renamed in 1.63]
//, ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered// [unused since 1.60+] the close button now uses regular button colors.
#endif
};
// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.
// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code.
// During initialization or between frames, feel free to just poke into ImGuiStyle directly.
// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description.
// In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
enum ImGuiStyleVar_
{
// Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions)
ImGuiStyleVar_Alpha, // float Alpha
ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding
ImGuiStyleVar_WindowRounding, // float WindowRounding
ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize
ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize
ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign
ImGuiStyleVar_ChildRounding, // float ChildRounding
ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize
ImGuiStyleVar_PopupRounding, // float PopupRounding
ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize
ImGuiStyleVar_FramePadding, // ImVec2 FramePadding
ImGuiStyleVar_FrameRounding, // float FrameRounding
ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize
ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing
ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing
ImGuiStyleVar_IndentSpacing, // float IndentSpacing
ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
ImGuiStyleVar_GrabMinSize, // float GrabMinSize
ImGuiStyleVar_GrabRounding, // float GrabRounding
ImGuiStyleVar_TabRounding, // float TabRounding
ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign
ImGuiStyleVar_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT // [renamed in 1.60]
#endif
};
// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
enum ImGuiColorEditFlags_
{
ImGuiColorEditFlags_None = 0,
ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer).
ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square.
ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs)
ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square).
ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead.
ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.
ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default)
// User Options (right-click on widget to change some of them).
ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well).
ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex.
ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // "
ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // "
ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.
ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value.
ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value.
ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format.
ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format.
// Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to
// override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup.
ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_PickerHueBar,
// [Internal] Masks
ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_DisplayHSV|ImGuiColorEditFlags_DisplayHex,
ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float,
ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar,
ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_InputHSV
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69]
#endif
};
// Identify a mouse button.
// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.
enum ImGuiMouseButton_
{
ImGuiMouseButton_Left = 0,
ImGuiMouseButton_Right = 1,
ImGuiMouseButton_Middle = 2,
ImGuiMouseButton_COUNT = 5
};
// Enumeration for GetMouseCursor()
// User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here
enum ImGuiMouseCursor_
{
ImGuiMouseCursor_None = -1,
ImGuiMouseCursor_Arrow = 0,
ImGuiMouseCursor_TextInput, // When hovering over InputText, etc.
ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions)
ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border
ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column
ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window
ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window
ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks)
ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle.
ImGuiMouseCursor_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT // [renamed in 1.60]
#endif
};
// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions
// Represent a condition.
// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always.
enum ImGuiCond_
{
ImGuiCond_Always = 1 << 0, // Set the variable
ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed)
ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file)
ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time)
};
//-----------------------------------------------------------------------------
// Helpers: Memory allocations macros
// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE()
// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
//-----------------------------------------------------------------------------
struct ImNewDummy {};
inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; }
inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new()
#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE)
#define IM_FREE(_PTR) ImGui::MemFree(_PTR)
#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR)
#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
template<typename T> void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } }
//-----------------------------------------------------------------------------
// Helper: ImVector<>
// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug).
//-----------------------------------------------------------------------------
// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it.
// - We use std-like naming convention here, which is a little unusual for this codebase.
// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs.
// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that,
// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset.
//-----------------------------------------------------------------------------
template<typename T>
struct ImVector
{
int Size;
int Capacity;
T* Data;
// Provide standard typedefs but we don't use them ourselves.
typedef T value_type;
typedef value_type* iterator;
typedef const value_type* const_iterator;
// Constructors, destructor
inline ImVector() { Size = Capacity = 0; Data = NULL; }
inline ImVector(const ImVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
inline ImVector<T>& operator=(const ImVector<T>& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; }
inline ~ImVector() { if (Data) IM_FREE(Data); }
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
inline int size_in_bytes() const { return Size * (int)sizeof(T); }
inline int capacity() const { return Capacity; }
inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } }
inline T* begin() { return Data; }
inline const T* begin() const { return Data; }
inline T* end() { return Data + Size; }
inline const T* end() const { return Data + Size; }
inline T& front() { IM_ASSERT(Size > 0); return Data[0]; }
inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; }
inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; }
inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; }
inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation
inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; }
// NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden.
inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; }
inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); }
inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; }
inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; }
inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; }
inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }
inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; }
inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; }
inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; }
};
//-----------------------------------------------------------------------------
// ImGuiStyle
// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame().
// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values,
// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors.
//-----------------------------------------------------------------------------
struct ImGuiStyle
{
float Alpha; // Global alpha applies to everything in Dear ImGui.
ImVec2 WindowPadding; // Padding within a window.
float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows.
float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.
float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
float ScrollbarRounding; // Radius of grab corners for scrollbar.
float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
float TabBorderSize; // Thickness of border around tabs.
float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
ImVec4 Colors[ImGuiCol_COUNT];
IMGUI_API ImGuiStyle();
IMGUI_API void ScaleAllSizes(float scale_factor);
};
//-----------------------------------------------------------------------------
// ImGuiIO
// Communicate most settings and inputs/outputs to Dear ImGui using this structure.
// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage.
//-----------------------------------------------------------------------------
struct ImGuiIO
{
//------------------------------------------------------------------
// Configuration (fill once) // Default value
//------------------------------------------------------------------
ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end.
ImVec2 DisplaySize; // <unset> // Main display size, in pixels.
float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds.
const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory.
const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging.
int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state.
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
void* UserData; // = NULL // Store your own data for retrieval by callbacks.
ImFontAtlas*Fonts; // <auto> // Font atlas: load, rasterize and pack one or more fonts into a single texture.
float FontGlobalScale; // = 1.0f // Global scale all fonts
bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel.
ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.
// Miscellaneous options
bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations.
bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63)
bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63)
bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected.
float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to -1.0f to disable.
//------------------------------------------------------------------
// Platform Functions
// (the imgui_impl_xxxx back-end files are setting those up for you)
//------------------------------------------------------------------
// Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff.
const char* BackendPlatformName; // = NULL
const char* BackendRendererName; // = NULL
void* BackendPlatformUserData; // = NULL // User data for platform back-end
void* BackendRendererUserData; // = NULL // User data for renderer back-end
void* BackendLanguageUserData; // = NULL // User data for non C++ programming language back-end
// Optional: Access OS clipboard
// (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
const char* (*GetClipboardTextFn)(void* user_data);
void (*SetClipboardTextFn)(void* user_data, const char* text);
void* ClipboardUserData;
// Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows)
// (default to use native imm32 api on Windows)
void (*ImeSetInputScreenPosFn)(int x, int y);
void* ImeWindowHandle; // = NULL // (Windows) Set this to your HWND to get automatic IME cursor positioning.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// [OBSOLETE since 1.60+] Rendering function, will be automatically called in Render(). Please call your rendering function yourself now!
// You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Render(). See example applications if you are unsure of how to implement this.
void (*RenderDrawListsFn)(ImDrawData* data);
#else
// This is only here to keep ImGuiIO the same size/layout, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h.
void* RenderDrawListsFnUnused;
#endif
//------------------------------------------------------------------
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text.
float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends.
bool KeyCtrl; // Keyboard modifier pressed: Control
bool KeyShift; // Keyboard modifier pressed: Shift
bool KeyAlt; // Keyboard modifier pressed: Alt
bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).
float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs. Cleared back to zero by EndFrame(). Keyboard keys will be auto-mapped and be written here by NewFrame().
// Functions
IMGUI_API void AddInputCharacter(unsigned int c); // Queue new character input
IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue new character input from an UTF-16 character, it can be a surrogate
IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue new characters input from an UTF-8 string
IMGUI_API void ClearInputCharacters(); // Clear the text input buffer manually
//------------------------------------------------------------------
// Output - Updated by NewFrame() or EndFrame()/Render()
// (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is
// generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!)
//------------------------------------------------------------------
bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).
bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).
bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
float Framerate; // Application framerate estimate, in frame per second. Solely for convenience. Rolling average estimation based on io.DeltaTime over 120 frames.
int MetricsRenderVertices; // Vertices output during last call to Render()
int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
int MetricsRenderWindows; // Number of visible windows
int MetricsActiveWindows; // Number of active windows
int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts.
ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
//------------------------------------------------------------------
// [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
ImGuiKeyModFlags KeyMods; // Key mods flags (same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags), updated by NewFrame()
ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)
ImVec2 MouseClickedPos[5]; // Position at time of clicking
double MouseClickedTime[5]; // Time of last click (used to figure out double-click)
bool MouseClicked[5]; // Mouse button went from !Down to Down
bool MouseDoubleClicked[5]; // Has mouse button been double-clicked?
bool MouseReleased[5]; // Mouse button went from Down to !Down
bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window. We don't request mouse capture from the application if click started outside ImGui bounds.
bool MouseDownWasDoubleClick[5]; // Track if button down was a double-click
float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
float KeysDownDurationPrev[512]; // Previous duration the key has been down
float NavInputsDownDuration[ImGuiNavInput_COUNT];
float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16
ImVector<ImWchar> InputQueueCharacters; // Queue of _characters_ input (obtained by platform back-end). Fill using AddInputCharacter() helper.
IMGUI_API ImGuiIO();
};
//-----------------------------------------------------------------------------
// Misc data structures
//-----------------------------------------------------------------------------
// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used.
// The callback function should return 0 by default.
// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details)
// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB
// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows
// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration
// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow.
struct ImGuiInputTextCallbackData
{
ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only
ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only
void* UserData; // What user passed to InputText() // Read-only
// Arguments for the different callback events
// - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary.
// - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state.
ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0;
ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History]
char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer!
int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length()
int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1
bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always]
int CursorPos; // // Read-write // [Completion,History,Always]
int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection)
int SelectionEnd; // // Read-write // [Completion,History,Always]
// Helper functions for text manipulation.
// Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection.
IMGUI_API ImGuiInputTextCallbackData();
IMGUI_API void DeleteChars(int pos, int bytes_count);
IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL);
bool HasSelection() const { return SelectionStart != SelectionEnd; }
};
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
struct ImGuiSizeCallbackData
{
void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints()
ImVec2 Pos; // Read-only. Window position, for reference.
ImVec2 CurrentSize; // Read-only. Current window size.
ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing.
};
// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()
struct ImGuiPayload
{
// Members
void* Data; // Data (copied and owned by dear imgui)
int DataSize; // Data size
// [Internal]
ImGuiID SourceId; // Source item id
ImGuiID SourceParentId; // Source parent id (if available)
int DataFrameCount; // Data timestamp
char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max)
bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)
bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.
ImGuiPayload() { Clear(); }
void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }
bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }
bool IsPreview() const { return Preview; }
bool IsDelivery() const { return Delivery; }
};
//-----------------------------------------------------------------------------
// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead.
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
// OBSOLETED in 1.72 (from July 2019)
static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); }
// OBSOLETED in 1.71 (from June 2019)
static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); }
// OBSOLETED in 1.70 (from May 2019)
static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; }
// OBSOLETED in 1.69 (from Mar 2019)
static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); }
// OBSOLETED in 1.66 (from Sep 2018)
static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); }
// OBSOLETED in 1.63 (between Aug 2018 and Sept 2018)
static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); }
// OBSOLETED in 1.61 (between Apr 2018 and Aug 2018)
IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'!
IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags = 0);
IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags = 0);
// OBSOLETED in 1.60 (between Dec 2017 and Apr 2018)
static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); }
static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { IM_UNUSED(on_edge); IM_UNUSED(outward); IM_ASSERT(0); return pos; }
}
typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent
typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData;
#endif
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
// Helper: Unicode defines
#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value).
#ifdef IMGUI_USE_WCHAR32
#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build.
#else
#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build.
#endif
// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame");
struct ImGuiOnceUponAFrame
{
ImGuiOnceUponAFrame() { RefFrame = -1; }
mutable int RefFrame;
operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }
};
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct ImGuiTextFilter
{
IMGUI_API ImGuiTextFilter(const char* default_filter = "");
IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const;
IMGUI_API void Build();
void Clear() { InputBuf[0] = 0; Build(); }
bool IsActive() const { return !Filters.empty(); }
// [Internal]
struct ImGuiTextRange
{
const char* b;
const char* e;
ImGuiTextRange() { b = e = NULL; }
ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; }
bool empty() const { return b == e; }
IMGUI_API void split(char separator, ImVector<ImGuiTextRange>* out) const;
};
char InputBuf[256];
ImVector<ImGuiTextRange>Filters;
int CountGrep;
};
// Helper: Growable text buffer for logging/accumulating text
// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder')
struct ImGuiTextBuffer
{
ImVector<char> Buf;
IMGUI_API static char EmptyString[1];
ImGuiTextBuffer() { }
inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }
const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; }
const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator
int size() const { return Buf.Size ? Buf.Size - 1 : 0; }
bool empty() const { return Buf.Size <= 1; }
void clear() { Buf.clear(); }
void reserve(int capacity) { Buf.reserve(capacity); }
const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; }
IMGUI_API void append(const char* str, const char* str_end = NULL);
IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2);
IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2);
};
// Helper: Key->Value storage
// Typically you don't have to worry about this since a storage is held within each Window.
// We use it to e.g. store collapse state for a tree (Int 0/1)
// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame)
// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.
struct ImGuiStorage
{
// [Internal]
struct ImGuiStoragePair
{
ImGuiID key;
union { int val_i; float val_f; void* val_p; };
ImGuiStoragePair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
ImGuiStoragePair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; }
ImGuiStoragePair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; }
};
ImVector<ImGuiStoragePair> Data;
// - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)
// - Set***() functions find pair, insertion on demand if missing.
// - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.
void Clear() { Data.clear(); }
IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const;
IMGUI_API void SetInt(ImGuiID key, int val);
IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const;
IMGUI_API void SetBool(ImGuiID key, bool val);
IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const;
IMGUI_API void SetFloat(ImGuiID key, float val);
IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL
IMGUI_API void SetVoidPtr(ImGuiID key, void* val);
// - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set.
// - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
// - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct)
// float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar;
IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0);
IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false);
IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f);
IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL);
// Use on your own storage if you know only integer are being stored (open/close all tree nodes)
IMGUI_API void SetAllInt(int val);
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
IMGUI_API void BuildSortByKey();
};
// Helper: Manually clip large list of items.
// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all.
// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped.
// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null.
// Usage:
// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced.
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// ImGui::Text("line number %d", i);
// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor).
// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.)
// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
struct ImGuiListClipper
{
int DisplayStart, DisplayEnd;
int ItemsCount;
// [Internal]
int StepNo;
float ItemsHeight;
float StartPosY;
// items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step).
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
// If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step().
ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want).
~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false.
IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
IMGUI_API void End(); // Automatically called on the last call of Step() that returns false.
};
// Helpers macros to generate 32-bit encoded colors
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
#define IM_COL32_R_SHIFT 16
#define IM_COL32_G_SHIFT 8
#define IM_COL32_B_SHIFT 0
#define IM_COL32_A_SHIFT 24
#define IM_COL32_A_MASK 0xFF000000
#else
#define IM_COL32_R_SHIFT 0
#define IM_COL32_G_SHIFT 8
#define IM_COL32_B_SHIFT 16
#define IM_COL32_A_SHIFT 24
#define IM_COL32_A_MASK 0xFF000000
#endif
#define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT))
#define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF
#define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black
#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000
// Helper: ImColor() implicitly converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.
// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.
// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.
struct ImColor
{
ImVec4 Value;
ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; }
ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; }
ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; }
ImColor(const ImVec4& col) { Value = col; }
inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); }
inline operator ImVec4() const { return Value; }
// FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.
inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }
static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); }
};
//-----------------------------------------------------------------------------
// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)
// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.
//-----------------------------------------------------------------------------
// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h]
// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering,
// you can poke into the draw list for that! Draw callback may be useful for example to:
// A) Change your GPU render state,
// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc.
// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }'
// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering back-end accordingly.
#ifndef ImDrawCallback
typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd);
#endif
// Special Draw callback value to request renderer back-end to reset the graphics/render state.
// The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address.
// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored.
// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call).
#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1)
// Typically, 1 command = 1 GPU draw call (unless command is a callback)
// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset'
// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices.
struct ImDrawCmd
{
unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates
ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bit indices.
unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far.
ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
void* UserCallbackData; // The draw callback code can access this.
ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; }
};
// Vertex index, default to 16-bit
// To allow large meshes with 16-bit indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end (recommended).
// To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in imconfig.h.
#ifndef ImDrawIdx
typedef unsigned short ImDrawIdx;
#endif
// Vertex layout
#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT
struct ImDrawVert
{
ImVec2 pos;
ImVec2 uv;
ImU32 col;
};
#else
// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h
// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine.
// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared a the time you'd want to set your type up.
// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM.
IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
#endif
// For use by ImDrawListSplitter.
struct ImDrawChannel
{
ImVector<ImDrawCmd> _CmdBuffer;
ImVector<ImDrawIdx> _IdxBuffer;
};
// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order.
// This is used by the Columns api, so items of each column can be batched together in a same draw call.
struct ImDrawListSplitter
{
int _Current; // Current channel number (0)
int _Count; // Number of active channels (1+)
ImVector<ImDrawChannel> _Channels; // Draw channels (not resized down so _Count might be < Channels.Size)
inline ImDrawListSplitter() { Clear(); }
inline ~ImDrawListSplitter() { ClearFreeMemory(); }
inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame
IMGUI_API void ClearFreeMemory();
IMGUI_API void Split(ImDrawList* draw_list, int count);
IMGUI_API void Merge(ImDrawList* draw_list);
IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx);
};
enum ImDrawCornerFlags_
{
ImDrawCornerFlags_None = 0,
ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1
ImDrawCornerFlags_TopRight = 1 << 1, // 0x2
ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4
ImDrawCornerFlags_BotRight = 1 << 3, // 0x8
ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3
ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC
ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5
ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA
ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience
};
enum ImDrawListFlags_
{
ImDrawListFlags_None = 0,
ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles)
ImDrawListFlags_AntiAliasedFill = 1 << 1, // Filled shapes have anti-aliased edges (*2 the number of vertices)
ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled.
};
// Draw command list
// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame,
// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering.
// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to
// access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
struct ImDrawList
{
// This is what you have to render
ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
// [Internal, used while building lists]
const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
const char* _OwnerName; // Pointer to owner window's name for debugging
unsigned int _VtxCurrentOffset; // [Internal] Always 0 unless 'Flags & ImDrawListFlags_AllowVtxOffset'.
unsigned int _VtxCurrentIdx; // [Internal] Generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0.
ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImVector<ImVec4> _ClipRectStack; // [Internal]
ImVector<ImTextureID> _TextureIdStack; // [Internal]
ImVector<ImVec2> _Path; // [Internal] current path building
ImDrawListSplitter _Splitter; // [Internal] for channels api
// If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)
ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); }
~ImDrawList() { ClearFreeMemory(); }
IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
IMGUI_API void PushClipRectFullScreen();
IMGUI_API void PopClipRect();
IMGUI_API void PushTextureID(ImTextureID texture_id);
IMGUI_API void PopTextureID();
inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
// Primitives
// - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners.
// - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred).
// In future versions we will use textures to provide cheaper and higher-quality circles.
// Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides.
IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4 bits corresponding to which corner to round
IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size)
IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col);
IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col);
IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f);
IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 12);
IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f);
IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments);
IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness);
IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order.
IMGUI_API void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0);
// Image primitives
// - Read FAQ to understand what ImTextureID is.
// - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle.
// - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture.
IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE);
IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE);
IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All);
// Stateful path API, add points then finish with PathFillConvex() or PathStroke()
inline void PathClear() { _Path.Size = 0; }
inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } // Note: Anti-aliased filling requires points to be in clockwise order.
inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); _Path.Size = 0; }
IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 10);
IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
IMGUI_API void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0);
IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All);
// Advanced
IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
// Advanced: Channels
// - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives)
// - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end)
// - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place!
// Prefer using your own persistent copy of ImDrawListSplitter as you can stack them.
// Using the ImDrawList::ChannelsXXXX you cannot stack a split over another.
inline void ChannelsSplit(int count) { _Splitter.Split(this, count); }
inline void ChannelsMerge() { _Splitter.Merge(this); }
inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); }
// Internal helpers
// NB: all primitives needs to be reserved via PrimReserve() beforehand!
IMGUI_API void Clear();
IMGUI_API void ClearFreeMemory();
IMGUI_API void PrimReserve(int idx_count, int vtx_count);
IMGUI_API void PrimUnreserve(int idx_count, int vtx_count);
IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles)
IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);
inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); }
IMGUI_API void UpdateClipRect();
IMGUI_API void UpdateTextureID();
};
// All draw data to render a Dear ImGui frame
// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose,
// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList)
struct ImDrawData
{
bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here.
int CmdListsCount; // Number of ImDrawList* to render
int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size
int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size
ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use)
ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use)
ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.
// Functions
ImDrawData() { Valid = false; Clear(); }
~ImDrawData() { Clear(); }
void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext!
IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};
//-----------------------------------------------------------------------------
// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont)
//-----------------------------------------------------------------------------
struct ImFontConfig
{
void* FontData; // // TTF/OTF data
int FontDataSize; // // TTF/OTF data size
bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
int FontNo; // 0 // Index of font within TTF/OTF file
float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height).
int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.
int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
// [Internal]
char Name[40]; // Name (strictly to ease debugging)
ImFont* DstFont;
IMGUI_API ImFontConfig();
};
// Hold rendering data for one glyph.
// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this)
struct ImFontGlyph
{
unsigned int Codepoint : 31; // 0x0000..0xFFFF
unsigned int Visible : 1; // Flag to allow early out when rendering
float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
float X0, Y0, X1, Y1; // Glyph corners
float U0, V0, U1, V1; // Texture coordinates
};
// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges().
// This is essentially a tightly packed of vector of 64k booleans = 8KB storage.
struct ImFontGlyphRangesBuilder
{
ImVector<ImU32> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
ImFontGlyphRangesBuilder() { Clear(); }
inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); }
inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array
inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array
inline void AddChar(ImWchar c) { SetBit(c); } // Add character
IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext
IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
};
// See ImFontAtlas::AddCustomRectXXX functions.
struct ImFontAtlasCustomRect
{
unsigned short Width, Height; // Input // Desired rectangle dimension
unsigned short X, Y; // Output // Packed position in Atlas
unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000)
float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance
ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset
ImFont* Font; // Input // For custom font glyphs only: target font
ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
bool IsPacked() const { return X != 0xFFFF; }
};
enum ImFontAtlasFlags_
{
ImFontAtlasFlags_None = 0,
ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two
ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas
};
// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding:
// - One or more fonts.
// - Custom graphics data needed to render the shapes needed by Dear ImGui.
// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas).
// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api.
// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you.
// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples)
// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API.
// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details.
// Common pitfalls:
// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the
// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.
// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction.
// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed,
// - Even though many functions are suffixed with "TTF", OTF data is supported just as well.
// - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future!
struct ImFontAtlas
{
IMGUI_API ImFontAtlas();
IMGUI_API ~ImFontAtlas();
IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates).
IMGUI_API void Clear(); // Clear all input and output.
// Build atlas, retrieve pixel data.
// User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
// The pitch is always = Width * BytesPerPixels (1 or 4)
// Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into
// the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste.
IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
bool IsBuilt() const { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
void SetTexID(ImTextureID id) { TexID = id; }
//-------------------------------------------
// Glyph Ranges
//-------------------------------------------
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
// NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
// NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data.
IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters
//-------------------------------------------
// [BETA] Custom Rectangles/Glyphs API
//-------------------------------------------
// You can request arbitrary rectangles to be packed into the atlas, for your own purposes.
// After calling Build(), you can query the rectangle position and render your pixels.
// You can also request your rectangles to be mapped as font glyph (given a font + Unicode point),
// so you can render e.g. custom colorful icons and use them as regular glyphs.
// Read docs/FONTS.txt for more details about using colorful icons.
// Note: this API may be redesigned later in order to support multi-monitor varying DPI settings.
IMGUI_API int AddCustomRectRegular(int width, int height);
IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0));
const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
// [Internal]
IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const;
IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
//-------------------------------------------
// Members
//-------------------------------------------
bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0.
// [Internal]
// NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
int TexWidth; // Texture width calculated during Build().
int TexHeight; // Texture height calculated during Build().
ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
ImVector<ImFontAtlasCustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
ImVector<ImFontConfig> ConfigData; // Internal data
int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+
typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+
#endif
};
// Font runtime data and rendering
// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
struct ImFont
{
// Members: Hot ~20/24 bytes (for CalcTextSize)
ImVector<float> IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI).
float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX
float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading)
// Members: Hot ~36/48 bytes (for CalcTextSize + render loop)
ImVector<ImWchar> IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point.
ImVector<ImFontGlyph> Glyphs; // 12-16 // out // // All glyphs.
const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar)
ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels
// Members: Cold ~32/40 bytes
ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into
const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData
short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
ImWchar FallbackChar; // 2 // in // = '?' // Replacement character if a glyph isn't found. Only set via SetFallbackChar()
ImWchar EllipsisChar; // 2 // out // = -1 // Character used for ellipsis rendering.
bool DirtyLookupTables; // 1 // out //
float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale()
float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints.
// Methods
IMGUI_API ImFont();
IMGUI_API ~ImFont();
IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
bool IsLoaded() const { return ContainerAtlas != NULL; }
const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const;
IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
// [Internal] Don't use!
IMGUI_API void BuildLookupTable();
IMGUI_API void ClearOutputData();
IMGUI_API void GrowIndex(int new_size);
IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
IMGUI_API void SetGlyphVisible(ImWchar c, bool visible);
IMGUI_API void SetFallbackChar(ImWchar c);
IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);
};
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h)
#ifdef IMGUI_INCLUDE_IMGUI_USER_H
#include "imgui_user.h"
#endif
#endif // #ifndef IMGUI_DISABLE
| [
"simon.lucas@etu.unistra.fr"
] | simon.lucas@etu.unistra.fr |
7aa74f51856dcaf4cf8c1c14d474521d55974c2b | 1cae363f621efaa3bdd2b8708fd4b6bf337fe147 | /SharingFaces/src/main.cpp | 0d752d0c5abd888642015934a7ef73606782e71c | [
"MIT"
] | permissive | grahamplace/SharingFaces | a7446d1b3602ff11178e6ef1d896443dfe86373a | d890fca21cc766c8838d79410366bab8298ea941 | refs/heads/master | 2021-06-04T05:14:42.525562 | 2016-10-10T15:51:53 | 2016-10-10T15:51:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,650 | cpp | #define INSTALL
//#define USE_WHITE_POINT
#include "ofMain.h"
#include "SharingFacesUtils.h"
const int installWidth = 1080, installHeight = 1920;
class ofApp : public ofBaseApp {
public:
#ifdef INSTALL
static const int camWidth = 1920, camHeight = 1080;
ofxBlackMagic cam;
#else
static const int camWidth = 1280, camHeight = 720;
ofVideoGrabber cam;
#endif
ofShader shader;
FaceOverlay overlay;
ofxFaceTrackerThreaded tracker;
BinnedData<FaceTrackerData> data;
FaceCompare faceCompare;
MultiThreadedImageSaver imageSaver;
bool useBlackMagic;
bool rotate;
int binSize;
float neighborRadius;
int neighborCount;
ofImage rotated;
FaceTrackerData nearestData;
string lastLabel;
ofImage similar;
ofVec3f whitePoint;
Hysteresis presence;
FadeTimer presenceFade, faceFade;
vector< pair<ofVec2f, FaceTrackerData> > currentData;
void setup() {
useSharedData();
#ifdef INSTALL
ofLogToFile("../local/log.txt");
#endif
loadSettings();
tracker.setup();
tracker.setHaarMinSize(175);
tracker.setRescale(.25);
tracker.setIterations(3);
tracker.setTolerance(2);
tracker.setClamp(3);
tracker.setAttempts(4);
#ifdef INSTALL
cam.setup(camWidth, camHeight, 30);
#else
cam.setup(camWidth, camHeight, false);
#endif
if(rotate) {
data.setup(camHeight, camWidth, binSize);
} else {
data.setup(camWidth, camHeight, binSize);
}
loadMetadata(data);
presence.setDelay(0, 4);
presenceFade.setLength(4, .1);
presenceFade.start();
faceFade.setLength(0, 30);
faceFade.start();
shader.load("shaders/colorbalance.vs", "shaders/colorbalance.fs");
ofDisableAntiAliasing();
glPointSize(2);
ofSetLineWidth(3);
ofSetLogLevel(OF_LOG_VERBOSE);
}
void exit() {
imageSaver.exit();
tracker.stopThread();
#ifdef INSTALL
cam.close();
#endif
}
void loadSettings() {
#ifdef INSTALL
rotate = true;
#else
rotate = false;
#endif
binSize = 10;
neighborRadius = 20;
neighborCount = 100;
}
void checkScreenSize() {
if(ofGetWindowHeight() != installHeight ||
ofGetWindowWidth() != installWidth) {
ofSetFullscreen(false);
ofSetFullscreen(true);
}
}
void update() {
#ifdef INSTALL
checkScreenSize();
if(cam.update()) {
ofPixels& pixels = cam.getColorPixels();
pixels.setImageType(OF_IMAGE_COLOR); // drop alpha
#else
cam.update();
if(cam.isFrameNew()) {
ofPixels& pixels = cam.getPixels();
#endif
if(rotate) {
ofxCv::transpose(pixels, rotated);
} else {
ofxCv::copy(pixels, rotated);
}
Mat rotatedMat = toCv(rotated);
if(tracker.update(rotatedMat)) {
ofVec2f position = tracker.getPosition();
vector<FaceTrackerData*> neighbors = data.getNeighborsCount(position, neighborCount);
FaceTrackerData curData;
curData.load(tracker);
if(!neighbors.empty()) {
nearestData = *faceCompare.nearest(curData, neighbors);
if(nearestData.label != lastLabel) {
similar.load(nearestData.getImageFilename());
#ifdef USE_WHITE_POINT
whitePoint = getWhitePoint(similar);
#endif
}
lastLabel = nearestData.label;
}
if(faceCompare.different(curData, currentData) && faceCompare.different(curData, neighbors)) {
saveFace(curData, rotated);
currentData.push_back(pair<ofVec2f, FaceTrackerData>(position, curData));
}
}
presence.update(tracker.getFound());
if(presence.wasTriggered()) {
presenceFade.stop();
faceFade.stop();
}
if(presence.wasUntriggered()) {
for(int i = 0; i < currentData.size(); i++) {
data.add(currentData[i].first, currentData[i].second);
}
currentData.clear();
presenceFade.start();
faceFade.start();
}
}
}
void draw() {
ofBackground(255);
CGDisplayHideCursor(NULL);
ofSetColor(255);
if(similar.isAllocated()) {
#ifdef USE_WHITE_POINT
shader.begin();
shader.setUniformTexture("tex", similar, 0);
shader.setUniform3fv("whitePoint", (float*) &whitePoint);
similar.draw(0, 0);
shader.end();
#else
similar.draw(0, 0);
#endif
}
ofPushStyle();
if(presenceFade.getActive()) {
ofSetColor(0, ofMap(presenceFade.get(), 0, 1, 0, 128));
ofFill();
ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
ofSetColor(255, ofMap(presenceFade.get(), 0, 1, 0, 32));
data.drawBins();
ofSetColor(255, ofMap(presenceFade.get(), 0, 1, 0, 64));
data.drawData();
}
ofSetColor(255, 64);
ofNoFill();
if(!tracker.getFound()) {
ofDrawCircle(tracker.getPosition(), 10);
}
ofSetColor(255, 96 * faceFade.get());
overlay.draw(tracker);
ofPopStyle();
#ifndef INSTALL
drawFramerate();
#endif
}
void keyPressed(int key) {
if(key == 'f') {
ofToggleFullscreen();
}
}
void saveFace(FaceTrackerData& data, ofImage& img) {
string basePath = ofGetTimestampString("%Y.%m.%d/%H.%M.%S.%i");
data.save("metadata/" + basePath + ".face");
imageSaver.saveImage(img.getPixels(), data.getImageFilename());
}
};
#include "ofAppGlutWindow.h"
int main() {
#ifdef INSTALL
ofSetupOpenGL(installWidth, installHeight, OF_FULLSCREEN);
#else
ofSetupOpenGL(1280, 720, OF_WINDOW);
#endif
ofRunApp(new ofApp());
}
| [
"kyle@kylemcdonald.net"
] | kyle@kylemcdonald.net |
06046dcdfddbc08cd30ab6a62800d4f61a4d676d | f05155d1c9c41fcc6e31686505f856fd2fbc06de | /2020/August/B. T-shirt buying.cpp | a0d4922be7c0581e46484857b7ee0d6018baa3b1 | [] | no_license | T-tasir/Competetive-Programming | 22308db58c827a8dfa9d2f879f7a1c135f3ab96a | b56ab712fd2147a69b90b7300e281b9b6ed85852 | refs/heads/main | 2023-08-18T07:35:22.656508 | 2021-10-14T13:20:33 | 2021-10-14T13:20:33 | 368,572,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,494 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double dl;
typedef unsigned long long ull;
#define pb push_back
#define PB pop_back
#define nn "\n"
#define O_O ios_base::sync_with_stdio(false); cin.tie(NULL)
#define all(p) p.begin(),p.end()
#define zz(v) (ll)v.size()
#define ss ' '
#define MEM(a,b) memset(a,(b),sizeof(a))
#define CLR(p) memset(p,0,sizeof(p))
#define f0(i,b) for(int i=0;i<(b);i++)
#define f1(i,b) for(int i=1;i<=(b);i++)
#define f2(i,a,b) for(int i=(a);i<=(b);i++)
#define fr(i,b,a) for(int i=(b);i>=(a);i--)
#define rep(i,a,b,c) for(int i=(a);i!=(b);i+=(c))
#define arrsize(a) (sizeof(a)/sizeof(a[0]))
//#define arrsize(a) (sizeof(a)/sizeof(*a))
#define S(a) scanf("%lld",&a)
#define SS(a,b) scanf("%lld %lld",&a,&b)
#define SSS(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) (a*b)/gcd(a,b)
#define pi acos(-1.0)
#define ff first
#define sc second
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector< pair <ll, ll> > vpll;
typedef vector<ll> vll;
typedef map<string,ll> msl;
typedef map<ll,ll> mll;
#define yes cout << "YES\n"
#define no cout<<"NO\n"
//memset(ar,-1,sizeof(ar));
//#define sort(x) sort(x.begin(), x.end())
//sort(a,a+n,greater<ll>())
//for (auto it = mp.begin(); it != mp.end(); ++it){}
#define MAX 1000005
#define precision(a) fixed << setprecision(a)
#define mod 1000000007
ll ar[MAX],br[MAX],cr[MAX];
int main()
{
//O_O ;
ll n;cin>>n;
for(ll i=0;i<n;i++) cin>>ar[i];
for(ll i=0;i<n;i++) cin>>br[i];
for(ll i=0;i<n;i++) cin>>cr[i];
priority_queue<ll,vector<ll>,greater<ll>>q[5][5];
for(ll i=0;i<n;i++){
q[br[i]][cr[i]].push(ar[i]);
}
ll t;cin>>t;
while(t--)
{
ll f,b,c;
cin>>c;
ll ans=INT_MAX;
for(ll i=1;i<=3;i++)
{
if(!q[c][i].empty()&&q[c][i].top()<ans)
{
ans=q[c][i].top();
f=c,b=i;
}
}
for(ll i=1;i<=3;i++)
{
if(!q[i][c].empty()&&q[i][c].top()<ans)
{
ans=q[i][c].top();
f=i,b=c;
}
}
if(ans==INT_MAX) ans=-1;
else
{
q[f][b].pop();
}
cout<<ans<<ss;
}
cout<<nn;
return 0;
}
| [
"allmoontasir256@gmail.com"
] | allmoontasir256@gmail.com |
679af95decde2189d9db767bb8677d2c549a3d54 | 1ecb42c06d372f090ecf062c448be0ce0ebc2481 | /Interface/Interface.ino | 7d1cbd234ad4f735aba1b6ae1a943a95429453a8 | [] | no_license | alextzik/arduino_workshop-2019 | c72a6e4c3ef4ade1f9290b3568636081296b9c2a | 2231e8b42db2367c8a306d533d89833063456476 | refs/heads/master | 2022-01-13T11:47:35.194089 | 2021-12-29T17:43:29 | 2021-12-29T17:43:29 | 178,888,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | ino | #include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
#define btnNONE 0
#define btnRIGHT 1
#define btnUP 2
#define btnDOWN 3
#define btnLEFT 4
#define btnSELECT 5
// Number of codes
#define CODES 2
// Menu Variables
bool menu_flag = 0;
int last_btn = btnNONE;
int pos = 0;
// Interface Variables
int code_flag = 0;
bool setup_flag = 0;
void setup() {
pinMode(10, INPUT);
pinMode(A0, INPUT);
lcd.begin(16, 2);
lcdSetup();
Serial.begin(9600);
}
void loop() {
int btn = readkeypad();
if (btn != btnNONE && last_btn == btnNONE) {
Serial.print("Button pressed: ");
Serial.println(btn);
menu(btn);
}
last_btn = btn;
CodePicker();
}
void CodePicker() {
if (code_flag == 1) {
code1();
} else if (code_flag == 2) {
code2();
}
}
void menu(int x) {
if (menu_flag == 0) {
menu_flag = 1;
lcdPrint(pos);
return;
}
if (x == btnUP || x == btnLEFT) {
pos--;
if (pos < 0) {
pos = 0;
}
} else if (x == btnDOWN || x == btnRIGHT) {
pos++;
if (pos > CODES - 1) {
pos = CODES - 1;
}
}
lcdPrint(pos);
if (x == btnSELECT) {
code_flag = pos + 1;
setup_flag = 1;
pos = 0;
menu_flag = 0;
lcdSetup();
}
}
| [
"noreply@github.com"
] | alextzik.noreply@github.com |
d82290b5a4b0d36b90cc70cb5aaeb651f397f261 | 5fa0e32ee5bf534e4a187870985d62d55eb3d5c6 | /humble-crap/prosaic-download-queue.hpp | 84785dec9954b949e3388daa5e08a9196dd159cd | [
"Unlicense"
] | permissive | lukesalisbury/humble-crap | 271ce3b6df1dfa9f1e7a8d710509e4e82bb1629c | 814c551cfdfa2687d531b50d350a0d2a6f5cf832 | refs/heads/master | 2021-01-18T17:14:59.234310 | 2019-10-28T05:30:37 | 2019-10-28T05:30:37 | 12,215,398 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,618 | hpp | /****************************************************************************
* Copyright © Luke Salisbury
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
****************************************************************************/
#ifndef PROSAICDOWNLOADQUEUE_HPP
#define PROSAICDOWNLOADQUEUE_HPP
#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtCore>
#include <QNetworkCookieJar>
#include <QNetworkCookie>
#if defined(WIN32)
#define BREAKPOINT() *((int *) nullptr) = 0; exit(3);
#else
#define BREAKPOINT() raise(SIGABRT);
#endif
enum { DIS_INACTIVE, DIS_ACTIVE, DIS_COMPLETED};
class ProsaicDownloadQueue;
class DownloadItem: public QObject
{
Q_OBJECT
public:
DownloadItem(QString owner, QUrl address, QString outputFilename);
DownloadItem() {}
public slots:
void requestWrite();
void requestCompleted();
void requestProgress(qint64 bytesReceived, qint64 bytesTotal);
void requestError(QNetworkReply::NetworkError code);
public:
ProsaicDownloadQueue * parentQueue = nullptr;
QNetworkReply * networkReply = nullptr;
QFile * file = nullptr;
QString filename = "";
QString temporaryFilename = "";
QString owner = "";
QString userKey = "";
QString userCategory = "";
QUrl address = QUrl("");
quint8 state = 0; // { Pause, Running, completed }
int id = 0;
bool eventsSet = false;
bool cache = false;
bool resumable = false;
bool returnContent = false;
bool overwriting = false;
qint64 fileSize = 0;
qint64 existSize = 0;
qint64 downloadSize = 0;
public:
QVariantMap getItemDetail();
QVariantMap getFullDetail();
void start(QNetworkReply * reply);
void pause();
void cancel();
void setup();
};
class ProsaicDownloadQueue: public QObject
{
Q_OBJECT
public:
ProsaicDownloadQueue();
~ProsaicDownloadQueue();
signals:
void error( int id, QNetworkReply::NetworkError code);
void completed( int id );
void progress( int id, qint64 bytesReceived, qint64 bytesTotal);
void updated();
private:
QNetworkAccessManager * webmanager = nullptr;
protected:
public:
Q_PROPERTY(QVariantList items READ getItemList)
QList<DownloadItem*> queue;
QVariantList getItemList();
Q_INVOKABLE QVariantMap getItemDetail(int id);
Q_INVOKABLE bool changeDownloadItemState(int id, qint8 state);
Q_INVOKABLE void ableUserDownloadItem( QString user, qint8 state);
Q_INVOKABLE int append(QString url, QString as, QString userKey, QString userCategory, bool returnData = false, qint8 state = DIS_INACTIVE);
Q_INVOKABLE void openDirectory(int id);
void startDownloadItem(DownloadItem * item);
void pauseDownloadItem(DownloadItem * item);
void cancelDownloadItem(DownloadItem * item);
};
#endif // HUMBLEDOWNLOADQUEUE_HPP
| [
"dev@lukesalisbury.name"
] | dev@lukesalisbury.name |
cb8b2108965a6a783dbb83883f589dd805b04816 | 2b8adcdd03d8a41c4b4283f741e60078b54e34f7 | /src/servo/ServoPublisher.cpp | 715ef9818033fa5e738ed84fdd366620ae9afdc4 | [
"MIT"
] | permissive | CatixBot/KinematicsNode | e998fdad16ef3d3131581210cf017837826f0893 | 451d109a472807029de8dc7392dd851f3039c3db | refs/heads/main | 2023-03-06T10:25:36.892843 | 2021-02-13T23:56:14 | 2021-02-13T23:56:14 | 310,109,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | #include "servo/ServoPublisher.h"
#include <catix_messages/ServoState.h>
servo::ServoPublisher::ServoPublisher(size_t servoIndex, ros::NodeHandle& node)
: servoIndex(servoIndex)
, publisherServoState(node.advertise<catix_messages::ServoState>("Catix/Servo", 1))
{
}
bool servo::ServoPublisher::setAngle(double servoAngle)
{
catix_messages::ServoState servoStateMessage;
servoStateMessage.servo_index = static_cast<uint8_t>(this->servoIndex);
servoStateMessage.rotate_angle = servoAngle;
this->publisherServoState.publish(servoStateMessage);
ROS_INFO("Joint %d: [%frad]", this->servoIndex, servoAngle);
return true;
}
| [
"wurty@mail.ru"
] | wurty@mail.ru |
999f844da7b1cd0e9d34277833576946d42d8e23 | 182e1eee62c32297d8dbbf47d089b01443e1dcf2 | /HW3/Page.cpp | 6a08b2e214c98491eb8dbec7fdffb919d7351a3f | [] | no_license | emrebayrm/CSE_312_Operating_System_HWs | 0aee110f5d5ddb11ae3fddb6006630b773578dd7 | 40fdafe415506f9b74843d6d4c3c14bd63b72197 | refs/heads/master | 2021-07-25T11:05:34.733269 | 2017-11-07T18:33:18 | 2017-11-07T18:33:18 | 109,873,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | //
// Created by emre on 5/27/17.
//
#include "Page.h"
| [
"noreply@github.com"
] | emrebayrm.noreply@github.com |
6b4de02fdbcdbfea56c614b471323076d262b774 | e2d636e98335b75980a4c150fa97d3e74d7c5f9a | /lua-grpc/lua/client/BindClientAsyncReaderWriter.cpp | d927af5e1af2860c1770eea4015dd2d1173bfbf5 | [] | no_license | zkqcommon/grpc_lua | 1c32202cd65c5c0834d8ec26d2d67f47e05d1088 | 94fef213f9a66b85a530a83a59a84bb0995cc2b7 | refs/heads/master | 2020-11-25T16:41:05.622618 | 2019-08-27T02:45:39 | 2019-08-27T02:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,831 | cpp | #include "BindClientAsyncReaderWriter.h"
#include "impl/CbWrapper.h"
#include "../common/GetTimeoutMs.h"
#include "../../core/client/client_async_reader_writer.h" // for ClientAsyncReaderWriter
#include "../../core/client/service_stub.h" // for ServiceStub
#include "../../core/common/completion_queue_for_next.h" // to cast GetCompletionQueue()
#include "../../core/common/status.h" // for Status
#include <LuaIntf/LuaIntf.h>
#include <string>
using namespace core;
using namespace LuaIntf;
namespace {
ClientAsyncReaderWriter GetClientAsyncReaderWriter(
const ServiceStub& stub, const std::string& sMethod,
const LuaRef& timeoutSec, const LuaRef& luaStatusCb)
{
const ChannelSptr pChannel = stub.GetChannelSptr();
const CompletionQueueSptr pCq = stub.GetCompletionQueue();
assert(pChannel);
assert(pCq);
int64_t nTimeoutMs = util::GetTimeoutMs(timeoutSec);
StatusCb cbStatus = CbWrapper::WrapLuaStatusCb(luaStatusCb);
return ClientAsyncReaderWriter(pChannel, sMethod, pCq,
nTimeoutMs, cbStatus);
}
// luaMsgCb is nil or function(string)
void ReadEach(ClientAsyncReaderWriter* pRw, const LuaRef& luaMsgCb)
{
assert(pRw);
pRw->ReadEach(CbWrapper::WrapLuaMsgCb(luaMsgCb));
}
} // namespace
namespace client {
void BindClientAsyncReaderWriter(const LuaRef& mod)
{
lua_State* L = mod.state();
assert(L);
LuaBinding(mod).beginClass<ClientAsyncReaderWriter>("ClientAsyncReaderWriter")
.addFactory(&GetClientAsyncReaderWriter)
.addFunction("read_each", &ReadEach)
.addFunction("write", &ClientAsyncReaderWriter::Write)
.addFunction("close_writing", &ClientAsyncReaderWriter::CloseWriting)
.endClass();
} // BindClientAsyncReaderWriter()
} // namespace client
| [
"c_chenzhiyong@163.com"
] | c_chenzhiyong@163.com |
e3ef4d83672c4473ed44224b29e8c4a0550c9fde | 47797f5a4fdf3752ee8299df273162b4ec37c5be | /lab_hash/lphashtable.cpp | 557fd1fe56d4e9e6decd9355349fc62603baf92f | [] | no_license | jasonwhwang/cs225 | 54de7f3f8a7d22947596e37d6032be1f567bc312 | 88a906e72081ad9bddae6dbd8ce121567f93b72f | refs/heads/master | 2020-04-14T14:58:35.347276 | 2019-01-03T02:37:49 | 2019-01-03T02:37:49 | 163,912,871 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,604 | cpp | /**
* @file lphashtable.cpp
* Implementation of the LPHashTable class.
*
* @author Chase Geigle
* @date Spring 2011
* @date Summer 2012
*/
#include "lphashtable.h"
using hashes::hash;
using std::pair;
template <class K, class V>
LPHashTable<K, V>::LPHashTable(size_t tsize)
{
if (tsize <= 0)
tsize = 17;
size = findPrime(tsize);
table = new pair<K, V>*[size];
should_probe = new bool[size];
for (size_t i = 0; i < size; i++) {
table[i] = NULL;
should_probe[i] = false;
}
elems = 0;
}
template <class K, class V>
LPHashTable<K, V>::~LPHashTable()
{
for (size_t i = 0; i < size; i++)
delete table[i];
delete[] table;
delete[] should_probe;
}
template <class K, class V>
LPHashTable<K, V> const& LPHashTable<K, V>::operator=(LPHashTable const& rhs)
{
if (this != &rhs) {
for (size_t i = 0; i < size; i++)
delete table[i];
delete[] table;
delete[] should_probe;
table = new pair<K, V>*[rhs.size];
should_probe = new bool[rhs.size];
for (size_t i = 0; i < rhs.size; i++) {
should_probe[i] = rhs.should_probe[i];
if (rhs.table[i] == NULL)
table[i] = NULL;
else
table[i] = new pair<K, V>(*(rhs.table[i]));
}
size = rhs.size;
elems = rhs.elems;
}
return *this;
}
template <class K, class V>
LPHashTable<K, V>::LPHashTable(LPHashTable<K, V> const& other)
{
table = new pair<K, V>*[other.size];
should_probe = new bool[other.size];
for (size_t i = 0; i < other.size; i++) {
should_probe[i] = other.should_probe[i];
if (other.table[i] == NULL)
table[i] = NULL;
else
table[i] = new pair<K, V>(*(other.table[i]));
}
size = other.size;
elems = other.elems;
}
template <class K, class V>
void LPHashTable<K, V>::insert(K const& key, V const& value)
{
size_t idx = hash(key, size);
elems++;
if(shouldResize()) {
resizeTable();
}
while(table[idx] != NULL) {
idx = (idx+1) % size;
}
table[idx] = new pair<K, V>(key, value);
should_probe[idx] = true;
}
template <class K, class V>
void LPHashTable<K, V>::remove(K const& key)
{
int idx = findIndex(key);
if (idx != -1) {
delete table[idx];
table[idx] = NULL;
--elems;
}
}
template <class K, class V>
int LPHashTable<K, V>::findIndex(const K& key) const
{
size_t idx = hash(key, size);
size_t start = idx;
while (should_probe[idx]) {
if (table[idx] != NULL && table[idx]->first == key)
return idx;
idx = (idx + 1) % size;
// if we've looped all the way around, the key has not been found
if (idx == start)
break;
}
return -1;
}
template <class K, class V>
V LPHashTable<K, V>::find(K const& key) const
{
int idx = findIndex(key);
if (idx != -1)
return table[idx]->second;
return V();
}
template <class K, class V>
V& LPHashTable<K, V>::operator[](K const& key)
{
// First, attempt to find the key and return its value by reference
int idx = findIndex(key);
if (idx == -1) {
// otherwise, insert the default value and return it
insert(key, V());
idx = findIndex(key);
}
return table[idx]->second;
}
template <class K, class V>
bool LPHashTable<K, V>::keyExists(K const& key) const
{
return findIndex(key) != -1;
}
template <class K, class V>
void LPHashTable<K, V>::clear()
{
for (size_t i = 0; i < size; i++)
delete table[i];
delete[] table;
delete[] should_probe;
table = new pair<K, V>*[17];
should_probe = new bool[17];
for (size_t i = 0; i < 17; i++)
should_probe[i] = false;
size = 17;
elems = 0;
}
template <class K, class V>
void LPHashTable<K, V>::resizeTable()
{
size_t newSize = findPrime(size * 2);
pair<K, V>** temp = new pair<K, V>*[newSize];
delete[] should_probe;
should_probe = new bool[newSize];
for (size_t i = 0; i < newSize; i++) {
temp[i] = NULL;
should_probe[i] = false;
}
for (size_t i = 0; i < size; i++) {
if (table[i] != NULL) {
size_t idx = hash(table[i]->first, newSize);
while (temp[idx] != NULL)
idx = (idx + 1) % newSize;
temp[idx] = table[i];
should_probe[idx] = true;
}
}
delete[] table;
// don't delete elements since we just moved their pointers around
table = temp;
size = newSize;
}
| [
"jasonwhwang@gmail.com"
] | jasonwhwang@gmail.com |
31b9b6aa6caa16af897d0585cb690eec652cd9af | 867dc15d20698dd36af40ff9b26177c23f8b8479 | /Classes/GameLayer/GameMap.cpp | 1e39ed596102e12ee74668f54bd23dcbf866f458 | [] | no_license | jianin45/SuperMario | d3a26c546b0abcb2ff1173a2e65051a3ab722abc | 9492c41f095e31a19612309aa710ff8ef23166db | refs/heads/master | 2021-01-21T02:24:13.061136 | 2015-02-25T01:58:11 | 2015-02-25T01:58:11 | 30,167,372 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | //
// GameMap.cpp
// SuperMarry
//
// Created by Hello,world! on 15/1/28.
//
//
#include "GameMap.h"
GameMap::GameMap()
//mario_birthPos(Point::ZERO)
{
}
GameMap::~GameMap()
{
}
GameMap* GameMap::create(const char *tmxFile)
{
GameMap* game_map = new GameMap();
if (game_map && game_map->initWithTMXFile(tmxFile))
{
game_map->extraInit();
game_map->autorelease();
return game_map;
}
CC_SAFE_DELETE(game_map);
return NULL;
}
void GameMap::extraInit()
{
tile_size = _tileSize;
map_size = _mapSize;
}
/*
Point GameMap::getMarioBirthPos()
{
return mario_birthPos;
}
*/
| [
"jianin45@sina.com"
] | jianin45@sina.com |
bb7b5394bd49302e826f89756c3a6dd348c6e514 | d4b921fe134ba911579a9791426a1689d1aa0b35 | /Lab2/make_sequence.cpp | 4d09c4d10bf30aebf7ada20b6d400e4821b766e1 | [] | no_license | FluenceYHL/OperateSystem | ffcedc5d5ee5f76f6ed0935c41b14f7839d74e5b | f184c9b9147a6b67cc0a165983313e6d80c433d6 | refs/heads/master | 2020-04-09T01:14:13.612057 | 2018-12-31T13:18:05 | 2018-12-31T13:18:05 | 159,896,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,485 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <ctime>
int main() {
srand(time(nullptr));
int cur = 1;
constexpr int page = 256;
constexpr int initSize = 64 * page;
auto getRand = [](int l, int r) {
l = std::abs(l), r = std::abs(r);
if(l == r) return l;
if(l > r) std::swap(l, r);
return l + rand() % (r - l);
};
std::vector<int> sequence{ cur = rand() % (initSize - 1) };
for(int i = 1;i < initSize; ++i) {
auto r = rand() % 10;
if(r < 7) {
if(cur >= initSize - 1)
cur -= rand() % (page);
sequence.emplace_back(++cur);
}
else if(r < 8) {
auto l = rand() % 20;
if(l < 17)
sequence.emplace_back(cur = getRand(cur - (page << 1), cur));
else if(l < 19)
sequence.emplace_back(cur = getRand(cur - (page << 2), cur - (page << 1)));
else
sequence.emplace_back(cur = getRand(0, cur - (page << 2)));
}
else {
auto l = rand() % 20;
if(l < 17)
sequence.emplace_back(cur = std::min(initSize - (page << 1), getRand(cur, cur + (page << 1))));
else if(l < 19)
sequence.emplace_back(cur = std::min(initSize - (page << 1), getRand(cur + (page << 1), cur + (page << 2))));
else
sequence.emplace_back(cur = std::min(initSize - (page << 1), getRand(cur + (page << 2), initSize)));
}
}
std::ofstream out("./sequence(3).txt", std::ios::trunc);
std::cout << "initSize : " << initSize << "\n";
for(const auto it : sequence)
out << it << " ";
out.close();
return 0;
} | [
"noreply@github.com"
] | FluenceYHL.noreply@github.com |
25dd0027a12ad6d303135ccfb366bd51aac1ef92 | f6bfcb7b46d827999bc2a69ad9a3689f7926740e | /src/GoldHook/CodeGenerator.cpp | 3c1b008a74cecc9c0a9467ae817ddddd2ec39e89 | [] | no_license | darfink/GoldMeta | d2818a5bd82f0ad0744c8f4b8c1627d62f648ffe | 7e234195db1674a7cc504db86e15d092e9af40a1 | refs/heads/master | 2016-09-06T16:52:59.627807 | 2014-03-04T11:42:52 | 2014-03-04T11:42:52 | 14,727,581 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,973 | cpp | #include <asmjit/asmjit.h>
#include <GoldMeta/Gold/IModuleFunction.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <cstddef>
#include <cassert>
#include <vector>
#include "../Default.hpp"
#include "HookContext.hpp"
#include "CodeGenerator.hpp"
#include "VTableOffset.hpp"
// We want to keep these to a minimum
using namespace asmjit;
using namespace asmjit::host;
namespace gm {
CodeGenerator::CodeGenerator(IFunctionBase* function) :
mAssembler(new Assembler(&mJitRuntime)),
mHasNonHiddenReturn(false),
mFunctionBase(function),
mLastArgument(0)
{
assert(mFunctionBase != nullptr);
assert(mAssembler);
mConventionInfo = mFunctionBase->GetConventionInfo();
mHasNonHiddenReturn = mConventionInfo.GetReturnMethod() != ReturnMethod::Hidden && mConventionInfo.GetReturn().GetType() != DataType::Void;
// Calculate where the first argument will be relative to EBP
for(const DataType& parameter : mConventionInfo.GetParameters()) {
mLastArgument += parameter.GetStackSize();
}
}
FNCallHook CodeGenerator::GenerateCallHook() {
if(!mCallHook) {
mAssembler->clear();
// We use this to avoid to several memory accesses
Label callerContext = mAssembler->newLabel();
mAssembler->push(ebp);
mAssembler->mov(ebp, esp);
// We need to push the arguments in reverse order (and the first argument should be the context, if required)
size_t index = mConventionInfo.GetParameters().size() + (mConventionInfo.IsMethod() ? sizeof(uintptr_t) : 0);
if(index > 0) {
// Copy the 'arguments' array pointer to EDX
mAssembler->mov(edx, dword_ptr(ebp, 12));
for(const DataType& parameter : mConventionInfo.GetParameters()) {
mAssembler->mov(eax, ptr(edx, --index * sizeof(uintptr_t)));
this->PushParameter(parameter, ptr(eax));
}
if(mConventionInfo.IsMethod()) {
mAssembler->mov(eax, dword_ptr(edx, 0));
mAssembler->mov(eax, dword_ptr(eax));
mAssembler->mov(dword_ptr(callerContext), eax);
}
}
// Call 'IFunctionBase::GetCallableAddress' to retrieve the address that we should use
// for calling the original function. The result will be stored in EAX for later usage.
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::GetCallableAddress)));
if(mConventionInfo.IsMethod()) {
// If it is a method, we need to supply the context
mAssembler->mov(ecx, dword_ptr(callerContext));
}
if(mConventionInfo.GetReturnMethod() == ReturnMethod::Hidden) {
// If the return is done by a hidden parameter, push it!
mAssembler->push(dword_ptr(ebp, 8));
}
// Call the original function
mAssembler->call(eax);
if(!mConventionInfo.IsCalleClean()) {
mAssembler->add(esp, mConventionInfo.GetStackSize());
}
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
// Copy the source address to the EAX register
mAssembler->mov(ecx, dword_ptr(ebp, 8));
if(mHasNonHiddenReturn == true) {
this->SaveReturn(mConventionInfo.GetReturn(), ptr(ecx));
}
}
mAssembler->pop(ebp);
mAssembler->ret(8);
// ------------------------------------------------------
if(mConventionInfo.IsMethod()) {
mAssembler->bind(callerContext);
mAssembler->dptr(nullptr);
}
// Retrieve the assembly code, ready for execution
mCallHook.reset(mAssembler->make(), [](void* code) { MemoryManager::getGlobal()->release(code); });
}
return reinterpret_cast<FNCallHook>(mCallHook.get());
}
void* CodeGenerator::GenerateHookHandler() {
if(!mHookHandler) {
mAssembler->clear();
// Because hooks can be called recursively, we cannot store any data in the assembly, so we only store it
// temporarily at these label addresses until we have received a hook context, then we copy the values.
Label returnData = mAssembler->newLabel();
Label callerAddress = mAssembler->newLabel();
Label calleeContext = mAssembler->newLabel();
Label skipOrigCall = mAssembler->newLabel();
Label returnToCaller = mAssembler->newLabel();
Label skipCopyReturn = mAssembler->newLabel();
// Save the callback address for later
mAssembler->pop(dword_ptr(callerAddress));
if(mConventionInfo.IsMethod()) {
// The object instance is in ecx, so copy it to the hook context
mAssembler->mov(dword_ptr(calleeContext), ecx);
}
if(mConventionInfo.GetReturnMethod() == ReturnMethod::Hidden) {
// We need the return address for later
mAssembler->pop(dword_ptr(returnData));
}
// Call the function method 'OnEntry'. This function setups some necessary data, but above all,
// it returns the current hook context in EAX. This is where we store all data for this call. To avoid
// heap allocations, the hook context is only allocated when necessary, otherwise it is reused.
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::OnEntry)));
// Function prolog - Normally the function parameters start at [EBP + 8], but since we have
// popped the caller return address from the stack, the location as been dislocated by 4 bytes.
// So this means that the first argument can be accessed at [EBP + 4] instead.
mAssembler->push(ebp);
mAssembler->mov(ebp, esp);
// ------------------------------------------------------
// These are not scratch registers, they need to be preserved
mAssembler->push(ebx);
mAssembler->push(esi);
mAssembler->push(edi);
// Copy the hook context to EBX
mAssembler->mov(ebx, eax);
// Copy the caller address to the hook context
mAssembler->mov(eax, dword_ptr(callerAddress));
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, callerAddress)), eax);
if(mConventionInfo.IsMethod()) {
// Copy the callee context to the hook context
mAssembler->mov(eax, dword_ptr(calleeContext));
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, calleeContext)), eax);
}
if(mConventionInfo.GetReturnMethod() == ReturnMethod::Hidden) {
// Copy the hidden return address to the hook context
mAssembler->mov(eax, dword_ptr(returnData));
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, originalReturn)), eax);
}
// Generate the assembly code for calling all modules that are listed as 'pre' hooks
this->CallModules(Tense::Pre);
// Check whether we should call the original function or not.
mAssembler->cmp(dword_ptr(ebx, offsetof(HookContext, highestResult)), static_cast<int>(Result::Supersede));
mAssembler->je(skipOrigCall);
{
size_t stackDisplacement = mLastArgument;
for(const DataType& parameter : boost::adaptors::reverse(mConventionInfo.GetParameters())) {
// Push each function parameter to the target module, and add the EBP offset (first argument at [EBP + 4])
stackDisplacement -= this->PushParameter(parameter, ptr(ebp, stackDisplacement));
}
// Call 'IFunctionBase::GetCallableAddress' to retrieve the address that we should use
// for calling the original function. The result will be stored in EAX for later usage.
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::GetCallableAddress)));
if(mConventionInfo.IsMethod()) {
// If it is a method, we need to supply the context
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, calleeContext)));
}
if(mConventionInfo.GetReturnMethod() == ReturnMethod::Hidden) {
// In case the return value is hidden, push the result data address
mAssembler->push(dword_ptr(ebx, offsetof(HookContext, originalReturn)));
}
// Call the original function!
mAssembler->call(eax);
if(!mConventionInfo.IsCalleClean()) {
// We need to clean up the stack after us
mAssembler->add(esp, mConventionInfo.GetStackSize());
}
if(mHasNonHiddenReturn == true) {
// We need to copy the original return value to the hook context so function modules may access the value
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, originalReturn)));
this->SaveReturn(mConventionInfo.GetReturn(), ptr(ecx));
}
}
// TODO: Avoid this useless jump for void functions
mAssembler->jmp(skipCopyReturn);
mAssembler->bind(skipOrigCall);
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
// The function has been superseded, so we set the original return value to the overridden one (since no original value exists)
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, overrideReturn)));
mAssembler->mov(edx, dword_ptr(ebx, offsetof(HookContext, originalReturn)));
this->CopyData(mConventionInfo.GetReturn(), ptr(ecx), ptr(edx));
}
mAssembler->bind(skipCopyReturn);
// Generate the assembly code for calling all modules that are listed as 'post' hooks
this->CallModules(Tense::Post);
// ------------------------------------------------------
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
// Check whether we should use a overridden return value or the original one, returned by the function
mAssembler->cmp(dword_ptr(ebx, offsetof(HookContext, highestResult)), static_cast<int>(Result::Override));
mAssembler->cmovne(eax, dword_ptr(ebx, offsetof(HookContext, originalReturn)));
mAssembler->cmove(eax, dword_ptr(ebx, offsetof(HookContext, overrideReturn)));
mAssembler->mov(dword_ptr(returnData), eax);
}
// Since we pop EBX, we set the 'caller' address so we can use it later
mAssembler->mov(eax, dword_ptr(ebx, offsetof(HookContext, callerAddress)));
mAssembler->mov(dword_ptr(callerAddress), eax);
// We are going to call member functions of 'IFunctionBase'
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
// Reset preserved registers
mAssembler->pop(edi);
mAssembler->pop(esi);
mAssembler->pop(ebx);
// Ensure that the stack isn't unbalanced
mAssembler->cmp(esp, ebp);
mAssembler->je(returnToCaller);
{
// If the stack has become displaced, we cannot return execution to the caller. This should
// actually never happen, but just in case it does, I have created a check for it. The 'InvalidESP'
// member function will be called and report this error and forcefully exit the application.
// If this happens, there is (probably) something wrong with the assembly code, or a user callback
// that has specified a wrong calling convention which results in an invalid ESP value.
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::InvalidESP)));
}
mAssembler->bind(returnToCaller);
mAssembler->pop(ebp);
// Call the 'OnExit' method
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::OnExit)));
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
// If it is a hidden return, we just need to return the pointer
mAssembler->mov(ecx, dword_ptr(returnData));
if(mHasNonHiddenReturn == true) {
// Otherwise we need to copy the data to the appropriate register
this->SetReturn(mConventionInfo.GetReturn(), ptr(ecx));
}
}
if(mConventionInfo.IsCalleClean()) {
size_t stackSize = 0;
// We can't use 'ConventionInfo::GetStackSize', because it accounts for the (possible) hidden return parameter that we popped earlier
for(const DataType& parameter : mConventionInfo.GetParameters()) {
stackSize += parameter.GetStackSize();
}
// We need to clean up the stack space ourself
mAssembler->add(esp, stackSize);
}
// Return to the calling address
mAssembler->jmp(dword_ptr(callerAddress));
// ------------------------------------------------------
// ... and append the '.data' section
mAssembler->bind(callerAddress);
mAssembler->dptr(nullptr);
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
mAssembler->bind(returnData);
mAssembler->dptr(nullptr);
}
if(mConventionInfo.IsMethod()) {
mAssembler->bind(calleeContext);
mAssembler->dptr(nullptr);
}
mHookHandler.reset(mAssembler->make(), [](void* code) { MemoryManager::getGlobal()->release(code); });
}
return mHookHandler.get();
}
void CodeGenerator::CallModules(Tense::Type tense) {
// Define all labels that we are utilizing
Label iterateModule = mAssembler->newLabel();
Label skipHighResult = mAssembler->newLabel();
Label endCallModule = mAssembler->newLabel();
// Update the hook context with the current tense
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, tense)), tense);
// Call 'ResetIterator' (required since we call both Pre & Post)
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::ResetIterator)));
// Copy 'IFunctionBase' to ECX and call 'IterateModule'
mAssembler->bind(iterateModule);
mAssembler->mov(ecx, reinterpret_cast<uintptr_t>(mFunctionBase));
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IFunctionBase>(&IFunctionBase::IterateModule)));
// The return value of type 'IModuleFunction' is NULL when we have reached the end
mAssembler->cmp(eax, NULL);
mAssembler->je(endCallModule);
{
// Set the currently active function module in the hook context
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, module)), eax);
// Call the method 'IsCallable' to determine whether we should handle this module or not
mAssembler->push(tense);
mAssembler->mov(ecx, eax);
mAssembler->mov(eax, dword_ptr(ecx));
mAssembler->call(dword_ptr(eax, VTableOffset<IModuleFunction>(&IModuleFunction::IsCallable)));
mAssembler->cmp(al, false);
mAssembler->je(iterateModule);
size_t stackDisplacement = mLastArgument;
for(const DataType& parameter : boost::adaptors::reverse(mConventionInfo.GetParameters())) {
// Push each function parameter to the target module, and add the EBP offset (first argument at [EBP + 4])
stackDisplacement -= this->PushParameter(parameter, ptr(ebp, stackDisplacement));
}
// The last argument is the hook context
mAssembler->push(ebx);
if(mConventionInfo.GetReturnMethod() == ReturnMethod::Hidden) {
// In case the return value is hidden, push the result data address
mAssembler->push(dword_ptr(ebx, offsetof(HookContext, currentReturn)));
}
// Call the module function with the associated context
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, module)));
mAssembler->mov(edx, dword_ptr(ecx));
mAssembler->call(dword_ptr(edx, VTableOffset<IModuleFunction>(&IModuleFunction::GetCallback)));
mAssembler->push(eax);
mAssembler->call(dword_ptr(edx, VTableOffset<IModuleFunction>(&IModuleFunction::GetContext)));
mAssembler->mov(ecx, eax);
mAssembler->pop(eax);
mAssembler->call(eax);
// Assign the current module result to the 'previous' result
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, currentResult)));
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, currentResult)), static_cast<int>(Result::Unset));
// Replace 'previous' result with the current module function result
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, previousResult)), ecx);
// Check if we need to replace the highest result with the one returned
mAssembler->cmp(ecx, dword_ptr(ebx, offsetof(HookContext, highestResult)));
mAssembler->jbe(skipHighResult);
mAssembler->mov(dword_ptr(ebx, offsetof(HookContext, highestResult)), ecx);
mAssembler->bind(skipHighResult);
if(mHasNonHiddenReturn == true) {
// We need to retrieve the return value so we can replace the original return value
// if necessary. Although we handle the return value of all functions, because floating point
// return values demand that they are popped from the floating point stack.
mAssembler->push(ecx);
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, currentReturn)));
this->SaveReturn(mConventionInfo.GetReturn(), ptr(ecx));
mAssembler->pop(ecx);
}
if(mConventionInfo.GetReturn().GetType() != DataType::Void) {
// Check if the module function should override the original return value
mAssembler->cmp(ecx, static_cast<int>(Result::Override));
mAssembler->jb(iterateModule);
mAssembler->cmp(ecx, dword_ptr(ebx, offsetof(HookContext, highestResult)));
mAssembler->jb(iterateModule);
// We need to dereference the addresses twice, so we move them to EAX:EDX first
mAssembler->mov(ecx, dword_ptr(ebx, offsetof(HookContext, currentReturn)));
mAssembler->mov(edx, dword_ptr(ebx, offsetof(HookContext, overrideReturn)));
// Then we copy data data between the source to the destination
this->CopyData(mConventionInfo.GetReturn(), ptr(ecx), ptr(edx));
}
}
mAssembler->jmp(iterateModule);
mAssembler->bind(endCallModule);
}
// This method may only touch the ECX, ESI and/or EDI registers
size_t CodeGenerator::PushParameter(const DataType& type, Mem source) {
size_t displacement = source.getDisplacement();
size_t typeSize = type.GetSize();
switch(type.GetType()) {
default: assert(false);
case DataType::Pointer:
case DataType::Integral:
case DataType::Structure: {
// Update the memory operand size
source.setSize(std::min(typeSize, sizeof(size_t)));
switch(typeSize) {
default: {
assert(type.GetType() == DataType::Structure);
// Make room on the stack for our data
mAssembler->sub(esp, type.GetStackSize());
// Since arguments aren't pushed in bytes, but in double words, we take that into consideration
source.setDisplacement(displacement - (type.GetStackSize() - sizeof(uint)));
if(typeSize <= sizeof(uint) * 6 && typeSize % sizeof(uint) == 0) {
// We push one double word at a time
source.setSize(sizeof(uint));
// We updated the displacement value
displacement = source.getDisplacement();
for(size_t index = 0; index < typeSize; index += sizeof(uint)) {
source.setDisplacement(displacement + index);
mAssembler->mov(ecx, source);
mAssembler->mov(dword_ptr(esp, index), ecx);
}
} else /* It's more effective with a bitwise copy operation */ {
this->PerformBitwiseCopy(typeSize, source, ptr(esp));
}
break;
}
case sizeof(byte):
case sizeof(ushort):
mAssembler->movzx(ecx, source);
mAssembler->push(ecx);
break;
case sizeof(uint):
mAssembler->push(source);
break;
case sizeof(uint64):
mAssembler->push(source);
source.setDisplacement(displacement - sizeof(size_t));
mAssembler->push(source);
break;
}
break;
}
case DataType::FloatingPoint: {
source.setSize(typeSize);
if(typeSize == sizeof(double)) {
source.setDisplacement(displacement - sizeof(size_t));
}
mAssembler->fld(source);
mAssembler->sub(esp, typeSize);
mAssembler->fstp(ptr(esp, 0, typeSize));
break;
}
}
return type.GetStackSize();
}
void CodeGenerator::SaveReturn(const DataType& type, Mem destination) {
size_t typeSize = type.GetSize();
switch(type.GetType()) {
default: assert(false);
case DataType::Pointer:
case DataType::Integral:
case DataType::Structure: {
switch(typeSize) {
default:
assert(type.GetType() == DataType::Structure);
break;
case sizeof(byte):
mAssembler->mov(destination, al);
break;
case sizeof(ushort):
mAssembler->mov(destination, ax);
break;
case sizeof(uint):
mAssembler->mov(destination, eax);
break;
case sizeof(uint64):
mAssembler->mov(destination, eax);
destination.setDisplacement(destination.getDisplacement() - sizeof(size_t));
mAssembler->mov(destination, edx);
break;
}
break;
}
case DataType::FloatingPoint: {
destination.setSize(typeSize);
mAssembler->fstp(destination);
break;
}
}
}
void CodeGenerator::SetReturn(const DataType& type, Mem source) {
size_t typeSize = type.GetSize();
switch(type.GetType()) {
default: assert(false);
case DataType::Pointer:
case DataType::Integral:
case DataType::Structure: {
switch(typeSize) {
default:
assert(type.GetType() == DataType::Structure);
break;
case sizeof(byte):
mAssembler->mov(al, source);
break;
case sizeof(ushort):
mAssembler->mov(ax, source);
break;
case sizeof(uint):
mAssembler->mov(eax, source);
break;
case sizeof(uint64):
mAssembler->mov(eax, source);
source.setDisplacement(source.getDisplacement() - sizeof(size_t));
mAssembler->mov(edx, source);
break;
}
break;
}
case DataType::FloatingPoint: {
source.setSize(typeSize);
mAssembler->fld(source);
break;
}
}
}
void CodeGenerator::PerformBitwiseCopy(size_t size, const Mem& source, const Mem& destination) {
uint dwords = size / sizeof(size_t);
uint bytes = size % sizeof(size_t);
mAssembler->lea(edi, destination);
mAssembler->lea(esi, source);
if(dwords > 0) {
mAssembler->mov(ecx, dwords);
mAssembler->rep_movsd();
}
if(bytes > 0) {
mAssembler->mov(ecx, bytes);
mAssembler->rep_movsb();
}
}
// May only touch the EAX register (and x87 floating point stack)
void CodeGenerator::CopyData(const DataType& type, Mem source, Mem destination) {
size_t typeSize = type.GetSize();
switch(type.GetType()) {
case DataType::Pointer:
case DataType::Structure:
case DataType::Integral: {
switch(typeSize) {
default: {
assert(type.GetType() == DataType::Structure);
this->PerformBitwiseCopy(typeSize, source, destination);
break;
}
case sizeof(byte):
mAssembler->mov(al, source);
mAssembler->mov(destination, al);
break;
case sizeof(ushort):
mAssembler->mov(ax, source);
mAssembler->mov(destination, ax);
break;
case sizeof(uint):
mAssembler->mov(eax, source);
mAssembler->mov(destination, eax);
break;
case sizeof(uint64):
size_t sourceDisp = source.getDisplacement();
size_t destDisp = destination.getDisplacement();
// We copy two double words
for(int i = 0; i < 2; i++) {
destination.setDisplacement(destDisp - sizeof(size_t) * i);
source.setDisplacement(sourceDisp - sizeof(size_t) * i);
mAssembler->mov(eax, source);
mAssembler->mov(destination, eax);
}
break;
}
break;
}
case DataType::FloatingPoint: {
source.setSize(typeSize);
destination.setSize(typeSize);
mAssembler->fld(source);
mAssembler->fstp(destination);
break;
}
}
}
}
| [
"elliott.darfink@gmail.com"
] | elliott.darfink@gmail.com |
7fdd7cb81bb64f573303066d1fb0d00ae91dd4f8 | 4591a91b39bf975b0779482ce4a908a9dc2cc17d | /rk3288/head/Transfer.h | aee646040ea79dce1cffadcebec73c3d01686fa3 | [] | no_license | hongquanzhou/bear_fault_diagnose | bcaf2f386c86dab28fc5fcdbca2d60fec6ae1a04 | 5f65c5f33bc253a03ebd3a2ef99cb127208831b7 | refs/heads/master | 2023-04-14T04:40:02.223660 | 2021-04-26T07:16:46 | 2021-04-26T07:16:46 | 286,705,838 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include "utils.h"
#include "Infer.h"
using namespace std;
class Transfer
{
private:
string serverIp;
string signalBase;
string modelBase;
int serverPort;
int len;
int sin_size;
int client_sockfd;
struct sockaddr_in remote_addr;
Infer *infer;
char buf[BUFSIZ];
public:
Transfer(string ip,int port,string signal,string model,Infer* in);
int transmit(const char* buf);
int receive(char* buf);
~Transfer();
int processOnece();
}; | [
"18121350@bjtu.edu.cn"
] | 18121350@bjtu.edu.cn |
41ea9747846f7ad0023a0e3ae97b6af1b1070b68 | 8567438779e6af0754620a25d379c348e4cd5a5d | /third_party/WebKit/Source/core/frame/FrameSerializer.h | 290394485438e727ee54a712dd5e1c6693ef2e63 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 5,798 | h | /*
* Copyright (C) 2011 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 promo te 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.
*/
#ifndef FrameSerializer_h
#define FrameSerializer_h
#include "core/CoreExport.h"
#include "platform/heap/Handle.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/KURLHash.h"
#include "wtf/Deque.h"
#include "wtf/Forward.h"
#include "wtf/HashSet.h"
#include "wtf/Vector.h"
namespace blink {
class Attribute;
class CSSRule;
class CSSStyleSheet;
class CSSValue;
class Document;
class Element;
class FontResource;
class ImageResourceContent;
class LocalFrame;
class SharedBuffer;
class StylePropertySet;
struct SerializedResource;
// This class is used to serialize frame's contents back to text (typically
// HTML). It serializes frame's document and resources such as images and CSS
// stylesheets.
class CORE_EXPORT FrameSerializer final {
STACK_ALLOCATED();
public:
enum ResourceHasCacheControlNoStoreHeader {
NoCacheControlNoStoreHeader,
HasCacheControlNoStoreHeader
};
class Delegate {
public:
// Controls whether HTML serialization should skip the given element.
virtual bool shouldIgnoreElement(const Element&) { return false; }
// Controls whether HTML serialization should skip the given attribute.
virtual bool shouldIgnoreAttribute(const Element&, const Attribute&) {
return false;
}
// Method allowing the Delegate control which URLs are written into the
// generated html document.
//
// When URL of the element needs to be rewritten, this method should
// return true and populate |rewrittenLink| with a desired value of the
// html attribute value to be used in place of the original link.
// (i.e. in place of img.src or iframe.src or object.data).
//
// If no link rewriting is desired, this method should return false.
virtual bool rewriteLink(const Element&, String& rewrittenLink) {
return false;
}
// Tells whether to skip serialization of a subresource or CSSStyleSheet
// with a given URI. Used to deduplicate resources across multiple frames.
virtual bool shouldSkipResourceWithURL(const KURL&) { return false; }
// Tells whether to skip serialization of a subresource.
virtual bool shouldSkipResource(ResourceHasCacheControlNoStoreHeader) {
return false;
}
// Returns custom attributes that need to add in order to serialize the
// element.
virtual Vector<Attribute> getCustomAttributes(const Element&) {
return Vector<Attribute>();
}
};
// Constructs a serializer that will write output to the given deque of
// SerializedResources and uses the Delegate for controlling some
// serialization aspects. Callers need to ensure that both arguments stay
// alive until the FrameSerializer gets destroyed.
FrameSerializer(Deque<SerializedResource>&, Delegate&);
// Initiates the serialization of the frame. All serialized content and
// retrieved resources are added to the Deque passed to the constructor.
// The first resource in that deque is the frame's serialized content.
// Subsequent resources are images, css, etc.
void serializeFrame(const LocalFrame&);
static String markOfTheWebDeclaration(const KURL&);
private:
// Serializes the stylesheet back to text and adds it to the resources if URL
// is not-empty. It also adds any resources included in that stylesheet
// (including any imported stylesheets and their own resources).
void serializeCSSStyleSheet(CSSStyleSheet&, const KURL&);
// Serializes the css rule (including any imported stylesheets), adding
// referenced resources.
void serializeCSSRule(CSSRule*);
bool shouldAddURL(const KURL&);
void addToResources(const String& mimeType,
ResourceHasCacheControlNoStoreHeader,
PassRefPtr<const SharedBuffer>,
const KURL&);
void addImageToResources(ImageResourceContent*, const KURL&);
void addFontToResources(FontResource*);
void retrieveResourcesForProperties(const StylePropertySet*, Document&);
void retrieveResourcesForCSSValue(const CSSValue&, Document&);
Deque<SerializedResource>* m_resources;
HashSet<KURL> m_resourceURLs;
bool m_isSerializingCss;
Delegate& m_delegate;
};
} // namespace blink
#endif // FrameSerializer_h
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
29c6f7619f4c6c47d3c1cc819cad7f6034e9854c | ba19c65239f9d9b47547864dfbd27be1acf4a5ce | /sim/check/check.ino | 2a9778b882566195c0b9d7c611c6caa66bbbd667 | [] | no_license | vk-0002/Arduino_Projects | 01cc91bd4d8c5069744ca9c50ac58706d5ebe134 | b4064bcb9c29a185a88215bf31cded66defbc5c4 | refs/heads/master | 2023-07-17T23:50:13.796457 | 2021-09-04T06:36:09 | 2021-09-04T06:36:09 | 403,064,365 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | ino | #include <SoftwareSerial.h>
//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2
void setup()
{
//Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
Serial.begin(57600);
//Begin serial communication with Arduino and SIM800L
mySerial.begin(57600);
Serial.println("Initializing...");
delay(1000);
mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
updateSerial();
mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
updateSerial();
mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
updateSerial();
mySerial.println("AT+CREG?"); //Check whether it has registered in the network
updateSerial();
}
void loop()
{
updateSerial();
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
}
while(mySerial.available())
{
Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
}
}
| [
"vaibhavkshirsagar225@gmail.com"
] | vaibhavkshirsagar225@gmail.com |
aaa3a6ff603c4ec7dd925cd11c3adcde7f624117 | 5abcd25ca63733a326a0a86aa86a6aa76c94d4e3 | /src/RequestData.h | ed4dcee567610e1f601a7dff9bc2925713be5688 | [
"BSD-3-Clause"
] | permissive | NTUSTcs1091/Group3 | a9ad34cbe90e38e34563246dbb399319eb59eb9b | 7558d8b634836c713559538ddacc4f008cd56fe8 | refs/heads/master | 2023-06-03T14:42:46.477515 | 2021-06-29T08:13:21 | 2021-06-29T08:13:21 | 345,690,454 | 0 | 4 | BSD-3-Clause | 2021-06-28T09:24:28 | 2021-03-08T14:50:05 | C++ | UTF-8 | C++ | false | false | 1,140 | h | /*
Copyright (c) 2021 Chiu Yen-Chen, Swen Sun-Yen, Wen Yong-Wei, Yuan Wei-Chen.
All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. See the AUTHORS file for names of contributors.
*/
#ifndef SHORTLINK_SRC_REQUESTDATA_H_
#define SHORTLINK_SRC_REQUESTDATA_H_
#include <string>
namespace shortlink {
// For every RequestData, it might has a type of Create, Search, and Invalid.
enum RequestType { kInvalid, kSearch, kCreate };
// RequestData is a class of a data structure that represents a request that a
// user sends to the server. Example:
// RequestData data = RequestData();
// data.target = "3arUqBH";
// data.requestMethod = "Search";
class RequestData {
public:
// Default constructor, all memeber variables would be 0 or "";
RequestData();
// Constructor that sets all the memeber variables with the parameters.
RequestData(const std::string tar, const RequestType method);
// Default destructor
~RequestData();
std::string target;
RequestType requestMethod;
};
} // namespace shortlink
#endif // SHORTLINKSERVER_SRC_REQUESTDATA_H_
| [
"will889889@gmail.com"
] | will889889@gmail.com |
381dbb9d1331e50ea3b74c7c9cfbfc997d60fc1e | 844969bd953d7300f02172c867725e27b518c08e | /SDK/BP_AI_wpn_cutlass_ItemDesc_classes.h | cd630bcc7d4dde9921c316742c6228bea9385d35 | [] | no_license | zanzo420/SoT-Python-Offset-Finder | 70037c37991a2df53fa671e3c8ce12c45fbf75a5 | d881877da08b5c5beaaca140f0ab768223b75d4d | refs/heads/main | 2023-07-18T17:25:01.596284 | 2021-09-09T12:31:51 | 2021-09-09T12:31:51 | 380,604,174 | 0 | 0 | null | 2021-06-26T22:07:04 | 2021-06-26T22:07:03 | null | UTF-8 | C++ | false | false | 824 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_AI_wpn_cutlass_ItemDesc.BP_AI_wpn_cutlass_ItemDesc_C
// 0x0000 (FullSize[0x0130] - InheritedSize[0x0130])
class UBP_AI_wpn_cutlass_ItemDesc_C : public UItemWithoutIconsDesc
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_AI_wpn_cutlass_ItemDesc.BP_AI_wpn_cutlass_ItemDesc_C");
return ptr;
}
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"51171051+DougTheDruid@users.noreply.github.com"
] | 51171051+DougTheDruid@users.noreply.github.com |
2d7c94e42d0334871d64143eae6486f9a0ebbaf3 | 7351bfa321d486a26d0aa8fa211c0eac26699565 | /mainwindow.h | 78cc4ebf39cc29bb4bfe12a7aada50325d963e9b | [] | no_license | troe88/gps_draw | 69c7031240da67a67dda306061e7c35bcb5768a2 | 8cb16b8bd4e4fa77f7779c6f85c4eaffd2f80fb3 | refs/heads/master | 2021-01-19T06:43:36.250245 | 2015-05-15T08:17:02 | 2015-05-15T08:17:02 | 35,628,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QtGui>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
#include <QGraphicsRectItem>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void prepareTable();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"dmitry.trok@gmai.com"
] | dmitry.trok@gmai.com |
0512463c12f813406b3266fe826053f74515def0 | 22561a413e066740733dd6bc8d92021f65d4a9ae | /Algorithm/Solution105.cpp | 5d70cad77f5da81332090d4ff200a0b3414e2a69 | [] | no_license | Pancf/Algorithm | 9c76198658146bd77d05220888f288b29e2fdef8 | 9a6de7f212abd371969b4ce3198e4e0b684a7e51 | refs/heads/master | 2023-04-07T21:06:57.071177 | 2021-04-09T09:06:33 | 2021-04-09T09:09:52 | 73,789,124 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,198 | cpp | //
// Solution105.cpp
// Algorithm
//
// Created by Pancf on 2020/12/6.
// Copyright © 2020 Pancf. All rights reserved.
//
#include "Solution105.hpp"
static TreeNode* build(std::vector<int> &preorder, std::vector<int> &inorder, int leftIdx, int rightIdx, int rootIdxInPreorder)
{
if (leftIdx == rightIdx) {
// leaf node
TreeNode *node = new TreeNode(inorder[leftIdx]);
return node;
}
int rootIdx = leftIdx;
for (int i = leftIdx; i <= rightIdx; ++i) {
if (preorder[rootIdxInPreorder] == inorder[i]) {
rootIdx = i;
break;
}
}
TreeNode *root = new TreeNode(inorder[rootIdx]);
if (rootIdx > leftIdx) root->left = build(preorder, inorder, leftIdx, rootIdx - 1, rootIdxInPreorder + 1);
if (rootIdx < rightIdx) root->right = build(preorder, inorder, rootIdx + 1, rightIdx, rootIdxInPreorder + rootIdx - leftIdx + 1);
return root;
}
TreeNode* Solution105::buildTree(std::vector<int> &preorder, std::vector<int> &inorder)
{
if (preorder.empty() || inorder.empty()) return nullptr;
int size = (int)preorder.size();
auto root = build(preorder, inorder, 0, size - 1, 0);
return root;
}
| [
"panchenfeng@stu.xmu.edu.cn"
] | panchenfeng@stu.xmu.edu.cn |
f11d4b91984a127b9f1f2e20e43388d77bf0d20d | e93312c9388e16180be80e79d811e3338cf5e902 | /Cpp/InlineSample/InlineSample.cpp | b7ea69c059ef040a6004412727e7104749be463b | [
"MIT"
] | permissive | VontineDev/repos | 787d64e5222005359d0b510bf74f158fef870ba1 | 0e98250a00d3deb0da4907898c3972222f14a5c8 | refs/heads/main | 2023-04-17T05:10:57.202546 | 2021-04-29T02:18:15 | 2021-04-29T02:18:15 | 362,630,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | cpp | // InlineSample.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <iostream>
using namespace std;
#define ADD(a,b)((a)+(b))
int Add(int a, int b)
{
return a + b;
}
inline int AddNew(int a, int b)
{
return a + b;
}
int main()
{
int a, b;
scanf_s("%d%d", &a, &b);
printf("ADD(): %d", ADD(a, b));
printf("Add(): %d", Add(a, b));
printf("AddNew(): %d", AddNew(a, b));
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| [
"57723128+VontineDev@users.noreply.github.com"
] | 57723128+VontineDev@users.noreply.github.com |
1022e992ae53f3aae4cadd0aa523c8d63b011e8d | 588ae69239b6211ed4aa7310824eae0c36229acc | /inc/run.hpp | 06a32a787876be61d324207a52ee1d802b11f860 | [] | no_license | ZARAG-YAN/My-Project | 00c69b240d1b851ad1c2fcb46577bbf85ebc9b03 | 1a17cde25dda89b669af848dc7c4b735e2ba9571 | refs/heads/master | 2020-04-26T01:53:13.249448 | 2019-03-22T12:53:04 | 2019-03-22T12:53:04 | 173,218,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | hpp | #include <sstream>
#include <iostream>
void start(char [][10], char [][10], int&, int&);
bool user_input(int&, int&, char [][10]);
void run();
| [
"zara030396@gmail.com"
] | zara030396@gmail.com |
cad4f7ae1a02dbe8b1004ff3b5a0b7efc49ac210 | a796d62943524337fffd2ff594f494390ae84c5e | /src/game/server/hl2/npc_antlionguard.cpp | 16a50b789331e725396e75048f56de16e1436416 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | blockspacer/source-asw-sdk | 12c4be5e05f76f8b5a1b0e6671d34b66d6385a68 | 88156ac5a4204becb06c6d383e2a947c8b2b27a3 | refs/heads/master | 2021-09-10T09:49:32.508970 | 2018-03-23T23:10:13 | 2018-03-23T23:10:13 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 155,328 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Antlion Guard
//
//=============================================================================//
#include "cbase.h"
#include "ai_hint.h"
#include "ai_localnavigator.h"
#include "ai_memory.h"
#include "ai_moveprobe.h"
#include "npcevent.h"
#include "IEffects.h"
#include "ndebugoverlay.h"
#include "soundent.h"
#include "soundenvelope.h"
#include "ai_squad.h"
#include "ai_network.h"
#include "ai_pathfinder.h"
#include "ai_navigator.h"
#include "ai_senses.h"
#include "npc_rollermine.h"
#include "ai_blended_movement.h"
#include "physics_prop_ragdoll.h"
#include "iservervehicle.h"
#include "player_pickup.h"
#include "props.h"
#include "antlion_dust.h"
#include "npc_antlion.h"
#include "decals.h"
#include "prop_combine_ball.h"
#include "eventqueue.h"
#include "te_effect_dispatch.h"
#include "Sprite.h"
#include "particle_parse.h"
#include "particle_system.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
inline void TraceHull_SkipPhysics( const Vector &vecAbsStart, const Vector &vecAbsEnd, const Vector &hullMin,
const Vector &hullMax, unsigned int mask, const CBaseEntity *ignore,
int collisionGroup, trace_t *ptr, float minMass );
ConVar g_debug_antlionguard( "g_debug_antlionguard", "0" );
ConVar sk_antlionguard_dmg_charge( "sk_antlionguard_dmg_charge", "0" );
ConVar sk_antlionguard_dmg_shove( "sk_antlionguard_dmg_shove", "0" );
#if HL2_EPISODIC
// When enabled, add code to have the antlion bleed profusely as it is badly injured.
#define ANTLIONGUARD_BLOOD_EFFECTS 2
ConVar g_antlionguard_hemorrhage( "g_antlionguard_hemorrhage", "1", FCVAR_NONE, "If 1, guard will emit a bleeding particle effect when wounded." );
#endif
// Spawnflags
#define SF_ANTLIONGUARD_SERVERSIDE_RAGDOLL ( 1 << 16 )
#define SF_ANTLIONGUARD_INSIDE_FOOTSTEPS ( 1 << 17 )
#define ENVELOPE_CONTROLLER (CSoundEnvelopeController::GetController())
#define ANTLIONGUARD_MODEL "models/antlion_guard.mdl"
#define MIN_BLAST_DAMAGE 25.0f
#define MIN_CRUSH_DAMAGE 20.0f
//==================================================
//
// Antlion Guard
//
//==================================================
#define ANTLIONGUARD_MAX_OBJECTS 128
#define ANTLIONGUARD_MIN_OBJECT_MASS 8
#define ANTLIONGUARD_MAX_OBJECT_MASS 750
#define ANTLIONGUARD_FARTHEST_PHYSICS_OBJECT 350
#define ANTLIONGUARD_OBJECTFINDING_FOV DOT_45DEGREE // 1/sqrt(2)
//Melee definitions
#define ANTLIONGUARD_MELEE1_RANGE 156.0f
#define ANTLIONGUARD_MELEE1_CONE 0.7f
// Antlion summoning
#define ANTLIONGUARD_SUMMON_COUNT 3
// Sight
#define ANTLIONGUARD_FOV_NORMAL -0.4f
// cavern guard's poisoning behavior
#if HL2_EPISODIC
#define ANTLIONGUARD_POISON_TO 12 // we only poison Gordon down to twelve to give him a chance to regen up to 20 by the next charge
#endif
#define ANTLIONGUARD_CHARGE_MIN 256
#define ANTLIONGUARD_CHARGE_MAX 2048
ConVar sk_antlionguard_health( "sk_antlionguard_health", "0" );
int g_interactionAntlionGuardFoundPhysicsObject = 0; // We're moving to a physics object to shove it, don't all choose the same object
int g_interactionAntlionGuardShovedPhysicsObject = 0; // We've punted an object, it is now clear to be chosen by others
//==================================================
// AntlionGuardSchedules
//==================================================
enum
{
SCHED_ANTLIONGUARD_CHARGE = LAST_SHARED_SCHEDULE,
SCHED_ANTLIONGUARD_CHARGE_CRASH,
SCHED_ANTLIONGUARD_CHARGE_CANCEL,
SCHED_ANTLIONGUARD_PHYSICS_ATTACK,
SCHED_ANTLIONGUARD_PHYSICS_DAMAGE_HEAVY,
SCHED_ANTLIONGUARD_UNBURROW,
SCHED_ANTLIONGUARD_CHARGE_TARGET,
SCHED_ANTLIONGUARD_FIND_CHARGE_POSITION,
SCHED_ANTLIONGUARD_MELEE_ATTACK1,
SCHED_ANTLIONGUARD_SUMMON,
SCHED_ANTLIONGUARD_PATROL_RUN,
SCHED_ANTLIONGUARD_ROAR,
SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE,
SCHED_FORCE_ANTLIONGUARD_PHYSICS_ATTACK,
SCHED_ANTLIONGUARD_CANT_ATTACK,
SCHED_ANTLIONGUARD_TAKE_COVER_FROM_ENEMY,
SCHED_ANTLIONGUARD_CHASE_ENEMY
};
//==================================================
// AntlionGuardTasks
//==================================================
enum
{
TASK_ANTLIONGUARD_CHARGE = LAST_SHARED_TASK,
TASK_ANTLIONGUARD_GET_PATH_TO_PHYSOBJECT,
TASK_ANTLIONGUARD_SHOVE_PHYSOBJECT,
TASK_ANTLIONGUARD_SUMMON,
TASK_ANTLIONGUARD_SET_FLINCH_ACTIVITY,
TASK_ANTLIONGUARD_GET_PATH_TO_CHARGE_POSITION,
TASK_ANTLIONGUARD_GET_PATH_TO_NEAREST_NODE,
TASK_ANTLIONGUARD_GET_CHASE_PATH_ENEMY_TOLERANCE,
TASK_ANTLIONGUARD_OPPORTUNITY_THROW,
TASK_ANTLIONGUARD_FIND_PHYSOBJECT,
};
//==================================================
// AntlionGuardConditions
//==================================================
enum
{
COND_ANTLIONGUARD_PHYSICS_TARGET = LAST_SHARED_CONDITION,
COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID,
COND_ANTLIONGUARD_HAS_CHARGE_TARGET,
COND_ANTLIONGUARD_CAN_SUMMON,
COND_ANTLIONGUARD_CAN_CHARGE
};
enum
{
SQUAD_SLOT_ANTLIONGUARD_CHARGE = LAST_SHARED_SQUADSLOT,
};
//==================================================
// AntlionGuard Activities
//==================================================
Activity ACT_ANTLIONGUARD_SEARCH;
Activity ACT_ANTLIONGUARD_PEEK_FLINCH;
Activity ACT_ANTLIONGUARD_PEEK_ENTER;
Activity ACT_ANTLIONGUARD_PEEK_EXIT;
Activity ACT_ANTLIONGUARD_PEEK1;
Activity ACT_ANTLIONGUARD_BARK;
Activity ACT_ANTLIONGUARD_PEEK_SIGHTED;
Activity ACT_ANTLIONGUARD_SHOVE_PHYSOBJECT;
Activity ACT_ANTLIONGUARD_FLINCH_LIGHT;
Activity ACT_ANTLIONGUARD_UNBURROW;
Activity ACT_ANTLIONGUARD_ROAR;
Activity ACT_ANTLIONGUARD_RUN_HURT;
// Flinches
Activity ACT_ANTLIONGUARD_PHYSHIT_FR;
Activity ACT_ANTLIONGUARD_PHYSHIT_FL;
Activity ACT_ANTLIONGUARD_PHYSHIT_RR;
Activity ACT_ANTLIONGUARD_PHYSHIT_RL;
// Charge
Activity ACT_ANTLIONGUARD_CHARGE_START;
Activity ACT_ANTLIONGUARD_CHARGE_CANCEL;
Activity ACT_ANTLIONGUARD_CHARGE_RUN;
Activity ACT_ANTLIONGUARD_CHARGE_CRASH;
Activity ACT_ANTLIONGUARD_CHARGE_STOP;
Activity ACT_ANTLIONGUARD_CHARGE_HIT;
Activity ACT_ANTLIONGUARD_CHARGE_ANTICIPATION;
// Anim events
int AE_ANTLIONGUARD_CHARGE_HIT;
int AE_ANTLIONGUARD_SHOVE_PHYSOBJECT;
int AE_ANTLIONGUARD_SHOVE;
int AE_ANTLIONGUARD_FOOTSTEP_LIGHT;
int AE_ANTLIONGUARD_FOOTSTEP_HEAVY;
int AE_ANTLIONGUARD_CHARGE_EARLYOUT;
int AE_ANTLIONGUARD_VOICE_GROWL;
int AE_ANTLIONGUARD_VOICE_BARK;
int AE_ANTLIONGUARD_VOICE_PAIN;
int AE_ANTLIONGUARD_VOICE_SQUEEZE;
int AE_ANTLIONGUARD_VOICE_SCRATCH;
int AE_ANTLIONGUARD_VOICE_GRUNT;
int AE_ANTLIONGUARD_VOICE_ROAR;
int AE_ANTLIONGUARD_BURROW_OUT;
struct PhysicsObjectCriteria_t
{
CBaseEntity *pTarget;
Vector vecCenter; // Center point to look around
float flRadius; // Radius to search within
float flTargetCone;
bool bPreferObjectsAlongTargetVector; // Prefer objects that we can strike easily as we move towards our target
float flNearRadius; // If we won't hit the player with the object, but get this close, throw anyway
};
#define MAX_FAILED_PHYSOBJECTS 8
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CNPC_AntlionGuard : public CAI_BlendedNPC
{
public:
DECLARE_CLASS( CNPC_AntlionGuard, CAI_BlendedNPC );
DECLARE_SERVERCLASS();
DECLARE_DATADESC();
CNPC_AntlionGuard( void );
Class_T Classify( void ) { return CLASS_ANTLION; }
virtual int GetSoundInterests( void ) { return (SOUND_WORLD|SOUND_COMBAT|SOUND_PLAYER|SOUND_DANGER); }
virtual bool QueryHearSound( CSound *pSound );
const impactdamagetable_t &GetPhysicsImpactDamageTable( void );
virtual int MeleeAttack1Conditions( float flDot, float flDist );
virtual int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
virtual int TranslateSchedule( int scheduleType );
virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info );
virtual void DeathSound( const CTakeDamageInfo &info );
virtual void Event_Killed( const CTakeDamageInfo &info );
virtual int SelectSchedule( void );
virtual float GetAutoAimRadius() { return 36.0f; }
virtual void Precache( void );
virtual void Spawn( void );
virtual void Activate( void );
virtual void HandleAnimEvent( animevent_t *pEvent );
virtual void UpdateEfficiency( bool bInPVS ) { SetEfficiency( ( GetSleepState() != AISS_AWAKE ) ? AIE_DORMANT : AIE_NORMAL ); SetMoveEfficiency( AIME_NORMAL ); }
virtual void PrescheduleThink( void );
virtual void GatherConditions( void );
virtual void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
virtual void StartTask( const Task_t *pTask );
virtual void RunTask( const Task_t *pTask );
virtual void StopLoopingSounds();
virtual bool HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sender );
// Input handlers.
void InputSetShoveTarget( inputdata_t &inputdata );
void InputSetChargeTarget( inputdata_t &inputdata );
void InputClearChargeTarget( inputdata_t &inputdata );
void InputUnburrow( inputdata_t &inputdata );
void InputRagdoll( inputdata_t &inputdata );
void InputEnableBark( inputdata_t &inputdata );
void InputDisableBark( inputdata_t &inputdata );
void InputSummonedAntlionDied( inputdata_t &inputdata );
void InputEnablePreferPhysicsAttack( inputdata_t &inputdata );
void InputDisablePreferPhysicsAttack( inputdata_t &inputdata );
virtual bool IsLightDamage( const CTakeDamageInfo &info );
virtual bool IsHeavyDamage( const CTakeDamageInfo &info );
virtual bool OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval );
virtual bool BecomeRagdollOnClient( const Vector &force );
virtual void UpdateOnRemove( void );
virtual bool IsUnreachable( CBaseEntity* pEntity ); // Is entity is unreachable?
virtual float MaxYawSpeed( void );
virtual bool OverrideMove( float flInterval );
virtual bool CanBecomeRagdoll( void );
virtual bool ShouldProbeCollideAgainstEntity( CBaseEntity *pEntity );
virtual Activity NPC_TranslateActivity( Activity baseAct );
#if HL2_EPISODIC
//---------------------------------
// Navigation & Movement -- prevent stopping paths for the guard
//---------------------------------
class CNavigator : public CAI_ComponentWithOuter<CNPC_AntlionGuard, CAI_Navigator>
{
typedef CAI_ComponentWithOuter<CNPC_AntlionGuard, CAI_Navigator> BaseClass;
public:
CNavigator( CNPC_AntlionGuard *pOuter )
: BaseClass( pOuter )
{
}
bool GetStoppingPath( CAI_WaypointList *pClippedWaypoints );
};
CAI_Navigator * CreateNavigator() { return new CNavigator( this ); }
#endif
DEFINE_CUSTOM_AI;
private:
inline bool CanStandAtPoint( const Vector &vecPos, Vector *pOut );
bool RememberFailedPhysicsTarget( CBaseEntity *pTarget );
void GetPhysicsShoveDir( CBaseEntity *pObject, float flMass, Vector *pOut );
void CreateGlow( CSprite **pSprite, const char *pAttachName );
void DestroyGlows( void );
void Footstep( bool bHeavy );
int SelectCombatSchedule( void );
int SelectUnreachableSchedule( void );
bool CanSummon( bool bIgnoreTime );
void SummonAntlions( void );
void ChargeLookAhead( void );
bool EnemyIsRightInFrontOfMe( CBaseEntity **pEntity );
bool HandleChargeImpact( Vector vecImpact, CBaseEntity *pEntity );
bool ShouldCharge( const Vector &startPos, const Vector &endPos, bool useTime, bool bCheckForCancel );
bool ShouldWatchEnemy( void );
void ImpactShock( const Vector &origin, float radius, float magnitude, CBaseEntity *pIgnored = NULL );
void BuildScheduleTestBits( void );
void Shove( void );
void FoundEnemy( void );
void LostEnemy( void );
void UpdateHead( void );
void UpdatePhysicsTarget( bool bPreferObjectsAlongTargetVector, float flRadius = ANTLIONGUARD_FARTHEST_PHYSICS_OBJECT );
void MaintainPhysicsTarget( void );
void ChargeDamage( CBaseEntity *pTarget );
void StartSounds( void );
void SetHeavyDamageAnim( const Vector &vecSource );
float ChargeSteer( void );
CBaseEntity *FindPhysicsObjectTarget( const PhysicsObjectCriteria_t &criteria );
Vector GetPhysicsHitPosition( CBaseEntity *pObject, CBaseEntity *pTarget, Vector *vecTrajectory, float *flClearDistance );
bool CanStandAtShoveTarget( CBaseEntity *pShoveObject, CBaseEntity *pTarget, Vector *pOut );
CBaseEntity *GetNextShoveTarget( CBaseEntity *pLastEntity, AISightIter_t &iter );
int m_nFlinchActivity;
bool m_bStopped;
bool m_bIsBurrowed;
bool m_bBarkEnabled;
float m_flNextSummonTime;
int m_iNumLiveAntlions;
float m_flSearchNoiseTime;
float m_flAngerNoiseTime;
float m_flBreathTime;
float m_flChargeTime;
float m_flPhysicsCheckTime;
float m_flNextHeavyFlinchTime;
float m_flNextRoarTime;
int m_iChargeMisses;
bool m_bDecidedNotToStop;
bool m_bPreferPhysicsAttack;
CNetworkVar( bool, m_bCavernBreed ); // If this guard is meant to be a cavern dweller (uses different assets)
CNetworkVar( bool, m_bInCavern ); // Behavioral hint telling the guard to change his behavior
Vector m_vecPhysicsTargetStartPos;
Vector m_vecPhysicsHitPosition;
EHANDLE m_hShoveTarget;
EHANDLE m_hChargeTarget;
EHANDLE m_hChargeTargetPosition;
EHANDLE m_hOldTarget;
EHANDLE m_hPhysicsTarget;
CUtlVectorFixed<EHANDLE, MAX_FAILED_PHYSOBJECTS> m_FailedPhysicsTargets;
COutputEvent m_OnSummon;
CSoundPatch *m_pGrowlHighSound;
CSoundPatch *m_pGrowlLowSound;
CSoundPatch *m_pGrowlIdleSound;
CSoundPatch *m_pBreathSound;
CSoundPatch *m_pConfusedSound;
string_t m_iszPhysicsPropClass;
string_t m_strShoveTargets;
CSprite *m_hCaveGlow[2];
#if ANTLIONGUARD_BLOOD_EFFECTS
CNetworkVar( uint8, m_iBleedingLevel );
unsigned char GetBleedingLevel( void ) const;
#endif
protected:
int m_poseThrow;
int m_poseHead_Yaw, m_poseHead_Pitch;
virtual void PopulatePoseParameters( void );
// inline accessors
public:
inline bool IsCavernBreed( void ) const { return m_bCavernBreed; }
inline bool IsInCavern( void ) const { return m_bInCavern; }
};
//==================================================
// CNPC_AntlionGuard::m_DataDesc
//==================================================
BEGIN_DATADESC( CNPC_AntlionGuard )
DEFINE_FIELD( m_nFlinchActivity, FIELD_INTEGER ),
DEFINE_FIELD( m_bStopped, FIELD_BOOLEAN ),
DEFINE_KEYFIELD( m_bIsBurrowed, FIELD_BOOLEAN, "startburrowed" ),
DEFINE_KEYFIELD( m_bBarkEnabled, FIELD_BOOLEAN, "allowbark" ),
DEFINE_FIELD( m_flNextSummonTime, FIELD_TIME ),
DEFINE_FIELD( m_iNumLiveAntlions, FIELD_INTEGER ),
DEFINE_FIELD( m_flSearchNoiseTime, FIELD_TIME ),
DEFINE_FIELD( m_flAngerNoiseTime, FIELD_TIME ),
DEFINE_FIELD( m_flBreathTime, FIELD_TIME ),
DEFINE_FIELD( m_flChargeTime, FIELD_TIME ),
DEFINE_FIELD( m_hShoveTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_hChargeTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_hChargeTargetPosition, FIELD_EHANDLE ),
DEFINE_FIELD( m_hOldTarget, FIELD_EHANDLE ),
// m_FailedPhysicsTargets // We do not save/load these
DEFINE_FIELD( m_hPhysicsTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_vecPhysicsTargetStartPos, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecPhysicsHitPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_flPhysicsCheckTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextHeavyFlinchTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextRoarTime, FIELD_TIME ),
DEFINE_FIELD( m_iChargeMisses, FIELD_INTEGER ),
DEFINE_FIELD( m_bDecidedNotToStop, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bPreferPhysicsAttack, FIELD_BOOLEAN ),
#if ANTLIONGUARD_BLOOD_EFFECTS
DEFINE_FIELD( m_iBleedingLevel, FIELD_CHARACTER ),
#endif
DEFINE_KEYFIELD( m_bCavernBreed,FIELD_BOOLEAN, "cavernbreed" ),
DEFINE_KEYFIELD( m_bInCavern, FIELD_BOOLEAN, "incavern" ),
DEFINE_KEYFIELD( m_strShoveTargets, FIELD_STRING, "shovetargets" ),
DEFINE_AUTO_ARRAY( m_hCaveGlow, FIELD_CLASSPTR ),
DEFINE_OUTPUT( m_OnSummon, "OnSummon" ),
DEFINE_SOUNDPATCH( m_pGrowlHighSound ),
DEFINE_SOUNDPATCH( m_pGrowlLowSound ),
DEFINE_SOUNDPATCH( m_pGrowlIdleSound ),
DEFINE_SOUNDPATCH( m_pBreathSound ),
DEFINE_SOUNDPATCH( m_pConfusedSound ),
DEFINE_INPUTFUNC( FIELD_STRING, "SetShoveTarget", InputSetShoveTarget ),
DEFINE_INPUTFUNC( FIELD_STRING, "SetChargeTarget", InputSetChargeTarget ),
DEFINE_INPUTFUNC( FIELD_VOID, "ClearChargeTarget", InputClearChargeTarget ),
DEFINE_INPUTFUNC( FIELD_VOID, "Unburrow", InputUnburrow ),
DEFINE_INPUTFUNC( FIELD_VOID, "Ragdoll", InputRagdoll ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableBark", InputEnableBark ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableBark", InputDisableBark ),
DEFINE_INPUTFUNC( FIELD_VOID, "SummonedAntlionDied", InputSummonedAntlionDied ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnablePreferPhysicsAttack", InputEnablePreferPhysicsAttack ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisablePreferPhysicsAttack", InputDisablePreferPhysicsAttack ),
END_DATADESC()
//Fast Growl (Growl High)
envelopePoint_t envAntlionGuardFastGrowl[] =
{
{ 1.0f, 1.0f,
0.2f, 0.4f,
},
{ 0.1f, 0.1f,
0.8f, 1.0f,
},
{ 0.0f, 0.0f,
0.4f, 0.8f,
},
};
//Bark 1 (Growl High)
envelopePoint_t envAntlionGuardBark1[] =
{
{ 1.0f, 1.0f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
0.4f, 0.6f,
},
};
//Bark 2 (Confused)
envelopePoint_t envAntlionGuardBark2[] =
{
{ 1.0f, 1.0f,
0.1f, 0.2f,
},
{ 0.2f, 0.3f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
0.4f, 0.6f,
},
};
//Pain
envelopePoint_t envAntlionGuardPain1[] =
{
{ 1.0f, 1.0f,
0.1f, 0.2f,
},
{ -1.0f, -1.0f,
0.5f, 0.8f,
},
{ 0.1f, 0.2f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
0.5f, 0.75f,
},
};
//Squeeze (High Growl)
envelopePoint_t envAntlionGuardSqueeze[] =
{
{ 1.0f, 1.0f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
1.0f, 1.5f,
},
};
//Scratch (Low Growl)
envelopePoint_t envAntlionGuardScratch[] =
{
{ 1.0f, 1.0f,
0.4f, 0.6f,
},
{ 0.5f, 0.5f,
0.4f, 0.6f,
},
{ 0.0f, 0.0f,
1.0f, 1.5f,
},
};
//Grunt
envelopePoint_t envAntlionGuardGrunt[] =
{
{ 0.6f, 1.0f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
0.1f, 0.2f,
},
};
envelopePoint_t envAntlionGuardGrunt2[] =
{
{ 0.2f, 0.4f,
0.1f, 0.2f,
},
{ 0.0f, 0.0f,
0.4f, 0.6f,
},
};
//==============================================================================================
// ANTLION GUARD PHYSICS DAMAGE TABLE
//==============================================================================================
static impactentry_t antlionGuardLinearTable[] =
{
{ 100*100, 10 },
{ 250*250, 25 },
{ 350*350, 50 },
{ 500*500, 75 },
{ 1000*1000,100 },
};
static impactentry_t antlionGuardAngularTable[] =
{
{ 50* 50, 10 },
{ 100*100, 25 },
{ 150*150, 50 },
{ 200*200, 75 },
};
impactdamagetable_t gAntlionGuardImpactDamageTable =
{
antlionGuardLinearTable,
antlionGuardAngularTable,
ARRAYSIZE(antlionGuardLinearTable),
ARRAYSIZE(antlionGuardAngularTable),
200*200,// minimum linear speed squared
180*180,// minimum angular speed squared (360 deg/s to cause spin/slice damage)
15, // can't take damage from anything under 15kg
10, // anything less than 10kg is "small"
5, // never take more than 1 pt of damage from anything under 15kg
128*128,// <15kg objects must go faster than 36 in/s to do damage
45, // large mass in kg
2, // large mass scale (anything over 500kg does 4X as much energy to read from damage table)
1, // large mass falling scale
0, // my MIN velocity
};
//-----------------------------------------------------------------------------
// Purpose:
// Output : const impactdamagetable_t
//-----------------------------------------------------------------------------
const impactdamagetable_t &CNPC_AntlionGuard::GetPhysicsImpactDamageTable( void )
{
return gAntlionGuardImpactDamageTable;
}
//==================================================
// CNPC_AntlionGuard
//==================================================
CNPC_AntlionGuard::CNPC_AntlionGuard( void )
{
m_bCavernBreed = false;
m_bInCavern = false;
m_iszPhysicsPropClass = AllocPooledString( "prop_physics" );
}
LINK_ENTITY_TO_CLASS( npc_antlionguard, CNPC_AntlionGuard );
IMPLEMENT_SERVERCLASS_ST(CNPC_AntlionGuard, DT_NPC_AntlionGuard)
SendPropBool( SENDINFO( m_bCavernBreed ) ),
SendPropBool( SENDINFO( m_bInCavern ) ),
#if ANTLIONGUARD_BLOOD_EFFECTS
SendPropInt( SENDINFO( m_iBleedingLevel ), 2, SPROP_UNSIGNED ),
#endif
END_SEND_TABLE()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::UpdateOnRemove( void )
{
DestroyGlows();
// Chain to the base class
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Precache( void )
{
PrecacheModel( ANTLIONGUARD_MODEL );
PrecacheScriptSound( "NPC_AntlionGuard.Shove" );
PrecacheScriptSound( "NPC_AntlionGuard.HitHard" );
if ( HasSpawnFlags(SF_ANTLIONGUARD_INSIDE_FOOTSTEPS) )
{
PrecacheScriptSound( "NPC_AntlionGuard.Inside.StepLight" );
PrecacheScriptSound( "NPC_AntlionGuard.Inside.StepHeavy" );
}
else
{
PrecacheScriptSound( "NPC_AntlionGuard.StepLight" );
PrecacheScriptSound( "NPC_AntlionGuard.StepHeavy" );
}
#if HL2_EPISODIC
PrecacheScriptSound( "NPC_AntlionGuard.NearStepLight" );
PrecacheScriptSound( "NPC_AntlionGuard.NearStepHeavy" );
PrecacheScriptSound( "NPC_AntlionGuard.FarStepLight" );
PrecacheScriptSound( "NPC_AntlionGuard.FarStepHeavy" );
PrecacheScriptSound( "NPC_AntlionGuard.BreatheLoop" );
PrecacheScriptSound( "NPC_AntlionGuard.ShellCrack" );
PrecacheScriptSound( "NPC_AntlionGuard.Pain_Roar" );
PrecacheModel( "sprites/grubflare1.vmt" );
#endif // HL2_EPISODIC
PrecacheScriptSound( "NPC_AntlionGuard.Anger" );
PrecacheScriptSound( "NPC_AntlionGuard.Roar" );
PrecacheScriptSound( "NPC_AntlionGuard.Die" );
PrecacheScriptSound( "NPC_AntlionGuard.GrowlHigh" );
PrecacheScriptSound( "NPC_AntlionGuard.GrowlIdle" );
PrecacheScriptSound( "NPC_AntlionGuard.BreathSound" );
PrecacheScriptSound( "NPC_AntlionGuard.Confused" );
PrecacheScriptSound( "NPC_AntlionGuard.Fallover" );
PrecacheScriptSound( "NPC_AntlionGuard.FrustratedRoar" );
PrecacheParticleSystem( "blood_antlionguard_injured_light" );
PrecacheParticleSystem( "blood_antlionguard_injured_heavy" );
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::DestroyGlows( void )
{
if ( m_hCaveGlow[0] )
{
UTIL_Remove( m_hCaveGlow[0] );
// reset it to NULL in case there is a double death cleanup for some reason.
m_hCaveGlow[0] = NULL;
}
if ( m_hCaveGlow[1] )
{
UTIL_Remove( m_hCaveGlow[1] );
// reset it to NULL in case there is a double death cleanup for some reason.
m_hCaveGlow[1] = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::CreateGlow( CSprite **pSprite, const char *pAttachName )
{
if ( pSprite == NULL )
return;
// Create the glow sprite
*pSprite = CSprite::SpriteCreate( "sprites/grubflare1.vmt", GetLocalOrigin(), false );
Assert( *pSprite );
if ( *pSprite == NULL )
return;
(*pSprite)->TurnOn();
(*pSprite)->SetTransparency( kRenderWorldGlow, 156, 169, 121, 164, kRenderFxNoDissipation );
(*pSprite)->SetScale( 1.0f );
(*pSprite)->SetGlowProxySize( 16.0f );
int nAttachment = LookupAttachment( pAttachName );
(*pSprite)->SetParent( this, nAttachment );
(*pSprite)->SetLocalOrigin( vec3_origin );
// Don't uselessly animate, we're a static sprite!
(*pSprite)->SetThink( NULL );
(*pSprite)->SetNextThink( TICK_NEVER_THINK );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Spawn( void )
{
Precache();
SetModel( ANTLIONGUARD_MODEL );
// Switch our skin (for now), if we're the cavern guard
if ( m_bCavernBreed )
{
m_nSkin = 1;
// Add glows
CreateGlow( &(m_hCaveGlow[0]), "attach_glow1" );
CreateGlow( &(m_hCaveGlow[1]), "attach_glow2" );
}
else
{
m_hCaveGlow[0] = NULL;
m_hCaveGlow[1] = NULL;
}
SetHullType( HULL_LARGE );
SetHullSizeNormal();
SetDefaultEyeOffset();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetMoveType( MOVETYPE_STEP );
SetNavType( NAV_GROUND );
SetBloodColor( BLOOD_COLOR_YELLOW );
m_iHealth = sk_antlionguard_health.GetFloat();
m_iMaxHealth = m_iHealth;
m_flFieldOfView = ANTLIONGUARD_FOV_NORMAL;
m_flPhysicsCheckTime = 0;
m_flChargeTime = 0;
m_flNextRoarTime = 0;
m_flNextSummonTime = 0;
m_iNumLiveAntlions = 0;
m_iChargeMisses = 0;
m_flNextHeavyFlinchTime = 0;
m_bDecidedNotToStop = false;
ClearHintGroup();
m_bStopped = false;
m_hShoveTarget = NULL;
m_hChargeTarget = NULL;
m_hChargeTargetPosition = NULL;
m_hPhysicsTarget = NULL;
m_HackedGunPos.x = 10;
m_HackedGunPos.y = 0;
m_HackedGunPos.z = 30;
CapabilitiesClear();
CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_MELEE_ATTACK1 | bits_CAP_SQUAD );
CapabilitiesAdd( bits_CAP_SKIP_NAV_GROUND_CHECK );
NPCInit();
BaseClass::Spawn();
//See if we're supposed to start burrowed
if ( m_bIsBurrowed )
{
AddEffects( EF_NODRAW );
AddFlag( FL_NOTARGET );
m_spawnflags |= SF_NPC_GAG;
AddSolidFlags( FSOLID_NOT_SOLID );
m_takedamage = DAMAGE_NO;
if ( m_hCaveGlow[0] )
m_hCaveGlow[0]->TurnOff();
if ( m_hCaveGlow[1] )
m_hCaveGlow[1]->TurnOff();
}
// Do not dissolve
AddEFlags( EFL_NO_DISSOLVE );
// We get a minute of free knowledge about the target
GetEnemies()->SetEnemyDiscardTime( 120.0f );
GetEnemies()->SetFreeKnowledgeDuration( 60.0f );
// We need to bloat the absbox to encompass all the hitboxes
Vector absMin = -Vector(100,100,0);
Vector absMax = Vector(100,100,128);
CollisionProp()->SetSurroundingBoundsType( USE_SPECIFIED_BOUNDS, &absMin, &absMax );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Activate( void )
{
BaseClass::Activate();
// Find all nearby physics objects and add them to the list of objects we will sense
CBaseEntity *pObject = NULL;
while ( ( pObject = gEntList.FindEntityInSphere( pObject, WorldSpaceCenter(), 2500 ) ) != NULL )
{
// Can't throw around debris
if ( pObject->GetCollisionGroup() == COLLISION_GROUP_DEBRIS )
continue;
// We can only throw a few types of things
if ( !FClassnameIs( pObject, "prop_physics" ) && !FClassnameIs( pObject, "func_physbox" ) )
continue;
// Ensure it's mass is within range
IPhysicsObject *pPhysObj = pObject->VPhysicsGetObject();
if( ( pPhysObj == NULL ) || ( pPhysObj->GetMass() > ANTLIONGUARD_MAX_OBJECT_MASS ) || ( pPhysObj->GetMass() < ANTLIONGUARD_MIN_OBJECT_MASS ) )
continue;
// Tell the AI sensing list that we want to consider this
g_AI_SensedObjectsManager.AddEntity( pObject );
if ( g_debug_antlionguard.GetInt() == 5 )
{
Msg("Antlion Guard: Added prop with model '%s' to sense list.\n", STRING(pObject->GetModelName()) );
pObject->m_debugOverlays |= OVERLAY_BBOX_BIT;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Return true if the guard's allowed to summon antlions
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::CanSummon( bool bIgnoreTime )
{
if ( !m_bBarkEnabled )
return false;
if ( !bIgnoreTime && m_flNextSummonTime > gpGlobals->curtime )
return false;
// Hit the max number of them allowed? Only summon when we're 2 down.
if ( m_iNumLiveAntlions >= MAX(1, ANTLIONGUARD_SUMMON_COUNT-1) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Our enemy is unreachable. Select a schedule.
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::SelectUnreachableSchedule( void )
{
// If we're in the cavern setting, we opt out of this
if ( m_bInCavern )
return SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE;
// Summon antlions if we can
if ( HasCondition( COND_ANTLIONGUARD_CAN_SUMMON ) )
return SCHED_ANTLIONGUARD_SUMMON;
// First, look for objects near ourselves
PhysicsObjectCriteria_t criteria;
criteria.bPreferObjectsAlongTargetVector = false;
criteria.flNearRadius = (40*12);
criteria.flRadius = (250*12);
criteria.flTargetCone = -1.0f;
criteria.pTarget = GetEnemy();
criteria.vecCenter = GetAbsOrigin();
CBaseEntity *pTarget = FindPhysicsObjectTarget( criteria );
if ( pTarget == NULL && GetEnemy() )
{
// Use the same criteria, but search near the target instead of us
criteria.vecCenter = GetEnemy()->GetAbsOrigin();
pTarget = FindPhysicsObjectTarget( criteria );
}
// If we found one, we'll want to attack it
if ( pTarget )
{
m_hPhysicsTarget = pTarget;
SetCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
m_vecPhysicsTargetStartPos = m_hPhysicsTarget->WorldSpaceCenter();
// Tell any squadmates I'm going for this item so they don't as well
if ( GetSquad() != NULL )
{
GetSquad()->BroadcastInteraction( g_interactionAntlionGuardFoundPhysicsObject, (void *)((CBaseEntity *)m_hPhysicsTarget), this );
}
return SCHED_ANTLIONGUARD_PHYSICS_ATTACK;
}
// Deal with a visible player
if ( HasCondition( COND_SEE_ENEMY ) )
{
// Roar at the player as show of frustration
if ( m_flNextRoarTime < gpGlobals->curtime )
{
m_flNextRoarTime = gpGlobals->curtime + RandomFloat( 20,40 );
return SCHED_ANTLIONGUARD_ROAR;
}
// If we're under attack, then let's leave for a bit
if ( GetEnemy() && HasCondition( COND_HEAVY_DAMAGE ) )
{
Vector dir = GetEnemy()->GetAbsOrigin() - GetAbsOrigin();
VectorNormalize(dir);
GetMotor()->SetIdealYaw( -dir );
return SCHED_ANTLIONGUARD_TAKE_COVER_FROM_ENEMY;
}
}
// If we're too far away, try to close distance to our target first
float flDistToEnemySqr = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).LengthSqr();
if ( flDistToEnemySqr > Square( 100*12 ) )
return SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE;
// Fire that we're unable to reach our target!
if ( GetEnemy() && GetEnemy()->IsPlayer() )
{
m_OnLostPlayer.FireOutput( this, this );
}
m_OnLostEnemy.FireOutput( this, this );
GetEnemies()->MarkAsEluded( GetEnemy() );
// Move randomly for the moment
return SCHED_ANTLIONGUARD_CANT_ATTACK;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::SelectCombatSchedule( void )
{
ClearHintGroup();
/*
bool bCanCharge = false;
if ( HasCondition( COND_SEE_ENEMY ) )
{
bCanCharge = ShouldCharge( GetAbsOrigin(), GetEnemy()->GetAbsOrigin(), true, false );
}
*/
// Attack if we can
if ( HasCondition(COND_CAN_MELEE_ATTACK1) )
return SCHED_MELEE_ATTACK1;
// Otherwise, summon antlions
if ( HasCondition(COND_ANTLIONGUARD_CAN_SUMMON) )
{
// If I can charge, and have antlions, charge instead
if ( HasCondition( COND_ANTLIONGUARD_CAN_CHARGE ) && m_iNumLiveAntlions )
return SCHED_ANTLIONGUARD_CHARGE;
return SCHED_ANTLIONGUARD_SUMMON;
}
// See if we can bark
if ( HasCondition( COND_ENEMY_UNREACHABLE ) )
return SelectUnreachableSchedule();
//Physics target
if ( HasCondition( COND_ANTLIONGUARD_PHYSICS_TARGET ) && !m_bInCavern )
return SCHED_ANTLIONGUARD_PHYSICS_ATTACK;
// If we've missed a couple of times, and we can summon, make it harder
if ( m_iChargeMisses >= 2 && CanSummon(true) )
{
m_iChargeMisses--;
return SCHED_ANTLIONGUARD_SUMMON;
}
// Charging
if ( HasCondition( COND_ANTLIONGUARD_CAN_CHARGE ) )
{
// Don't let other squad members charge while we're doing it
OccupyStrategySlot( SQUAD_SLOT_ANTLIONGUARD_CHARGE );
return SCHED_ANTLIONGUARD_CHARGE;
}
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::ShouldCharge( const Vector &startPos, const Vector &endPos, bool useTime, bool bCheckForCancel )
{
// Don't charge in tight spaces unless forced to
if ( hl2_episodic.GetBool() && m_bInCavern && !(m_hChargeTarget.Get() && m_hChargeTarget->IsAlive()) )
return false;
// Must have a target
if ( !GetEnemy() )
return false;
// No one else in the squad can be charging already
if ( IsStrategySlotRangeOccupied( SQUAD_SLOT_ANTLIONGUARD_CHARGE, SQUAD_SLOT_ANTLIONGUARD_CHARGE ) )
return false;
// Don't check the distance once we start charging
if ( !bCheckForCancel )
{
// Don't allow use to charge again if it's been too soon
if ( useTime && ( m_flChargeTime > gpGlobals->curtime ) )
return false;
float distance = UTIL_DistApprox2D( startPos, endPos );
// Must be within our tolerance range
if ( ( distance < ANTLIONGUARD_CHARGE_MIN ) || ( distance > ANTLIONGUARD_CHARGE_MAX ) )
return false;
}
if ( GetSquad() )
{
// If someone in our squad is closer to the enemy, then don't charge (we end up hitting them more often than not!)
float flOurDistToEnemySqr = ( GetAbsOrigin() - GetEnemy()->GetAbsOrigin() ).LengthSqr();
AISquadIter_t iter;
for ( CAI_BaseNPC *pSquadMember = GetSquad()->GetFirstMember( &iter ); pSquadMember; pSquadMember = GetSquad()->GetNextMember( &iter ) )
{
if ( pSquadMember->IsAlive() == false || pSquadMember == this )
continue;
if ( ( pSquadMember->GetAbsOrigin() - GetEnemy()->GetAbsOrigin() ).LengthSqr() < flOurDistToEnemySqr )
return false;
}
}
//FIXME: We'd like to exclude small physics objects from this check!
// We only need to hit the endpos with the edge of our bounding box
Vector vecDir = endPos - startPos;
VectorNormalize( vecDir );
float flWidth = WorldAlignSize().x * 0.5;
Vector vecTargetPos = endPos - (vecDir * flWidth);
// See if we can directly move there
AIMoveTrace_t moveTrace;
GetMoveProbe()->MoveLimit( NAV_GROUND, startPos, vecTargetPos, MASK_NPCSOLID_BRUSHONLY, GetEnemy(), &moveTrace );
// Draw the probe
if ( g_debug_antlionguard.GetInt() == 1 )
{
Vector enemyDir = (vecTargetPos - startPos);
float enemyDist = VectorNormalize( enemyDir );
NDebugOverlay::BoxDirection( startPos, GetHullMins(), GetHullMaxs() + Vector(enemyDist,0,0), enemyDir, 0, 255, 0, 8, 1.0f );
}
// If we're not blocked, charge
if ( IsMoveBlocked( moveTrace ) )
{
// Don't allow it if it's too close to us
if ( UTIL_DistApprox( WorldSpaceCenter(), moveTrace.vEndPosition ) < ANTLIONGUARD_CHARGE_MIN )
return false;
// Allow some special cases to not block us
if ( moveTrace.pObstruction != NULL )
{
// If we've hit the world, see if it's a cliff
if ( moveTrace.pObstruction == GetContainingEntity( INDEXENT(0) ) )
{
// Can't be too far above/below the target
if ( fabs( moveTrace.vEndPosition.z - vecTargetPos.z ) > StepHeight() )
return false;
// Allow it if we got pretty close
if ( UTIL_DistApprox( moveTrace.vEndPosition, vecTargetPos ) < 64 )
return true;
}
// Hit things that will take damage
if ( moveTrace.pObstruction->m_takedamage != DAMAGE_NO )
return true;
// Hit things that will move
if ( moveTrace.pObstruction->GetMoveType() == MOVETYPE_VPHYSICS )
return true;
}
return false;
}
// Only update this if we've requested it
if ( useTime )
{
m_flChargeTime = gpGlobals->curtime + 4.0f;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::SelectSchedule( void )
{
// Don't do anything if we're burrowed
if ( m_bIsBurrowed )
return SCHED_IDLE_STAND;
#if 0
// Debug physics object finding
if ( 0 ) //g_debug_antlionguard.GetInt() == 3 )
{
m_flPhysicsCheckTime = 0;
UpdatePhysicsTarget( false );
return SCHED_IDLE_STAND;
}
#endif
// Flinch on heavy damage, but not if we've flinched too recently.
// This is done to prevent stun-locks from grenades.
if ( !m_bInCavern && HasCondition( COND_HEAVY_DAMAGE ) && m_flNextHeavyFlinchTime < gpGlobals->curtime )
{
m_flNextHeavyFlinchTime = gpGlobals->curtime + 8.0f;
return SCHED_ANTLIONGUARD_PHYSICS_DAMAGE_HEAVY;
}
// Prefer to use physics, in this case
if ( m_bPreferPhysicsAttack )
{
// If we have a target, try to go for it
if ( HasCondition( COND_ANTLIONGUARD_PHYSICS_TARGET ) )
return SCHED_ANTLIONGUARD_PHYSICS_ATTACK;
}
// Charge after a target if it's set
if ( m_hChargeTarget && m_hChargeTargetPosition )
{
ClearCondition( COND_ANTLIONGUARD_HAS_CHARGE_TARGET );
ClearHintGroup();
if ( m_hChargeTarget->IsAlive() == false )
{
m_hChargeTarget = NULL;
m_hChargeTargetPosition = NULL;
SetEnemy( m_hOldTarget );
if ( m_hOldTarget == NULL )
{
m_NPCState = NPC_STATE_ALERT;
}
}
else
{
m_hOldTarget = GetEnemy();
SetEnemy( m_hChargeTarget );
UpdateEnemyMemory( m_hChargeTarget, m_hChargeTarget->GetAbsOrigin() );
//If we can't see the target, run to somewhere we can
if ( ShouldCharge( GetAbsOrigin(), GetEnemy()->GetAbsOrigin(), false, false ) == false )
return SCHED_ANTLIONGUARD_FIND_CHARGE_POSITION;
return SCHED_ANTLIONGUARD_CHARGE_TARGET;
}
}
// See if we need to clear a path to our enemy
if ( HasCondition( COND_ENEMY_OCCLUDED ) || HasCondition( COND_ENEMY_UNREACHABLE ) )
{
CBaseEntity *pBlocker = GetEnemyOccluder();
if ( ( pBlocker != NULL ) && FClassnameIs( pBlocker, "prop_physics" ) && !m_bInCavern )
{
m_hPhysicsTarget = pBlocker;
return SCHED_ANTLIONGUARD_PHYSICS_ATTACK;
}
}
//Only do these in combat states
if ( m_NPCState == NPC_STATE_COMBAT && GetEnemy() )
return SelectCombatSchedule();
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::MeleeAttack1Conditions( float flDot, float flDist )
{
// Don't attack again too soon
if ( GetNextAttack() > gpGlobals->curtime )
return 0;
// While charging, we can't melee attack
if ( IsCurSchedule( SCHED_ANTLIONGUARD_CHARGE ) )
return 0;
if ( hl2_episodic.GetBool() && m_bInCavern )
{
// Predict where they'll be and see if THAT is within range
Vector vecPredPos;
UTIL_PredictedPosition( GetEnemy(), 0.25f, &vecPredPos );
if ( ( GetAbsOrigin() - vecPredPos ).Length() > ANTLIONGUARD_MELEE1_RANGE )
return COND_TOO_FAR_TO_ATTACK;
}
else
{
// Must be close enough
if ( flDist > ANTLIONGUARD_MELEE1_RANGE )
return COND_TOO_FAR_TO_ATTACK;
}
// Must be within a viable cone
if ( flDot < ANTLIONGUARD_MELEE1_CONE )
return COND_NOT_FACING_ATTACK;
// If the enemy is on top of me, I'm allowed to hit the sucker
if ( GetEnemy()->GetGroundEntity() == this )
return COND_CAN_MELEE_ATTACK1;
trace_t tr;
TraceHull_SkipPhysics( WorldSpaceCenter(), GetEnemy()->WorldSpaceCenter(), Vector(-10,-10,-10), Vector(10,10,10), MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr, VPhysicsGetObject()->GetMass() * 0.5 );
// If we hit anything, go for it
if ( tr.fraction < 1.0f )
return COND_CAN_MELEE_ATTACK1;
return 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CNPC_AntlionGuard::MaxYawSpeed( void )
{
Activity eActivity = GetActivity();
// Stay still
if (( eActivity == ACT_ANTLIONGUARD_SEARCH ) ||
( eActivity == ACT_ANTLIONGUARD_PEEK_ENTER ) ||
( eActivity == ACT_ANTLIONGUARD_PEEK_EXIT ) ||
( eActivity == ACT_ANTLIONGUARD_PEEK1 ) ||
( eActivity == ACT_ANTLIONGUARD_BARK ) ||
( eActivity == ACT_ANTLIONGUARD_PEEK_SIGHTED ) ||
( eActivity == ACT_MELEE_ATTACK1 ) )
return 0.0f;
CBaseEntity *pEnemy = GetEnemy();
if ( pEnemy != NULL && pEnemy->IsPlayer() == false )
return 16.0f;
// Turn slowly when you're charging
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_START )
return 4.0f;
if ( hl2_episodic.GetBool() && m_bInCavern )
{
// Allow a better turning rate when moving quickly but not charging the player
if ( ( eActivity == ACT_ANTLIONGUARD_CHARGE_RUN ) && IsCurSchedule( SCHED_ANTLIONGUARD_CHARGE ) == false )
return 16.0f;
}
// Turn more slowly as we close in on our target
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_RUN )
{
if ( pEnemy == NULL )
return 2.0f;
float dist = UTIL_DistApprox2D( GetEnemy()->WorldSpaceCenter(), WorldSpaceCenter() );
if ( dist > 512 )
return 16.0f;
//FIXME: Alter by skill level
float yawSpeed = RemapVal( dist, 0, 512, 1.0f, 2.0f );
yawSpeed = clamp( yawSpeed, 1.0f, 2.0f );
return yawSpeed;
}
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_STOP )
return 8.0f;
switch( eActivity )
{
case ACT_TURN_LEFT:
case ACT_TURN_RIGHT:
return 40.0f;
break;
case ACT_RUN:
default:
return 20.0f;
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : flInterval -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::OverrideMove( float flInterval )
{
// If the guard's charging, we're handling the movement
if ( IsCurSchedule( SCHED_ANTLIONGUARD_CHARGE ) )
return true;
// TODO: This code increases the guard's ability to successfully hit a target, but adds a new dimension of navigation
// trouble to do with him not being able to "close the distance" between himself and the object he wants to hit.
// Fixing this will require some thought on how he picks the correct distances to his targets and when he's "close enough". -- jdw
/*
if ( m_hPhysicsTarget != NULL )
{
float flWidth = m_hPhysicsTarget->CollisionProp()->BoundingRadius2D();
GetLocalNavigator()->AddObstacle( m_hPhysicsTarget->WorldSpaceCenter(), flWidth * 0.75f, AIMST_AVOID_OBJECT );
//NDebugOverlay::Sphere( m_hPhysicsTarget->WorldSpaceCenter(), vec3_angle, flWidth, 255, 255, 255, 0, true, 0.5f );
}
*/
return BaseClass::OverrideMove( flInterval );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Shove( void )
{
if ( GetNextAttack() > gpGlobals->curtime )
return;
CBaseEntity *pHurt = NULL;
CBaseEntity *pTarget;
pTarget = ( m_hShoveTarget == NULL ) ? GetEnemy() : m_hShoveTarget.Get();
if ( pTarget == NULL )
{
m_hShoveTarget = NULL;
return;
}
//Always damage bullseyes if we're scripted to hit them
if ( pTarget->Classify() == CLASS_BULLSEYE )
{
pTarget->TakeDamage( CTakeDamageInfo( this, this, 1.0f, DMG_CRUSH ) );
m_hShoveTarget = NULL;
return;
}
float damage = ( pTarget->IsPlayer() ) ? sk_antlionguard_dmg_shove.GetFloat() : 250;
// If the target's still inside the shove cone, ensure we hit him
Vector vecForward, vecEnd;
AngleVectors( GetAbsAngles(), &vecForward );
float flDistSqr = ( pTarget->WorldSpaceCenter() - WorldSpaceCenter() ).LengthSqr();
Vector2D v2LOS = ( pTarget->WorldSpaceCenter() - WorldSpaceCenter() ).AsVector2D();
Vector2DNormalize(v2LOS);
float flDot = DotProduct2D (v2LOS, vecForward.AsVector2D() );
if ( flDistSqr < (ANTLIONGUARD_MELEE1_RANGE*ANTLIONGUARD_MELEE1_RANGE) && flDot >= ANTLIONGUARD_MELEE1_CONE )
{
vecEnd = pTarget->WorldSpaceCenter();
}
else
{
vecEnd = WorldSpaceCenter() + ( BodyDirection3D() * ANTLIONGUARD_MELEE1_RANGE );
}
// Use the melee trace to ensure we hit everything there
trace_t tr;
CTakeDamageInfo dmgInfo( this, this, damage, DMG_SLASH );
CTraceFilterMelee traceFilter( this, COLLISION_GROUP_NONE, &dmgInfo, 1.0, true );
Ray_t ray;
ray.Init( WorldSpaceCenter(), vecEnd, Vector(-16,-16,-16), Vector(16,16,16) );
enginetrace->TraceRay( ray, MASK_SHOT_HULL, &traceFilter, &tr );
pHurt = tr.m_pEnt;
// Knock things around
ImpactShock( tr.endpos, 100.0f, 250.0f );
if ( pHurt )
{
Vector traceDir = ( tr.endpos - tr.startpos );
VectorNormalize( traceDir );
// Generate enough force to make a 75kg guy move away at 600 in/sec
Vector vecForce = traceDir * ImpulseScale( 75, 600 );
CTakeDamageInfo info( this, this, vecForce, tr.endpos, damage, DMG_CLUB );
pHurt->TakeDamage( info );
m_hShoveTarget = NULL;
EmitSound( "NPC_AntlionGuard.Shove" );
// If the player, throw him around
if ( pHurt->IsPlayer() )
{
//Punch the view
pHurt->ViewPunch( QAngle(20,0,-20) );
//Shake the screen
UTIL_ScreenShake( pHurt->GetAbsOrigin(), 100.0, 1.5, 1.0, 2, SHAKE_START );
//Red damage indicator
color32 red = {128,0,0,128};
UTIL_ScreenFade( pHurt, red, 1.0f, 0.1f, FFADE_IN );
Vector forward, up;
AngleVectors( GetLocalAngles(), &forward, NULL, &up );
pHurt->ApplyAbsVelocityImpulse( forward * 400 + up * 150 );
// in the episodes, the cavern guard poisons the player
#if HL2_EPISODIC
// If I am a cavern guard attacking the player, and he still lives, then poison him too.
if ( m_bInCavern && pHurt->IsPlayer() && pHurt->IsAlive() && pHurt->m_iHealth > ANTLIONGUARD_POISON_TO)
{
// That didn't finish them. Take them down to one point with poison damage. It'll heal.
pHurt->TakeDamage( CTakeDamageInfo( this, this, pHurt->m_iHealth - ANTLIONGUARD_POISON_TO, DMG_POISON ) );
}
#endif
}
else
{
CBaseCombatCharacter *pVictim = ToBaseCombatCharacter( pHurt );
if ( pVictim )
{
if ( NPC_Rollermine_IsRollermine( pVictim ) )
{
Pickup_OnPhysGunDrop( pVictim, NULL, LAUNCHED_BY_CANNON );
}
// FIXME: This causes NPCs that are not physically motivated to hop into the air strangely -- jdw
// pVictim->ApplyAbsVelocityImpulse( BodyDirection2D() * 400 + Vector( 0, 0, 250 ) );
}
m_hShoveTarget = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CTraceFilterCharge : public CTraceFilterEntitiesOnly
{
public:
// It does have a base, but we'll never network anything below here..
DECLARE_CLASS_NOBASE( CTraceFilterCharge );
CTraceFilterCharge( const IHandleEntity *passentity, int collisionGroup, CNPC_AntlionGuard *pAttacker )
: m_pPassEnt(passentity), m_collisionGroup(collisionGroup), m_pAttacker(pAttacker)
{
}
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
if ( !StandardFilterRules( pHandleEntity, contentsMask ) )
return false;
if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) )
return false;
// Don't test if the game code tells us we should ignore this collision...
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if ( pEntity )
{
if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) )
return false;
if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) )
return false;
if ( pEntity->m_takedamage == DAMAGE_NO )
return false;
// Translate the vehicle into its driver for damage
if ( pEntity->GetServerVehicle() != NULL )
{
CBaseEntity *pDriver = pEntity->GetServerVehicle()->GetPassenger();
if ( pDriver != NULL )
{
pEntity = pDriver;
}
}
Vector attackDir = pEntity->WorldSpaceCenter() - m_pAttacker->WorldSpaceCenter();
VectorNormalize( attackDir );
float flDamage = ( pEntity->IsPlayer() ) ? sk_antlionguard_dmg_shove.GetFloat() : 250;;
CTakeDamageInfo info( m_pAttacker, m_pAttacker, flDamage, DMG_CRUSH );
CalculateMeleeDamageForce( &info, attackDir, info.GetAttacker()->WorldSpaceCenter(), 4.0f );
CBaseCombatCharacter *pVictimBCC = pEntity->MyCombatCharacterPointer();
// Only do these comparisons between NPCs
if ( pVictimBCC )
{
// Can only damage other NPCs that we hate
if ( m_pAttacker->IRelationType( pEntity ) == D_HT )
{
pEntity->TakeDamage( info );
return true;
}
}
else
{
// Otherwise just damage passive objects in our way
pEntity->TakeDamage( info );
Pickup_ForcePlayerToDropThisObject( pEntity );
}
}
return false;
}
public:
const IHandleEntity *m_pPassEnt;
int m_collisionGroup;
CNPC_AntlionGuard *m_pAttacker;
};
#define MIN_FOOTSTEP_NEAR_DIST Square( 80*12.0f )// ft
//-----------------------------------------------------------------------------
// Purpose: Plays a footstep sound with temporary distance fades
// Input : bHeavy - Larger back hoof is considered a "heavy" step
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Footstep( bool bHeavy )
{
#ifdef HL2COOP
CBasePlayer *pPlayer = UTIL_GetNearestPlayer(GetAbsOrigin());
#else
CBasePlayer *pPlayer = AI_GetSinglePlayer();
Assert( pPlayer != NULL );
#endif
if ( pPlayer == NULL )
return;
float flDistanceToPlayerSqr = ( pPlayer->GetAbsOrigin() - GetAbsOrigin() ).LengthSqr();
float flNearVolume = RemapValClamped( flDistanceToPlayerSqr, Square(10*12.0f), MIN_FOOTSTEP_NEAR_DIST, VOL_NORM, 0.0f );
EmitSound_t soundParams;
CPASAttenuationFilter filter( this );
if ( bHeavy )
{
if ( flNearVolume > 0.0f )
{
soundParams.m_pSoundName = "NPC_AntlionGuard.NearStepHeavy";
soundParams.m_flVolume = flNearVolume;
soundParams.m_nFlags = SND_CHANGE_VOL;
EmitSound( filter, entindex(), soundParams );
}
EmitSound( "NPC_AntlionGuard.FarStepHeavy" );
}
else
{
if ( flNearVolume > 0.0f )
{
soundParams.m_pSoundName = "NPC_AntlionGuard.NearStepLight";
soundParams.m_flVolume = flNearVolume;
soundParams.m_nFlags = SND_CHANGE_VOL;
EmitSound( filter, entindex(), soundParams );
}
EmitSound( "NPC_AntlionGuard.FarStepLight" );
}
}
extern ConVar sv_gravity;
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pObject -
// *pOut -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::GetPhysicsShoveDir( CBaseEntity *pObject, float flMass, Vector *pOut )
{
const Vector vecStart = pObject->WorldSpaceCenter();
const Vector vecTarget = GetEnemy()->WorldSpaceCenter();
const float flBaseSpeed = 800.0f;
float flSpeed = RemapValClamped( flMass, 0.0f, 150.0f, flBaseSpeed * 2.0f, flBaseSpeed );
// Try the most direct route
Vector vecToss = VecCheckThrow( this, vecStart, vecTarget, flSpeed, 1.0f );
// If this failed then try a little faster (flattens the arc)
if ( vecToss == vec3_origin )
{
vecToss = VecCheckThrow( this, vecStart, vecTarget, flSpeed * 1.25f, 1.0f );
if ( vecToss == vec3_origin )
{
const float flGravity = sv_gravity.GetFloat();
vecToss = (vecTarget - vecStart);
// throw at a constant time
float time = vecToss.Length( ) / flSpeed;
vecToss = vecToss * (1.0f / time);
// adjust upward toss to compensate for gravity loss
vecToss.z += flGravity * time * 0.5f;
}
}
// Save out the result
if ( pOut )
{
*pOut = vecToss;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pEvent -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::HandleAnimEvent( animevent_t *pEvent )
{
if ( pEvent->Event() == AE_ANTLIONGUARD_CHARGE_EARLYOUT )
{
// Robin: Removed this because it usually made him look less intelligent, not more.
// This code left here so we don't get warnings in the console.
/*
// Cancel the charge if it's no longer valid
if ( ShouldCharge( GetAbsOrigin(), GetEnemy()->GetAbsOrigin(), false, true ) == false )
{
SetSchedule( SCHED_ANTLIONGUARD_CHARGE_CANCEL );
}
*/
return;
}
// Don't handle anim events after death
if ( m_NPCState == NPC_STATE_DEAD )
{
BaseClass::HandleAnimEvent( pEvent );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_SHOVE_PHYSOBJECT )
{
if ( m_hPhysicsTarget == NULL )
{
// Disrupt other objects near us anyway
ImpactShock( WorldSpaceCenter(), 150, 250.0f );
return;
}
// If we have no enemy, we don't really have a direction to throw the object
// in. But, we still want to clobber it so the animevent doesn't happen fruitlessly,
// and we want to clear the condition flags and other state regarding the m_hPhysicsTarget.
// So, skip the code relevant to computing a launch vector specific to the object I'm
// striking, but use the ImpactShock call further below to punch everything in the neighborhood.
CBaseEntity *pEnemy = GetEnemy();
if ( pEnemy != NULL )
{
//Setup the throw velocity
IPhysicsObject *physObj = m_hPhysicsTarget->VPhysicsGetObject();
Vector vecShoveVel = ( pEnemy->GetAbsOrigin() - m_hPhysicsTarget->WorldSpaceCenter() );
float flTargetDist = VectorNormalize( vecShoveVel );
// Must still be close enough to our target
Vector shoveDir = m_hPhysicsTarget->WorldSpaceCenter() - WorldSpaceCenter();
float shoveDist = VectorNormalize( shoveDir );
if ( shoveDist > 300.0f )
{
// Pick a new target next time (this one foiled us!)
RememberFailedPhysicsTarget( m_hPhysicsTarget );
m_hPhysicsTarget = NULL;
return;
}
// Toss this if we're episodic
if ( hl2_episodic.GetBool() )
{
Vector vecTargetDir = vecShoveVel;
// Get our shove direction
GetPhysicsShoveDir( m_hPhysicsTarget, physObj->GetMass(), &vecShoveVel );
// If the player isn't looking at me, and isn't reachable, be more forgiving about hitting them
if ( HasCondition( COND_ENEMY_UNREACHABLE ) && HasCondition( COND_ENEMY_FACING_ME ) == false )
{
// Build an arc around the top of the target that we'll offset our aim by
Vector vecOffset;
float flSin, flCos;
float flRad = random->RandomFloat( 0, M_PI / 6.0f ); // +/- 30 deg
if ( random->RandomInt( 0, 1 ) )
flRad *= -1.0f;
SinCos( flRad, &flSin, &flCos );
// Rotate the 2-d circle to be "facing" along our shot direction
Vector vecArc;
QAngle vecAngles;
VectorAngles( vecTargetDir, vecAngles );
VectorRotate( Vector( 0.0f, flCos, flSin ), vecAngles, vecArc );
// Find the radius by which to avoid the player
float flOffsetRadius = ( m_hPhysicsTarget->CollisionProp()->BoundingRadius() + GetEnemy()->CollisionProp()->BoundingRadius() ) * 1.5f;
// Add this to our velocity to offset it
vecShoveVel += ( vecArc * flOffsetRadius );
}
// Factor out mass
vecShoveVel *= physObj->GetMass();
// FIXME: We need to restore this on the object at some point if we do this!
float flDragCoef = 0.0f;
physObj->SetDragCoefficient( &flDragCoef, &flDragCoef );
}
else
{
if ( flTargetDist < 512 )
flTargetDist = 512;
if ( flTargetDist > 1024 )
flTargetDist = 1024;
vecShoveVel *= flTargetDist * 3 * physObj->GetMass(); //FIXME: Scale by skill
vecShoveVel[2] += physObj->GetMass() * 350.0f;
}
if ( NPC_Rollermine_IsRollermine( m_hPhysicsTarget ) )
{
Pickup_OnPhysGunDrop( m_hPhysicsTarget, NULL, LAUNCHED_BY_CANNON );
}
//Send it flying
AngularImpulse angVel( random->RandomFloat(-180, 180), 100, random->RandomFloat(-360, 360) );
physObj->ApplyForceCenter( vecShoveVel );
physObj->AddVelocity( NULL, &angVel );
}
//Display dust
Vector vecRandom = RandomVector( -1, 1);
VectorNormalize( vecRandom );
g_pEffects->Dust( m_hPhysicsTarget->WorldSpaceCenter(), vecRandom, 64.0f, 32 );
// If it's being held by the player, break that bond
Pickup_ForcePlayerToDropThisObject( m_hPhysicsTarget );
EmitSound( "NPC_AntlionGuard.HitHard" );
//Clear the state information, we're done
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID );
// Disrupt other objects near it, including the m_hPhysicsTarget if we had no valid enemy
ImpactShock( m_hPhysicsTarget->WorldSpaceCenter(), 150, 250.0f, pEnemy != NULL ? m_hPhysicsTarget : NULL );
// Notify any squad members that we're no longer monopolizing this object
if ( GetSquad() != NULL )
{
GetSquad()->BroadcastInteraction( g_interactionAntlionGuardShovedPhysicsObject, (void *)((CBaseEntity *)m_hPhysicsTarget), this );
}
m_hPhysicsTarget = NULL;
m_FailedPhysicsTargets.RemoveAll();
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_CHARGE_HIT )
{
UTIL_ScreenShake( GetAbsOrigin(), 32.0f, 4.0f, 1.0f, 512, SHAKE_START );
EmitSound( "NPC_AntlionGuard.HitHard" );
Vector startPos = GetAbsOrigin();
float checkSize = ( CollisionProp()->BoundingRadius() + 8.0f );
Vector endPos = startPos + ( BodyDirection3D() * checkSize );
CTraceFilterCharge traceFilter( this, COLLISION_GROUP_NONE, this );
Ray_t ray;
ray.Init( startPos, endPos, GetHullMins(), GetHullMaxs() );
trace_t tr;
enginetrace->TraceRay( ray, MASK_SHOT, &traceFilter, &tr );
if ( g_debug_antlionguard.GetInt() == 1 )
{
Vector hullMaxs = GetHullMaxs();
hullMaxs.x += checkSize;
NDebugOverlay::BoxDirection( startPos, GetHullMins(), hullMaxs, BodyDirection2D(), 100, 255, 255, 20, 1.0f );
}
//NDebugOverlay::Box3D( startPos, endPos, BodyDirection2D(),
if ( m_hChargeTarget && m_hChargeTarget->IsAlive() == false )
{
m_hChargeTarget = NULL;
m_hChargeTargetPosition = NULL;
}
// Cause a shock wave from this point which will distrupt nearby physics objects
ImpactShock( tr.endpos, 200, 500 );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_SHOVE )
{
EmitSound("NPC_AntlionGuard.StepLight", pEvent->eventtime );
Shove();
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_FOOTSTEP_LIGHT )
{
if ( HasSpawnFlags(SF_ANTLIONGUARD_INSIDE_FOOTSTEPS) )
{
#if HL2_EPISODIC
Footstep( false );
#else
EmitSound("NPC_AntlionGuard.Inside.StepLight", pEvent->eventtime );
#endif // HL2_EPISODIC
}
else
{
#if HL2_EPISODIC
Footstep( false );
#else
EmitSound("NPC_AntlionGuard.StepLight", pEvent->eventtime );
#endif // HL2_EPISODIC
}
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_FOOTSTEP_HEAVY )
{
if ( HasSpawnFlags(SF_ANTLIONGUARD_INSIDE_FOOTSTEPS) )
{
#if HL2_EPISODIC
Footstep( true );
#else
EmitSound( "NPC_AntlionGuard.Inside.StepHeavy", pEvent->eventtime );
#endif // HL2_EPISODIC
}
else
{
#if HL2_EPISODIC
Footstep( true );
#else
EmitSound( "NPC_AntlionGuard.StepHeavy", pEvent->eventtime );
#endif // HL2_EPISODIC
}
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_GROWL )
{
StartSounds();
float duration = 0.0f;
if ( random->RandomInt( 0, 10 ) < 6 )
{
duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardFastGrowl, ARRAYSIZE(envAntlionGuardFastGrowl) );
}
else
{
duration = 1.0f;
EmitSound( "NPC_AntlionGuard.FrustratedRoar" );
ENVELOPE_CONTROLLER.SoundFadeOut( m_pGrowlHighSound, 0.5f, false );
}
m_flAngerNoiseTime = gpGlobals->curtime + duration + random->RandomFloat( 2.0f, 4.0f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, 0.1f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration - 0.2f;
EmitSound( "NPC_AntlionGuard.Anger" );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_BARK )
{
StartSounds();
float duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardBark1, ARRAYSIZE(envAntlionGuardBark1) );
ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pConfusedSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardBark2, ARRAYSIZE(envAntlionGuardBark2) );
m_flAngerNoiseTime = gpGlobals->curtime + duration + random->RandomFloat( 2.0f, 4.0f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, 0.1f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration - 0.2f;
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_ROAR )
{
StartSounds();
float duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardFastGrowl, ARRAYSIZE(envAntlionGuardFastGrowl) );
m_flAngerNoiseTime = gpGlobals->curtime + duration + random->RandomFloat( 2.0f, 4.0f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, 0.1f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration - 0.2f;
EmitSound( "NPC_AntlionGuard.Roar" );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_PAIN )
{
StartSounds();
float duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pConfusedSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardPain1, ARRAYSIZE(envAntlionGuardPain1) );
ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardBark2, ARRAYSIZE(envAntlionGuardBark2) );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, 0.1f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration - 0.2f;
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_SQUEEZE )
{
StartSounds();
float duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardSqueeze, ARRAYSIZE(envAntlionGuardSqueeze) );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.6f, random->RandomFloat( 2.0f, 4.0f ) );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pBreathSound, random->RandomInt( 60, 80 ), random->RandomFloat( 2.0f, 4.0f ) );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + ( duration * 0.5f );
EmitSound( "NPC_AntlionGuard.Anger" );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_SCRATCH )
{
StartSounds();
float duration = random->RandomFloat( 2.0f, 4.0f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.6f, duration );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pBreathSound, random->RandomInt( 60, 80 ), duration );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration;
EmitSound( "NPC_AntlionGuard.Anger" );
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_VOICE_GRUNT )
{
StartSounds();
float duration = ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pConfusedSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardGrunt, ARRAYSIZE(envAntlionGuardGrunt) );
ENVELOPE_CONTROLLER.SoundPlayEnvelope( m_pGrowlHighSound, SOUNDCTRL_CHANGE_VOLUME, envAntlionGuardGrunt2, ARRAYSIZE(envAntlionGuardGrunt2) );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, 0.1f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 0.1f );
m_flBreathTime = gpGlobals->curtime + duration;
return;
}
if ( pEvent->Event() == AE_ANTLIONGUARD_BURROW_OUT )
{
EmitSound( "NPC_Antlion.BurrowOut" );
//Shake the screen
UTIL_ScreenShake( GetAbsOrigin(), 0.5f, 80.0f, 1.0f, 256.0f, SHAKE_START );
//Throw dust up
UTIL_CreateAntlionDust( GetAbsOrigin() + Vector(0,0,24), GetLocalAngles() );
RemoveEffects( EF_NODRAW );
RemoveFlag( FL_NOTARGET );
if ( m_bCavernBreed )
{
if ( m_hCaveGlow[0] )
m_hCaveGlow[0]->TurnOn();
if ( m_hCaveGlow[1] )
m_hCaveGlow[1]->TurnOn();
}
return;
}
BaseClass::HandleAnimEvent( pEvent );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::SetHeavyDamageAnim( const Vector &vecSource )
{
if ( !m_bInCavern )
{
Vector vFacing = BodyDirection2D();
Vector vDamageDir = ( vecSource - WorldSpaceCenter() );
vDamageDir.z = 0.0f;
VectorNormalize( vDamageDir );
Vector vDamageRight, vDamageUp;
VectorVectors( vDamageDir, vDamageRight, vDamageUp );
float damageDot = DotProduct( vFacing, vDamageDir );
float damageRightDot = DotProduct( vFacing, vDamageRight );
// See if it's in front
if ( damageDot > 0.0f )
{
// See if it's right
if ( damageRightDot > 0.0f )
{
m_nFlinchActivity = ACT_ANTLIONGUARD_PHYSHIT_FR;
}
else
{
m_nFlinchActivity = ACT_ANTLIONGUARD_PHYSHIT_FL;
}
}
else
{
// Otherwise it's from behind
if ( damageRightDot < 0.0f )
{
m_nFlinchActivity = ACT_ANTLIONGUARD_PHYSHIT_RR;
}
else
{
m_nFlinchActivity = ACT_ANTLIONGUARD_PHYSHIT_RL;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
CTakeDamageInfo dInfo = info;
// Don't take damage from another antlion guard!
if ( dInfo.GetAttacker() && dInfo.GetAttacker() != this && FClassnameIs( dInfo.GetAttacker(), "npc_antlionguard" ) )
return 0;
if ( ( dInfo.GetDamageType() & DMG_CRUSH ) && !( dInfo.GetDamageType() & DMG_VEHICLE ) )
{
// Don't take damage from physics objects that weren't thrown by the player.
CBaseEntity *pInflictor = dInfo.GetInflictor();
IPhysicsObject *pObj = pInflictor->VPhysicsGetObject();
if ( !pObj || !( pObj->GetGameFlags() & FVPHYSICS_WAS_THROWN ) )
{
return 0;
}
}
// Hack to make antlion guard harder in HARD
if ( g_pGameRules->IsSkillLevel(SKILL_HARD) && !(info.GetDamageType() & DMG_CRUSH) )
{
dInfo.SetDamage( dInfo.GetDamage() * 0.75 );
}
// Cap damage taken by crushing (otherwise we can get crushed oddly)
if ( ( dInfo.GetDamageType() & DMG_CRUSH ) && dInfo.GetDamage() > 100 )
{
dInfo.SetDamage( 100 );
}
// Only take damage from what we classify as heavy damages (explosions, refrigerators, etc)
if ( IsHeavyDamage( dInfo ) )
{
// Always take a set amount of damage from a combine ball
if ( info.GetInflictor() && UTIL_IsCombineBall( info.GetInflictor() ) )
{
dInfo.SetDamage( 50 );
}
UTIL_ScreenShake( GetAbsOrigin(), 32.0f, 8.0f, 0.5f, 512, SHAKE_START );
// Set our response animation
SetHeavyDamageAnim( dInfo.GetDamagePosition() );
// Explosive barrels don't carry through their attacker, so this
// condition isn't set, and we still want to flinch. So we set it.
SetCondition( COND_HEAVY_DAMAGE );
// TODO: Make this its own effect!
CEffectData data;
data.m_vOrigin = dInfo.GetDamagePosition();
data.m_vNormal = -dInfo.GetDamageForce();
VectorNormalize( data.m_vNormal );
DispatchEffect( "HunterDamage", data );
// Play a sound for a physics impact
if ( dInfo.GetDamageType() & DMG_CRUSH )
{
EmitSound("NPC_AntlionGuard.ShellCrack");
}
// Roar in pain
EmitSound( "NPC_AntlionGuard.Pain_Roar" );
// TODO: This will require a more complete solution; for now let's shelve it!
/*
if ( dInfo.GetDamageType() & DMG_BLAST )
{
// Create the dust effect in place
CParticleSystem *pParticle = (CParticleSystem *) CreateEntityByName( "info_particle_system" );
if ( pParticle != NULL )
{
// Setup our basic parameters
pParticle->KeyValue( "start_active", "1" );
pParticle->KeyValue( "effect_name", "fire_medium_02_nosmoke" );
pParticle->SetParent( this );
pParticle->SetParentAttachment( "SetParentAttachment", "attach_glow2", true );
pParticle->SetLocalOrigin( Vector( -16, 24, 0 ) );
DispatchSpawn( pParticle );
if ( gpGlobals->curtime > 0.5f )
pParticle->Activate();
pParticle->SetThink( &CBaseEntity::SUB_Remove );
pParticle->SetNextThink( gpGlobals->curtime + random->RandomFloat( 2.0f, 3.0f ) );
}
}
*/
}
int nPreHealth = GetHealth();
int nDamageTaken = BaseClass::OnTakeDamage_Alive( dInfo );
// See if we've crossed a measured phase in our health and flinch from that to show we do take damage
if ( !m_bInCavern && HasCondition( COND_HEAVY_DAMAGE ) == false && ( info.GetDamageType() & DMG_BULLET ) )
{
bool bTakeHeavyDamage = false;
// Do an early flinch so that players understand the guard can be hurt by
if ( ( (float) GetHealth() / (float) GetMaxHealth() ) > 0.9f )
{
float flPrePerc = (float) nPreHealth / (float) GetMaxHealth();
float flPostPerc = (float) GetHealth() / (float) GetMaxHealth();
if ( flPrePerc >= 0.95f && flPostPerc < 0.95f )
{
bTakeHeavyDamage = true;
}
}
// Otherwise see if we've passed a measured point in our health
if ( bTakeHeavyDamage == false )
{
const float flNumDamagePhases = 5.0f;
float flDenom = ( (float) GetMaxHealth() / flNumDamagePhases );
int nPreDamagePhase = ceil( (float) nPreHealth / flDenom );
int nPostDamagePhase = ceil( (float) GetHealth() / flDenom );
if ( nPreDamagePhase != nPostDamagePhase )
{
bTakeHeavyDamage = true;
}
}
// Flinch if we should
if ( bTakeHeavyDamage )
{
// Set our response animation
SetHeavyDamageAnim( dInfo.GetDamagePosition() );
// Roar in pain
EmitSound( "NPC_AntlionGuard.Pain_Roar" );
// Flinch!
SetCondition( COND_HEAVY_DAMAGE );
}
}
return nDamageTaken;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pAttacker -
// flDamage -
// &vecDir -
// *ptr -
// bitsDamageType -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::TraceAttack( const CTakeDamageInfo &inputInfo, const Vector &vecDir, trace_t *ptr )
{
CTakeDamageInfo info = inputInfo;
// Bullets are weak against us, buckshot less so
if ( info.GetDamageType() & DMG_BUCKSHOT )
{
info.ScaleDamage( 0.5f );
}
else if ( info.GetDamageType() & DMG_BULLET )
{
info.ScaleDamage( 0.25f );
}
// Make sure we haven't rounded down to a minimal amount
if ( info.GetDamage() < 1.0f )
{
info.SetDamage( 1.0f );
}
BaseClass::TraceAttack( info, vecDir, ptr );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::StartTask( const Task_t *pTask )
{
switch ( pTask->iTask )
{
case TASK_ANTLIONGUARD_SET_FLINCH_ACTIVITY:
SetIdealActivity( (Activity) m_nFlinchActivity );
break;
case TASK_ANTLIONGUARD_SUMMON:
SummonAntlions();
m_OnSummon.FireOutput( this, this, 0 );
TaskComplete();
break;
case TASK_ANTLIONGUARD_SHOVE_PHYSOBJECT:
{
if ( ( m_hPhysicsTarget == NULL ) || ( GetEnemy() == NULL ) )
{
TaskFail( "Tried to shove a NULL physics target!\n" );
break;
}
//Get the direction and distance to our thrown object
Vector dirToTarget = ( m_hPhysicsTarget->WorldSpaceCenter() - WorldSpaceCenter() );
float distToTarget = VectorNormalize( dirToTarget );
dirToTarget.z = 0;
//Validate it's still close enough to shove
//FIXME: Real numbers
if ( distToTarget > 256.0f )
{
RememberFailedPhysicsTarget( m_hPhysicsTarget );
m_hPhysicsTarget = NULL;
TaskFail( "Shove target moved\n" );
break;
}
//Validate its offset from our facing
float targetYaw = UTIL_VecToYaw( dirToTarget );
float offset = UTIL_AngleDiff( targetYaw, UTIL_AngleMod( GetLocalAngles().y ) );
if ( fabs( offset ) > 55 )
{
RememberFailedPhysicsTarget( m_hPhysicsTarget );
m_hPhysicsTarget = NULL;
TaskFail( "Shove target off-center\n" );
break;
}
//Blend properly
SetPoseParameter( m_poseThrow, offset );
//Start playing the animation
SetActivity( ACT_ANTLIONGUARD_SHOVE_PHYSOBJECT );
}
break;
case TASK_ANTLIONGUARD_FIND_PHYSOBJECT:
{
if ( m_bInCavern && !m_bPreferPhysicsAttack )
{
TaskFail( "Cavern guard is not allowed to use physics attacks." );
}
// Force the antlion guard to find a physobject
m_flPhysicsCheckTime = 0;
UpdatePhysicsTarget( false, (100*12) );
if ( m_hPhysicsTarget )
{
TaskComplete();
}
else
{
TaskFail( "Failed to find a physobject.\n" );
}
}
break;
case TASK_ANTLIONGUARD_GET_PATH_TO_PHYSOBJECT:
{
if ( ( m_hPhysicsTarget == NULL ) || ( GetEnemy() == NULL ) )
{
TaskFail( "Tried to find a path to NULL physics target!\n" );
break;
}
Vector vecGoalPos = m_vecPhysicsHitPosition;
AI_NavGoal_t goal( GOALTYPE_LOCATION, vecGoalPos, ACT_RUN );
if ( GetNavigator()->SetGoal( goal ) )
{
if ( g_debug_antlionguard.GetInt() == 1 )
{
NDebugOverlay::Cross3D( vecGoalPos, Vector(8,8,8), -Vector(8,8,8), 0, 255, 0, true, 2.0f );
NDebugOverlay::Line( vecGoalPos, m_hPhysicsTarget->WorldSpaceCenter(), 0, 255, 0, true, 2.0f );
NDebugOverlay::Line( m_hPhysicsTarget->WorldSpaceCenter(), GetEnemy()->WorldSpaceCenter(), 0, 255, 0, true, 2.0f );
}
// Face the enemy
GetNavigator()->SetArrivalDirection( GetEnemy() );
TaskComplete();
}
else
{
if ( g_debug_antlionguard.GetInt() == 1 )
{
NDebugOverlay::Cross3D( vecGoalPos, Vector(8,8,8), -Vector(8,8,8), 255, 0, 0, true, 2.0f );
NDebugOverlay::Line( vecGoalPos, m_hPhysicsTarget->WorldSpaceCenter(), 255, 0, 0, true, 2.0f );
NDebugOverlay::Line( m_hPhysicsTarget->WorldSpaceCenter(), GetEnemy()->WorldSpaceCenter(), 255, 0, 0, true, 2.0f );
}
RememberFailedPhysicsTarget( m_hPhysicsTarget );
m_hPhysicsTarget = NULL;
TaskFail( "Unable to navigate to physics attack target!\n" );
break;
}
//!!!HACKHACK - this is a hack that covers a bug in antlion guard physics target selection! (Tracker #77601)
// This piece of code (combined with some code in GatherConditions) COVERS THE BUG by escaping the schedule
// if 30 seconds have passed (it should never take this long for the guard to get to an object and hit it).
// It's too scary to figure out why this particular antlion guard can't get to its object, but we're shipping
// like, tomorrow. (sjb) 8/22/2007
m_flWaitFinished = gpGlobals->curtime + 30.0f;
}
break;
case TASK_ANTLIONGUARD_CHARGE:
{
// HACK: Because the guard stops running his normal blended movement
// here, he also needs to remove his blended movement layers!
GetMotor()->MoveStop();
SetActivity( ACT_ANTLIONGUARD_CHARGE_START );
m_bDecidedNotToStop = false;
}
break;
case TASK_ANTLIONGUARD_GET_PATH_TO_CHARGE_POSITION:
{
if ( !m_hChargeTargetPosition )
{
TaskFail( "Tried to find a charge position without one specified.\n" );
break;
}
// Move to the charge position
AI_NavGoal_t goal( GOALTYPE_LOCATION, m_hChargeTargetPosition->GetAbsOrigin(), ACT_RUN );
if ( GetNavigator()->SetGoal( goal ) )
{
// We want to face towards the charge target
Vector vecDir = m_hChargeTarget->GetAbsOrigin() - m_hChargeTargetPosition->GetAbsOrigin();
VectorNormalize( vecDir );
vecDir.z = 0;
GetNavigator()->SetArrivalDirection( vecDir );
TaskComplete();
}
else
{
m_hChargeTarget = NULL;
m_hChargeTargetPosition = NULL;
TaskFail( FAIL_NO_ROUTE );
}
}
break;
case TASK_ANTLIONGUARD_GET_PATH_TO_NEAREST_NODE:
{
if ( !GetEnemy() )
{
TaskFail( FAIL_NO_ENEMY );
break;
}
// Find the nearest node to the enemy
int node = GetNavigator()->GetNetwork()->NearestNodeToPoint( this, GetEnemy()->GetAbsOrigin(), false );
CAI_Node *pNode = GetNavigator()->GetNetwork()->GetNode( node );
if( pNode == NULL )
{
TaskFail( FAIL_NO_ROUTE );
break;
}
Vector vecNodePos = pNode->GetPosition( GetHullType() );
AI_NavGoal_t goal( GOALTYPE_LOCATION, vecNodePos, ACT_RUN );
if ( GetNavigator()->SetGoal( goal ) )
{
GetNavigator()->SetArrivalDirection( GetEnemy() );
TaskComplete();
break;
}
TaskFail( FAIL_NO_ROUTE );
break;
}
break;
case TASK_ANTLIONGUARD_GET_CHASE_PATH_ENEMY_TOLERANCE:
{
// Chase the enemy, but allow local navigation to succeed if it gets within the goal tolerance
// GetNavigator()->SetLocalSucceedOnWithinTolerance( true );
if ( GetNavigator()->SetGoal( GOALTYPE_ENEMY ) )
{
TaskComplete();
}
else
{
RememberUnreachable(GetEnemy());
TaskFail(FAIL_NO_ROUTE);
}
// GetNavigator()->SetLocalSucceedOnWithinTolerance( false );
}
break;
case TASK_ANTLIONGUARD_OPPORTUNITY_THROW:
{
// If we've got some live antlions, look for a physics object to throw
if ( m_iNumLiveAntlions >= 2 && RandomFloat(0,1) > 0.5 )
{
m_FailedPhysicsTargets.RemoveAll();
UpdatePhysicsTarget( false, m_bPreferPhysicsAttack ? (100*12) : ANTLIONGUARD_FARTHEST_PHYSICS_OBJECT );
if ( HasCondition( COND_ANTLIONGUARD_PHYSICS_TARGET ) && !m_bInCavern )
{
SetSchedule( SCHED_ANTLIONGUARD_PHYSICS_ATTACK );
}
}
TaskComplete();
}
break;
default:
BaseClass::StartTask(pTask);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Calculate & apply damage & force for a charge to a target.
// Done outside of the guard because we need to do this inside a trace filter.
//-----------------------------------------------------------------------------
void ApplyChargeDamage( CBaseEntity *pAntlionGuard, CBaseEntity *pTarget, float flDamage )
{
Vector attackDir = ( pTarget->WorldSpaceCenter() - pAntlionGuard->WorldSpaceCenter() );
VectorNormalize( attackDir );
Vector offset = RandomVector( -32, 32 ) + pTarget->WorldSpaceCenter();
// Generate enough force to make a 75kg guy move away at 700 in/sec
Vector vecForce = attackDir * ImpulseScale( 75, 700 );
// Deal the damage
CTakeDamageInfo info( pAntlionGuard, pAntlionGuard, vecForce, offset, flDamage, DMG_CLUB );
pTarget->TakeDamage( info );
#if HL2_EPISODIC
// If I am a cavern guard attacking the player, and he still lives, then poison him too.
Assert( dynamic_cast<CNPC_AntlionGuard *>(pAntlionGuard) );
if ( static_cast<CNPC_AntlionGuard *>(pAntlionGuard)->IsInCavern() && pTarget->IsPlayer() && pTarget->IsAlive() && pTarget->m_iHealth > ANTLIONGUARD_POISON_TO)
{
// That didn't finish them. Take them down to one point with poison damage. It'll heal.
pTarget->TakeDamage( CTakeDamageInfo( pAntlionGuard, pAntlionGuard, pTarget->m_iHealth - ANTLIONGUARD_POISON_TO, DMG_POISON ) );
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: A simple trace filter class to skip small moveable physics objects
//-----------------------------------------------------------------------------
class CTraceFilterSkipPhysics : public CTraceFilter
{
public:
// It does have a base, but we'll never network anything below here..
DECLARE_CLASS_NOBASE( CTraceFilterSkipPhysics );
CTraceFilterSkipPhysics( const IHandleEntity *passentity, int collisionGroup, float minMass )
: m_pPassEnt(passentity), m_collisionGroup(collisionGroup), m_minMass(minMass)
{
}
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
if ( !StandardFilterRules( pHandleEntity, contentsMask ) )
return false;
if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) )
return false;
// Don't test if the game code tells us we should ignore this collision...
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if ( pEntity )
{
if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) )
return false;
if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) )
return false;
// don't test small moveable physics objects (unless it's an NPC)
if ( !pEntity->IsNPC() && pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
IPhysicsObject *pPhysics = pEntity->VPhysicsGetObject();
Assert(pPhysics);
if ( pPhysics->IsMoveable() && pPhysics->GetMass() < m_minMass )
return false;
}
// If we hit an antlion, don't stop, but kill it
if ( pEntity->Classify() == CLASS_ANTLION )
{
CBaseEntity *pGuard = (CBaseEntity*)EntityFromEntityHandle( m_pPassEnt );
ApplyChargeDamage( pGuard, pEntity, pEntity->GetHealth() );
return false;
}
}
return true;
}
private:
const IHandleEntity *m_pPassEnt;
int m_collisionGroup;
float m_minMass;
};
inline void TraceHull_SkipPhysics( const Vector &vecAbsStart, const Vector &vecAbsEnd, const Vector &hullMin,
const Vector &hullMax, unsigned int mask, const CBaseEntity *ignore,
int collisionGroup, trace_t *ptr, float minMass )
{
Ray_t ray;
ray.Init( vecAbsStart, vecAbsEnd, hullMin, hullMax );
CTraceFilterSkipPhysics traceFilter( ignore, collisionGroup, minMass );
enginetrace->TraceRay( ray, mask, &traceFilter, ptr );
}
//-----------------------------------------------------------------------------
// Purpose: Return true if our charge target is right in front of the guard
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::EnemyIsRightInFrontOfMe( CBaseEntity **pEntity )
{
if ( !GetEnemy() )
return false;
if ( (GetEnemy()->WorldSpaceCenter() - WorldSpaceCenter()).LengthSqr() < (156*156) )
{
Vector vecLOS = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() );
vecLOS.z = 0;
VectorNormalize( vecLOS );
Vector vBodyDir = BodyDirection2D();
if ( DotProduct( vecLOS, vBodyDir ) > 0.8 )
{
// He's in front of me, and close. Make sure he's not behind a wall.
trace_t tr;
UTIL_TraceLine( WorldSpaceCenter(), GetEnemy()->EyePosition(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
if ( tr.m_pEnt == GetEnemy() )
{
*pEntity = tr.m_pEnt;
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: While charging, look ahead and see if we're going to run into anything.
// If we are, start the gesture so it looks like we're anticipating the hit.
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::ChargeLookAhead( void )
{
trace_t tr;
Vector vecForward;
GetVectors( &vecForward, NULL, NULL );
Vector vecTestPos = GetAbsOrigin() + ( vecForward * m_flGroundSpeed * 0.75 );
Vector testHullMins = GetHullMins();
testHullMins.z += (StepHeight() * 2);
TraceHull_SkipPhysics( GetAbsOrigin(), vecTestPos, testHullMins, GetHullMaxs(), MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr, VPhysicsGetObject()->GetMass() * 0.5 );
//NDebugOverlay::Box( tr.startpos, testHullMins, GetHullMaxs(), 0, 255, 0, true, 0.1f );
//NDebugOverlay::Box( vecTestPos, testHullMins, GetHullMaxs(), 255, 0, 0, true, 0.1f );
if ( tr.fraction != 1.0 )
{
// Start playing the hit animation
AddGesture( ACT_ANTLIONGUARD_CHARGE_ANTICIPATION );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles the guard charging into something. Returns true if it hit the world.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::HandleChargeImpact( Vector vecImpact, CBaseEntity *pEntity )
{
// Cause a shock wave from this point which will disrupt nearby physics objects
ImpactShock( vecImpact, 128, 350 );
// Did we hit anything interesting?
if ( !pEntity || pEntity->IsWorld() )
{
// Robin: Due to some of the finicky details in the motor, the guard will hit
// the world when it is blocked by our enemy when trying to step up
// during a moveprobe. To get around this, we see if the enemy's within
// a volume in front of the guard when we hit the world, and if he is,
// we hit him anyway.
EnemyIsRightInFrontOfMe( &pEntity );
// Did we manage to find him? If not, increment our charge miss count and abort.
if ( pEntity->IsWorld() )
{
m_iChargeMisses++;
return true;
}
}
// Hit anything we don't like
if ( IRelationType( pEntity ) == D_HT && ( GetNextAttack() < gpGlobals->curtime ) )
{
EmitSound( "NPC_AntlionGuard.Shove" );
if ( !IsPlayingGesture( ACT_ANTLIONGUARD_CHARGE_HIT ) )
{
RestartGesture( ACT_ANTLIONGUARD_CHARGE_HIT );
}
ChargeDamage( pEntity );
pEntity->ApplyAbsVelocityImpulse( ( BodyDirection2D() * 400 ) + Vector( 0, 0, 200 ) );
if ( !pEntity->IsAlive() && GetEnemy() == pEntity )
{
SetEnemy( NULL );
}
SetNextAttack( gpGlobals->curtime + 2.0f );
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
// We've hit something, so clear our miss count
m_iChargeMisses = 0;
return false;
}
// Hit something we don't hate. If it's not moveable, crash into it.
if ( pEntity->GetMoveType() == MOVETYPE_NONE || pEntity->GetMoveType() == MOVETYPE_PUSH )
return true;
// If it's a vphysics object that's too heavy, crash into it too.
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
IPhysicsObject *pPhysics = pEntity->VPhysicsGetObject();
if ( pPhysics )
{
// If the object is being held by the player, knock it out of his hands
if ( pPhysics->GetGameFlags() & FVPHYSICS_PLAYER_HELD )
{
Pickup_ForcePlayerToDropThisObject( pEntity );
return false;
}
if ( (!pPhysics->IsMoveable() || pPhysics->GetMass() > VPhysicsGetObject()->GetMass() * 0.5f ) )
return true;
}
}
return false;
/*
ROBIN: Wrote & then removed this. If we want to have large rocks that the guard
should smack around, then we should enable it.
else
{
// If we hit a physics prop, smack the crap out of it. (large rocks)
// Factor the object mass into it, because we want to move it no matter how heavy it is.
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
CTakeDamageInfo info( this, this, 250, DMG_BLAST );
info.SetDamagePosition( vecImpact );
float flForce = ImpulseScale( pEntity->VPhysicsGetObject()->GetMass(), 250 );
flForce *= random->RandomFloat( 0.85, 1.15 );
// Calculate the vector and stuff it into the takedamageinfo
Vector vecForce = BodyDirection3D();
VectorNormalize( vecForce );
vecForce *= flForce;
vecForce *= phys_pushscale.GetFloat();
info.SetDamageForce( vecForce );
pEntity->VPhysicsTakeDamage( info );
}
}
*/
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float CNPC_AntlionGuard::ChargeSteer( void )
{
trace_t tr;
Vector testPos, steer, forward, right;
QAngle angles;
const float testLength = m_flGroundSpeed * 0.15f;
//Get our facing
GetVectors( &forward, &right, NULL );
steer = forward;
const float faceYaw = UTIL_VecToYaw( forward );
//Offset right
VectorAngles( forward, angles );
angles[YAW] += 45.0f;
AngleVectors( angles, &forward );
//Probe out
testPos = GetAbsOrigin() + ( forward * testLength );
//Offset by step height
Vector testHullMins = GetHullMins();
testHullMins.z += (StepHeight() * 2);
//Probe
TraceHull_SkipPhysics( GetAbsOrigin(), testPos, testHullMins, GetHullMaxs(), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr, VPhysicsGetObject()->GetMass() * 0.5f );
//Debug info
if ( g_debug_antlionguard.GetInt() == 1 )
{
if ( tr.fraction == 1.0f )
{
NDebugOverlay::BoxDirection( GetAbsOrigin(), testHullMins, GetHullMaxs() + Vector(testLength,0,0), forward, 0, 255, 0, 8, 0.1f );
}
else
{
NDebugOverlay::BoxDirection( GetAbsOrigin(), testHullMins, GetHullMaxs() + Vector(testLength,0,0), forward, 255, 0, 0, 8, 0.1f );
}
}
//Add in this component
steer += ( right * 0.5f ) * ( 1.0f - tr.fraction );
//Offset left
angles[YAW] -= 90.0f;
AngleVectors( angles, &forward );
//Probe out
testPos = GetAbsOrigin() + ( forward * testLength );
// Probe
TraceHull_SkipPhysics( GetAbsOrigin(), testPos, testHullMins, GetHullMaxs(), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr, VPhysicsGetObject()->GetMass() * 0.5f );
//Debug
if ( g_debug_antlionguard.GetInt() == 1 )
{
if ( tr.fraction == 1.0f )
{
NDebugOverlay::BoxDirection( GetAbsOrigin(), testHullMins, GetHullMaxs() + Vector(testLength,0,0), forward, 0, 255, 0, 8, 0.1f );
}
else
{
NDebugOverlay::BoxDirection( GetAbsOrigin(), testHullMins, GetHullMaxs() + Vector(testLength,0,0), forward, 255, 0, 0, 8, 0.1f );
}
}
//Add in this component
steer -= ( right * 0.5f ) * ( 1.0f - tr.fraction );
//Debug
if ( g_debug_antlionguard.GetInt() == 1 )
{
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( steer * 512.0f ), 255, 255, 0, true, 0.1f );
NDebugOverlay::Cross3D( GetAbsOrigin() + ( steer * 512.0f ), Vector(2,2,2), -Vector(2,2,2), 255, 255, 0, true, 0.1f );
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( BodyDirection3D() * 256.0f ), 255, 0, 255, true, 0.1f );
NDebugOverlay::Cross3D( GetAbsOrigin() + ( BodyDirection3D() * 256.0f ), Vector(2,2,2), -Vector(2,2,2), 255, 0, 255, true, 0.1f );
}
return UTIL_AngleDiff( UTIL_VecToYaw( steer ), faceYaw );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::RunTask( const Task_t *pTask )
{
switch (pTask->iTask)
{
case TASK_ANTLIONGUARD_SET_FLINCH_ACTIVITY:
AutoMovement( );
if ( IsActivityFinished() )
{
TaskComplete();
}
break;
case TASK_ANTLIONGUARD_SHOVE_PHYSOBJECT:
if ( IsActivityFinished() )
{
TaskComplete();
}
break;
/*
case TASK_RUN_PATH:
{
}
break;
*/
case TASK_ANTLIONGUARD_CHARGE:
{
Activity eActivity = GetActivity();
// See if we're trying to stop after hitting/missing our target
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_STOP || eActivity == ACT_ANTLIONGUARD_CHARGE_CRASH )
{
if ( IsActivityFinished() )
{
TaskComplete();
return;
}
// Still in the process of slowing down. Run movement until it's done.
AutoMovement();
return;
}
// Check for manual transition
if ( ( eActivity == ACT_ANTLIONGUARD_CHARGE_START ) && ( IsActivityFinished() ) )
{
SetActivity( ACT_ANTLIONGUARD_CHARGE_RUN );
}
// See if we're still running
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_RUN || eActivity == ACT_ANTLIONGUARD_CHARGE_START )
{
if ( HasCondition( COND_NEW_ENEMY ) || HasCondition( COND_LOST_ENEMY ) || HasCondition( COND_ENEMY_DEAD ) )
{
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
return;
}
else
{
if ( GetEnemy() != NULL )
{
Vector goalDir = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() );
VectorNormalize( goalDir );
if ( DotProduct( BodyDirection2D(), goalDir ) < 0.25f )
{
if ( !m_bDecidedNotToStop )
{
// We've missed the target. Randomly decide not to stop, which will cause
// the guard to just try and swing around for another pass.
m_bDecidedNotToStop = true;
if ( RandomFloat(0,1) > 0.3 )
{
m_iChargeMisses++;
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
}
}
}
else
{
m_bDecidedNotToStop = false;
}
}
}
}
// Steer towards our target
float idealYaw;
if ( GetEnemy() == NULL )
{
idealYaw = GetMotor()->GetIdealYaw();
}
else
{
idealYaw = CalcIdealYaw( GetEnemy()->GetAbsOrigin() );
}
// Add in our steering offset
idealYaw += ChargeSteer();
// Turn to face
GetMotor()->SetIdealYawAndUpdate( idealYaw );
// See if we're going to run into anything soon
ChargeLookAhead();
// Let our animations simply move us forward. Keep the result
// of the movement so we know whether we've hit our target.
AIMoveTrace_t moveTrace;
if ( AutoMovement( GetEnemy(), &moveTrace ) == false )
{
// Only stop if we hit the world
if ( HandleChargeImpact( moveTrace.vEndPosition, moveTrace.pObstruction ) )
{
// If we're starting up, this is an error
if ( eActivity == ACT_ANTLIONGUARD_CHARGE_START )
{
TaskFail( "Unable to make initial movement of charge\n" );
return;
}
// Crash unless we're trying to stop already
if ( eActivity != ACT_ANTLIONGUARD_CHARGE_STOP )
{
if ( moveTrace.fStatus == AIMR_BLOCKED_WORLD && moveTrace.vHitNormal == vec3_origin )
{
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
}
else
{
SetActivity( ACT_ANTLIONGUARD_CHARGE_CRASH );
}
}
}
else if ( moveTrace.pObstruction )
{
// If we hit an antlion, don't stop, but kill it
if ( moveTrace.pObstruction->Classify() == CLASS_ANTLION )
{
if ( FClassnameIs( moveTrace.pObstruction, "npc_antlionguard" ) )
{
// Crash unless we're trying to stop already
if ( eActivity != ACT_ANTLIONGUARD_CHARGE_STOP )
{
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
}
}
else
{
ApplyChargeDamage( this, moveTrace.pObstruction, moveTrace.pObstruction->GetHealth() );
}
}
}
}
}
break;
case TASK_WAIT_FOR_MOVEMENT:
{
// the cavern antlion can clothesline gordon
if ( m_bInCavern )
{
// See if we're going to run into anything soon
ChargeLookAhead();
if ( HasCondition(COND_CAN_MELEE_ATTACK1) )
{
CBaseEntity *pEntity = GetEnemy();
if (pEntity && pEntity->IsPlayer())
{
EmitSound( "NPC_AntlionGuard.Shove" );
if ( !IsPlayingGesture( ACT_ANTLIONGUARD_CHARGE_HIT ) )
{
RestartGesture( ACT_ANTLIONGUARD_CHARGE_HIT );
}
ChargeDamage( pEntity );
pEntity->ApplyAbsVelocityImpulse( ( BodyDirection2D() * 400 ) + Vector( 0, 0, 200 ) );
if ( !pEntity->IsAlive() && GetEnemy() == pEntity )
{
SetEnemy( NULL );
}
SetNextAttack( gpGlobals->curtime + 2.0f );
SetActivity( ACT_ANTLIONGUARD_CHARGE_STOP );
// We've hit something, so clear our miss count
m_iChargeMisses = 0;
AutoMovement();
TaskComplete();
return;
}
}
}
BaseClass::RunTask( pTask );
}
break;
default:
BaseClass::RunTask(pTask);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Summon antlions around the guard
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::SummonAntlions( void )
{
// We want to spawn them around the guard
Vector vecForward, vecRight;
AngleVectors( QAngle(0,GetAbsAngles().y,0), &vecForward, &vecRight, NULL );
// Spawn positions
struct spawnpos_t
{
float flForward;
float flRight;
};
spawnpos_t sAntlionSpawnPositions[] =
{
{ 0, 200 },
{ 0, -200 },
{ 128, 128 },
{ 128, -128 },
{ -128, 128 },
{ -128, -128 },
{ 200, 0 },
{ -200, 0 },
};
// Only spawn up to our max count
int iSpawnPoint = 0;
for ( int i = 0; (m_iNumLiveAntlions < ANTLIONGUARD_SUMMON_COUNT) && (iSpawnPoint < ARRAYSIZE(sAntlionSpawnPositions)); i++ )
{
// Determine spawn position for the antlion
Vector vecSpawn = GetAbsOrigin() + ( sAntlionSpawnPositions[iSpawnPoint].flForward * vecForward ) + ( sAntlionSpawnPositions[iSpawnPoint].flRight * vecRight );
iSpawnPoint++;
// Randomise it a little
vecSpawn.x += RandomFloat( -64, 64 );
vecSpawn.y += RandomFloat( -64, 64 );
vecSpawn.z += 64;
// Make sure it's clear, and make sure we hit something
trace_t tr;
UTIL_TraceHull( vecSpawn, vecSpawn - Vector(0,0,128), NAI_Hull::Mins( HULL_MEDIUM ), NAI_Hull::Maxs( HULL_MEDIUM ), MASK_NPCSOLID, NULL, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid || tr.allsolid || tr.fraction == 1.0 )
{
if ( g_debug_antlionguard.GetInt() == 2 )
{
NDebugOverlay::Box( tr.endpos, NAI_Hull::Mins( HULL_MEDIUM ), NAI_Hull::Maxs( HULL_MEDIUM ), 255, 0, 0, true, 5.0f );
}
continue;
}
// Ensure it's dirt or sand
const surfacedata_t *pdata = physprops->GetSurfaceData( tr.surface.surfaceProps );
if ( ( pdata->game.material != CHAR_TEX_DIRT ) && ( pdata->game.material != CHAR_TEX_SAND ) )
{
if ( g_debug_antlionguard.GetInt() == 2 )
{
NDebugOverlay::Box( tr.endpos, NAI_Hull::Mins( HULL_MEDIUM ), NAI_Hull::Maxs( HULL_MEDIUM ), 255, 128, 128, true, 5.0f );
}
continue;
}
// Make sure the guard can see it
trace_t tr_vis;
UTIL_TraceLine( WorldSpaceCenter(), tr.endpos, MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr_vis );
if ( tr_vis.fraction != 1.0 )
{
if ( g_debug_antlionguard.GetInt() == 2 )
{
NDebugOverlay::Line( WorldSpaceCenter(), tr.endpos, 255, 0, 0, true, 5.0f );
}
continue;
}
CAI_BaseNPC *pent = (CAI_BaseNPC*)CreateEntityByName( "npc_antlion" );
if ( !pent )
break;
CNPC_Antlion *pAntlion = assert_cast<CNPC_Antlion*>(pent);
if ( g_debug_antlionguard.GetInt() == 2 )
{
NDebugOverlay::Box( tr.endpos, NAI_Hull::Mins( HULL_MEDIUM ), NAI_Hull::Maxs( HULL_MEDIUM ), 0, 255, 0, true, 5.0f );
NDebugOverlay::Line( WorldSpaceCenter(), tr.endpos, 0, 255, 0, true, 5.0f );
}
vecSpawn = tr.endpos;
pAntlion->SetAbsOrigin( vecSpawn );
// Start facing our enemy if we have one, otherwise just match the guard.
Vector vecFacing = vecForward;
if ( GetEnemy() )
{
vecFacing = GetEnemy()->GetAbsOrigin() - GetAbsOrigin();
VectorNormalize( vecFacing );
}
QAngle vecAngles;
VectorAngles( vecFacing, vecAngles );
pAntlion->SetAbsAngles( vecAngles );
pAntlion->AddSpawnFlags( SF_NPC_FALL_TO_GROUND );
pAntlion->AddSpawnFlags( SF_NPC_FADE_CORPSE );
// Make the antlion fire my input when he dies
pAntlion->KeyValue( "OnDeath", UTIL_VarArgs("%s,SummonedAntlionDied,,0,-1", STRING(GetEntityName())) );
// Start the antlion burrowed, and tell him to come up
pAntlion->m_bStartBurrowed = true;
DispatchSpawn( pAntlion );
pAntlion->Activate();
g_EventQueue.AddEvent( pAntlion, "Unburrow", RandomFloat(0.1, 1.0), this, this );
// Add it to our squad
if ( GetSquad() != NULL )
{
GetSquad()->AddToSquad( pAntlion );
}
// Set the antlion's enemy to our enemy
if ( GetEnemy() )
{
pAntlion->SetEnemy( GetEnemy() );
pAntlion->SetState( NPC_STATE_COMBAT );
pAntlion->UpdateEnemyMemory( GetEnemy(), GetEnemy()->GetAbsOrigin() );
}
m_iNumLiveAntlions++;
}
if ( g_debug_antlionguard.GetInt() == 2 )
{
Msg("Guard summoned antlion count: %d\n", m_iNumLiveAntlions );
}
if ( m_iNumLiveAntlions > 2 )
{
m_flNextSummonTime = gpGlobals->curtime + RandomFloat( 15,20 );
}
else
{
m_flNextSummonTime = gpGlobals->curtime + RandomFloat( 10,15 );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::FoundEnemy( void )
{
m_flAngerNoiseTime = gpGlobals->curtime + 2.0f;
SetState( NPC_STATE_COMBAT );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::LostEnemy( void )
{
m_flSearchNoiseTime = gpGlobals->curtime + 2.0f;
SetState( NPC_STATE_ALERT );
m_OnLostPlayer.FireOutput( this, this );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputSetShoveTarget( inputdata_t &inputdata )
{
if ( IsAlive() == false )
return;
CBaseEntity *pTarget = gEntList.FindEntityByName( NULL, inputdata.value.String(), NULL, inputdata.pActivator, inputdata.pCaller );
if ( pTarget == NULL )
{
Warning( "**Guard %s cannot find shove target %s\n", GetClassname(), inputdata.value.String() );
m_hShoveTarget = NULL;
return;
}
m_hShoveTarget = pTarget;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputSetChargeTarget( inputdata_t &inputdata )
{
if ( !IsAlive() )
return;
// Pull the target & position out of the string
char parseString[255];
Q_strncpy(parseString, inputdata.value.String(), sizeof(parseString));
// Get charge target name
char *pszParam = strtok(parseString," ");
CBaseEntity *pTarget = gEntList.FindEntityByName( NULL, pszParam, NULL, inputdata.pActivator, inputdata.pCaller );
if ( !pTarget )
{
Warning( "ERROR: Guard %s cannot find charge target '%s'\n", STRING(GetEntityName()), pszParam );
return;
}
// Get the charge position name
pszParam = strtok(NULL," ");
CBaseEntity *pPosition = gEntList.FindEntityByName( NULL, pszParam, NULL, inputdata.pActivator, inputdata.pCaller );
if ( !pPosition )
{
Warning( "ERROR: Guard %s cannot find charge position '%s'\nMake sure you've specified the parameters as [target start]!\n", STRING(GetEntityName()), pszParam );
return;
}
// Make sure we don't stack charge targets
if ( m_hChargeTarget )
{
if ( GetEnemy() == m_hChargeTarget )
{
SetEnemy( NULL );
}
}
SetCondition( COND_ANTLIONGUARD_HAS_CHARGE_TARGET );
m_hChargeTarget = pTarget;
m_hChargeTargetPosition = pPosition;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputClearChargeTarget( inputdata_t &inputdata )
{
m_hChargeTarget = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : baseAct -
// Output : Activity
//-----------------------------------------------------------------------------
Activity CNPC_AntlionGuard::NPC_TranslateActivity( Activity baseAct )
{
//See which run to use
if ( ( baseAct == ACT_RUN ) && IsCurSchedule( SCHED_ANTLIONGUARD_CHARGE ) )
return (Activity) ACT_ANTLIONGUARD_CHARGE_RUN;
// Do extra code if we're trying to close on an enemy in a confined space (unless scripted)
if ( hl2_episodic.GetBool() && m_bInCavern && baseAct == ACT_RUN && IsInAScript() == false )
return (Activity) ACT_ANTLIONGUARD_CHARGE_RUN;
if ( ( baseAct == ACT_RUN ) && ( m_iHealth <= (m_iMaxHealth/4) ) )
return (Activity) ACT_ANTLIONGUARD_RUN_HURT;
return baseAct;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::ShouldWatchEnemy( void )
{
Activity nActivity = GetActivity();
if ( ( nActivity == ACT_ANTLIONGUARD_SEARCH ) ||
( nActivity == ACT_ANTLIONGUARD_PEEK_ENTER ) ||
( nActivity == ACT_ANTLIONGUARD_PEEK_EXIT ) ||
( nActivity == ACT_ANTLIONGUARD_PEEK1 ) ||
( nActivity == ACT_ANTLIONGUARD_PEEK_SIGHTED ) ||
( nActivity == ACT_ANTLIONGUARD_SHOVE_PHYSOBJECT ) ||
( nActivity == ACT_ANTLIONGUARD_PHYSHIT_FR ) ||
( nActivity == ACT_ANTLIONGUARD_PHYSHIT_FL ) ||
( nActivity == ACT_ANTLIONGUARD_PHYSHIT_RR ) ||
( nActivity == ACT_ANTLIONGUARD_PHYSHIT_RL ) ||
( nActivity == ACT_ANTLIONGUARD_CHARGE_CRASH ) ||
( nActivity == ACT_ANTLIONGUARD_CHARGE_HIT ) ||
( nActivity == ACT_ANTLIONGUARD_CHARGE_ANTICIPATION ) )
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::UpdateHead( void )
{
float yaw = GetPoseParameter( m_poseHead_Yaw );
float pitch = GetPoseParameter( m_poseHead_Pitch );
// If we should be watching our enemy, turn our head
if ( ShouldWatchEnemy() && ( GetEnemy() != NULL ) )
{
Vector enemyDir = GetEnemy()->WorldSpaceCenter() - WorldSpaceCenter();
VectorNormalize( enemyDir );
float angle = VecToYaw( BodyDirection3D() );
float angleDiff = VecToYaw( enemyDir );
angleDiff = UTIL_AngleDiff( angleDiff, angle + yaw );
SetPoseParameter( m_poseHead_Yaw, UTIL_Approach( yaw + angleDiff, yaw, 50 ) );
angle = UTIL_VecToPitch( BodyDirection3D() );
angleDiff = UTIL_VecToPitch( enemyDir );
angleDiff = UTIL_AngleDiff( angleDiff, angle + pitch );
SetPoseParameter( m_poseHead_Pitch, UTIL_Approach( pitch + angleDiff, pitch, 50 ) );
}
else
{
// Otherwise turn the head back to its normal position
SetPoseParameter( m_poseHead_Yaw, UTIL_Approach( 0, yaw, 10 ) );
SetPoseParameter( m_poseHead_Pitch, UTIL_Approach( 0, pitch, 10 ) );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::MaintainPhysicsTarget( void )
{
if ( m_hPhysicsTarget == NULL || GetEnemy() == NULL )
return;
// Update our current target to make sure it's still valid
float flTargetDistSqr = ( m_hPhysicsTarget->WorldSpaceCenter() - m_vecPhysicsTargetStartPos ).LengthSqr();
bool bTargetMoved = ( flTargetDistSqr > Square(30*12.0f) );
bool bEnemyCloser = ( ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).LengthSqr() <= flTargetDistSqr );
// Make sure this hasn't moved too far or that the player is now closer
if ( bTargetMoved || bEnemyCloser )
{
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
SetCondition( COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID );
m_hPhysicsTarget = NULL;
return;
}
else
{
SetCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID );
}
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::Cross3D( m_hPhysicsTarget->WorldSpaceCenter(), -Vector(32,32,32), Vector(32,32,32), 255, 255, 255, true, 1.0f );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::UpdatePhysicsTarget( bool bPreferObjectsAlongTargetVector, float flRadius )
{
if ( GetEnemy() == NULL )
return;
// Already have a target, don't bother looking
if ( m_hPhysicsTarget != NULL )
return;
// Too soon to check again
if ( m_flPhysicsCheckTime > gpGlobals->curtime )
return;
// Attempt to find a valid shove target
PhysicsObjectCriteria_t criteria;
criteria.pTarget = GetEnemy();
criteria.vecCenter = GetEnemy()->GetAbsOrigin();
criteria.flRadius = flRadius;
criteria.flTargetCone = ANTLIONGUARD_OBJECTFINDING_FOV;
criteria.bPreferObjectsAlongTargetVector = bPreferObjectsAlongTargetVector;
criteria.flNearRadius = (20*12); // TODO: It may preferable to disable this for legacy products as well -- jdw
m_hPhysicsTarget = FindPhysicsObjectTarget( criteria );
// Found one, so interrupt us if we care
if ( m_hPhysicsTarget != NULL )
{
SetCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
m_vecPhysicsTargetStartPos = m_hPhysicsTarget->WorldSpaceCenter();
}
// Don't search again for another second
m_flPhysicsCheckTime = gpGlobals->curtime + 1.0f;
}
//-----------------------------------------------------------------------------
// Purpose: Let the probe know I can run through small debris
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::ShouldProbeCollideAgainstEntity( CBaseEntity *pEntity )
{
if ( m_iszPhysicsPropClass != pEntity->m_iClassname )
return BaseClass::ShouldProbeCollideAgainstEntity( pEntity );
if ( m_hPhysicsTarget == pEntity )
return false;
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
IPhysicsObject *pPhysObj = pEntity->VPhysicsGetObject();
if( pPhysObj && pPhysObj->GetMass() <= ANTLIONGUARD_MAX_OBJECT_MASS )
{
return false;
}
}
return BaseClass::ShouldProbeCollideAgainstEntity( pEntity );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::PrescheduleThink( void )
{
BaseClass::PrescheduleThink();
// Don't do anything after death
if ( m_NPCState == NPC_STATE_DEAD )
return;
// If we're burrowed, then don't do any of this
if ( m_bIsBurrowed )
return;
// Automatically update our physics target when chasing enemies
if ( IsCurSchedule( SCHED_ANTLIONGUARD_CHASE_ENEMY ) ||
IsCurSchedule( SCHED_ANTLIONGUARD_PATROL_RUN ) ||
IsCurSchedule( SCHED_ANTLIONGUARD_CANT_ATTACK ) ||
IsCurSchedule( SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE ) )
{
bool bCheckAlongLine = ( IsCurSchedule( SCHED_ANTLIONGUARD_CHASE_ENEMY ) || IsCurSchedule( SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE ) );
UpdatePhysicsTarget( bCheckAlongLine );
}
else if ( !IsCurSchedule( SCHED_ANTLIONGUARD_PHYSICS_ATTACK ) )
{
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
m_hPhysicsTarget = NULL;
}
UpdateHead();
if ( ( m_flGroundSpeed <= 0.0f ) )
{
if ( m_bStopped == false )
{
StartSounds();
float duration = random->RandomFloat( 2.0f, 8.0f );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.0f, duration );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pBreathSound, random->RandomInt( 40, 60 ), duration );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, duration );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pGrowlIdleSound, random->RandomInt( 120, 140 ), duration );
m_flBreathTime = gpGlobals->curtime + duration - (duration*0.75f);
}
m_bStopped = true;
if ( m_flBreathTime < gpGlobals->curtime )
{
StartSounds();
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, random->RandomFloat( 0.2f, 0.3f ), random->RandomFloat( 0.5f, 1.0f ) );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pGrowlIdleSound, random->RandomInt( 80, 120 ), random->RandomFloat( 0.5f, 1.0f ) );
m_flBreathTime = gpGlobals->curtime + random->RandomFloat( 1.0f, 8.0f );
}
}
else
{
if ( m_bStopped )
{
StartSounds();
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pBreathSound, 0.6f, random->RandomFloat( 2.0f, 4.0f ) );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pBreathSound, random->RandomInt( 140, 160 ), random->RandomFloat( 2.0f, 4.0f ) );
ENVELOPE_CONTROLLER.SoundChangeVolume( m_pGrowlIdleSound, 0.0f, 1.0f );
ENVELOPE_CONTROLLER.SoundChangePitch( m_pGrowlIdleSound, random->RandomInt( 90, 110 ), 0.2f );
}
m_bStopped = false;
}
// Put danger sounds out in front of us
for ( int i = 0; i < 3; i++ )
{
CSoundEnt::InsertSound( SOUND_DANGER, WorldSpaceCenter() + ( BodyDirection3D() * 128 * (i+1) ), 128, 0.1f, this );
}
#if ANTLIONGUARD_BLOOD_EFFECTS
// compute and if necessary transmit the bleeding level for the particle effect
m_iBleedingLevel = GetBleedingLevel();
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::GatherConditions( void )
{
BaseClass::GatherConditions();
if ( CanSummon(false) )
{
SetCondition( COND_ANTLIONGUARD_CAN_SUMMON );
}
else
{
ClearCondition( COND_ANTLIONGUARD_CAN_SUMMON );
}
// Make sure our physics target is still valid
MaintainPhysicsTarget();
if( IsCurSchedule(SCHED_ANTLIONGUARD_PHYSICS_ATTACK) )
{
if( gpGlobals->curtime > m_flWaitFinished )
{
ClearCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
SetCondition( COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID );
m_hPhysicsTarget = NULL;
}
}
// See if we can charge the target
if ( GetEnemy() )
{
if ( ShouldCharge( GetAbsOrigin(), GetEnemy()->GetAbsOrigin(), true, false ) )
{
SetCondition( COND_ANTLIONGUARD_CAN_CHARGE );
}
else
{
ClearCondition( COND_ANTLIONGUARD_CAN_CHARGE );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::StopLoopingSounds()
{
//Stop all sounds
ENVELOPE_CONTROLLER.SoundDestroy( m_pGrowlHighSound );
ENVELOPE_CONTROLLER.SoundDestroy( m_pGrowlIdleSound );
ENVELOPE_CONTROLLER.SoundDestroy( m_pBreathSound );
ENVELOPE_CONTROLLER.SoundDestroy( m_pConfusedSound );
m_pGrowlHighSound = NULL;
m_pGrowlIdleSound = NULL;
m_pBreathSound = NULL;
m_pConfusedSound = NULL;
BaseClass::StopLoopingSounds();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputUnburrow( inputdata_t &inputdata )
{
if ( IsAlive() == false )
return;
if ( m_bIsBurrowed == false )
return;
m_spawnflags &= ~SF_NPC_GAG;
RemoveSolidFlags( FSOLID_NOT_SOLID );
AddSolidFlags( FSOLID_NOT_STANDABLE );
m_takedamage = DAMAGE_YES;
SetSchedule( SCHED_ANTLIONGUARD_UNBURROW );
m_bIsBurrowed = false;
}
//------------------------------------------------------------------------------
// Purpose : Returns true is entity was remembered as unreachable.
// After a time delay reachability is checked
// Input :
// Output :
//------------------------------------------------------------------------------
bool CNPC_AntlionGuard::IsUnreachable(CBaseEntity *pEntity)
{
float UNREACHABLE_DIST_TOLERANCE_SQ = (240 * 240);
// Note that it's ok to remove elements while I'm iterating
// as long as I iterate backwards and remove them using FastRemove
for (int i=m_UnreachableEnts.Count()-1;i>=0;i--)
{
// Remove any dead elements
if (m_UnreachableEnts[i].hUnreachableEnt == NULL)
{
m_UnreachableEnts.FastRemove(i);
}
else if (pEntity == m_UnreachableEnts[i].hUnreachableEnt)
{
// Test for reachability on any elements that have timed out
if ( gpGlobals->curtime > m_UnreachableEnts[i].fExpireTime ||
pEntity->GetAbsOrigin().DistToSqr(m_UnreachableEnts[i].vLocationWhenUnreachable) > UNREACHABLE_DIST_TOLERANCE_SQ)
{
m_UnreachableEnts.FastRemove(i);
return false;
}
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Return the point at which the guard wants to stand on to knock the physics object at the target entity
// Input : *pObject - Object to be shoved.
// *pTarget - Target to be shoved at.
// *vecTrajectory - Trajectory to our target
// *flClearDistance - Distance behind the entity we're clear to use
// Output : Position at which to attempt to strike the object
//-----------------------------------------------------------------------------
Vector CNPC_AntlionGuard::GetPhysicsHitPosition( CBaseEntity *pObject, CBaseEntity *pTarget, Vector *vecTrajectory, float *flClearDistance )
{
// Get the trajectory we want to knock the object along
Vector vecToTarget = pTarget->WorldSpaceCenter() - pObject->WorldSpaceCenter();
VectorNormalize( vecToTarget );
vecToTarget.z = 0;
// Get the distance we want to be from the object when we hit it
IPhysicsObject *pPhys = pObject->VPhysicsGetObject();
Vector extent = physcollision->CollideGetExtent( pPhys->GetCollide(), pObject->GetAbsOrigin(), pObject->GetAbsAngles(), -vecToTarget );
float flDist = ( extent - pObject->WorldSpaceCenter() ).Length() + CollisionProp()->BoundingRadius() + 32.0f;
if ( vecTrajectory != NULL )
{
*vecTrajectory = vecToTarget;
}
if ( flClearDistance != NULL )
{
*flClearDistance = flDist;
}
// Position at which we'd like to be
return (pObject->WorldSpaceCenter() + ( vecToTarget * -flDist ));
}
//-----------------------------------------------------------------------------
// Purpose: See if we're able to stand on the ground at this point
// Input : &vecPos - Position to try
// *pOut - Result position (only valid if we return true)
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
inline bool CNPC_AntlionGuard::CanStandAtPoint( const Vector &vecPos, Vector *pOut )
{
Vector vecStart = vecPos + Vector( 0, 0, (4*12) );
Vector vecEnd = vecPos - Vector( 0, 0, (4*12) );
trace_t tr;
bool bTraceCleared = false;
// Start high and try to go lower, looking for the ground between here and there
// We do this first because it's more likely to succeed in the typical guard arenas (with open terrain)
UTIL_TraceHull( vecStart, vecEnd, GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid && !tr.allsolid )
{
// We started in solid but didn't end up there, see if we can stand where we ended up
UTIL_TraceHull( tr.endpos, tr.endpos, GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr );
// Must not be in solid
bTraceCleared = ( !tr.allsolid && !tr.startsolid );
}
else
{
// Must not be in solid and must have found a floor (otherwise we're potentially hanging over a ledge)
bTraceCleared = ( tr.allsolid == false && tr.fraction < 1.0f );
}
// Either we're clear or we're still unlucky
if ( bTraceCleared == false )
{
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::Box( vecPos, GetHullMins(), GetHullMaxs(), 255, 0, 0, 0, 15.0f );
}
return false;
}
if ( pOut )
{
*pOut = tr.endpos;
}
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::Box( (*pOut), GetHullMins(), GetHullMaxs(), 0, 255, 0, 0, 15.0f );
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether or not the guard can stand in a position to strike a specified object
// Input : *pShoveObject - Object being shoved
// *pTarget - Target we're shoving the object at
// *pOut - The position we decide to stand at
// Output : Returns true if the guard can stand and deliver.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::CanStandAtShoveTarget( CBaseEntity *pShoveObject, CBaseEntity *pTarget, Vector *pOut )
{
// Get the position we want to be at to swing at the object
float flClearDistance;
Vector vecTrajectory;
Vector vecHitPosition = GetPhysicsHitPosition( pShoveObject, pTarget, &vecTrajectory, &flClearDistance );
Vector vecStandPosition;
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::HorzArrow( pShoveObject->WorldSpaceCenter(), pShoveObject->WorldSpaceCenter() + vecTrajectory * 64.0f, 16.0f, 255, 255, 0, 16, true, 15.0f );
}
// If we failed, try around the sides
if ( CanStandAtPoint( vecHitPosition, &vecStandPosition ) == false )
{
// Get the angle (in reverse) to the target
float flRad = atan2( -vecTrajectory.y, -vecTrajectory.x );
float flRadOffset = DEG2RAD( 45.0f );
// Build an offset vector, rotating around the base
Vector vecSkewTrajectory;
SinCos( flRad + flRadOffset, &vecSkewTrajectory.y, &vecSkewTrajectory.x );
vecSkewTrajectory.z = 0.0f;
// Try to the side
if ( CanStandAtPoint( ( pShoveObject->WorldSpaceCenter() + ( vecSkewTrajectory * flClearDistance ) ), &vecStandPosition ) == false )
{
// Try the other side
SinCos( flRad - flRadOffset, &vecSkewTrajectory.y, &vecSkewTrajectory.x );
vecSkewTrajectory.z = 0.0f;
if ( CanStandAtPoint( ( pShoveObject->WorldSpaceCenter() + ( vecSkewTrajectory * flClearDistance ) ), &vecStandPosition ) == false )
return false;
}
}
// Found it, report it
if ( pOut != NULL )
{
*pOut = vecStandPosition;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Iterate through a number of lists depending on our criteria
//-----------------------------------------------------------------------------
CBaseEntity *CNPC_AntlionGuard::GetNextShoveTarget( CBaseEntity *pLastEntity, AISightIter_t &iter )
{
// Try to find scripted items first
if ( m_strShoveTargets != NULL_STRING )
{
CBaseEntity *pFound = gEntList.FindEntityByName( pLastEntity, m_strShoveTargets );
if ( pFound )
return pFound;
}
// Failing that, use our senses
if ( iter != (AISightIter_t)(-1) )
return GetSenses()->GetNextSeenEntity( &iter );
return GetSenses()->GetFirstSeenEntity( &iter, SEEN_MISC );
}
//-----------------------------------------------------------------------------
// Purpose: Search for a physics item to swat at the player
// Output : Returns the object we're going to swat.
//-----------------------------------------------------------------------------
CBaseEntity *CNPC_AntlionGuard::FindPhysicsObjectTarget( const PhysicsObjectCriteria_t &criteria )
{
// Must have a valid target entity
if ( criteria.pTarget == NULL )
return NULL;
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::Circle( GetAbsOrigin(), QAngle( -90, 0, 0 ), criteria.flRadius, 255, 0, 0, 8, true, 2.0f );
}
// Get the vector to our target, from ourself
Vector vecDirToTarget = criteria.pTarget->GetAbsOrigin() - GetAbsOrigin();
VectorNormalize( vecDirToTarget );
vecDirToTarget.z = 0;
// Cost is determined by distance to the object, modified by how "in line" it is with our target direction of travel
// Use the distance to the player as the base cost for throwing an object (avoids pushing things too close to the player)
float flLeastCost = ( criteria.bPreferObjectsAlongTargetVector ) ? ( criteria.pTarget->GetAbsOrigin() - GetAbsOrigin() ).LengthSqr() : Square( criteria.flRadius );
float flCost;
AISightIter_t iter = (AISightIter_t)(-1);
CBaseEntity *pObject = NULL;
CBaseEntity *pNearest = NULL;
Vector vecBestHitPosition = vec3_origin;
// Look through the list of sensed objects for possible targets
while( ( pObject = GetNextShoveTarget( pObject, iter ) ) != NULL )
{
// If we couldn't shove this object last time, don't try again
if ( m_FailedPhysicsTargets.Find( pObject ) != m_FailedPhysicsTargets.InvalidIndex() )
continue;
// Ignore things less than half a foot in diameter
if ( pObject->CollisionProp()->BoundingRadius() < 6.0f )
continue;
IPhysicsObject *pPhysObj = pObject->VPhysicsGetObject();
if ( pPhysObj == NULL )
continue;
// Ignore motion disabled props
if ( pPhysObj->IsMoveable() == false )
continue;
// Ignore things lighter than 5kg
if ( pPhysObj->GetMass() < 5.0f )
continue;
// Ignore objects moving too quickly (they'll be too hard to catch otherwise)
Vector velocity;
pPhysObj->GetVelocity( &velocity, NULL );
if ( velocity.LengthSqr() > (16*16) )
continue;
// Get the direction from us to the physics object
Vector vecDirToObject = pObject->WorldSpaceCenter() - GetAbsOrigin();
VectorNormalize( vecDirToObject );
vecDirToObject.z = 0;
Vector vecObjCenter = pObject->WorldSpaceCenter();
float flDistSqr = 0.0f;
float flDot = 0.0f;
// If we want to find things along the vector to the target, do so
if ( criteria.bPreferObjectsAlongTargetVector )
{
// Object must be closer than our target
if ( ( GetAbsOrigin() - vecObjCenter ).LengthSqr() > ( GetAbsOrigin() - criteria.pTarget->GetAbsOrigin() ).LengthSqr() )
continue;
// Calculate a "cost" to this object
flDistSqr = ( GetAbsOrigin() - vecObjCenter ).LengthSqr();
flDot = DotProduct( vecDirToTarget, vecDirToObject );
// Ignore things outside our allowed cone
if ( flDot < criteria.flTargetCone )
continue;
// The more perpendicular we are, the higher the cost
float flCostScale = RemapValClamped( flDot, 1.0f, criteria.flTargetCone, 1.0f, 4.0f );
flCost = flDistSqr * flCostScale;
}
else
{
// Straight distance cost
flCost = ( criteria.vecCenter - vecObjCenter ).LengthSqr();
}
// This must be a less costly object to use
if ( flCost >= flLeastCost )
{
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::Box( vecObjCenter, -Vector(16,16,16), Vector(16,16,16), 255, 0, 0, 0, 2.0f );
}
continue;
}
// Check for a (roughly) clear trajectory path from the object to target
trace_t tr;
UTIL_TraceLine( vecObjCenter, criteria.pTarget->BodyTarget( vecObjCenter ), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
// See how close to our target we got (we still look good hurling things that won't necessarily hit)
if ( ( tr.endpos - criteria.pTarget->WorldSpaceCenter() ).LengthSqr() > Square(criteria.flNearRadius) )
continue;
// Must be able to stand at a position to hit the object
Vector vecHitPosition;
if ( CanStandAtShoveTarget( pObject, criteria.pTarget, &vecHitPosition ) == false )
{
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::HorzArrow( GetAbsOrigin(), pObject->WorldSpaceCenter(), 32.0f, 255, 0, 0, 64, true, 2.0f );
}
continue;
}
// Take this as the best object so far
pNearest = pObject;
flLeastCost = flCost;
vecBestHitPosition = vecHitPosition;
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::HorzArrow( GetAbsOrigin(), pObject->WorldSpaceCenter(), 16.0f, 255, 255, 0, 0, true, 2.0f );
}
}
// Set extra info if we've succeeded
if ( pNearest != NULL )
{
m_vecPhysicsHitPosition = vecBestHitPosition;
if ( g_debug_antlionguard.GetInt() == 3 )
{
NDebugOverlay::HorzArrow( GetAbsOrigin(), pNearest->WorldSpaceCenter(), 32.0f, 0, 255, 0, 128, true, 2.0f );
}
}
return pNearest;
}
//-----------------------------------------------------------------------------
// Purpose: Allows for modification of the interrupt mask for the current schedule.
// In the most cases the base implementation should be called first.
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::BuildScheduleTestBits( void )
{
BaseClass::BuildScheduleTestBits();
// Interrupt if we can shove something
if ( IsCurSchedule( SCHED_ANTLIONGUARD_CHASE_ENEMY ) )
{
SetCustomInterruptCondition( COND_ANTLIONGUARD_PHYSICS_TARGET );
SetCustomInterruptCondition( COND_ANTLIONGUARD_CAN_SUMMON );
}
// Interrupt if we've been given a charge target
if ( IsCurSchedule( SCHED_ANTLIONGUARD_CHARGE ) == false )
{
SetCustomInterruptCondition( COND_ANTLIONGUARD_HAS_CHARGE_TARGET );
}
// Once we commit to doing this, just do it!
if ( IsCurSchedule( SCHED_MELEE_ATTACK1 ) )
{
ClearCustomInterruptCondition( COND_ENEMY_OCCLUDED );
}
// Always take heavy damage
SetCustomInterruptCondition( COND_HEAVY_DAMAGE );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &origin -
// radius -
// magnitude -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::ImpactShock( const Vector &origin, float radius, float magnitude, CBaseEntity *pIgnored )
{
// Also do a local physics explosion to push objects away
float adjustedDamage, flDist;
Vector vecSpot;
float falloff = 1.0f / 2.5f;
CBaseEntity *pEntity = NULL;
// Find anything within our radius
while ( ( pEntity = gEntList.FindEntityInSphere( pEntity, origin, radius ) ) != NULL )
{
// Don't affect the ignored target
if ( pEntity == pIgnored )
continue;
if ( pEntity == this )
continue;
// UNDONE: Ask the object if it should get force if it's not MOVETYPE_VPHYSICS?
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS || ( pEntity->VPhysicsGetObject() && pEntity->IsPlayer() == false ) )
{
vecSpot = pEntity->BodyTarget( GetAbsOrigin() );
// decrease damage for an ent that's farther from the bomb.
flDist = ( GetAbsOrigin() - vecSpot ).Length();
if ( radius == 0 || flDist <= radius )
{
adjustedDamage = flDist * falloff;
adjustedDamage = magnitude - adjustedDamage;
if ( adjustedDamage < 1 )
{
adjustedDamage = 1;
}
CTakeDamageInfo info( this, this, adjustedDamage, DMG_BLAST );
CalculateExplosiveDamageForce( &info, (vecSpot - GetAbsOrigin()), GetAbsOrigin() );
pEntity->VPhysicsTakeDamage( info );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTarget -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::ChargeDamage( CBaseEntity *pTarget )
{
if ( pTarget == NULL )
return;
CBasePlayer *pPlayer = ToBasePlayer( pTarget );
if ( pPlayer != NULL )
{
//Kick the player angles
pPlayer->ViewPunch( QAngle( 20, 20, -30 ) );
Vector dir = pPlayer->WorldSpaceCenter() - WorldSpaceCenter();
VectorNormalize( dir );
dir.z = 0.0f;
Vector vecNewVelocity = dir * 250.0f;
vecNewVelocity[2] += 128.0f;
pPlayer->SetAbsVelocity( vecNewVelocity );
color32 red = {128,0,0,128};
UTIL_ScreenFade( pPlayer, red, 1.0f, 0.1f, FFADE_IN );
}
// Player takes less damage
float flDamage = ( pPlayer == NULL ) ? 250 : sk_antlionguard_dmg_charge.GetFloat();
// If it's being held by the player, break that bond
Pickup_ForcePlayerToDropThisObject( pTarget );
// Calculate the physics force
ApplyChargeDamage( this, pTarget, flDamage );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputRagdoll( inputdata_t &inputdata )
{
if ( IsAlive() == false )
return;
//Set us to nearly dead so the velocity from death is minimal
SetHealth( 1 );
CTakeDamageInfo info( this, this, GetHealth(), DMG_CRUSH );
BaseClass::TakeDamage( info );
}
//-----------------------------------------------------------------------------
// Purpose: make m_bPreferPhysicsAttack true
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputEnablePreferPhysicsAttack( inputdata_t &inputdata )
{
m_bPreferPhysicsAttack = true;
}
//-----------------------------------------------------------------------------
// Purpose: make m_bPreferPhysicsAttack false
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputDisablePreferPhysicsAttack( inputdata_t &inputdata )
{
m_bPreferPhysicsAttack = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode )
{
// Figure out what to do next
if ( failedSchedule == SCHED_ANTLIONGUARD_CHASE_ENEMY && HasCondition( COND_ENEMY_UNREACHABLE ) )
return SelectUnreachableSchedule();
return BaseClass::SelectFailSchedule( failedSchedule,failedTask, taskFailCode );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : scheduleType -
// Output : int
//-----------------------------------------------------------------------------
int CNPC_AntlionGuard::TranslateSchedule( int scheduleType )
{
switch( scheduleType )
{
case SCHED_CHASE_ENEMY:
return SCHED_ANTLIONGUARD_CHASE_ENEMY;
break;
}
return BaseClass::TranslateSchedule( scheduleType );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::StartSounds( void )
{
//Initialize the additive sound channels
CPASAttenuationFilter filter( this );
if ( m_pGrowlHighSound == NULL )
{
m_pGrowlHighSound = ENVELOPE_CONTROLLER.SoundCreate( filter, entindex(), CHAN_VOICE, "NPC_AntlionGuard.GrowlHigh", ATTN_NORM );
if ( m_pGrowlHighSound )
{
ENVELOPE_CONTROLLER.Play( m_pGrowlHighSound,0.0f, 100 );
}
}
if ( m_pGrowlIdleSound == NULL )
{
m_pGrowlIdleSound = ENVELOPE_CONTROLLER.SoundCreate( filter, entindex(), CHAN_STATIC, "NPC_AntlionGuard.GrowlIdle", ATTN_NORM );
if ( m_pGrowlIdleSound )
{
ENVELOPE_CONTROLLER.Play( m_pGrowlIdleSound,0.0f, 100 );
}
}
if ( m_pBreathSound == NULL )
{
m_pBreathSound = ENVELOPE_CONTROLLER.SoundCreate( filter, entindex(), CHAN_ITEM, "NPC_AntlionGuard.BreathSound", ATTN_NORM );
if ( m_pBreathSound )
{
ENVELOPE_CONTROLLER.Play( m_pBreathSound, 0.0f, 100 );
}
}
if ( m_pConfusedSound == NULL )
{
m_pConfusedSound = ENVELOPE_CONTROLLER.SoundCreate( filter, entindex(), CHAN_WEAPON,"NPC_AntlionGuard.Confused", ATTN_NORM );
if ( m_pConfusedSound )
{
ENVELOPE_CONTROLLER.Play( m_pConfusedSound, 0.0f, 100 );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputEnableBark( inputdata_t &inputdata )
{
m_bBarkEnabled = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputDisableBark( inputdata_t &inputdata )
{
m_bBarkEnabled = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::DeathSound( const CTakeDamageInfo &info )
{
EmitSound( "NPC_AntlionGuard.Die" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::Event_Killed( const CTakeDamageInfo &info )
{
BaseClass::Event_Killed( info );
// Tell all of my antlions to burrow away, 'cos they fear the Freeman
if ( m_iNumLiveAntlions )
{
CBaseEntity *pSearch = NULL;
// Iterate through all antlions and see if there are any orphans
while ( ( pSearch = gEntList.FindEntityByClassname( pSearch, "npc_antlion" ) ) != NULL )
{
CNPC_Antlion *pAntlion = assert_cast<CNPC_Antlion *>(pSearch);
// See if it's a live orphan
if ( pAntlion && pAntlion->GetOwnerEntity() == NULL && pAntlion->IsAlive() )
{
g_EventQueue.AddEvent( pAntlion, "BurrowAway", RandomFloat(0.1, 2.0), this, this );
}
}
}
DestroyGlows();
// If I'm bleeding, stop due to decreased pressure of hemolymph after
// cessation of aortic contraction
#if ANTLIONGUARD_BLOOD_EFFECTS
m_iBleedingLevel = 0;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Don't become a ragdoll until we've finished our death anim
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::CanBecomeRagdoll( void )
{
if ( IsCurSchedule( SCHED_DIE ) )
return true;
return hl2_episodic.GetBool();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &force -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::BecomeRagdollOnClient( const Vector &force )
{
if ( !CanBecomeRagdoll() )
return false;
EmitSound( "NPC_AntlionGuard.Fallover" );
// Become server-side ragdoll if we're flagged to do it
if ( m_spawnflags & SF_ANTLIONGUARD_SERVERSIDE_RAGDOLL )
{
CTakeDamageInfo info;
// Fake the info
info.SetDamageType( DMG_GENERIC );
info.SetDamageForce( force );
info.SetDamagePosition( WorldSpaceCenter() );
CBaseEntity *pRagdoll = CreateServerRagdoll( this, 0, info, COLLISION_GROUP_NONE );
// Transfer our name to the new ragdoll
pRagdoll->SetName( GetEntityName() );
pRagdoll->SetCollisionGroup( COLLISION_GROUP_DEBRIS );
// Get rid of our old body
UTIL_Remove(this);
return true;
}
return BaseClass::BecomeRagdollOnClient( force );
}
//-----------------------------------------------------------------------------
// Purpose: Override how we face our target as we move
// Output :
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval )
{
Vector vecFacePosition = vec3_origin;
CBaseEntity *pFaceTarget = NULL;
bool bFaceTarget = false;
// FIXME: this will break scripted sequences that walk when they have an enemy
if ( m_hChargeTarget )
{
vecFacePosition = m_hChargeTarget->GetAbsOrigin();
pFaceTarget = m_hChargeTarget;
bFaceTarget = true;
}
#ifdef HL2_EPISODIC
else if ( GetEnemy() && IsCurSchedule( SCHED_ANTLIONGUARD_CANT_ATTACK ) )
{
// Always face our enemy when randomly patrolling around
vecFacePosition = GetEnemy()->EyePosition();
pFaceTarget = GetEnemy();
bFaceTarget = true;
}
#endif // HL2_EPISODIC
else if ( GetEnemy() && GetNavigator()->GetMovementActivity() == ACT_RUN )
{
Vector vecEnemyLKP = GetEnemyLKP();
// Only start facing when we're close enough
if ( ( UTIL_DistApprox( vecEnemyLKP, GetAbsOrigin() ) < 512 ) || IsCurSchedule( SCHED_ANTLIONGUARD_PATROL_RUN ) )
{
vecFacePosition = vecEnemyLKP;
pFaceTarget = GetEnemy();
bFaceTarget = true;
}
}
// Face
if ( bFaceTarget )
{
AddFacingTarget( pFaceTarget, vecFacePosition, 1.0, 0.2 );
}
return BaseClass::OverrideMoveFacing( move, flInterval );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::IsHeavyDamage( const CTakeDamageInfo &info )
{
// Struck by blast
if ( info.GetDamageType() & DMG_BLAST )
{
if ( info.GetDamage() > MIN_BLAST_DAMAGE )
return true;
}
// Struck by large object
if ( info.GetDamageType() & DMG_CRUSH )
{
IPhysicsObject *pPhysObject = info.GetInflictor()->VPhysicsGetObject();
if ( ( pPhysObject != NULL ) && ( pPhysObject->GetGameFlags() & FVPHYSICS_WAS_THROWN ) )
{
// Always take hits from a combine ball
if ( UTIL_IsAR2CombineBall( info.GetInflictor() ) )
return true;
// If we're under half health, stop being interrupted by heavy damage
if ( GetHealth() < (GetMaxHealth() * 0.25) )
return false;
// Ignore physics damages that don't do much damage
if ( info.GetDamage() < MIN_CRUSH_DAMAGE )
return false;
return true;
}
return false;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::IsLightDamage( const CTakeDamageInfo &info )
{
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pChild -
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::InputSummonedAntlionDied( inputdata_t &inputdata )
{
m_iNumLiveAntlions--;
Assert( m_iNumLiveAntlions >= 0 );
if ( g_debug_antlionguard.GetInt() == 2 )
{
Msg("Guard summoned antlion count: %d\n", m_iNumLiveAntlions );
}
}
//-----------------------------------------------------------------------------
// Purpose: Filter out sounds we don't care about
// Input : *pSound - sound to test against
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::QueryHearSound( CSound *pSound )
{
// Don't bother with danger sounds from antlions or other guards
if ( pSound->SoundType() == SOUND_DANGER && ( pSound->m_hOwner != NULL && pSound->m_hOwner->Classify() == CLASS_ANTLION ) )
return false;
return BaseClass::QueryHearSound( pSound );
}
#if HL2_EPISODIC
//---------------------------------------------------------
// Prevent the cavern guard from using stopping paths, as it occasionally forces him off the navmesh.
//---------------------------------------------------------
bool CNPC_AntlionGuard::CNavigator::GetStoppingPath( CAI_WaypointList *pClippedWaypoints )
{
if (GetOuter()->m_bInCavern)
{
return false;
}
else
{
return BaseClass::GetStoppingPath( pClippedWaypoints );
}
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTarget -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::RememberFailedPhysicsTarget( CBaseEntity *pTarget )
{
// Already in the list?
if ( m_FailedPhysicsTargets.Find( pTarget ) != m_FailedPhysicsTargets.InvalidIndex() )
return true;
// We're not holding on to any more
if ( ( m_FailedPhysicsTargets.Count() + 1 ) > MAX_FAILED_PHYSOBJECTS )
return false;
m_FailedPhysicsTargets.AddToTail( pTarget );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Handle squad or NPC interactions
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_AntlionGuard::HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sender )
{
// Don't chase targets that other guards in our squad may be going after!
if ( interactionType == g_interactionAntlionGuardFoundPhysicsObject )
{
RememberFailedPhysicsTarget( (CBaseEntity *) data );
return true;
}
// Mark a shoved object as being free to pursue again
if ( interactionType == g_interactionAntlionGuardShovedPhysicsObject )
{
CBaseEntity *pObject = (CBaseEntity *) data;
m_FailedPhysicsTargets.FindAndRemove( pObject );
return true;
}
return BaseClass::HandleInteraction( interactionType, data, sender );
}
//-----------------------------------------------------------------------------
// Purpose: Cache whatever pose parameters we intend to use
//-----------------------------------------------------------------------------
void CNPC_AntlionGuard::PopulatePoseParameters( void )
{
m_poseThrow = LookupPoseParameter("throw");
m_poseHead_Pitch = LookupPoseParameter("head_pitch");
m_poseHead_Yaw = LookupPoseParameter("head_yaw" );
BaseClass::PopulatePoseParameters();
}
#if ANTLIONGUARD_BLOOD_EFFECTS
//-----------------------------------------------------------------------------
// Purpose: Return desired level for the continuous bleeding effect (not the
// individual blood spurts you see per bullet hit)
// Return 0 for don't bleed,
// 1 for mild bleeding
// 2 for severe bleeding
//-----------------------------------------------------------------------------
unsigned char CNPC_AntlionGuard::GetBleedingLevel( void ) const
{
if ( m_iHealth > ( m_iMaxHealth >> 1 ) )
{ // greater than 50%
return 0;
}
else if ( m_iHealth > ( m_iMaxHealth >> 2 ) )
{ // less than 50% but greater than 25%
return 1;
}
else
{
return 2;
}
}
#endif
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_antlionguard, CNPC_AntlionGuard )
// Interactions
DECLARE_INTERACTION( g_interactionAntlionGuardFoundPhysicsObject )
DECLARE_INTERACTION( g_interactionAntlionGuardShovedPhysicsObject )
// Squadslots
DECLARE_SQUADSLOT( SQUAD_SLOT_ANTLIONGUARD_CHARGE )
//Tasks
DECLARE_TASK( TASK_ANTLIONGUARD_CHARGE )
DECLARE_TASK( TASK_ANTLIONGUARD_GET_PATH_TO_PHYSOBJECT )
DECLARE_TASK( TASK_ANTLIONGUARD_SHOVE_PHYSOBJECT )
DECLARE_TASK( TASK_ANTLIONGUARD_SUMMON )
DECLARE_TASK( TASK_ANTLIONGUARD_SET_FLINCH_ACTIVITY )
DECLARE_TASK( TASK_ANTLIONGUARD_GET_PATH_TO_CHARGE_POSITION )
DECLARE_TASK( TASK_ANTLIONGUARD_GET_PATH_TO_NEAREST_NODE )
DECLARE_TASK( TASK_ANTLIONGUARD_GET_CHASE_PATH_ENEMY_TOLERANCE )
DECLARE_TASK( TASK_ANTLIONGUARD_OPPORTUNITY_THROW )
DECLARE_TASK( TASK_ANTLIONGUARD_FIND_PHYSOBJECT )
//Activities
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_SEARCH )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PEEK_FLINCH )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PEEK_ENTER )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PEEK_EXIT )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PEEK1 )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_BARK )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PEEK_SIGHTED )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_START )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_CANCEL )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_RUN )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_CRASH )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_STOP )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_HIT )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_CHARGE_ANTICIPATION )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_SHOVE_PHYSOBJECT )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_FLINCH_LIGHT )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_UNBURROW )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_ROAR )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_RUN_HURT )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PHYSHIT_FR )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PHYSHIT_FL )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PHYSHIT_RR )
DECLARE_ACTIVITY( ACT_ANTLIONGUARD_PHYSHIT_RL )
//Adrian: events go here
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_CHARGE_HIT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_SHOVE_PHYSOBJECT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_SHOVE )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_FOOTSTEP_LIGHT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_FOOTSTEP_HEAVY )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_CHARGE_EARLYOUT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_GROWL )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_BARK )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_PAIN )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_SQUEEZE )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_SCRATCH )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_GRUNT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_BURROW_OUT )
DECLARE_ANIMEVENT( AE_ANTLIONGUARD_VOICE_ROAR )
DECLARE_CONDITION( COND_ANTLIONGUARD_PHYSICS_TARGET )
DECLARE_CONDITION( COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID )
DECLARE_CONDITION( COND_ANTLIONGUARD_HAS_CHARGE_TARGET )
DECLARE_CONDITION( COND_ANTLIONGUARD_CAN_SUMMON )
DECLARE_CONDITION( COND_ANTLIONGUARD_CAN_CHARGE )
//==================================================
// SCHED_ANTLIONGUARD_SUMMON
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_SUMMON,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ANTLIONGUARD_BARK"
" TASK_ANTLIONGUARD_SUMMON 0"
" TASK_ANTLIONGUARD_OPPORTUNITY_THROW 0"
" "
" Interrupts"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_ANTLIONGUARD_CHARGE
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHARGE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_CHASE_ENEMY"
" TASK_FACE_ENEMY 0"
" TASK_ANTLIONGUARD_CHARGE 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_HEAVY_DAMAGE"
// These are deliberately left out so they can be detected during the
// charge Task and correctly play the charge stop animation.
//" COND_NEW_ENEMY"
//" COND_ENEMY_DEAD"
//" COND_LOST_ENEMY"
)
//==================================================
// SCHED_ANTLIONGUARD_CHARGE_TARGET
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHARGE_TARGET,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_ANTLIONGUARD_CHARGE 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_ENEMY_DEAD"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_ANTLIONGUARD_CHARGE_SMASH
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHARGE_CRASH,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ANTLIONGUARD_CHARGE_CRASH"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_ANTLIONGUARD_PHYSICS_ATTACK
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_PHYSICS_ATTACK,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_CHASE_ENEMY"
" TASK_ANTLIONGUARD_GET_PATH_TO_PHYSOBJECT 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ENEMY 0"
" TASK_ANTLIONGUARD_SHOVE_PHYSOBJECT 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_ENEMY_DEAD"
" COND_LOST_ENEMY"
" COND_NEW_ENEMY"
" COND_ANTLIONGUARD_PHYSICS_TARGET_INVALID"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_FORCE_ANTLIONGUARD_PHYSICS_ATTACK
//==================================================
DEFINE_SCHEDULE
(
SCHED_FORCE_ANTLIONGUARD_PHYSICS_ATTACK,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_CANT_ATTACK"
" TASK_ANTLIONGUARD_FIND_PHYSOBJECT 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_PHYSICS_ATTACK"
""
" Interrupts"
" COND_ANTLIONGUARD_PHYSICS_TARGET"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_ANTLIONGUARD_CANT_ATTACK
// If we're here, the guard can't chase enemy, can't find a physobject to attack with, and can't summon
//==================================================
#ifdef HL2_EPISODIC
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CANT_ATTACK,
" Tasks"
" TASK_SET_ROUTE_SEARCH_TIME 2" // Spend 5 seconds trying to build a path if stuck
" TASK_GET_PATH_TO_RANDOM_NODE 1024"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_WAIT_PVS 0"
""
" Interrupts"
" COND_GIVE_WAY"
" COND_NEW_ENEMY"
" COND_ANTLIONGUARD_PHYSICS_TARGET"
" COND_HEAVY_DAMAGE"
)
#else
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CANT_ATTACK,
" Tasks"
" TASK_WAIT 5"
""
" Interrupts"
)
#endif
//==================================================
// SCHED_ANTLIONGUARD_PHYSICS_DAMAGE_HEAVY
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_PHYSICS_DAMAGE_HEAVY,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_RESET_ACTIVITY 0"
" TASK_ANTLIONGUARD_SET_FLINCH_ACTIVITY 0"
""
" Interrupts"
)
//==================================================
// SCHED_ANTLIONGUARD_UNBURROW
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_UNBURROW,
" Tasks"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ANTLIONGUARD_UNBURROW"
""
" Interrupts"
)
//==================================================
// SCHED_ANTLIONGUARD_CHARGE_CANCEL
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHARGE_CANCEL,
" Tasks"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ANTLIONGUARD_CHARGE_CANCEL"
""
" Interrupts"
)
//==================================================
// SCHED_ANTLIONGUARD_FIND_CHARGE_POSITION
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_FIND_CHARGE_POSITION,
" Tasks"
" TASK_ANTLIONGUARD_GET_PATH_TO_CHARGE_POSITION 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
" COND_ENEMY_DEAD"
" COND_GIVE_WAY"
" COND_TASK_FAILED"
" COND_HEAVY_DAMAGE"
)
//=========================================================
// > SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHASE_ENEMY_TOLERANCE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_PATROL_RUN"
" TASK_ANTLIONGUARD_GET_PATH_TO_NEAREST_NODE 500"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_CAN_MELEE_ATTACK1"
" COND_GIVE_WAY"
" COND_NEW_ENEMY"
" COND_ANTLIONGUARD_CAN_SUMMON"
" COND_ANTLIONGUARD_PHYSICS_TARGET"
" COND_HEAVY_DAMAGE"
" COND_ANTLIONGUARD_CAN_CHARGE"
);
//=========================================================
// > PATROL_RUN
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_PATROL_RUN,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_CANT_ATTACK"
" TASK_SET_ROUTE_SEARCH_TIME 3" // Spend 3 seconds trying to build a path if stuck
" TASK_ANTLIONGUARD_GET_PATH_TO_NEAREST_NODE 500"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_CAN_MELEE_ATTACK1"
" COND_GIVE_WAY"
" COND_NEW_ENEMY"
" COND_ANTLIONGUARD_PHYSICS_TARGET"
" COND_ANTLIONGUARD_CAN_SUMMON"
" COND_HEAVY_DAMAGE"
" COND_ANTLIONGUARD_CAN_CHARGE"
);
//==================================================
// SCHED_ANTLIONGUARD_ROAR
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_ROAR,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ANTLIONGUARD_ROAR"
" "
" Interrupts"
" COND_HEAVY_DAMAGE"
)
//==================================================
// SCHED_ANTLIONGUARD_TAKE_COVER_FROM_ENEMY
//==================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_TAKE_COVER_FROM_ENEMY,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ANTLIONGUARD_CANT_ATTACK"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_STOP_MOVING 0"
""
" Interrupts"
" COND_TASK_FAILED"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ANTLIONGUARD_PHYSICS_TARGET"
" COND_ANTLIONGUARD_CAN_SUMMON"
" COND_HEAVY_DAMAGE"
)
//=========================================================
// SCHED_ANTLIONGUARD_CHASE_ENEMY
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ANTLIONGUARD_CHASE_ENEMY,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_GET_CHASE_PATH_TO_ENEMY 300"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_CAN_RANGE_ATTACK1"
// " COND_CAN_MELEE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK2"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_TASK_FAILED"
" COND_LOST_ENEMY"
" COND_HEAVY_DAMAGE"
" COND_ANTLIONGUARD_CAN_CHARGE"
)
AI_END_CUSTOM_NPC()
| [
"demizexp@gmail.com"
] | demizexp@gmail.com |
df8dacfc06db409ce9ed5a080e8bff0891427bb9 | 015989f7730445efce710a216829b0a6029b4f9a | /myfunc.h | 49d26fca228366e59ae0d9d41310990dbab7d73c | [] | no_license | wriordan3/327_proj1_make | 87b3d12a15e0b009faa0684d0121a4893fac9b75 | 3ef9c0223ff765291eab9a004649d3f1adc5fa40 | refs/heads/master | 2020-12-22T16:49:48.904426 | 2020-02-02T04:59:34 | 2020-02-02T04:59:34 | 236,864,060 | 0 | 0 | null | 2020-01-28T23:20:24 | 2020-01-28T23:20:24 | null | UTF-8 | C++ | false | false | 88 | h | #include <iostream>
#ifndef _MYFUNC_H_
#define _MYFUNC_H_
std::string func();
#endif
| [
"william.riordan.17@cnu.edu"
] | william.riordan.17@cnu.edu |
84b468e201d5202167f252b1dd735a56e223bece | c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29 | /src/module-wx.new/generated/Class_wx_TextAttrDimension.h | 5e577da83548252ba727e96bb9d1c1d934cb36c8 | [] | no_license | gura-lang/gura | 972725895c93c22e0ec87c17166df4d15bdbe338 | 03aff5e2b7fe4f761a16400ae7cc6fa7fec73a47 | refs/heads/master | 2021-01-25T08:04:38.269289 | 2020-05-09T12:42:23 | 2020-05-09T12:42:23 | 7,141,465 | 25 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,420 | h | //----------------------------------------------------------------------------
// wxTextAttrDimension
//----------------------------------------------------------------------------
#ifndef __CLASS_WX_TEXTATTRDIMENSION_H__
#define __CLASS_WX_TEXTATTRDIMENSION_H__
#include <wx/richtext/richtextbuffer.h>
Gura_BeginModuleScope(wx)
//----------------------------------------------------------------------------
// Class declaration for wxTextAttrDimension
//----------------------------------------------------------------------------
Gura_DeclareUserClass(wx_TextAttrDimension);
//----------------------------------------------------------------------------
// Object declaration for wxTextAttrDimension
//----------------------------------------------------------------------------
class Object_wx_TextAttrDimension : public Object {
protected:
wxTextAttrDimension *_pEntity;
GuraObjectObserver *_pObserver;
bool _ownerFlag;
public:
Gura_DeclareObjectAccessor(wx_TextAttrDimension)
public:
inline Object_wx_TextAttrDimension(wxTextAttrDimension *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object(Gura_UserClass(wx_AboutDialogInfo)),
_pEntity(pEntity), _pObserver(pObserver), _ownerFlag(ownerFlag) {}
inline Object_wx_TextAttrDimension(Class *pClass, wxTextAttrDimension *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object(pClass),
_pEntity(pEntity), _pObserver(pObserver), _ownerFlag(ownerFlag) {}
virtual ~Object_wx_TextAttrDimension();
virtual Object *Clone() const;
virtual String ToString(bool exprFlag);
inline void SetEntity(wxTextAttrDimension *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) {
if (_ownerFlag) delete _pEntity;
_pEntity = pEntity;
_pObserver = pObserver;
_ownerFlag = ownerFlag;
}
inline void InvalidateEntity() { _pEntity = nullptr, _pObserver = nullptr, _ownerFlag = false; }
inline wxTextAttrDimension *GetEntity() {
return static_cast<wxTextAttrDimension *>(_pEntity);
}
inline wxTextAttrDimension *ReleaseEntity() {
wxTextAttrDimension *pEntity = GetEntity();
InvalidateEntity();
return pEntity;
}
inline void NotifyGuraObjectDeleted() {
if (_pObserver != nullptr) _pObserver->GuraObjectDeleted();
}
inline bool IsInvalid(Environment &env) const {
if (_pEntity != nullptr) return false;
SetError_InvalidWxObject(env, "wxTextAttrDimension");
return true;
}
};
Gura_EndModuleScope(wx)
#endif
| [
"ypsitau@nifty.com"
] | ypsitau@nifty.com |
0e7fbc1dce965d2d82606c449b1d0546c325d201 | c28b5f019de28eeacee5bcc9ee9165844c0e6d7a | /src/zslb/zslbmodule.cpp | 527f535a2573e723545aa9e4c6fbd3d1556747d7 | [
"MIT"
] | permissive | silbatech/silba-src | 9fa7c6592ae88aa9c785e207f7e2ce82592f2b16 | 8fa0435d469e9a704a3ebc8ff902b2dbbca19520 | refs/heads/main | 2023-03-10T01:02:04.905051 | 2021-02-16T12:12:17 | 2021-02-16T12:12:17 | 339,229,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,364 | cpp | // Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zslb/zslbmodule.h"
#include "zslbchain.h"
#include "libzerocoin/Commitment.h"
#include "libzerocoin/Coin.h"
#include "hash.h"
#include "main.h"
#include "iostream"
bool PublicCoinSpend::Verify(const libzerocoin::Accumulator& a, bool verifyParams) const {
return validate();
}
bool PublicCoinSpend::validate() const {
libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false);
// Check that it opens to the input values
libzerocoin::Commitment commitment(
¶ms->coinCommitmentGroup, getCoinSerialNumber(), randomness);
if (commitment.getCommitmentValue() != pubCoin.getValue()){
return error("%s: commitments values are not equal\n", __func__);
}
// Now check that the signature validates with the serial
if (!HasValidSignature()) {
return error("%s: signature invalid\n", __func__);;
}
return true;
}
const uint256 PublicCoinSpend::signatureHash() const
{
CHashWriter h(0, 0);
h << ptxHash << denomination << getCoinSerialNumber() << randomness << txHash << outputIndex << getSpendType();
return h.GetHash();
}
namespace ZSLBModule {
bool createInput(CTxIn &in, CZerocoinMint &mint, uint256 hashTxOut) {
libzerocoin::ZerocoinParams *params = Params().Zerocoin_Params(false);
uint8_t nVersion = mint.GetVersion();
if (nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION) {
// No v1 serials accepted anymore.
return error("%s: failed to set zSLB privkey mint version=%d\n", __func__, nVersion);
}
CKey key;
if (!mint.GetKeyPair(key))
return error("%s: failed to set zSLB privkey mint version=%d\n", __func__, nVersion);
PublicCoinSpend spend(params, mint.GetSerialNumber(), mint.GetRandomness(), key.GetPubKey());
spend.setTxOutHash(hashTxOut);
spend.outputIndex = mint.GetOutputIndex();
spend.txHash = mint.GetTxHash();
spend.setDenom(mint.GetDenomination());
std::vector<unsigned char> vchSig;
if (!key.Sign(spend.signatureHash(), vchSig))
throw std::runtime_error("ZSLBModule failed to sign signatureHash\n");
spend.setVchSig(vchSig);
CDataStream ser(SER_NETWORK, PROTOCOL_VERSION);
ser << spend;
std::vector<unsigned char> data(ser.begin(), ser.end());
CScript scriptSigIn = CScript() << OP_ZEROCOINPUBLICSPEND << data.size();
scriptSigIn.insert(scriptSigIn.end(), data.begin(), data.end());
in = CTxIn(mint.GetTxHash(), mint.GetOutputIndex(), scriptSigIn, mint.GetDenomination());
in.nSequence = mint.GetDenomination();
return true;
}
bool parseCoinSpend(const CTxIn &in, const CTransaction &tx, const CTxOut &prevOut, PublicCoinSpend &publicCoinSpend) {
if (!in.IsZerocoinPublicSpend() || !prevOut.IsZerocoinMint())
return error("%s: invalid argument/s\n", __func__);
std::vector<char, zero_after_free_allocator<char> > data;
data.insert(data.end(), in.scriptSig.begin() + 4, in.scriptSig.end());
CDataStream serializedCoinSpend(data, SER_NETWORK, PROTOCOL_VERSION);
libzerocoin::ZerocoinParams *params = Params().Zerocoin_Params(false);
PublicCoinSpend spend(params, serializedCoinSpend);
spend.outputIndex = in.prevout.n;
spend.txHash = in.prevout.hash;
CMutableTransaction txNew(tx);
txNew.vin.clear();
spend.setTxOutHash(txNew.GetHash());
// Check prev out now
CValidationState state;
if (!TxOutToPublicCoin(prevOut, spend.pubCoin, state))
return error("%s: cannot get mint from output\n", __func__);
spend.setDenom(spend.pubCoin.getDenomination());
publicCoinSpend = spend;
return true;
}
bool validateInput(const CTxIn &in, const CTxOut &prevOut, const CTransaction &tx, PublicCoinSpend &publicSpend) {
// Now prove that the commitment value opens to the input
if (!parseCoinSpend(in, tx, prevOut, publicSpend)) {
return false;
}
if (libzerocoin::ZerocoinDenominationToAmount(
libzerocoin::IntToZerocoinDenomination(in.nSequence)) != prevOut.nValue) {
return error("PublicCoinSpend validateInput :: input nSequence different to prevout value\n");
}
return publicSpend.validate();
}
bool ParseZerocoinPublicSpend(const CTxIn &txIn, const CTransaction& tx, CValidationState& state, PublicCoinSpend& publicSpend)
{
CTxOut prevOut;
if(!GetOutput(txIn.prevout.hash, txIn.prevout.n ,state, prevOut)){
return state.DoS(100, error("%s: public zerocoin spend prev output not found, prevTx %s, index %d\n",
__func__, txIn.prevout.hash.GetHex(), txIn.prevout.n));
}
if (!ZSLBModule::parseCoinSpend(txIn, tx, prevOut, publicSpend)) {
return state.Invalid(error("%s: invalid public coin spend parse %s\n", __func__,
tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zslb");
}
return true;
}
}
| [
"silbatech@protonmail.com"
] | silbatech@protonmail.com |
d28494bc34c316f8cfdc072be05be258038b420b | 15c929e97632c4760654e9bff7543678ac392183 | /src/s2/s2pointutil_test.cc | bf42f1ec5998f2461b2b612e405c6fd5b19a97ed | [
"Apache-2.0"
] | permissive | figroc/s2geometry | ce47540f6e02c374fab87a1dd92a63b4e172d935 | 42919c4dff169231183a82adcd6e4883597b2915 | refs/heads/develop | 2021-07-02T22:56:30.817785 | 2021-02-11T05:45:23 | 2021-02-11T07:41:15 | 223,169,681 | 2 | 4 | Apache-2.0 | 2020-03-31T10:20:33 | 2019-11-21T12:31:45 | C++ | UTF-8 | C++ | false | false | 6,705 | cc | // Copyright 2005 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: ericv@google.com (Eric Veach)
#include "s2/s2pointutil.h"
#include <gtest/gtest.h>
#include "s2/s2cell.h"
#include "s2/s2coords.h"
#include "s2/s2edge_distances.h"
#include "s2/s2latlng.h"
#include "s2/s2measures.h"
#include "s2/s2predicates.h"
#include "s2/s2testing.h"
TEST(S2, Frames) {
Matrix3x3_d m;
S2Point z = S2Point(0.2, 0.5, -3.3).Normalize();
S2::GetFrame(z, &m);
EXPECT_TRUE(S2::ApproxEquals(m.Col(2), z));
EXPECT_TRUE(S2::IsUnitLength(m.Col(0)));
EXPECT_TRUE(S2::IsUnitLength(m.Col(1)));
EXPECT_DOUBLE_EQ(m.Det(), 1);
EXPECT_TRUE(S2::ApproxEquals(S2::ToFrame(m, m.Col(0)), S2Point(1, 0, 0)));
EXPECT_TRUE(S2::ApproxEquals(S2::ToFrame(m, m.Col(1)), S2Point(0, 1, 0)));
EXPECT_TRUE(S2::ApproxEquals(S2::ToFrame(m, m.Col(2)), S2Point(0, 0, 1)));
EXPECT_TRUE(S2::ApproxEquals(S2::FromFrame(m, S2Point(1, 0, 0)), m.Col(0)));
EXPECT_TRUE(S2::ApproxEquals(S2::FromFrame(m, S2Point(0, 1, 0)), m.Col(1)));
EXPECT_TRUE(S2::ApproxEquals(S2::FromFrame(m, S2Point(0, 0, 1)), m.Col(2)));
}
static void TestRotate(const S2Point& p, const S2Point& axis, S1Angle angle) {
S2Point result = S2::Rotate(p, axis, angle);
// "result" should be unit length.
EXPECT_TRUE(S2::IsUnitLength(result));
// "result" and "p" should be the same distance from "axis".
double kMaxPositionError = 1e-15;
EXPECT_LE((S1Angle(result, axis) - S1Angle(p, axis)).abs().radians(),
kMaxPositionError);
// Check that the rotation angle is correct. We allow a fixed error in the
// *position* of the result, so we need to convert this into a rotation
// angle. The allowable error can be very large as "p" approaches "axis".
double axis_distance = p.CrossProd(axis).Norm();
double max_rotation_error;
if (axis_distance < kMaxPositionError) {
max_rotation_error = 2 * M_PI;
} else {
max_rotation_error = asin(kMaxPositionError / axis_distance);
}
double actual_rotation = S2::TurnAngle(p, axis, result) + M_PI;
double rotation_error = remainder(angle.radians() - actual_rotation,
2 * M_PI);
EXPECT_LE(rotation_error, max_rotation_error);
}
TEST(S2, Rotate) {
for (int iter = 0; iter < 1000; ++iter) {
S2Point axis = S2Testing::RandomPoint();
S2Point target = S2Testing::RandomPoint();
// Choose a distance whose logarithm is uniformly distributed.
double distance = M_PI * pow(1e-15, S2Testing::rnd.RandDouble());
// Sometimes choose points near the far side of the axis.
if (S2Testing::rnd.OneIn(5)) distance = M_PI - distance;
S2Point p = S2::InterpolateAtDistance(S1Angle::Radians(distance),
axis, target);
// Choose the rotation angle.
double angle = 2 * M_PI * pow(1e-15, S2Testing::rnd.RandDouble());
if (S2Testing::rnd.OneIn(3)) angle = -angle;
if (S2Testing::rnd.OneIn(10)) angle = 0;
TestRotate(p, axis, S1Angle::Radians(angle));
}
}
// Given a point P, return the minimum level at which an edge of some S2Cell
// parent of P is nearly collinear with S2::Origin(). This is the minimum
// level for which Sign() may need to resort to expensive calculations in
// order to determine which side of an edge the origin lies on.
static int GetMinExpensiveLevel(const S2Point& p) {
S2CellId id(p);
for (int level = 0; level <= S2CellId::kMaxLevel; ++level) {
S2Cell cell(id.parent(level));
for (int k = 0; k < 4; ++k) {
S2Point a = cell.GetVertex(k);
S2Point b = cell.GetVertex(k + 1);
if (s2pred::TriageSign(a, b, S2::Origin(), a.CrossProd(b)) == 0) {
return level;
}
}
}
return S2CellId::kMaxLevel + 1;
}
TEST(S2, OriginTest) {
// To minimize the number of expensive Sign() calculations,
// S2::Origin() should not be nearly collinear with any commonly used edges.
// Two important categories of such edges are:
//
// - edges along a line of longitude (reasonably common geographically)
// - S2Cell edges (used extensively when computing S2Cell coverings)
//
// This implies that the origin:
//
// - should not be too close to either pole (since all lines of longitude
// converge at the poles)
// - should not be colinear with edges of any S2Cell except for very small
// ones (which are used less frequently)
//
// The point chosen below is about 66km from the north pole towards the East
// Siberian Sea. The purpose of the STtoUV(2/3) calculation is to keep the
// origin as far away as possible from the longitudinal edges of large
// S2Cells. (The line of longitude through the chosen point is always 1/3
// or 2/3 of the way across any S2Cell with longitudinal edges that it
// passes through.)
EXPECT_EQ(S2Point(-0.01, 0.01 * S2::STtoUV(2./3), 1).Normalize(),
S2::Origin());
// Check that the origin is not too close to either pole. (We don't use
// S2Earth because we don't want to depend on that package.)
double distance_km = acos(S2::Origin().z()) * S2Testing::kEarthRadiusKm;
EXPECT_GE(distance_km, 50.0);
S2_LOG(INFO) << "\nS2::Origin() coordinates: " << S2LatLng(S2::Origin())
<< ", distance from pole: " << distance_km << " km";
// Check that S2::Origin() is not collinear with the edges of any large
// S2Cell. We do this is two parts. For S2Cells that belong to either
// polar face, we simply need to check that S2::Origin() is not nearly
// collinear with any edge of any cell that contains it (except for small
// cells < 3 meters across).
EXPECT_GE(GetMinExpensiveLevel(S2::Origin()), 22);
// For S2Cells that belong to the four non-polar faces, only longitudinal
// edges can possibly be colinear with S2::Origin(). We check these edges
// by projecting S2::Origin() onto the equator, and then testing all S2Cells
// that contain this point to make sure that none of their edges are nearly
// colinear with S2::Origin() (except for small cells < 3 meters across).
S2Point equator_point(S2::Origin().x(), S2::Origin().y(), 0);
EXPECT_GE(GetMinExpensiveLevel(equator_point), 22);
}
| [
"jmr@google.com"
] | jmr@google.com |
b2169b2ad46032ca98d91bc1b1f18d30fa6f55b5 | 2a43df8cf1b29bf6f019e99c5a6b0fdb5a29b348 | /software/robot_arm/cliGet.ino | 03edd7cba9f4aa1adf3f7e32b3a7bb13fb074965 | [
"MIT"
] | permissive | SovGVD/arduino-robot-arm | 10911e9720c511ad5542458bba36d1369df63b81 | 0021a1922531d1973b165c69896d9e0b554501fa | refs/heads/master | 2022-12-08T06:27:21.173397 | 2020-08-30T07:20:04 | 2020-08-30T07:20:04 | 291,230,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | ino | double cliGetAngles(double id)
{
// TODO cliSerial->
Serial.print(currentArm.upper);
Serial.print("\t");
Serial.print(currentArm.lower);
Serial.print("\t");
Serial.print(currentArm.wrist);
Serial.println();
return 1;
}
double cliGetPosition(double id)
{
cliSerial->print(gripperPos.x);
Serial.print("\t");
cliSerial->print(gripperPos.y);
cliSerial->println();
return 1;
}
| [
"sovgvd@gmail.com"
] | sovgvd@gmail.com |
c229091eabfe4cd9b461e1eb8063be20b05a814c | dea494a091b835b60af7069ae1733efd6d5cab2f | /Regexpr/test.cpp | 4102dcfa34e8d609d8f42c4e32367371bd9f194b | [] | no_license | ddoocc/RegExpr | 55c69daa6d25d6f6ec8dd7048fd53069e9d060d1 | 71def19bbfb81320a443400d2f005c5bff00350e | refs/heads/master | 2021-05-15T23:14:27.909952 | 2017-10-13T03:55:55 | 2017-10-13T03:55:55 | 106,775,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | #include <iostream>
#include <vector>
#include <list>
#include <cstdio>
#include <deque>
#include <string>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include "GraphImpl.h"
int main(void) {
} | [
"cwang173@gmail.com"
] | cwang173@gmail.com |
86ca59eab5410eea8451b7a1c9d509dce76ae2f2 | 596cf6c2e73ab8ef53773f198ec9b0ed61e612f6 | /src/vm/peimagelayout.cpp | 0178664ebd8a7f474bff23cf055dd69aaae42cad | [
"MIT"
] | permissive | kangaroo/coreclr | 7387d38671eb127da84c39e763a960f81607670b | 6f1c48b59908a797313777d792c51413db43afcd | refs/heads/master | 2021-01-17T10:28:18.821450 | 2015-03-01T06:16:02 | 2015-03-01T06:28:09 | 30,268,501 | 2 | 1 | null | 2015-02-03T22:40:02 | 2015-02-03T22:39:58 | null | UTF-8 | C++ | false | false | 30,250 | cpp | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
#include "common.h"
#include "peimagelayout.h"
#include "peimagelayout.inl"
#include "pefingerprint.h"
#ifndef DACCESS_COMPILE
PEImageLayout* PEImageLayout::CreateFlat(const void *flat, COUNT_T size,PEImage* pOwner)
{
STANDARD_VM_CONTRACT;
return new RawImageLayout(flat,size,pOwner);
}
#ifdef FEATURE_FUSION
PEImageLayout* PEImageLayout::CreateFromStream(IStream* pIStream,PEImage* pOwner)
{
STANDARD_VM_CONTRACT;
return new StreamImageLayout(pIStream,pOwner);
}
#endif
PEImageLayout* PEImageLayout::CreateFromHMODULE(HMODULE hModule,PEImage* pOwner, BOOL bTakeOwnership)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
return new RawImageLayout(hModule,pOwner,bTakeOwnership,TRUE);
}
PEImageLayout* PEImageLayout::LoadFromFlat(PEImageLayout* pflatimage)
{
STANDARD_VM_CONTRACT;
return new ConvertedImageLayout(pflatimage);
}
PEImageLayout* PEImageLayout::Load(PEImage* pOwner, BOOL bNTSafeLoad, BOOL bThrowOnError)
{
STANDARD_VM_CONTRACT;
#if defined(CROSSGEN_COMPILE) || defined(FEATURE_PAL)
return PEImageLayout::Map(pOwner->GetFileHandle(), pOwner);
#else
PEImageLayoutHolder pAlloc(new LoadedImageLayout(pOwner,bNTSafeLoad,bThrowOnError));
if (pAlloc->GetBase()==NULL)
return NULL;
return pAlloc.Extract();
#endif
}
PEImageLayout* PEImageLayout::LoadFlat(HANDLE hFile,PEImage* pOwner)
{
STANDARD_VM_CONTRACT;
return new FlatImageLayout(hFile,pOwner);
}
PEImageLayout* PEImageLayout::Map(HANDLE hFile, PEImage* pOwner)
{
CONTRACT(PEImageLayout*)
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pOwner));
POSTCONDITION(CheckPointer(RETVAL));
POSTCONDITION(RETVAL->CheckFormat());
}
CONTRACT_END;
PEImageLayoutHolder pAlloc(new MappedImageLayout(hFile,pOwner));
if (pAlloc->GetBase()==NULL)
{
//cross-platform or a bad image
PEImageLayoutHolder pFlat(new FlatImageLayout(hFile, pOwner));
if (!pFlat->CheckFormat())
ThrowHR(COR_E_BADIMAGEFORMAT);
pAlloc=new ConvertedImageLayout(pFlat);
}
else
if(!pAlloc->CheckFormat())
ThrowHR(COR_E_BADIMAGEFORMAT);
RETURN pAlloc.Extract();
}
#ifdef FEATURE_PREJIT
//To force base relocation on Vista (which uses ASLR), unmask IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
//(0x40) for OptionalHeader.DllCharacteristics
void PEImageLayout::ApplyBaseRelocations()
{
STANDARD_VM_CONTRACT;
//
// Note that this is not a univeral routine for applying relocations. It handles only the subset
// required by NGen images. Also, it assumes that the image format is valid.
//
SSIZE_T delta = (SIZE_T) GetBase() - (SIZE_T) GetPreferredBase();
// Nothing to do - image is loaded at preferred base
if (delta == 0)
return;
LOG((LF_LOADER, LL_INFO100, "PEImage: Applying base relocations (preferred: %x, actual: %x)\n",
GetPreferredBase(), GetBase()));
COUNT_T dirSize;
TADDR dir = GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_BASERELOC, &dirSize);
// Minimize number of calls to VirtualProtect by keeping a whole section unprotected at a time.
BYTE * pWriteableRegion = NULL;
SIZE_T cbWriteableRegion = 0;
DWORD dwOldProtection = 0;
COUNT_T dirPos = 0;
while (dirPos < dirSize)
{
PIMAGE_BASE_RELOCATION r = (PIMAGE_BASE_RELOCATION)(dir + dirPos);
DWORD rva = VAL32(r->VirtualAddress);
BYTE * pageAddress = (BYTE *)GetBase() + rva;
// Check whether the page is outside the unprotected region
if ((SIZE_T)(pageAddress - pWriteableRegion) >= cbWriteableRegion)
{
// Restore the protection
if (dwOldProtection != 0)
{
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
dwOldProtection, &dwOldProtection))
ThrowLastError();
dwOldProtection = 0;
}
IMAGE_SECTION_HEADER *pSection = RvaToSection(rva);
PREFIX_ASSUME(pSection != NULL);
pWriteableRegion = (BYTE*)GetRvaData(VAL32(pSection->VirtualAddress));
cbWriteableRegion = VAL32(pSection->SizeOfRawData);
// Unprotect the section if it is not writable
if (((pSection->Characteristics & VAL32(IMAGE_SCN_MEM_WRITE)) == 0))
{
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
PAGE_READWRITE, &dwOldProtection))
ThrowLastError();
}
}
COUNT_T fixupsSize = VAL32(r->SizeOfBlock);
USHORT *fixups = (USHORT *) (r + 1);
_ASSERTE(fixupsSize > sizeof(IMAGE_BASE_RELOCATION));
_ASSERTE((fixupsSize - sizeof(IMAGE_BASE_RELOCATION)) % 2 == 0);
COUNT_T fixupsCount = (fixupsSize - sizeof(IMAGE_BASE_RELOCATION)) / 2;
_ASSERTE((BYTE *)(fixups + fixupsCount) <= (BYTE *)(dir + dirSize));
for (COUNT_T fixupIndex = 0; fixupIndex < fixupsCount; fixupIndex++)
{
USHORT fixup = VAL16(fixups[fixupIndex]);
BYTE * address = pageAddress + (fixup & 0xfff);
switch (fixup>>12)
{
case IMAGE_REL_BASED_PTR:
*(TADDR *)address += delta;
break;
#ifdef _TARGET_ARM_
case IMAGE_REL_BASED_THUMB_MOV32:
PutThumb2Mov32((UINT16 *)address, GetThumb2Mov32((UINT16 *)address) + delta);
break;
#endif
case IMAGE_REL_BASED_ABSOLUTE:
//no adjustment
break;
default:
_ASSERTE(!"Unhandled reloc type!");
}
}
dirPos += fixupsSize;
}
_ASSERTE(dirSize == dirPos);
if (dwOldProtection != 0)
{
// Restore the protection
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
dwOldProtection, &dwOldProtection))
ThrowLastError();
}
}
#endif // FEATURE_PREJIT
#ifndef FEATURE_CORECLR
// Event Tracing for Windows is used to log data for performance and functional testing purposes.
// The events in this structure are used to measure the time taken by PE image mapping. This is useful to reliably measure the
// performance of the assembly loader by subtracting the time taken by the possibly I/O-intensive work of PE image mapping.
struct ETWLoaderMappingPhaseHolder { // Special-purpose holder structure to ensure the LoaderMappingPhaseEnd ETW event is fired when returning from a function.
StackSString ETWCodeBase;
DWORD _dwAppDomainId;
BOOL initialized;
ETWLoaderMappingPhaseHolder(){
LIMITED_METHOD_CONTRACT;
_dwAppDomainId = ETWAppDomainIdNotAvailable;
initialized = FALSE;
}
void Init(DWORD dwAppDomainId, SString wszCodeBase) {
_dwAppDomainId = dwAppDomainId;
EX_TRY
{
ETWCodeBase.Append(wszCodeBase);
ETWCodeBase.Normalize(); // Ensures that the later cast to LPCWSTR does not throw.
}
EX_CATCH
{
ETWCodeBase.Clear();
}
EX_END_CATCH(RethrowTransientExceptions)
FireEtwLoaderMappingPhaseStart(_dwAppDomainId, ETWLoadContextNotAvailable, ETWFieldUnused, ETWLoaderLoadTypeNotAvailable, ETWCodeBase.IsEmpty() ? NULL : (LPCWSTR)ETWCodeBase, NULL, GetClrInstanceId());
initialized = TRUE;
}
~ETWLoaderMappingPhaseHolder() {
if (initialized) {
FireEtwLoaderMappingPhaseEnd(_dwAppDomainId, ETWLoadContextNotAvailable, ETWFieldUnused, ETWLoaderLoadTypeNotAvailable, ETWCodeBase.IsEmpty() ? NULL : (LPCWSTR)ETWCodeBase, NULL, GetClrInstanceId());
}
}
};
#endif // FEATURE_CORECLR
RawImageLayout::RawImageLayout(const void *flat, COUNT_T size,PEImage* pOwner)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
m_pOwner=pOwner;
m_Layout=LAYOUT_FLAT;
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
if (size)
{
HandleHolder mapping(WszCreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0,
size, NULL));
if (mapping==NULL)
ThrowLastError();
m_DataCopy.Assign(CLRMapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if(m_DataCopy==NULL)
ThrowLastError();
memcpy(m_DataCopy,flat,size);
flat=m_DataCopy;
}
TESTHOOKCALL(ImageMapped(GetPath(),flat,IM_FLAT));
Init((void*)flat,size);
}
RawImageLayout::RawImageLayout(const void *mapped, PEImage* pOwner, BOOL bTakeOwnership, BOOL bFixedUp)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
m_pOwner=pOwner;
m_Layout=LAYOUT_MAPPED;
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
if (bTakeOwnership)
{
#ifndef FEATURE_PAL
WCHAR wszDllName[MAX_PATH];
WszGetModuleFileName((HMODULE)mapped, wszDllName, MAX_PATH);
wszDllName[MAX_PATH - 1] = W('\0');
m_LibraryHolder=CLRLoadLibraryEx(wszDllName,NULL,GetLoadWithAlteredSearchPathFlag());
#else // !FEATURE_PAL
_ASSERTE(!"bTakeOwnership Should not be used on FEATURE_PAL");
#endif // !FEATURE_PAL
}
TESTHOOKCALL(ImageMapped(GetPath(),mapped,bFixedUp?IM_IMAGEMAP|IM_FIXEDUP:IM_IMAGEMAP));
IfFailThrow(Init((void*)mapped,(bool)(bFixedUp!=FALSE)));
}
ConvertedImageLayout::ConvertedImageLayout(PEImageLayout* source)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
m_Layout=LAYOUT_LOADED;
m_pOwner=source->m_pOwner;
_ASSERTE(!source->IsMapped());
PEFingerprintVerificationHolder verifyHolder(source->m_pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
if (!source->HasNTHeaders())
EEFileLoadException::Throw(GetPath(), COR_E_BADIMAGEFORMAT);
LOG((LF_LOADER, LL_INFO100, "PEImage: Opening manually mapped stream\n"));
m_FileMap.Assign(WszCreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0,
source->GetVirtualSize(), NULL));
if (m_FileMap == NULL)
ThrowLastError();
m_FileView.Assign(CLRMapViewOfFileEx(m_FileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0,
(void *) source->GetPreferredBase()));
if (m_FileView == NULL)
m_FileView.Assign(CLRMapViewOfFile(m_FileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (m_FileView == NULL)
ThrowLastError();
source->LayoutILOnly(m_FileView, TRUE); //@TODO should be false for streams
TESTHOOKCALL(ImageMapped(GetPath(),m_FileView,IM_IMAGEMAP));
IfFailThrow(Init(m_FileView));
#ifdef CROSSGEN_COMPILE
if (HasNativeHeader())
ApplyBaseRelocations();
#endif
}
MappedImageLayout::MappedImageLayout(HANDLE hFile, PEImage* pOwner)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
m_Layout=LAYOUT_MAPPED;
m_pOwner=pOwner;
// If mapping was requested, try to do SEC_IMAGE mapping
LOG((LF_LOADER, LL_INFO100, "PEImage: Opening OS mapped %S (hFile %p)\n", (LPCWSTR) GetPath(), hFile));
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_PAL
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
// Let OS map file for us
// This may fail on e.g. cross-platform (32/64) loads.
m_FileMap.Assign(WszCreateFileMapping(hFile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, NULL));
if (m_FileMap == NULL)
{
#ifndef CROSSGEN_COMPILE
#ifdef FEATURE_CORECLR
// There is no reflection-only load on CoreCLR and so we can always throw an error here.
// It is important on Windows Phone. All assemblies that we load must have SEC_IMAGE set
// so that the OS can perform signature verification.
ThrowLastError();
#else // FEATURE_CORECLR
// We need to ensure any signature validation errors are caught if Extended Secure Boot (ESB) is on.
// Also, we have to always throw here during NGen to ensure that the signature validation is never skipped.
if (GetLastError() != ERROR_BAD_EXE_FORMAT || IsCompilationProcess())
{
ThrowLastError();
}
#endif // FEATURE_CORECLR
#endif // CROSSGEN_COMPILE
return;
}
#ifdef _DEBUG
// Force relocs by occuping the preferred base while the actual mapping is performed
CLRMapViewHolder forceRelocs;
if (PEDecoder::GetForceRelocs())
{
forceRelocs.Assign(CLRMapViewOfFile(m_FileMap, 0, 0, 0, 0));
}
#endif // _DEBUG
#ifdef FEATURE_MIXEDMODE
//
// For our preliminary loads, we don't want to take the preferred base address. We want to leave
// that open for a LoadLibrary. So, we first a phony MapViewOfFile to occupy the base
// address temporarily.
//
// Note that this is bad if we are racing another thread which is doing a LoadLibrary. We
// may want to tweak this logic, but it's pretty difficult to tell MapViewOfFileEx to map
// a file NOT at its preferred base address. Hopefully the ulimate solution here will be
// just mapping the file once.
//
// There are two distinct cases that this code takes care of:
//
// * NGened IL-only assembly: The IL image will get mapped here and LoadLibrary will be called
// on the NGen image later. If we need to, we can avoid creating the fake view on VISTA in this
// case. ASLR will map the IL image and NGen image at different addresses for free.
//
// * Mixed-mode assembly (either NGened or not): The mixed-mode image will get mapped here and
// LoadLibrary will be called on the same image again later. Note that ASLR does not help
// in this case. The fake view has to be created even on VISTA in this case to avoid relocations.
//
CLRMapViewHolder temp;
// We don't want to map at the prefered address, so have the temporary view take it.
temp.Assign(CLRMapViewOfFile(m_FileMap, 0, 0, 0, 0));
if (temp == NULL)
ThrowLastError();
#endif // FEATURE_MIXEDMODE
m_FileView.Assign(CLRMapViewOfFile(m_FileMap, 0, 0, 0, 0));
if (m_FileView == NULL)
ThrowLastError();
TESTHOOKCALL(ImageMapped(GetPath(),m_FileView,IM_IMAGEMAP));
IfFailThrow(Init((void *) m_FileView));
#ifdef CROSSGEN_COMPILE
//Do base relocation for PE. Unlike LoadLibrary, MapViewOfFile will not do that for us even with SEC_IMAGE
if (pOwner->IsTrustedNativeImage())
{
// This should never happen in correctly setup system, but do a quick check right anyway to
// avoid running too far with bogus data
if (!HasCorHeader())
ThrowHR(COR_E_BADIMAGEFORMAT);
// For phone, we need to be permissive of MSIL assemblies pretending to be native images,
// to support forced fall back to JIT
// if (!HasNativeHeader())
// ThrowHR(COR_E_BADIMAGEFORMAT);
if (HasNativeHeader())
{
if (!IsNativeMachineFormat())
ThrowHR(COR_E_BADIMAGEFORMAT);
ApplyBaseRelocations();
}
}
else
#endif
if (!IsNativeMachineFormat() && !IsI386())
{
//can't rely on the image
Reset();
return;
}
#ifdef _DEBUG
if (forceRelocs != NULL)
{
forceRelocs.Release();
if (CheckNTHeaders()) {
// Reserve the space so nobody can use it. A potential bug is likely to
// result in a plain AV this way. It is not a good idea to use the original
// mapping for the reservation since since it would lock the file on the disk.
// ignore any errors
ClrVirtualAlloc((void*)GetPreferredBase(), GetVirtualSize(), MEM_RESERVE, PAGE_NOACCESS);
}
}
#endif // _DEBUG
#else //!FEATURE_PAL
#ifdef FEATURE_PREJIT
if (pOwner->IsTrustedNativeImage())
{
m_FileView = PAL_LOADLoadPEFile(hFile);
if (m_FileView == NULL)
ThrowHR(E_FAIL); // we don't have any indication of what kind of failure. Possibly a corrupt image.
LOG((LF_LOADER, LL_INFO1000, "PEImage: image %S (hFile %p) mapped @ %p\n",
(LPCWSTR) GetPath(), hFile, (void*)m_FileView));
TESTHOOKCALL(ImageMapped(GetPath(),m_FileView,IM_IMAGEMAP));
IfFailThrow(Init((void *) m_FileView));
// This should never happen in correctly setup system, but do a quick check right anyway to
// avoid running too far with bogus data
#ifdef MDIL
// In MDIL we need to be permissive of MSIL assemblies pretending to be native images,
// to support forced fall back to JIT
if ((HasNativeHeader() && !IsNativeMachineFormat()) || !HasCorHeader())
ThrowHR(COR_E_BADIMAGEFORMAT);
if (HasNativeHeader())
ApplyBaseRelocations();
#else
if (!IsNativeMachineFormat() || !HasCorHeader() || !HasNativeHeader())
ThrowHR(COR_E_BADIMAGEFORMAT);
//Do base relocation for PE, if necessary.
ApplyBaseRelocations();
#endif // MDIL
}
#else //FEATURE_PREJIT
//Do nothing. The file cannot be mapped unless it is an ngen image.
#endif //FEATURE_PREJIT
#endif // !FEATURE_PAL
}
#if !defined(CROSSGEN_COMPILE) && !defined(FEATURE_PAL)
LoadedImageLayout::LoadedImageLayout(PEImage* pOwner, BOOL bNTSafeLoad, BOOL bThrowOnError)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pOwner));
}
CONTRACTL_END;
m_Layout=LAYOUT_LOADED;
m_pOwner=pOwner;
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
DWORD dwFlags = GetLoadWithAlteredSearchPathFlag();
if (bNTSafeLoad)
dwFlags|=DONT_RESOLVE_DLL_REFERENCES;
m_Module = CLRLoadLibraryEx(pOwner->GetPath(), NULL, dwFlags);
if (m_Module == NULL)
{
if (!bThrowOnError)
return;
// Fetch the HRESULT upfront before anybody gets a chance to corrupt it
HRESULT hr = HRESULT_FROM_GetLastError();
EEFileLoadException::Throw(pOwner->GetPath(), hr, NULL);
}
TESTHOOKCALL(ImageMapped(GetPath(),m_Module,IM_LOADLIBRARY));
IfFailThrow(Init(m_Module,true));
LOG((LF_LOADER, LL_INFO1000, "PEImage: Opened HMODULE %S\n", (LPCWSTR) GetPath()));
}
#endif // !CROSSGEN_COMPILE && !FEATURE_PAL
FlatImageLayout::FlatImageLayout(HANDLE hFile, PEImage* pOwner)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pOwner));
}
CONTRACTL_END;
m_Layout=LAYOUT_FLAT;
m_pOwner=pOwner;
LOG((LF_LOADER, LL_INFO100, "PEImage: Opening flat %S\n", (LPCWSTR) GetPath()));
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
COUNT_T size = SafeGetFileSize(hFile, NULL);
if (size == 0xffffffff && GetLastError() != NOERROR)
{
ThrowLastError();
}
// It's okay if resource files are length zero
if (size > 0)
{
m_FileMap.Assign(WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL));
if (m_FileMap == NULL)
ThrowLastError();
m_FileView.Assign(CLRMapViewOfFile(m_FileMap, FILE_MAP_READ, 0, 0, 0));
if (m_FileView == NULL)
ThrowLastError();
}
TESTHOOKCALL(ImageMapped(GetPath(),m_FileView,IM_FLAT));
Init(m_FileView, size);
}
#ifdef FEATURE_FUSION
StreamImageLayout::StreamImageLayout(IStream* pIStream,PEImage* pOwner)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
m_Layout=LAYOUT_FLAT;
m_pOwner=pOwner;
PEFingerprintVerificationHolder verifyHolder(pOwner); // Do not remove: This holder ensures the IL file hasn't changed since the runtime started making assumptions about it.
#ifndef FEATURE_CORECLR
ETWLoaderMappingPhaseHolder loaderMappingPhaseHolder;
if (ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, TRACE_LEVEL_INFORMATION, CLR_PRIVATEBINDING_KEYWORD)) {
loaderMappingPhaseHolder.Init(GetAppDomain() ? GetAppDomain()->GetId().m_dwId : ETWAppDomainIdNotAvailable, GetPath());
}
#endif // FEATURE_CORECLR
STATSTG statStg;
IfFailThrow(pIStream->Stat(&statStg, STATFLAG_NONAME));
if (statStg.cbSize.u.HighPart > 0)
ThrowHR(COR_E_FILELOAD);
DWORD cbRead = 0;
// Resources files may have zero length (and would be mapped as FLAT)
if (statStg.cbSize.u.LowPart) {
m_FileMap.Assign(WszCreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
statStg.cbSize.u.LowPart, NULL));
if (m_FileMap == NULL)
ThrowWin32(GetLastError());
m_FileView.Assign(CLRMapViewOfFile(m_FileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (m_FileView == NULL)
ThrowWin32(GetLastError());
HRESULT hr = pIStream->Read(m_FileView, statStg.cbSize.u.LowPart, &cbRead);
if (hr == S_FALSE)
hr = COR_E_FILELOAD;
IfFailThrow(hr);
}
TESTHOOKCALL(ImageMapped(GetPath(),m_FileView,IM_FLAT));
Init(m_FileView,(COUNT_T)cbRead);
}
#endif // FEATURE_FUSION
#ifdef MDIL
BOOL PEImageLayout::GetILSizeFromMDILCLRCtlData(DWORD* pdwActualILSize)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
IMAGE_SECTION_HEADER* pMDILSection = FindSection(".mdil");
if (pMDILSection)
{
TADDR pMDILSectionStart = GetRvaData(VAL32(pMDILSection->VirtualAddress));
MDILHeader* mdilHeader = (MDILHeader*)pMDILSectionStart;
ClrCtlData* pClrCtlData = (ClrCtlData*)(pMDILSectionStart + mdilHeader->hdrSize);
*pdwActualILSize = pClrCtlData->ilImageSize;
return TRUE;
}
return FALSE;
}
#endif // MDIL
#endif // !DACESS_COMPILE
#ifdef DACCESS_COMPILE
void
PEImageLayout::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
DAC_ENUM_VTHIS();
EMEM_OUT(("MEM: %p PEFile\n", dac_cast<TADDR>(this)));
PEDecoder::EnumMemoryRegions(flags,false);
}
#endif //DACCESS_COMPILE
#if defined(_WIN64) && !defined(DACCESS_COMPILE)
#define IMAGE_HEADER_3264_SIZE_DIFF (sizeof(IMAGE_NT_HEADERS64) - sizeof(IMAGE_NT_HEADERS32))
// This function is expected to be in sync with LdrpCorFixupImage in the OS loader implementation (//depot/winmain/minkernel/ntdll/ldrcor.c).
bool PEImageLayout::ConvertILOnlyPE32ToPE64Worker()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(IsILOnly()); // This should be called for IL-Only images
PRECONDITION(Has32BitNTHeaders()); // // Image should be marked to have a PE32 header only.
PRECONDITION(IsPlatformNeutral());
}
CONTRACTL_END;
PBYTE pImage = (PBYTE)GetBase();
IMAGE_DOS_HEADER *pDosHeader = (IMAGE_DOS_HEADER*)pImage;
IMAGE_NT_HEADERS32 *pHeader32 = GetNTHeaders32();
IMAGE_NT_HEADERS64 *pHeader64 = GetNTHeaders64();
_ASSERTE(&pHeader32->OptionalHeader.Magic == &pHeader64->OptionalHeader.Magic);
_ASSERTE(pHeader32->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC));
// Move the data directory and section headers down IMAGE_HEADER_3264_SIZE_DIFF bytes.
PBYTE pStart32 = (PBYTE) &pHeader32->OptionalHeader.DataDirectory[0];
PBYTE pStart64 = (PBYTE) &pHeader64->OptionalHeader.DataDirectory[0];
_ASSERTE(pStart64 - pStart32 == IMAGE_HEADER_3264_SIZE_DIFF);
PBYTE pEnd32 = (PBYTE) (IMAGE_FIRST_SECTION(pHeader32)
+ VAL16(pHeader32->FileHeader.NumberOfSections));
// On AMD64, used for a 12-byte jump thunk + the original entry point offset.
if (((pEnd32 + IMAGE_HEADER_3264_SIZE_DIFF /* delta in headers to compute end of 64bit header */) - pImage) > OS_PAGE_SIZE ) {
// This should never happen. An IL_ONLY image should at most 3 sections.
_ASSERTE(!"ConvertILOnlyPE32ToPE64Worker: Insufficient room to rewrite headers as PE64");
return false;
}
memmove(pStart64, pStart32, pEnd32 - pStart32);
// Move the tail fields in reverse order.
pHeader64->OptionalHeader.NumberOfRvaAndSizes = pHeader32->OptionalHeader.NumberOfRvaAndSizes;
pHeader64->OptionalHeader.LoaderFlags = pHeader32->OptionalHeader.LoaderFlags;
pHeader64->OptionalHeader.SizeOfHeapCommit = VAL64(VAL32(pHeader32->OptionalHeader.SizeOfHeapCommit));
pHeader64->OptionalHeader.SizeOfHeapReserve = VAL64(VAL32(pHeader32->OptionalHeader.SizeOfHeapReserve));
pHeader64->OptionalHeader.SizeOfStackCommit = VAL64(VAL32(pHeader32->OptionalHeader.SizeOfStackCommit));
pHeader64->OptionalHeader.SizeOfStackReserve = VAL64(VAL32(pHeader32->OptionalHeader.SizeOfStackReserve));
// One more field that's not the same
pHeader64->OptionalHeader.ImageBase = VAL64(VAL32(pHeader32->OptionalHeader.ImageBase));
// The optional header changed size.
pHeader64->FileHeader.SizeOfOptionalHeader = VAL16(VAL16(pHeader64->FileHeader.SizeOfOptionalHeader) + 16);
pHeader64->OptionalHeader.Magic = VAL16(IMAGE_NT_OPTIONAL_HDR64_MAGIC);
// Now we just have to make a new 16-byte PPLABEL_DESCRIPTOR for the new entry point address & gp
PBYTE pEnd64 = (PBYTE) (IMAGE_FIRST_SECTION(pHeader64) + VAL16(pHeader64->FileHeader.NumberOfSections));
pHeader64->OptionalHeader.AddressOfEntryPoint = VAL32((ULONG) (pEnd64 - pImage));
// Should be PE32+ now
_ASSERTE(!Has32BitNTHeaders());
return true;
}
bool PEImageLayout::ConvertILOnlyPE32ToPE64()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(IsILOnly()); // This should be called for IL-Only images
PRECONDITION(Has32BitNTHeaders());
}
CONTRACTL_END;
bool fConvertedToPE64 = false;
// Only handle platform neutral IL assemblies
if (!IsPlatformNeutral())
{
return false;
}
PBYTE pageBase = (PBYTE)GetBase();
DWORD oldProtect;
if (!ClrVirtualProtect(pageBase, OS_PAGE_SIZE, PAGE_READWRITE, &oldProtect))
{
// We are not going to be able to update header.
return false;
}
fConvertedToPE64 = ConvertILOnlyPE32ToPE64Worker();
DWORD ignore;
if (!ClrVirtualProtect(pageBase, OS_PAGE_SIZE, oldProtect, &ignore))
{
// This is not so bad; just ignore it
}
return fConvertedToPE64;
}
#endif // defined(_WIN64) && !defined(DACCESS_COMPILE)
| [
"dotnet-bot@microsoft.com"
] | dotnet-bot@microsoft.com |
b2fa34537727f5eb91e1795c5688ee414e5d705c | bfbe1b1d95ad945e4ecec8bb0aab106c30eb8b05 | /unreal/Puerts/ThirdParty/Include/asio/asio/any_io_executor.hpp | 68871e3006a38bcb7fd54dec7af11d8a3fb60832 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Tencent/puerts | 1b1af6fa5589187a1f564aec43c073aaff0745c8 | bb573ac16db918c604c2230dfb6d780d935f7078 | refs/heads/master | 2023-09-03T13:55:05.475818 | 2023-08-31T08:08:32 | 2023-08-31T08:08:32 | 287,706,896 | 4,171 | 721 | NOASSERTION | 2023-09-12T11:18:11 | 2020-08-15T08:20:44 | C++ | UTF-8 | C++ | false | false | 9,535 | hpp | //
// any_io_executor.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_ANY_IO_EXECUTOR_HPP
#define ASIO_ANY_IO_EXECUTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
# include "asio/executor.hpp"
#else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
# include "asio/execution.hpp"
# include "asio/execution_context.hpp"
#endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
#include "asio/detail/push_options.hpp"
namespace puerts_asio {
#if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
typedef executor any_io_executor;
#else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
/// Polymorphic executor type for use with I/O objects.
/**
* The @c any_io_executor type is a polymorphic executor that supports the set
* of properties required by I/O objects. It is defined as the
* execution::any_executor class template parameterised as follows:
* @code execution::any_executor<
* execution::context_as_t<execution_context&>,
* execution::blocking_t::never_t,
* execution::prefer_only<execution::blocking_t::possibly_t>,
* execution::prefer_only<execution::outstanding_work_t::tracked_t>,
* execution::prefer_only<execution::outstanding_work_t::untracked_t>,
* execution::prefer_only<execution::relationship_t::fork_t>,
* execution::prefer_only<execution::relationship_t::continuation_t>
* > @endcode
*/
class any_io_executor :
#if defined(GENERATING_DOCUMENTATION)
public execution::any_executor<...>
#else // defined(GENERATING_DOCUMENTATION)
public execution::any_executor<
execution::context_as_t<execution_context&>,
execution::blocking_t::never_t,
execution::prefer_only<execution::blocking_t::possibly_t>,
execution::prefer_only<execution::outstanding_work_t::tracked_t>,
execution::prefer_only<execution::outstanding_work_t::untracked_t>,
execution::prefer_only<execution::relationship_t::fork_t>,
execution::prefer_only<execution::relationship_t::continuation_t>
>
#endif // defined(GENERATING_DOCUMENTATION)
{
public:
#if !defined(GENERATING_DOCUMENTATION)
typedef execution::any_executor<
execution::context_as_t<execution_context&>,
execution::blocking_t::never_t,
execution::prefer_only<execution::blocking_t::possibly_t>,
execution::prefer_only<execution::outstanding_work_t::tracked_t>,
execution::prefer_only<execution::outstanding_work_t::untracked_t>,
execution::prefer_only<execution::relationship_t::fork_t>,
execution::prefer_only<execution::relationship_t::continuation_t>
> base_type;
typedef void supportable_properties_type(
execution::context_as_t<execution_context&>,
execution::blocking_t::never_t,
execution::prefer_only<execution::blocking_t::possibly_t>,
execution::prefer_only<execution::outstanding_work_t::tracked_t>,
execution::prefer_only<execution::outstanding_work_t::untracked_t>,
execution::prefer_only<execution::relationship_t::fork_t>,
execution::prefer_only<execution::relationship_t::continuation_t>
);
#endif // !defined(GENERATING_DOCUMENTATION)
/// Default constructor.
any_io_executor() ASIO_NOEXCEPT
: base_type()
{
}
/// Construct in an empty state. Equivalent effects to default constructor.
any_io_executor(nullptr_t) ASIO_NOEXCEPT
: base_type(nullptr_t())
{
}
/// Copy constructor.
any_io_executor(const any_io_executor& e) ASIO_NOEXCEPT
: base_type(static_cast<const base_type&>(e))
{
}
#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move constructor.
any_io_executor(any_io_executor&& e) ASIO_NOEXCEPT
: base_type(static_cast<base_type&&>(e))
{
}
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Construct to point to the same target as another any_executor.
#if defined(GENERATING_DOCUMENTATION)
template <class... OtherSupportableProperties>
any_io_executor(execution::any_executor<OtherSupportableProperties...> e);
#else // defined(GENERATING_DOCUMENTATION)
template <typename OtherAnyExecutor>
any_io_executor(OtherAnyExecutor e,
typename constraint<
conditional<
!is_same<OtherAnyExecutor, any_io_executor>::value
&& is_base_of<execution::detail::any_executor_base,
OtherAnyExecutor>::value,
typename execution::detail::supportable_properties<
0, supportable_properties_type>::template
is_valid_target<OtherAnyExecutor>,
false_type
>::type::value
>::type = 0)
: base_type(ASIO_MOVE_CAST(OtherAnyExecutor)(e))
{
}
#endif // defined(GENERATING_DOCUMENTATION)
/// Construct a polymorphic wrapper for the specified executor.
#if defined(GENERATING_DOCUMENTATION)
template <ASIO_EXECUTION_EXECUTOR Executor>
any_io_executor(Executor e);
#else // defined(GENERATING_DOCUMENTATION)
template <ASIO_EXECUTION_EXECUTOR Executor>
any_io_executor(Executor e,
typename constraint<
conditional<
!is_same<Executor, any_io_executor>::value
&& !is_base_of<execution::detail::any_executor_base,
Executor>::value,
execution::detail::is_valid_target_executor<
Executor, supportable_properties_type>,
false_type
>::type::value
>::type = 0)
: base_type(ASIO_MOVE_CAST(Executor)(e))
{
}
#endif // defined(GENERATING_DOCUMENTATION)
/// Assignment operator.
any_io_executor& operator=(const any_io_executor& e) ASIO_NOEXCEPT
{
base_type::operator=(static_cast<const base_type&>(e));
return *this;
}
#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move assignment operator.
any_io_executor& operator=(any_io_executor&& e) ASIO_NOEXCEPT
{
base_type::operator=(static_cast<base_type&&>(e));
return *this;
}
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Assignment operator that sets the polymorphic wrapper to the empty state.
any_io_executor& operator=(nullptr_t)
{
base_type::operator=(nullptr_t());
return *this;
}
/// Destructor.
~any_io_executor()
{
}
/// Swap targets with another polymorphic wrapper.
void swap(any_io_executor& other) ASIO_NOEXCEPT
{
static_cast<base_type&>(*this).swap(static_cast<base_type&>(other));
}
/// Obtain a polymorphic wrapper with the specified property.
/**
* Do not call this function directly. It is intended for use with the
* puerts_asio::require and puerts_asio::prefer customisation points.
*
* For example:
* @code any_io_executor ex = ...;
* auto ex2 = puerts_asio::require(ex, execution::blocking.possibly); @endcode
*/
template <typename Property>
any_io_executor require(const Property& p,
typename constraint<
traits::require_member<const base_type&, const Property&>::is_valid
>::type = 0) const
{
return static_cast<const base_type&>(*this).require(p);
}
/// Obtain a polymorphic wrapper with the specified property.
/**
* Do not call this function directly. It is intended for use with the
* puerts_asio::prefer customisation point.
*
* For example:
* @code any_io_executor ex = ...;
* auto ex2 = puerts_asio::prefer(ex, execution::blocking.possibly); @endcode
*/
template <typename Property>
any_io_executor prefer(const Property& p,
typename constraint<
traits::prefer_member<const base_type&, const Property&>::is_valid
>::type = 0) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
};
#if !defined(GENERATING_DOCUMENTATION)
namespace traits {
#if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
template <>
struct equality_comparable<any_io_executor>
{
static const bool is_valid = true;
static const bool is_noexcept = true;
};
#endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT)
template <typename F>
struct execute_member<any_io_executor, F>
{
static const bool is_valid = true;
static const bool is_noexcept = false;
typedef void result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT)
template <typename Prop>
struct query_member<any_io_executor, Prop> :
query_member<any_io_executor::base_type, Prop>
{
};
#endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT)
template <typename Prop>
struct require_member<any_io_executor, Prop> :
require_member<any_io_executor::base_type, Prop>
{
typedef any_io_executor result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT)
template <typename Prop>
struct prefer_member<any_io_executor, Prop> :
prefer_member<any_io_executor::base_type, Prop>
{
typedef any_io_executor result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT)
} // namespace traits
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
} // namespace puerts_asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_ANY_IO_EXECUTOR_HPP
| [
"zombieyang@tencent.com"
] | zombieyang@tencent.com |
5fbb8c64d375e0cf39edc64f4278f6d8a04e1aab | 45c2892871f179902272150f42d780a1a4beb8ee | /interface_opencl/zlarfgx-v2.cpp | d9b4ebc9a5e117e4b6b8758e84dbee2621e6d6d9 | [] | no_license | alcubierre-drive/clmagma | 35b88162b057ee3cb8265c082e3679dcba1b158d | e6c2655d3ecd77972bec28bd15ed84bcbb7a1afa | refs/heads/master | 2021-02-27T15:40:02.552547 | 2020-03-07T11:05:21 | 2020-03-07T11:05:21 | 245,616,458 | 0 | 0 | null | 2020-03-07T10:59:33 | 2020-03-07T10:59:33 | null | UTF-8 | C++ | false | false | 9,240 | cpp | /*
-- clMAGMA (version 1.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2014
@precisions normal z -> s d c
*/
#include <cstdio>
#include "CL_MAGMA_RT.h"
#include "common_magma.h"
//#define BLOCK_SIZE 768
#define BLOCK_SIZE 256
#define PRECISION_z
//==============================================================================
/*
Generates Householder elementary reflector H = I - tau v v^T to reduce
H [ dx0 ] = [ beta ]
[ dx ] [ 0 ]
with beta = ±norm( [dx0, dx] ) = ±dxnorm[0].
Stores v over dx; first element of v is 1 and is not stored.
Stores beta over dx0.
Stores tau.
The difference with LAPACK's zlarfg is that the norm of dx, and hance beta,
are computed outside the routine and passed to it in dxnorm (array on the GPU).
*/
extern "C" magma_err_t
magma_zlarfgx_gpu(int n, magmaDoubleComplex_ptr dx0, size_t dx0_offset, magmaDoubleComplex_ptr dx, size_t dx_offset,
magmaDoubleComplex_ptr dtau, size_t dtau_offset, magmaDouble_ptr dxnorm, size_t dxnorm_offset,
magmaDoubleComplex_ptr dA, size_t dA_offset, int it,
magma_queue_t queue)
{
cl_int ciErrNum; // Error code var
cl_kernel ckKernel=NULL;
ckKernel = rt->KernelPool["magma_zlarfgx_gpu_kernel"];
if (!ckKernel)
{
printf ("Error: cannot locate kernel in line %d, file %s\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
int nn = 0;
ciErrNum = clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&n );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dx0 );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dx0_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dx );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dx_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dtau );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dtau_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDouble_ptr), (void*)&dxnorm );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dxnorm_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dA );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dA_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&it );
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clSetKernelArg at %d in file %s!\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
/*
dim3 blocks((n+BLOCK_SIZE-1) / BLOCK_SIZE);
dim3 threads( BLOCK_SIZE );
*/
size_t GlobalWorkSize[1]={0}, LocalWorkSize[1]={0};
LocalWorkSize[0] = BLOCK_SIZE;
GlobalWorkSize[0] = ((n+BLOCK_SIZE-1) / BLOCK_SIZE)*LocalWorkSize[0];
// launch kernel
ciErrNum = clEnqueueNDRangeKernel(
queue, ckKernel, 1, NULL, GlobalWorkSize, LocalWorkSize, 0, NULL, NULL);
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clEnqueueNDRangeKernel at %d in file %s \"%s\"\n",
__LINE__, __FILE__, rt->GetErrorCode(ciErrNum));
return MAGMA_ERR_UNKNOWN;
}
clFlush(queue);
return MAGMA_SUCCESS;
}
//==============================================================================
/*
Generates Householder elementary reflector H = I - tau v v^T to reduce
H [ dx0 ] = [ beta ]
[ dx ] [ 0 ]
with beta = ±norm( [dx0, dx] ) = ±dxnorm[0].
Stores v over dx; first element of v is 1 and is not stored.
Stores beta over dx0.
Stores tau.
The difference with LAPACK's zlarfg is that the norm of dx, and hance beta,
are computed outside the routine and passed to it in dxnorm (array on the GPU).
*/
extern "C" magma_err_t
magma_zlarfgtx_gpu(int n, magmaDoubleComplex_ptr dx0, size_t dx0_offset, magmaDoubleComplex_ptr dx, size_t dx_offset,
magmaDoubleComplex_ptr dtau, size_t dtau_offset, magmaDouble_ptr dxnorm, size_t dxnorm_offset,
magmaDoubleComplex_ptr dA, size_t dA_offset, int i,
magmaDoubleComplex_ptr V, size_t V_offset, int ldv, magmaDoubleComplex_ptr T, size_t T_offset, int ldt,
magmaDoubleComplex_ptr work, size_t work_offset,
magma_queue_t queue)
{
/* Generate the elementary reflector H(i) */
magma_zlarfgx_gpu(n, dx0, dx0_offset, dx, dx_offset, dtau, dtau_offset, dxnorm, dxnorm_offset, dA, dA_offset, i, queue);
if (i==0){
magmaDoubleComplex tt = MAGMA_Z_ONE;
magmablas_zlacpy(MagmaFull, 1, 1, dtau, dtau_offset, 1, T, T_offset+i+i*ldt, 1, queue);
magma_zsetmatrix(1, 1, &tt, 0, 1, dx0, dx0_offset, 1, queue);
}
else
{
/* Compute the i-th column of T */
cl_int ciErrNum; // Error code var
cl_kernel ckKernel=NULL;
ckKernel = rt->KernelPool["magma_zgemv_kernel3"]; // in zlarfbx.cl
if (!ckKernel)
{
printf ("Error: cannot locate kernel in line %d, file %s\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
int nn = 0;
ciErrNum = clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&n );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&V );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&V_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&ldv );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dx0 );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dx0_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&work );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&work_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dtau );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dtau_offset );
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clSetKernelArg at %d in file %s!\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
size_t GlobalWorkSize[1]={0}, LocalWorkSize[1]={0};
LocalWorkSize[0] = BLOCK_SIZE;
GlobalWorkSize[0] = i*LocalWorkSize[0];
// launch kernel
ciErrNum = clEnqueueNDRangeKernel(
queue, ckKernel, 1, NULL, GlobalWorkSize, LocalWorkSize, 0, NULL, NULL);
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clEnqueueNDRangeKernel at %d in file %s \"%s\"\n",
__LINE__, __FILE__, rt->GetErrorCode(ciErrNum));
return MAGMA_ERR_UNKNOWN;
}
//magma_zgemv_kernel3<<< i, BLOCK_SIZE, 0, magma_stream >>>(n, V, ldv, dx0, work, dtau);
clFlush(queue);
ckKernel = rt->KernelPool["magma_ztrmv_kernel2"]; // in zlarfx.cl
if (!ckKernel)
{
printf ("Error: cannot locate kernel in line %d, file %s\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
nn = 0;
ciErrNum = clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&T );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&T_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&ldt );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&work );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&work_offset );
magmaDoubleComplex_ptr T1 = T;
size_t T1_offset = T_offset + i*ldt;
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&T1 );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&T1_offset );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(magmaDoubleComplex_ptr), (void*)&dtau );
ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(int), (void*)&dtau_offset );
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clSetKernelArg at %d in file %s!\n", __LINE__, __FILE__);
return MAGMA_ERR_UNKNOWN;
}
LocalWorkSize[0] = i;
GlobalWorkSize[0] = i*LocalWorkSize[0];
// launch kernel
ciErrNum = clEnqueueNDRangeKernel(
queue, ckKernel, 1, NULL, GlobalWorkSize, LocalWorkSize, 0, NULL, NULL);
if (ciErrNum != CL_SUCCESS)
{
printf("Error: clEnqueueNDRangeKernel at %d in file %s \"%s\"\n",
__LINE__, __FILE__, rt->GetErrorCode(ciErrNum));
printf("block: %d, group: %d\n", LocalWorkSize[0], GlobalWorkSize[0]);
return MAGMA_ERR_UNKNOWN;
}
//magma_ztrmv_kernel2<<< i, i, 0, magma_stream >>>( T, ldt, work, T+i*ldt, dtau);
clFlush(queue);
}
return MAGMA_SUCCESS;
}
//==============================================================================
| [
"github::alcubierre-drive"
] | github::alcubierre-drive |
97fb27f7e00814d185e480159384f0fa76ef84ae | dd20fdcc226f7cec298546152ac64c14aa4ec9db | /customPlugins/edgeRealx.hpp | dea810a3905382c8dc142a93aab712702a74f731 | [] | no_license | jimbo07/openBBlib | e7caed66ce80afe4e2de7c529d3cbe087a231e10 | df1c5a93ab507e8334d78ca79d929d3714ef3b8c | refs/heads/master | 2022-08-22T15:26:23.654354 | 2020-02-06T12:46:28 | 2020-02-06T12:46:28 | 137,645,514 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | hpp | #ifndef _EDGERELAX
#define _EDGERELAX
#include <string.h>
#include <math.h>
#include <float.h>
#include <vector>
#include <iostream>
#include <algorithm>
#include <maya/MFnMesh.h>
#include <maya/MVector.h>
#include <maya/MIntArray.h>
#include <maya/MFloatArray.h>
#include <maya/MPointArray.h>
#include <maya/MItMeshVertex.h>
// THREADING
#include "tbb/tbb.h"
using namespace tbb;
class EdgeRelaxData
{
public:
unsigned int m_vertcount;
unsigned int m_cachedcount;
unsigned int m_iterations;
MPointArray m_points;
MPointArray m_relaxpoints;
std::vector<std::vector<int>> m_conids;
MFloatArray m_weights;
};
class EdgeRelax
{
public:
EdgeRelax();
virtual ~EdgeRelax();
void relax(MObject&, unsigned int);
void relax(MObject&, unsigned int, MFloatArray &weights);
void relax(MObject&, unsigned int, MPointArray&);
void relax(MObject&, unsigned int, MPointArray&, MFloatArray &weights);
private:
EdgeRelaxData *m_relaxData;
void buildTopology(MObject &mesh);
void doRelax();
struct ThreadedDeform
{
EdgeRelaxData *data;
void operator()( const blocked_range<int>& range ) const {
unsigned int idz;
unsigned int numcons;
for ( int idx = range.begin(); idx!=range.end(); ++idx )
{
numcons = data->m_conids[idx].size();
data->m_relaxpoints[idx] = MPoint();
for (unsigned int idy=0; idy < numcons; idy++)
{
idz = data->m_conids[idx][idy];
data->m_relaxpoints[idx] += data->m_points[idz];
}
data->m_relaxpoints[idx] = data->m_points[idx] + ((data->m_relaxpoints[idx] / float(numcons)) - data->m_points[idx]) * data->m_weights[idx];
}
}
};
};
#endif
| [
"noreply@github.com"
] | jimbo07.noreply@github.com |
d8f3a0bc688e3246c3c00fa02130d391ef952aca | 603a1e413cab3e40fc9a7cc5e2b789eb846a5b2b | /source/Scene/StageFileLoader.cpp | 1e3fb50f5e355138b8c7e97df1d14e052a5533c3 | [] | no_license | BooshSource/Petari | 999fdfda45411052942f3daafe7f3a78ff084899 | cb63f1782b56f3c023edd89ddee5bfeb659f20dd | refs/heads/master | 2023-02-09T10:43:37.879079 | 2021-01-08T00:05:27 | 2021-01-08T00:05:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | #include "Scene/StageFileLoader.h"
#include "MR/MemoryUtil.h"
#include "MR/FileUtil.h"
#include "System/Galaxy/GalaxyStatusAccessor.h"
#include <stdio.h>
void StageFileLoader::startLoadingStageFile()
{
s32 curZoneIdx = 0;
while (mZoneNum > curZoneIdx)
{
MR::mountAsyncArchive(mNames[curZoneIdx], MR::getAproposHeapForSceneArchive(0.029999999));
curZoneIdx++;
}
}
void StageFileLoader::waitLoadedStageFile()
{
s32 curZoneIdx = 0;
while(mZoneNum > curZoneIdx)
{
const char* curFile = mNames[curZoneIdx];
MR::recieveFile(curFile);
mountFilesInStageMapFile(curFile);
curZoneIdx++;
}
}
void StageFileLoader::makeStageArchiveName(char *pOut, u32 len, const char *pStageName)
{
snprintf(pOut, len, "/StageData/%s.arc", pStageName);
} | [
"xarf98@yahoo.com"
] | xarf98@yahoo.com |
e8fff037829f40c9f25f6babb666066237a4b672 | 88e18f396df6dc9bc3e45c106f560d0073438ef3 | /C++/General Projects/MorrisQp6/airplanes.cpp | 36016b64eefca8ce772961163d8206eb7af97b08 | [] | no_license | qmorrissmu/SMU-projects | 3f6f65065fc57ed93d3711c9e179aa819d459481 | e3db5e573d8b62798c17da2ba50966601a39b742 | refs/heads/master | 2022-11-30T08:09:38.945346 | 2020-07-31T22:42:02 | 2020-07-31T22:42:02 | 269,765,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include "airplanes.h"
#include <iostream>
using namespace std;
Airplanes::Airplanes()
{
int miles;
}
void Airplanes::setMiles(int aM)
{
miles = aM;
}
int Airplanes::getMiles()
{
return miles;
}
void Airplanes::getCarbonFootprint()
{
int avgEm = 223;
double wTP = 1.2;
double ff = 1.9;
float conversion = .0022;
float footprintA = miles*avgEm*wTP*ff*conversion;
cout << "The airplane's carbon footprint is " << footprintA << " lbs." << endl;
} | [
"noreply@github.com"
] | qmorrissmu.noreply@github.com |
65e650615a94ccd34c0c42e70c2869a0af872ea6 | 4ef3c5ed2cfa80eab58c148fd5b0879e222eeb77 | /examples/ShapeModel.cxx | 6a4d67b9a5d4d355ebc6c3e37ce7cc1055d15457 | [
"Apache-2.0"
] | permissive | GGiancarlos/ShapeModel | d6ef0317e22a0d2357e8d9e043f6a5386c01206b | 470af5c10a8044efa4ad1124256f062c7591bee7 | refs/heads/master | 2021-05-27T19:27:20.786221 | 2013-12-19T14:27:35 | 2014-01-02T21:42:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,885 | cxx | /*============================================================================
Library: Image Segmentation Using Statistical Shape Models
File: ShapeModel.cxx
Copyright 2013 Kitware, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
============================================================================*/
#include <vtkShapeModel.h>
#include <vtkMultiBlockDataSet.h>
#include <vtkPolyData.h>
#include <vtkProcrustesAlignmentFilter.h>
#include <vtkSmartPointer.h>
int main()
{
// Display image.
vtkSmartPointer<vtkMultiBlockDataSet> data
= vtkSmartPointer<vtkMultiBlockDataSet>::New();
// Load training data.
vtkSmartPointer<vtkProcrustesAlignmentFilter> procrustes
= vtkSmartPointer<vtkProcrustesAlignmentFilter>::New();
procrustes->SetInputData(data);
vtkSmartPointer<vtkBuildShapeModel> build
= vtkSmartPointer<vtkBuildShapeModel>::New();
build->SetInputConnection(procrustes->GetOutputPort());
build->Update();
vtkSmartPointer<vtkPolyData> mean = build->GetOutput(0);
// Create mesh of mean shape.
// Display mean shape.
// Rotate image if necessary.
vtkSmartPointer<vtkPolyData> points
= vtkSmartPointer<vtkPolyData>::New();
// Choose some points on boundary of image.
vtkSmartPointer<vtkFitShapeModel> fit
= vtkSmartPointer<vtkFitShapeModel>::New();
fit->SetInputData(0, points);
fit->SetInputConnection(1, build->GetOutputPort(1));
fit->SetInputConnection(2, build->GetOutputPort(0));
fit->Update();
vtkSmartPointer<vtkPolyData> segmentation = fit->GetOutput();
// Create mesh of segmentation.
// Display segmentation.
// Rotate image if necessary.
vtkSmartPointer<vtkNextShapeModelPoint> choose
= vtkSmartPointer<vtkNextShapeModelPoint>::New();
choose->SetInputData(0, segmentation);
choose->SetInputData(1, points);
const double THRESHOLD = 1.0e-12;
while(fit->GetMeanSquaredError() < THRESHOLD)
{
choose->Update();
vtkSmartPointer<vtkShapeModelPoint> next = choose->GetOutput();
double point[3];
next->GetData(point);
// Display point.
// Adjust position of point if necessary.
points->GetPoints()->InsertNextPoint(point);
fit->Update();
segmentation = fit->GetOutput();
// Create mesh of segmentation.
// Display segmentation.
// Rotate image if necessary.
}
return 0;
}
| [
"jamie.snape@kitware.com"
] | jamie.snape@kitware.com |
d7e5f8193132ee6953d482534f7a636d7953e3bd | 7fde4884897619ba5ad02d2d89e5efd31085dfb3 | /src/PE/ResourceData.cpp | 5fde9411e1f6e79f574806055a5996463c5728ec | [
"Apache-2.0"
] | permissive | tsarpaul/LIEF | d184de6f5bcb7ee966a8cff3bf4d9141b356e794 | de934b0f64e0304e78ef4d9d77ec5c16616c49c2 | refs/heads/master | 2022-11-19T03:45:52.534171 | 2020-07-17T21:54:36 | 2020-07-17T21:54:36 | 276,966,892 | 1 | 0 | Apache-2.0 | 2020-07-03T18:47:14 | 2020-07-03T18:47:13 | null | UTF-8 | C++ | false | false | 3,275 | cpp | /* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <iomanip>
#include "LIEF/PE/hash.hpp"
#include "LIEF/PE/ResourceData.hpp"
namespace LIEF {
namespace PE {
ResourceData::~ResourceData(void) = default;
ResourceData& ResourceData::operator=(ResourceData other) {
this->swap(other);
return *this;
}
ResourceData::ResourceData(const ResourceData& other) :
ResourceNode{static_cast<const ResourceNode&>(other)},
content_{other.content_},
code_page_{other.code_page_},
reserved_{other.reserved_}
{}
ResourceData* ResourceData::clone(void) const {
return new ResourceData{*this};
}
void ResourceData::swap(ResourceData& other) {
ResourceNode::swap(other);
std::swap(this->content_, other.content_);
std::swap(this->code_page_, other.code_page_);
std::swap(this->reserved_, other.reserved_);
}
ResourceData::ResourceData(void) :
content_{},
code_page_{0},
reserved_{0}
{}
ResourceData::ResourceData(const std::vector<uint8_t>& content, uint32_t code_page) :
content_{content},
code_page_{code_page},
reserved_{0}
{}
uint32_t ResourceData::code_page(void) const {
return this->code_page_;
}
const std::vector<uint8_t>& ResourceData::content(void) const {
return this->content_;
}
uint32_t ResourceData::reserved(void) const {
return this->reserved_;
}
uint32_t ResourceData::offset(void) const {
return this->offset_;
}
void ResourceData::code_page(uint32_t code_page) {
this->code_page_ = code_page;
}
void ResourceData::content(const std::vector<uint8_t>& content) {
this->content_ = content;
}
void ResourceData::reserved(uint32_t value) {
this->reserved_ = value;
}
void ResourceData::accept(Visitor& visitor) const {
visitor.visit(*this);
}
bool ResourceData::operator==(const ResourceData& rhs) const {
size_t hash_lhs = Hash::hash(*this);
size_t hash_rhs = Hash::hash(rhs);
return hash_lhs == hash_rhs;
}
bool ResourceData::operator!=(const ResourceData& rhs) const {
return not (*this == rhs);
}
std::ostream& operator<<(std::ostream& os, const ResourceData& data) {
os << static_cast<const ResourceNode&>(data) << std::endl;
os << " " << std::setw(13) << std::left << std::setfill(' ') << "Code page :" << data.code_page() << std::endl;
os << " " << std::setw(13) << std::left << std::setfill(' ') << "Reserved :" << data.reserved() << std::endl;
os << " " << std::setw(13) << std::left << std::setfill(' ') << "Size :" << data.content().size() << std::endl;
os << " " << std::setw(13) << std::left << std::setfill(' ') << "Hash :" << std::hex << Hash::hash(data.content()) << std::endl;
return os;
}
}
}
| [
"romainthomasc@gmail.com"
] | romainthomasc@gmail.com |
b5ddda29d33711165d1f2d316246c72409f8dc2c | 3c12cf51a77859b51dcdbf6759f82d8cec9090e9 | /src/environment.cpp | 5f8d04e256829de054a4723ad99a892068ae3e56 | [] | no_license | eslamhussein906/Lidar-Object-Detection-Sensor-Fusion-ND- | 9b8c29c8b6ab8fbe8b6efbc71b27ab85a46888a2 | 335c17cbfaf30a79acda76dd62c168de5b4555c1 | refs/heads/master | 2022-04-27T13:01:18.555171 | 2020-04-26T20:15:27 | 2020-04-26T20:15:27 | 259,123,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,743 | cpp | /* \author Aaron Brown */
// Create simple 3d highway enviroment using PCL
// for exploring self-driving car sensors
#include "sensors/lidar.h"
#include "render/render.h"
#include "processPointClouds.h"
// using templates for processPointClouds so also include .cpp to help linker
#include "processPointClouds.cpp"
std::vector<Car> initHighway(bool renderScene, pcl::visualization::PCLVisualizer::Ptr& viewer)
{
Car egoCar( Vect3(0,0,0), Vect3(4,2,2), Color(0,1,0), "egoCar");
Car car1( Vect3(15,0,0), Vect3(4,2,2), Color(0,0,1), "car1");
Car car2( Vect3(8,-4,0), Vect3(4,2,2), Color(0,0,1), "car2");
Car car3( Vect3(-12,4,0), Vect3(4,2,2), Color(0,0,1), "car3");
std::vector<Car> cars;
cars.push_back(egoCar);
cars.push_back(car1);
cars.push_back(car2);
cars.push_back(car3);
if(renderScene)
{
renderHighway(viewer);
egoCar.render(viewer);
car1.render(viewer);
car2.render(viewer);
car3.render(viewer);
}
return cars;
}
void simpleHighway(pcl::visualization::PCLVisualizer::Ptr& viewer)
{
// ----------------------------------------------------
// -----Open 3D viewer and display simple highway -----
// ----------------------------------------------------
// RENDER OPTIONS
bool renderScene = false;
bool render_box = true;
std::vector<Car> cars = initHighway(renderScene, viewer);
// TODO:: Create lidar sensor
Lidar *lidarPtr = new Lidar(cars,0);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudptr = lidarPtr->scan();
//renderRays(viewer, lidarPtr->position ,cloudptr);
//renderPointCloud(viewer,cloudptr, "Cloud");
// TODO:: Create point processor
ProcessPointClouds<pcl::PointXYZ> processPoints ;
std::pair<pcl::PointCloud<pcl::PointXYZ>::Ptr,pcl::PointCloud<pcl::PointXYZ>::Ptr> segmentCloud = processPoints.SegmentPlane(cloudptr,100, 0.2);
std::vector<typename pcl::PointCloud<pcl::PointXYZ>::Ptr> cloudClusters = processPoints.Clustering(segmentCloud.first,1.0,3,30);
int clusterId = 0;
std::vector<Color> colors = {Color(1,0,0), Color(0,1,0), Color(0,0,1)};
for(pcl::PointCloud<pcl::PointXYZ>::Ptr cluster :cloudClusters){
std::cout << "cluster size ";
processPoints.numPoints(cluster);
renderPointCloud(viewer,cluster,"obstCloud"+std::to_string(clusterId),colors[clusterId]);
//renderPointCloud(viewer,segmentCloud.first, "obstacle", Color(1,0,0));
//renderPointCloud(viewer,segmentCloud.second, "plane",Color(0,1,0));
if(render_box){
Box box =processPoints.BoundingBox(cluster);
renderBox(viewer, box,clusterId);
++clusterId;
}
}
//renderPointCloud(viewer,se,"obstCloud"+std::to_string(clusterId),colors[clusterId]);
}
//setAngle: SWITCH CAMERA ANGLE {XY, TopDown, Side, FPS}
void initCamera(CameraAngle setAngle, pcl::visualization::PCLVisualizer::Ptr& viewer)
{
viewer->setBackgroundColor (0, 0, 0);
// set camera position and angle
viewer->initCameraParameters();
// distance away in meters
int distance = 16;
switch(setAngle)
{
case XY : viewer->setCameraPosition(-distance, -distance, distance, 1, 1, 0); break;
case TopDown : viewer->setCameraPosition(0, 0, distance, 1, 0, 1); break;
case Side : viewer->setCameraPosition(0, -distance, 0, 0, 0, 1); break;
case FPS : viewer->setCameraPosition(-10, 0, 0, 0, 0, 1);
}
if(setAngle!=FPS)
viewer->addCoordinateSystem (1.0);
}
//void cityBlock(pcl::visualization::PCLVisualizer::Ptr& viewer){
void cityBlock(pcl::visualization::PCLVisualizer::Ptr& viewer, ProcessPointClouds<pcl::PointXYZI> pointProcessorI, pcl::PointCloud<pcl::PointXYZI>::Ptr& inputCloud){
inputCloud = pointProcessorI.FilterCloud(inputCloud,0.3,Eigen::Vector4f (-10, -5, -2, 1), Eigen::Vector4f ( 30, 8, 1, 1));
//std::pair<typename pcl::PointCloud<pcl::PointXYZI>::Ptr, typename pcl::PointCloud<pcl::PointXYZI>::Ptr> segmentCloud = pointProcessorI.SegmentPlane(inputCloud,25,0.3);
//std::vector<typename pcl::PointCloud<pcl::PointXYZI>::Ptr> cloudClusters = pointProcessorI.Clustering(cloudOutliers,0.53 ,10 ,500);
/********************* Segmentation using RanSAC algorithm ****************************/
std::unordered_set<int> inliers = pointProcessorI.Ransac(inputCloud, 25, 0.2);
pcl::PointCloud<pcl::PointXYZI>::Ptr cloudInliers(new pcl::PointCloud<pcl::PointXYZI>());
pcl::PointCloud<pcl::PointXYZI>::Ptr cloudOutliers(new pcl::PointCloud<pcl::PointXYZI>());
for(unsigned int index = 0; index < inputCloud->points.size(); index++)
{
pcl::PointXYZI point = inputCloud->points[index];
// check if this index inside the inliers or not
if(inliers.count(index))
cloudInliers->points.push_back(point);
else
cloudOutliers->points.push_back(point);
}
/****************************** euclidean Clustering *******************************************/
std::vector<typename pcl::PointCloud<pcl::PointXYZI>::Ptr> cloudClusters = pointProcessorI.euclideanClusterMain(cloudOutliers,0.53,10,350);
int clusterId = 0;
std::vector<Color> colors = {Color(1,0,0), Color(0,1,0), Color(0,0,1)};
for(pcl::PointCloud<pcl::PointXYZI>::Ptr cluster :cloudClusters){
std::cout << "cluster size ";
pointProcessorI.numPoints(cluster);
renderPointCloud(viewer,cluster,"obstCloud"+std::to_string(clusterId),colors[clusterId%colors.size()]);
Box box =pointProcessorI.BoundingBox(cluster);
renderBox(viewer, box,clusterId);
++clusterId;
}
renderPointCloud(viewer,cloudInliers,"planeCloud",colors[1]);
}
int main (int argc, char** argv)
{
std::cout << "starting enviroment" << std::endl;
pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
CameraAngle setAngle = XY;
initCamera(setAngle, viewer);
//simpleHighway(viewer);
//cityBlock(viewer);
ProcessPointClouds<pcl::PointXYZI> pointProcessorI ;
std::vector<boost::filesystem::path> stream = pointProcessorI.streamPcd("../src/sensors/data/pcd/data_1");
auto streamIterator = stream.begin();
pcl::PointCloud<pcl::PointXYZI>::Ptr inputCloudI;
while (!viewer->wasStopped ())
{ // Clear viewer
viewer->removeAllPointClouds();
viewer->removeAllShapes();
// Load pcd and run obstacle detection process
inputCloudI = pointProcessorI.loadPcd((*streamIterator).string());
cityBlock(viewer, pointProcessorI, inputCloudI);
streamIterator++;
if(streamIterator == stream.end())
streamIterator = stream.begin();
viewer->spinOnce ();
}
} | [
"eslamhussein906.com"
] | eslamhussein906.com |
f68aab0c68bacf1c27d4dd00bb4f6d9a316aa233 | 58433f51b2966696950374947f5f38e5ef4aa889 | /cpp_day02/ex00/main.cpp | d1062497621421bd3fa57cc71ba2d456b6240f54 | [] | no_license | tlutsyk/cpp_pool | 5693d445d93ca8ed599148310cc2dbcc515a8d57 | a37954a5cacb370434a25d3f21db16576e70bfb8 | refs/heads/master | 2021-09-18T13:03:22.432433 | 2018-07-14T12:39:44 | 2018-07-14T12:39:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | cpp | // ************************************************************************** //
// //
// ::: :::::::: //
// main.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: tlutsyk <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/04/03 09:56:57 by tlutsyk #+# #+# //
// Updated: 2018/04/03 09:56:58 by tlutsyk ### ########.fr //
// //
// ************************************************************************** //
#include "Pony.hpp"
void ponyOntheHeap(void) {
std::cout << "Start create horse on the heap" << std::endl;
Pony* strapone = new Pony(300, "Losharyk", "Fast as a tortue!");
strapone->ponyInfo();
std::cout << "Start delete horse on the heap" << std::endl;
delete strapone;
std::cout << "Pony on the heap was deleted!" << std::endl;
}
void ponyOntheStack(void) {
std::cout << "Start create horse on the stack" << std::endl;
Pony handony = Pony(150, "Serunchik", "Has a big dick!");
handony.ponyInfo();
std::cout << "Pony on the heap was deleted!" << std::endl;
}
int main(void){
ponyOntheHeap();
std::cout << std::endl << std::endl;
ponyOntheStack();
std::cout << std::endl;
std::cout << "Pony strapony say good buy" << std::endl;
return (0);
} | [
"tlutsyk@e1r7p9.unit.ua"
] | tlutsyk@e1r7p9.unit.ua |
c70fdbbaed3d8ec79ac71d4d000f8ce80eab344f | 5edd607642dbd400031985927c18140c7dc3cc4a | /6.Builder/6.BuilderCodingExcercise/main.cpp | 94af8c39ef1f501c21102bbfe2ae433ca558f4bb | [] | no_license | mersed/design-paterns | b2a35b1d47616658a09f0ed8665abb04bee8f103 | 2ddbe1b9264d631d53347725b376f2e8721e7fa0 | refs/heads/master | 2021-02-06T02:41:29.461598 | 2020-03-20T23:24:12 | 2020-03-20T23:24:12 | 243,866,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | cpp | #include <iostream>
#include <string>
// #include <ostream>
#include <vector>
// #include <sstream>
class Class
{
std::string class_name;
std::vector<std::pair<std::string, std::string>> fields;
const size_t indent_size = 2;
public:
Class() {};
/*
This is correct implementation. Udemy does not allow adding libraries which they did not add to excercises
std::string str() const
{
std::ostringstream oss;
std::string i(indent_size, ' ');
oss << "class " << class_name << std::endl;
oss << "{" << std::endl;
for(auto& field : fields)
oss << i << field.second << " " << field.first << ";" << std::endl;
oss << "};" << std::endl;
return oss.str();
}
*/
std::string str() const
{
std::string concat;
std::string i(indent_size, ' ');
concat += "class " + class_name + "\n";
concat += "{\n";
for(auto& field : fields)
concat += i + field.second + " " + field.first + ";\n";
concat += "};";
return concat;
}
friend class CodeBuilder;
};
class CodeBuilder
{
Class classInstance;
public:
CodeBuilder(const std::string& class_name)
{
classInstance.class_name = class_name;
}
CodeBuilder& add_field(const std::string& name, const std::string& type)
{
classInstance.fields.emplace_back(std::make_pair(name, type));
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const CodeBuilder& obj)
{
os << obj.classInstance.str();
return os;
}
};
int main() {
auto cb = CodeBuilder{"Person"}.add_field("name", "string").add_field("age", "int");
std::cout << cb;
return 0;
}
| [
"kahrimanovic.mersed@gmail.com"
] | kahrimanovic.mersed@gmail.com |
9e858ef1e1d22ee88a3161dc7867fd3dd3aba344 | 49fa120bf72225a07eaf922260f6131493fccec9 | /calc.h | 60ae7a70b2ba9164fcd386dbac53059cb77fa4da | [] | no_license | RS-codes/Qt5_Basic_assign10 | 2e50e55bad4151e31e1d51a2c1220b1075cc15ec | e8c7d8f60531d441115b07d095bba659d865c601 | refs/heads/master | 2023-04-17T07:36:32.673691 | 2021-04-23T04:06:29 | 2021-04-23T04:06:29 | 360,757,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | #ifndef CALC_H
#define CALC_H
#include <QObject>
#include <QDebug>
class calc : public QObject
{
Q_OBJECT
public:
explicit calc(QObject *parent = nullptr);
~calc();
int dogYears(int age);
int catYears(int age);
signals:
public slots:
};
#endif // CALC_H
| [
"RS-codes@github.com"
] | RS-codes@github.com |
751d4abd466756a923aa34b11121a04f46765ac7 | 6142f7482225a161bb166ae99dbd7e08795c3902 | /back up Company/Team.cpp | 79a0bbe9d5db6c8efe92b7e7c78a138a8d10a9f1 | [] | no_license | pavlinaikoleva/Tasks-from-ZZS | aec98ac9d903a21f89dd36288597c3f5076c120d | 290fcf8282405cdfd69dab2c15d00df6274d0311 | refs/heads/master | 2021-01-23T00:16:09.352469 | 2017-05-18T21:20:45 | 2017-05-18T21:20:45 | 85,714,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | cpp | #include<iostream>
#include <cstring>
#include "Team.h"
#include "employee.h"
using std::cin;
using std::cout;
using std::endl;
Team::Team(){}
Team::Team(Employee * _leader, const char * _nameTeamProject)
{
leader = _leader;
strcpy_s(nameTeamProject, strlen(_nameTeamProject) + 1, _nameTeamProject);
}
Team::Team(const char *_nameTeamProject)
{
strcpy_s(nameTeamProject, strlen(_nameTeamProject) + 1, _nameTeamProject);
leader = nullptr;
}
Team::Team(Employee * _leader, const char * _nameTeamProject, const vector<Employee*> & initVect)
{
leader = _leader;
strcpy_s(nameTeamProject, strlen(_nameTeamProject) + 1, _nameTeamProject);
members = initVect;
}
Employee* Team::getLeader()const
{
return leader;
}
const char * Team::getNameTeamProject()const
{
return nameTeamProject;
}
size_t Team::getCountMembers()const
{
return members.size();
}
void Team::setLeader(Employee* _newLeader)
{
leader = _newLeader;
}
void Team::setNameTeamProject(const char * _nameTeamProject)
{
strcpy_s(nameTeamProject, strlen(_nameTeamProject) + 1, _nameTeamProject);
}
void Team::setMembers(const vector<Employee*> & initVect)
{
members = initVect;
}
void Team::addMember(Employee * _newMember)
{
if (members.empty())
{
this->setLeader(_newMember);
}
members.push_back(_newMember);
}
void Team::addMember(Employee& _newMember)
{
if (members.empty())
{
this->setLeader(&_newMember);
}
members.push_back(&_newMember);
}
void Team::removeMember(const char * _EGN)
{
size_t cntMembers = members.size();
bool flag = true;
for (size_t i = 0;i < cntMembers&&flag;i++)
{
if (!strcmp(members[i]->getEGN(), _EGN))
{
if (members[i] == leader)
{
leader = nullptr;
//cout << "Team " << nameTeamProject << " has no leader please set leader" << endl;
}
flag = false;
members.erase(members.begin() + i);
}
}
}
void Team::printMembersOfTeam()const
{
cout << "Members of team " << nameTeamProject << endl;
size_t cntMembers = members.size();
for (size_t i = 0;i < cntMembers;i++)
{
members[i]->print();
}
} | [
"noreply@github.com"
] | pavlinaikoleva.noreply@github.com |
c4ba361f0ef93a4fdee0a4fd7dfc5789cfea40a2 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /essbasic/include/tencentcloud/essbasic/v20201222/model/CheckMobileVerificationResponse.h | 2a70682cee9d9bc6ba0cff40f97006db6f3a2cab | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,236 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CHECKMOBILEVERIFICATIONRESPONSE_H_
#define TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CHECKMOBILEVERIFICATIONRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Essbasic
{
namespace V20201222
{
namespace Model
{
/**
* CheckMobileVerification返回参数结构体
*/
class CheckMobileVerificationResponse : public AbstractModel
{
public:
CheckMobileVerificationResponse();
~CheckMobileVerificationResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取检测结果
计费结果码:
0: 验证结果一致
1: 手机号未实名
2: 姓名和手机号不一致
3: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致)
不收费结果码:
101: 查无记录
102: 非法姓名(长度,格式等不正确)
103: 非法手机号(长度,格式等不正确)
104: 非法身份证号(长度,校验位等不正确)
105: 认证未通过
106: 验证平台异常
* @return Result 检测结果
计费结果码:
0: 验证结果一致
1: 手机号未实名
2: 姓名和手机号不一致
3: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致)
不收费结果码:
101: 查无记录
102: 非法姓名(长度,格式等不正确)
103: 非法手机号(长度,格式等不正确)
104: 非法身份证号(长度,校验位等不正确)
105: 认证未通过
106: 验证平台异常
*/
int64_t GetResult() const;
/**
* 判断参数 Result 是否已赋值
* @return Result 是否已赋值
*/
bool ResultHasBeenSet() const;
/**
* 获取结果描述; 未通过时必选
* @return Description 结果描述; 未通过时必选
*/
std::string GetDescription() const;
/**
* 判断参数 Description 是否已赋值
* @return Description 是否已赋值
*/
bool DescriptionHasBeenSet() const;
private:
/**
* 检测结果
计费结果码:
0: 验证结果一致
1: 手机号未实名
2: 姓名和手机号不一致
3: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致)
不收费结果码:
101: 查无记录
102: 非法姓名(长度,格式等不正确)
103: 非法手机号(长度,格式等不正确)
104: 非法身份证号(长度,校验位等不正确)
105: 认证未通过
106: 验证平台异常
*/
int64_t m_result;
bool m_resultHasBeenSet;
/**
* 结果描述; 未通过时必选
*/
std::string m_description;
bool m_descriptionHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CHECKMOBILEVERIFICATIONRESPONSE_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
20ddfca4abf91aca25569bcc377f13f5fd186a66 | 608caefb3bf9343bfc3fdfc1f32ac76dcca9ddd4 | /KickerFP/KickerFP/header/Plane.h | e651ac8867a649abdea2abdb304346246af5bf66 | [] | no_license | isa1374/Kicker-CG | 23067fc36c1b476347a7bdf2b626b40ebffd0919 | 53c0de43e526635282c0abc39c5d9b26547a71b7 | refs/heads/master | 2021-08-20T01:24:49.789997 | 2017-11-27T22:59:21 | 2017-11-27T22:59:21 | 110,875,633 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | h | //
// Plane.h
// KickerFP
//
// Created by Karla on 20/11/17.
// Copyright © 2017 Isa. All rights reserved.
//
#ifndef Plane_h
#define Plane_h
class Plane{
public:
Plane(int w, int h);
~Plane();
void display(int stepSize, float *color);
private:
int m_w, m_h;
float specularMat0[3], shine;
};
#endif /* Plane_h */
| [
"karla@iMac-de-Karlita.local"
] | karla@iMac-de-Karlita.local |
caa0831f1d043e33e8acea15a9db082fa308f505 | 2f17e97deae811440177f3381a2fea0a34408e15 | /Chapter04/01_WindowDemo/WindowDemo.cpp | 51397067ca8c933978398002503f97537f634235 | [] | no_license | 0000duck/VisualCppZhangJun | e0890d86c584e6a5e1547c6bcc310379a9cea725 | acc9374febcd1b0077671bc960a96e82eb2c87dc | refs/heads/master | 2021-12-14T22:59:47.592746 | 2017-06-19T09:05:45 | 2017-06-19T09:05:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 728 | cpp | // WindowDemo.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "tchar.h"
#include "mainwnd.h"
#include "resource.h"
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
//建立主窗体
CMainWnd wnd;
HWND hWnd = wnd.CreateEx(hInstance, 0, _T("主窗体"), WS_OVERLAPPEDWINDOW, NULL, NULL, IDR_MAIN);
wnd.Show(SW_SHOW);
if(!hWnd)
{
MessageBox(NULL, _T("创建主窗体时错误。"), NULL, MB_OK);
return 0;
}
//消息循环
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
| [
"lius@CPEKW-Q1100534.is.ad.igt.com"
] | lius@CPEKW-Q1100534.is.ad.igt.com |
21fe7e37bd12d8a3a30687c058070b7dd6f73de7 | f1bd3cd6e66b16e92805de9938a046d72b8f5356 | /src/raptor_encoder_api.cpp | 5629e222a378e4f1404bd987d68c1778b80bc8af | [] | no_license | ywu40/RaptorCodes_Cplusplus_Python | cddf9e9947afe99f1bcc69f37c352cd894bfee2a | 68670f0f76dd0986559ebb61ef24284a3e0a8fd9 | refs/heads/master | 2020-06-04T10:25:10.726813 | 2015-05-03T18:02:54 | 2015-05-03T18:03:10 | 34,228,767 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | #include <stdio.h>
#include "raptor_encoder_api.h"
using std::vector;
void RaptorEncoder::set_data(const std::string &raw_data)
{
vector<unsigned char> vecData;
stringToVector(raw_data, vecData);
size_t data_size = vecData.size();
U8 *data_buf = new U8[data_size];
for (size_t i = 0; i < data_size; ++i)
{
data_buf[i] = raw_data[i];
}
CData data(data_buf, data_size);
encoder->AddData(&data);
delete[] data_buf;
data_buf = NULL;
}
void RaptorEncoder::stringToVector(const std::string &strData,
std::vector<unsigned char> &vecData)
{
vecData.resize(strData.size());
// convert the string to a vector<unsigned char>
for(unsigned int i = 0; i < strData.size(); i++)
{
vecData[i] = static_cast<unsigned char>(strData[i]);
}
}
void RaptorEncoder::get_data_access()
{
while (!encoder->encoded_sym.empty())
{
encodedSym.push(encoder->encoded_sym.front());
encoder->encoded_sym.pop();
}
}
vector<U8> RaptorEncoder::get_encodedSym()
{
CData data = encodedSym.front();
encodedSym.pop();
vector<U8> res;
U8 *buf = data.GetData();
int data_size = data.GetLen();
for (U32 j = 0; j < data_size; ++j)
{
res.push_back(buf[j]);
}
return res;
}
bool RaptorEncoder::is_empty()
{
return encodedSym.empty();
}
int RaptorEncoder::count_encodedSym()
{
return encodedSym.size();
}
| [
"yeqingwu2011@gmail.com"
] | yeqingwu2011@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.