hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7699b4a231424320a1c8676a121ad6cdae4873f3 | 1,990 | cpp | C++ | src/classlibnative/nls/nlsinfo.cpp | pentp/coreclr | fdef855fa1df3540ba632bfae850279d627bde66 | [
"MIT"
] | 1 | 2019-05-19T20:44:03.000Z | 2019-05-19T20:44:03.000Z | src/classlibnative/nls/nlsinfo.cpp | pentp/coreclr | fdef855fa1df3540ba632bfae850279d627bde66 | [
"MIT"
] | 2 | 2018-07-13T00:48:13.000Z | 2019-02-27T16:19:30.000Z | src/classlibnative/nls/nlsinfo.cpp | pentp/coreclr | fdef855fa1df3540ba632bfae850279d627bde66 | [
"MIT"
] | 1 | 2018-07-05T01:49:20.000Z | 2018-07-05T01:49:20.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
// Class: NLSInfo
//
//
// Purpose: This module implements the methods of the COMNlsInfo
// class. These methods are the helper functions for the
// Locale class.
//
// Date: August 12, 1998
//
////////////////////////////////////////////////////////////////////////////
//
// Include Files.
//
#include "common.h"
#include "object.h"
#include "excep.h"
#include "vars.hpp"
#include "interoputil.h"
#include "corhost.h"
#include <winnls.h>
#include "utilcode.h"
#include "frames.h"
#include "field.h"
#include "metasig.h"
#include "nls.h"
#include "nlsinfo.h"
/**
* This function returns a pointer to this table that we use in System.Globalization.EncodingTable.
* No error checking of any sort is performed. Range checking is entirely the responsibility of the managed
* code.
*/
FCIMPL0(EncodingDataItem *, COMNlsInfo::nativeGetEncodingTableDataPointer)
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return (EncodingDataItem *)EncodingDataTable;
}
FCIMPLEND
/**
* This function returns a pointer to this table that we use in System.Globalization.EncodingTable.
* No error checking of any sort is performed. Range checking is entirely the responsibility of the managed
* code.
*/
FCIMPL0(CodePageDataItem *, COMNlsInfo::nativeGetCodePageTableDataPointer)
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return ((CodePageDataItem*) CodePageDataTable);
}
FCIMPLEND
/**
* This function returns the number of items in EncodingDataTable.
*/
FCIMPL0(INT32, COMNlsInfo::nativeGetNumEncodingItems)
{
LIMITED_METHOD_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
return (m_nEncodingDataTableItems);
}
FCIMPLEND
| 25.844156 | 108 | 0.679899 | [
"object"
] |
769bd05f266a94044d886915dd82e1f96c6d2353 | 4,307 | hpp | C++ | easy_perception_deployment/include/ort_cpp_lib/p1_ort_base.hpp | quasi-robotics/easy_perception_deployment | 19f0df36aa94426f81576a0b605718a7d8ac2d12 | [
"Apache-2.0"
] | 40 | 2020-07-10T02:40:09.000Z | 2022-03-28T13:09:00.000Z | easy_perception_deployment/include/ort_cpp_lib/p1_ort_base.hpp | quasi-robotics/easy_perception_deployment | 19f0df36aa94426f81576a0b605718a7d8ac2d12 | [
"Apache-2.0"
] | 19 | 2020-09-15T14:50:09.000Z | 2022-03-14T12:36:57.000Z | easy_perception_deployment/include/ort_cpp_lib/p1_ort_base.hpp | cardboardcode/easy_perception_deployment | bf3ba2247fdddd1c6197762a5be453efd7031e02 | [
"Apache-2.0"
] | 8 | 2020-06-29T04:26:57.000Z | 2022-01-07T13:57:26.000Z | // Copyright 2020 Advanced Remanufacturing and Technology Centre
// Copyright 2020 ROS-Industrial Consortium Asia Pacific Team
//
// 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 ORT_CPP_LIB__P1_ORT_BASE_HPP_
#define ORT_CPP_LIB__P1_ORT_BASE_HPP_
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "opencv2/opencv.hpp"
#include "ort_cpp_lib/ort_base.hpp"
namespace Ort
{
/*! \class P1OrtBase
\brief An Precision-Level 1 (P1) ONNXRuntime (Ort) Base class object.
This class object instantiates a Precision Level 1 Ort Session which takes a
typical ONNX model used for solely image classification and
runs an inferenc engine.
*/
class P1OrtBase : public OrtBase
{
public:
/*! \brief A fixed minimal image size needed for a lower bound requirement
for image classification of adequate result.*/
static constexpr int64_t MIN_IMAGE_SIZE = 800;
/*! \brief A Constructor function*/
P1OrtBase(
float ratio,
int newW,
int newH,
int paddedW,
int paddedH,
const uint16_t numClasses,
const std::string & modelPath,
const boost::optional<size_t> & gpuIdx = boost::none,
const boost::optional<std::vector<std::vector<int64_t>>> &
inputShapes = boost::none);
/*! \brief A Destructor function*/
~P1OrtBase();
/*! \brief A Mutator function that runs the P1 Ort Session and gets P1
inference result.*/
std::vector<std::string> infer(const cv::Mat & inputImg);
/*! \brief A Getter function that gets the number of object names used for an
ongoing session.*/
uint16_t getNumClasses() const {return m_numClasses;}
/*! \brief A Getter function that gets the list of object text labels which
will be used for outputting visualized inference result or for specific use-case
filters.*/
const std::vector<std::string> & getClassNames() const {return m_classNames;}
/*! \brief A Mutator function that sets the list of object text labels to be
used for the P1 Ort Session.*/
void initClassNames(const std::vector<std::string> & classNames);
private:
/*! \brief The number of object text labels given an input label list.*/
const uint16_t m_numClasses;
/*! \brief The aspect ratio calculated from the dimension of an input image
frame, which is provided when the first input image is received by Processor.*/
float m_ratio;
/*! \brief The new padded frame dimensions of an input image. This is used for
P2 and P3 object detection.*/
int m_newW, m_newH, m_paddedW, m_paddedH;
/*! \brief A vector of object text labels given an input label list.*/
std::vector<std::string> m_classNames;
/*! \brief A Mutator function that converts a 3-layered 2D RGB input image
into a 1D input data tensor to be passed to the Ort Session for processing.\n
This variant takes a generic input image represented by a char pointer.
*/
void preprocess(
float * dst,
const unsigned char * src,
const int64_t targetImgWidth,
const int64_t targetImgHeight,
const size_t numChannels,
const std::vector<float> & meanVal = {},
const std::vector<float> & stdVal = {}) const;
/*! \brief An Mutator function that takes the inference output and determines
the most possible object identity given an input label list.
*/
std::vector<std::pair<int, float>> getTopKRaw(
const std::vector<float *> & inferenceOutput,
const uint16_t k = 1,
const bool useSoftmax = true) const;
/*! \brief A Mutator function that takes the inference output and determines
the most possible object identity given an input label list.
*/
std::vector<std::string> processTopK(
const std::vector<float *> & inferenceOutput,
const uint16_t k = 1,
const bool useSoftmax = true) const;
};
} // namespace Ort
#endif // ORT_CPP_LIB__P1_ORT_BASE_HPP_
| 38.455357 | 82 | 0.728814 | [
"object",
"vector",
"model"
] |
3721c7b9ca9ff0d3b70804382b3cbe5e16954aa0 | 8,823 | cpp | C++ | src/main.cpp | tommy1900/MPC-Project-HIGHSPEED-Matplot-DynamicVelocityReference-100msLatency | 3487753b89c79a1fb359992b7b0237455aa5e4f3 | [
"MIT"
] | null | null | null | src/main.cpp | tommy1900/MPC-Project-HIGHSPEED-Matplot-DynamicVelocityReference-100msLatency | 3487753b89c79a1fb359992b7b0237455aa5e4f3 | [
"MIT"
] | null | null | null | src/main.cpp | tommy1900/MPC-Project-HIGHSPEED-Matplot-DynamicVelocityReference-100msLatency | 3487753b89c79a1fb359992b7b0237455aa5e4f3 | [
"MIT"
] | null | null | null | #include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "helpers.h"
#include "json.hpp"
#include "MPC.h"
#include "cViz.h"
#include <fstream>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
// for convenience
using nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
double mph2ms(double x) { return x * 0.447; }
double ms2mph(double x) { return x / 0.447; }
// Global varibles for the moving average
double prev_t = Now();
std::deque<double> dist_que;
std::deque<double> dt_que;
double prev_x = 0, prev_y = 0, prev_v = 0;
int max_iters = 300;
double MA_acc(const double x, const double y, const double dt) {
double dist = Distance(x, y, prev_x, prev_y);
prev_x = x;
prev_y = y;
dist_que.push_back(dist);
dt_que.push_back(dt);
double acc = 0;
if (dist_que.size() > 5) { // 5 steps moving average
// Pop the old data first to avoid the wrong initial value
dist_que.pop_front();
dt_que.pop_front();
double v = 0;
double dist = 0, dt = 0;
for (size_t i = 0; i < dist_que.size(); i++) {
dist += dist_que[i];
dt += dt_que[i];
}
v = dist / dt;
acc = (v - prev_v) / dt;
prev_v = v;
}
return acc;
}
int main() {
uWS::Hub h;
// Visualization
DrawThePath();
int iters = 0;
std::vector<double> x_vals = {};
std::vector<double> y_vals = {};
/*std::vector<double> psi_vals = {};
std::vector<double> v_vals = {};
std::vector<double> cte_vals = {};
std::vector<double> epsi_vals = {};
std::vector<double> delta_vals = {};
std::vector<double> a_vals = {};
*/
// MPC is initialized here!
MPC mpc;
h.onMessage([&mpc, &x_vals, &y_vals, &iters](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
string sdata = string(data).substr(0, length);
//std::cout << sdata << std::endl;
if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {
string s = hasData(sdata);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
vector<double> ptsx = j[1]["ptsx"];
vector<double> ptsy = j[1]["ptsy"];
double px = j[1]["x"];
double py = j[1]["y"];
double psi = j[1]["psi"]; //cout<< "current psi: " <<psi<<endl;
double v = mph2ms(j[1]["speed"]); //cout<< "current m/s: " << v<<endl;
double dt = Now() - prev_t;
prev_t = Now();
// get the control feedback
double delta = j[1]["steering_angle"]; //cout<< "delta reading: " << delta<<endl;
double a = MA_acc(px, py, dt);
//Plotting
if(true){
//If set, save data for plotting
iters++; cout<<iters<<endl;
x_vals.push_back(px);
y_vals.push_back(py);
/*psi_vals.push_back(psi);
v_vals.push_back(v);
cte_vals.push_back(cte);
epsi_vals.push_back(epsi);
delta_vals.push_back(delta);
a_vals.push_back(a);*/
}
assert(ptsx.size() == ptsy.size()); // error check
Eigen::VectorXd xvals(ptsx.size());
Eigen::VectorXd yvals(ptsy.size());
// Convert back to vehicule/body coordinates
for (size_t i = 0; i < ptsx.size(); i++) {
double x = ptsx[i] - px;
double y = ptsy[i] - py;
xvals[i] = x * cos(-psi) - y * sin(-psi);
yvals[i] = x * sin(-psi) + y * cos(-psi);
}
// a spline could be useful for path generation,
// but since the path is given already, we can directly use a polyfit
// create the polyfit. and the coefficients are enough to calculate for the path plan
auto coeffs = polyfit(xvals, yvals, 3);
// since the coordinate is transfered to local coord
// current local position will then be
px = 0;
py = 0;
psi = 0;
double cte = polyeval(coeffs, px) - py; // cout<<"first cte: "<<cte<<endl;
double epsi = psi - atan(coeffs[1]); // since x is 0
// If the operation latency is considered
double Lf = 2.67;
double delay = 0.1;
px = px + v * cos(psi) * delay;
py = py + v * sin(psi) * delay;
psi = psi - v * delta / Lf * delay; // psi in rad and delta in rad
v += a * delay;
cte += v * sin(epsi) * delay;
epsi += - v * delta / Lf * delay;
// Now update the MPC with the info we got
Eigen::VectorXd state(8);
state << px, py, psi, v, cte, epsi,delta,a;
mpc.VelTune(xvals, yvals);
auto vars = mpc.Solve(state, coeffs);
//cout<< "The ouput of MPC: " << vars[0] <<endl;
json msgJson;
// delta given is in radius in the range of (-0.4~0.4), in the MPC, we constraint the delta output in the
// range of (-0.4~0.4) rad about(-25 deg ~ 25 deg) as well
// plus the output only receive a cmd [-1,1] which represent [-25deg 25deg]
msgJson["steering_angle"] = rad2deg(vars[0])/25.0;
msgJson["throttle"] = vars[1];
// Display the MPC predicted trajectory
vector<double> mpc_x_vals;
vector<double> mpc_y_vals;
//.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system
// the points in the simulator are connected by a Green line
for (int i = 2; i < vars.size(); i+=2) {
mpc_x_vals.push_back(vars[i]);
mpc_y_vals.push_back(vars[i+1]);
}
msgJson["mpc_x"] = mpc_x_vals;
msgJson["mpc_y"] = mpc_y_vals;
// Display the waypoints/reference line, fill it with 25 seperate points
vector<double> next_x_vals;
vector<double> next_y_vals;
double space = 2.5;
int num_points = 25;
for (int i = 1; i < num_points; i++) {
next_x_vals.push_back(space * i);
next_y_vals.push_back(polyeval(coeffs, space * i));
}
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
//std::cout << msg << std::endl;
// Latency
// The purpose is to mimic real driving conditions where
// the car does actuate the commands instantly.
//
// Feel free to play around with this value but should be to drive
// around the track with 100ms latency.
//
// NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE SUBMITTING.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
if(iters > max_iters){
plt::named_plot("Position ",x_vals, y_vals,"r--");
plt::legend();
plt::show();
exit(1);
}
/*if(iters > max_iters){
//Plot Graph for analysis of the first 100 iterations
plt::subplot(3, 1, 1);
plt::title("CTE");
plt::plot(cte_vals);
plt::subplot(3, 1, 2);
plt::title("Delta (Radians)");
plt::plot(delta_vals);
plt::subplot(3, 1, 3);
plt::title("Velocity");
plt::plot(v_vals);
plt::show();
iters = 0;
exit(1);
}*/
} // end "telemetry" if
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} // end websocket if
}); // end h.onMessage
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| 32.083636 | 115 | 0.540292 | [
"object",
"vector"
] |
3722a61260360c7e85b1ae70fd84b05c3fa5a047 | 872 | cpp | C++ | Source/Tutorial2DConstruct/SpriteActor.cpp | ant1982/Tutorial2DConstruct | 57559bfbe8612c917ab5908e8996615d50e52f7a | [
"MIT"
] | null | null | null | Source/Tutorial2DConstruct/SpriteActor.cpp | ant1982/Tutorial2DConstruct | 57559bfbe8612c917ab5908e8996615d50e52f7a | [
"MIT"
] | null | null | null | Source/Tutorial2DConstruct/SpriteActor.cpp | ant1982/Tutorial2DConstruct | 57559bfbe8612c917ab5908e8996615d50e52f7a | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "SpriteActor.h"
#include "PaperSpriteComponent.h"
// Sets default values
ASpriteActor::ASpriteActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
SpriteComponent = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("SpriteMesh"));
SetRootComponent(SpriteComponent);
}
// Called when the game starts or when spawned
void ASpriteActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ASpriteActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ASpriteActor::OnConstruction(const FTransform & Transform)
{
Super::OnConstruction(Transform);
FVector Position = GetActorLocation();
Position.Y = 0.f;
SetActorLocation(Position);
}
| 20.27907 | 115 | 0.758028 | [
"transform"
] |
372615b209778df686b1511bcca24d87881ae78a | 1,035 | cpp | C++ | 02_1_ofxOscPublisherExample/src/ofApp.cpp | asaiyuta/ofxPubSubOsc | bcec57e9842595f716926d42cca49167973c2942 | [
"MIT"
] | 75 | 2015-05-11T13:21:51.000Z | 2022-01-24T20:24:57.000Z | 02_1_ofxOscPublisherExample/src/ofApp.cpp | asaiyuta/ofxPubSubOsc | bcec57e9842595f716926d42cca49167973c2942 | [
"MIT"
] | 29 | 2015-05-11T14:39:05.000Z | 2021-09-30T05:34:45.000Z | 02_1_ofxOscPublisherExample/src/ofApp.cpp | asaiyuta/ofxPubSubOsc | bcec57e9842595f716926d42cca49167973c2942 | [
"MIT"
] | 10 | 2015-11-21T15:07:41.000Z | 2022-01-31T23:07:46.000Z | #include "ofMain.h"
#include "ofxOscPublisher.h"
/* launch this and ofxOscSubscriberExample */
class ofApp : public ofBaseApp {
public:
void setup() {
for(int i = 0; i < 16; i++) {
m.addVertex(ofVec2f());
}
ofSetWindowPosition(100, 100);
ofxPublishOsc("localhost", 9005, "/cursor", p);
ofxPublishOsc("localhost", 9005, "/fps", &ofGetFrameRate);
ofxPublishOsc("localhost", 9005, "/mesh", m.getVertices());
ofEnableSmoothing();
glPointSize(3);
}
void update() {
p.x = ofGetMouseX();
p.y = ofGetMouseY();
for(int i = 0; i < m.getNumVertices(); i++) {
m.setVertex(i, ofVec2f(ofRandom(200), ofRandom(200)));
}
}
void draw() {
ofBackground(255);
ofSetColor(0);
ofDrawBitmapString("move mouse here!", 10, 30);
m.drawVertices();
}
private:
ofPoint p;
ofMesh m;
};
int main() {
ofSetupOpenGL(200, 200, OF_WINDOW);
ofRunApp(new ofApp());
}
| 24.069767 | 67 | 0.550725 | [
"mesh"
] |
3730c044451367e5142a43e1212e1dbdc06a498f | 784 | cpp | C++ | 0088_Merge_Sorted_Array/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | 2 | 2019-02-18T15:32:57.000Z | 2019-03-18T12:55:35.000Z | 0088_Merge_Sorted_Array/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | 0088_Merge_Sorted_Array/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int ptr1 = 0, ptr2 = 0;
vector<int> v = nums1;
int ptr = 0;
while (ptr1 < m && ptr2 < n)
{
if (v[ptr1] <= nums2[ptr2])
{
nums1[ptr] = v[ptr1];
ptr++;
ptr1++;
}
else
{
nums1[ptr] = nums2[ptr2];
ptr++;
ptr2++;
}
}
while (ptr1 < m)
{
nums1[ptr++] = v[ptr1];
ptr1++;
}
while (ptr2 < n)
{
nums1[ptr++] = nums2[ptr2];
ptr2++;
}
}
};
| 20.102564 | 70 | 0.30102 | [
"vector"
] |
37329468569f4967b6ec1b44a9310b6dac2a1a76 | 518 | cpp | C++ | demo/PBHelloDemo.cpp | courtarro/protobuf_example | 70480e5083fc592fb79aa0f2b47e5e0704e3e76e | [
"MIT"
] | 1 | 2019-09-02T04:55:33.000Z | 2019-09-02T04:55:33.000Z | demo/PBHelloDemo.cpp | courtarro/protobuf_example | 70480e5083fc592fb79aa0f2b47e5e0704e3e76e | [
"MIT"
] | null | null | null | demo/PBHelloDemo.cpp | courtarro/protobuf_example | 70480e5083fc592fb79aa0f2b47e5e0704e3e76e | [
"MIT"
] | null | null | null | #include <PBHello.h>
#include <iostream>
using namespace std;
int main(int argc, const char** argv) {
if (argc != 2) {
fprintf(stderr, "Usage: pb_hello_demo message\n");
exit(EXIT_FAILURE);
}
my_company::hello_project::PBHello pbHello(argv[1]);
custom::hello_message msg = pbHello.getMessage();
cout << msg.text() << endl;
vector<int32_t> numbers = pbHello.getNumbers();
for (auto val : numbers) {
cout << val;
}
cout << endl;
return 0;
}
| 19.923077 | 58 | 0.594595 | [
"vector"
] |
37364372e7e1153b9f7bc57b10443517995000a8 | 2,146 | cpp | C++ | code archive/GJ/h123.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/GJ/h123.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/GJ/h123.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | /**********************************************************************************/
/* Problem: h123 "A.可魚果運輸問題" from NPSC 2013 高中組決賽 */
/* Language: C++ */
/* Result: AC (10ms, 210KB) on ZeroJudge */
/* Author: briansu at 2016-09-20 00:16:18 */
/**********************************************************************************/
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <sstream>
#include <stdio.h>
#include <vector>
#include <set>
#include <algorithm>
#include <stack>
#include <map>
#include <iomanip>
//#include <utility>
using namespace std;
typedef long long ll;
//typedef pair<int,ll> ill;
const double EPS=1e-3;
const ll INF=ll(1e18);
struct ill
{
int first;
ll second;
ill(int a,ll b){this->first=a;this->second=b;}
};
int main()
{
int T;
cin>>T;
for(;T>0;T--)
{
int n,m,s,e;
ll f;
cin>>n>>m>>s>>e>>f;
s--;e--;
vector<ill> v[n];
for(int i=1;i<=m;i++)
{
ll a,b,c,c1;
ll d;
cin>>a>>b>>c>>d>>c1;
a--;b--;
ll w;
if(f>d)w=c*d+(f-d)*c1;
else w=f*c;
v[a].push_back(ill(b,w));
}
bool vis[n];
memset(vis,0,sizeof(vis));
ll dis[n];
for(int i=0;i<n;i++)dis[i]=INF;
dis[s]=0;
int p=s;
while(1)
{
for(int k=0;k<v[p].size();k++)
{
ill i=v[p][k];
int to=i.first;ll w=i.second;
dis[to]=min(dis[to],dis[p]+w);
}
vis[p]=true;
ll least=INF;int leastid=-1;
for(int i=0;i<n;i++)
{
if(!vis[i]&&dis[i]<least){least=dis[i];leastid=i;}
}
if(leastid==-1)break;
p=leastid;
}
cout<<dis[e]<<endl;
}
}
| 24.953488 | 84 | 0.359739 | [
"vector"
] |
3737d42395f17e7a613267c865523cd27e5583d2 | 1,916 | cpp | C++ | 1]. DSA + CP/2]. Competitive Programming/03]. LeetCode/1]. Problems/C++/0018]. 4Sum.cpp | geeknarendra/The-Complete-FAANG-Preparation | 3ed22719022bc66bd05c5c1ed091fe605e979908 | [
"MIT"
] | 1 | 2022-01-26T01:11:10.000Z | 2022-01-26T01:11:10.000Z | 3]. Competitive Programming/03]. LeetCode/1]. Problems/C++/0018]. 4Sum.cpp | ankitrajbiswal/The-Complete-FAANG-Preparation | c963509101e9811abbb0c1b2e38ba14d19161d47 | [
"MIT"
] | null | null | null | 3]. Competitive Programming/03]. LeetCode/1]. Problems/C++/0018]. 4Sum.cpp | ankitrajbiswal/The-Complete-FAANG-Preparation | c963509101e9811abbb0c1b2e38ba14d19161d47 | [
"MIT"
] | null | null | null | /*
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
*/
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
return kSum(nums, target, 0, 4);
}
vector<vector<int>> kSum(vector<int> &nums,int target, int start, int k){
vector<vector<int>> res;
if(start == nums.size()){
return res;
}
int average_value = target / k;
if(nums[start] > average_value || nums.back() < average_value){
return res;
}
if(k == 2)
return twoSum(nums, target, start);
for(int i=start; i<nums.size(); i++){
if(i == start || nums[i] != nums[i-1]){
for(vector<int> &subset : kSum(nums, static_cast<long>(target)-nums[i], i+1, k-1)){
subset.insert(subset.begin(), nums[i]);
res.push_back(subset);
}
}
}
return res;
}
vector<vector<int>> twoSum(vector<int> &nums, int target,int start){
vector<vector<int>> res;
int low, high, curr_sum;
low = start; high = nums.size()-1;
while(low < high){
curr_sum = nums[low] + nums[high];
if(curr_sum < target || (low > start && nums[low] == nums[low-1])){
low++;
}
else if(curr_sum > target || (high < nums.size()-1 && nums[high] == nums[high+1])){
high--;
}
else{
res.push_back({nums[low], nums[high]});
low++;
high--;
}
}
return res;
}
}; | 27.371429 | 99 | 0.43476 | [
"vector"
] |
373cb0b1e7a47009996ee2b45212c0d47ed2767e | 10,045 | cpp | C++ | WiiYourself/WiiMoteWrapper.cpp | lshoek/aerial-pace-vr | 46bbf6bf0f8bf85ccc3693090b02ba4c76ead4fd | [
"MIT"
] | null | null | null | WiiYourself/WiiMoteWrapper.cpp | lshoek/aerial-pace-vr | 46bbf6bf0f8bf85ccc3693090b02ba4c76ead4fd | [
"MIT"
] | null | null | null | WiiYourself/WiiMoteWrapper.cpp | lshoek/aerial-pace-vr | 46bbf6bf0f8bf85ccc3693090b02ba4c76ead4fd | [
"MIT"
] | null | null | null | #include "WiiMoteWrapper.h"
#include <mmsystem.h>
using namespace std;
WiiMoteWrapper::WiiMoteWrapper()
{
degrees = 0;
startAngle = 0;
buttonOne = buttonTwo = buttonHome = false;
continueGame = true;
status = 0; //0 = wachten 1 = succes -1 = niet succes
}
void WiiMoteWrapper::start(){
wiiMoteMainStart();
}
WiiMoteWrapper::~WiiMoteWrapper()
{
}
// configs:
#define USE_BEEPS_AND_DELAYS // undefine to test library works without them
#define LOOK_FOR_ADDITIONAL_WIIMOTES // tries to connect any extra wiimotes
// ------------------------------------------------------------------------------------
// state-change callback example (we use polling for everything else):
// ------------------------------------------------------------------------------------
void on_state_change(wiimote &remote,
state_change_flags changed,
const wiimote_state &new_state)
{
// we use this callback to set report types etc. to respond to key events
// (like the wiimote connecting or extensions (dis)connecting).
// NOTE: don't access the public state from the 'remote' object here, as it will
// be out-of-date (it's only updated via RefreshState() calls, and these
// are reserved for the main application so it can be sure the values
// stay consistent between calls). Instead query 'new_state' only.
// the wiimote just connected
if (changed & CONNECTED)
{
// ask the wiimote to report everything (using the 'non-continous updates'
// default mode - updates will be frequent anyway due to the acceleration/IR
// values changing):
// note1: you don't need to set a report type for Balance Boards - the
// library does it automatically.
// note2: for wiimotes, the report mode that includes the extension data
// unfortunately only reports the 'BASIC' IR info (ie. no dot sizes),
// so let's choose the best mode based on the extension status:
remote.SetReportType(wiimote::IN_BUTTONS_ACCEL_IR_EXT); // no IR dots
}
// a MotionPlus was detected
if (changed & MOTIONPLUS_DETECTED)
{
// enable it if there isn't a normal extension plugged into it
// (MotionPlus devices don't report like normal extensions until
// enabled - and then, other extensions attached to it will no longer be
// reported (so disable the M+ when you want to access them again).
if (remote.ExtensionType == wiimote_state::NONE) {
bool res = remote.EnableMotionPlus();
_ASSERT(res);
}
}
// an extension is connected to the MotionPlus
else if (changed & MOTIONPLUS_EXTENSION_CONNECTED)
{
// We can't read it if the MotionPlus is currently enabled, so disable it:
if (remote.MotionPlusEnabled())
remote.DisableMotionPlus();
}
// an extension disconnected from the MotionPlus
else if (changed & MOTIONPLUS_EXTENSION_DISCONNECTED)
{
// enable the MotionPlus data again:
if (remote.MotionPlusConnected())
remote.EnableMotionPlus();
}
// another extension was just connected:
else if (changed & EXTENSION_CONNECTED)
{
#ifdef USE_BEEPS_AND_DELAYS
//Beep(1000, 200);
#endif
remote.SetReportType(wiimote::IN_BUTTONS_ACCEL_IR_EXT);
}
// extension was just disconnected:
else if (changed & EXTENSION_DISCONNECTED)
{
#ifdef USE_BEEPS_AND_DELAYS
//Beep(200, 300);
#endif
}
}
// ------------------------------------------------------------------------------------
void PrintTitle(HANDLE console)
{
BRIGHT_WHITE;
_tprintf(_T("\n"));
_tprintf(_T(" -WiiYourself!- "));
WHITE; _tprintf(_T("library Demo: "));
CYAN; _tprintf(_T("| (c) "));
BRIGHT_CYAN; _tprintf(_T("gl"));
BRIGHT_PURPLE; _tprintf(_T("."));
BRIGHT_CYAN; _tprintf(_T("tter"));
CYAN; _tprintf(_T(" 2007-10\n")
_T(" v") WIIYOURSELF_VERSION_STR
_T(" | http://gl.tter.org\n"));
CYAN; _tprintf(_T(" ______________________________________________________________________\n\n\n"));
}
// ------------------------------------------------------------------------------------
int WiiMoteWrapper::wiiMoteMainStart()
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
// write the title
//PrintTitle(console);
// create a wiimote object
wiimote remote;
// in this demo we use a state-change callback to get notified of
// extension-related events, and polling for everything else
// (note you don't have to use both, use whatever suits your app):
remote.ChangedCallback = on_state_change;
// notify us only when the wiimote connected sucessfully, or something
// related to extensions changes
remote.CallbackTriggerFlags = (state_change_flags)(CONNECTED | EXTENSION_CHANGED | MOTIONPLUS_CHANGED);
reconnect:
COORD pos = { 0, 6 };
//SetConsoleCursorPosition(console, pos);
// try to connect the first available wiimote in the system
// (available means 'installed, and currently Bluetooth-connected'):
//RED; _tprintf(_T("Looking for a Wiimote\n")); WHITE;
//static const TCHAR* wait_str[] = { _T(". "), _T(".. "), _T("...") };
unsigned count = 0;
while (!remote.Connect(wiimote::FIRST_AVAILABLE) && continueGame) {
//_tprintf(_T("\b\b\b\b%s "), wait_str[count % 3]);
count++;
#ifdef USE_BEEPS_AND_DELAYS
//Beep(500, 30);
Sleep(1000);
#endif
}
if (!continueGame){
return 0;
}
// connected - light all LEDs
remote.SetLEDs(0x0f);
//BRIGHT_CYAN; _tprintf(_T("\b\b\b\b... connected!")); WHITE;
status = 1;
#ifdef USE_BEEPS_AND_DELAYS
//Beep(1000, 300);
Sleep(2000);
#endif
COORD cursor_pos = { 0, 6 };
// print the button event instructions:
//BRIGHT_WHITE; _tprintf(_T("\r -- TRY: B = rumble, A = square, 1 = sine, 2 = daisy, Home = Exit --\n"));
while (continueGame)
{
// IMPORTANT: the wiimote state needs to be refreshed each pass
while (remote.RefreshState() == NO_CHANGE)
Sleep(1); // // don't hog the CPU if nothing changed
cursor_pos.Y = 8;
//SetConsoleCursorPosition(console, cursor_pos);
if (remote.ConnectionLost())
{
//BRIGHT_RED; _tprintf( _T(" *** connection lost! *** \n\n\n\n\n\n\n\n\n\n\n"));
//Beep(100, 1000);
Sleep(2000);
COORD pos = { 0, 6 };
//SetConsoleCursorPosition(console, pos);
//printf("\n\n\n");
goto reconnect;
}
// rumble if 'B' (trigger) is pressed
//remote.SetRumble(remote.Button.B());
// TEMP: Minus button disables MotionPlus (if connected) to allow its
// own extension port to work
static bool last_minus = false;
if (remote.Button.Minus() && !last_minus &&
(remote.ExtensionType == wiimote_state::MOTION_PLUS))
remote.DisableMotionPlus();
last_minus = remote.Button.Minus();
// actions for buttons just pressed/released:
static bool last_A = false, last_One = false, last_Two = false;
#define ON_PRESS_RELEASE(button, pressed_action, released_action) \
{ bool pressed = remote.Button.button(); \
if(pressed) \
{ /* just pressed? */ \
if(!last_##button) pressed_action; \
} \
else if(last_##button) /* just released */ \
released_action; \
/* remember the current button state for next time */ \
last_##button = pressed; }
// play audio whilst certain buttons are held
//ON_PRESS_RELEASE(A, remote.PlaySquareWave(FREQ_3130HZ, 0x20),remote.EnableSpeaker(false));
// Battery level:
/*CYAN; _tprintf(_T(" Battery: "));
(remote.bBatteryDrained) ? BRIGHT_RED :
(remote.BatteryPercent >= 30) ? BRIGHT_GREEN : BRIGHT_YELLOW;
_tprintf(_T("%3u%% "), remote.BatteryPercent);*/
// Rumble
//WHITE; _tprintf(_T("] "));
//if (remote.bRumble) {BRIGHT_WHITE; printf("RUMBLE ");} else_tprintf(_T(" "));
// Output method:
//CYAN; _tprintf(_T(" using %s\n"), (remote.IsUsingHIDwrites() ?
// _T("HID writes") : _T("WriteFile()")));
// Buttons:
//CYAN; _tprintf(_T(" Buttons: ")); WHITE; _tprintf(_T("["));
for (unsigned bit = 0; bit < 16; bit++)
{
WORD mask = (WORD)(1 << bit);
// skip unused bits
if ((wiimote_state::buttons::ALL & mask) == 0)
continue;
const TCHAR* button_name = wiimote::ButtonNameFromBit[bit];
bool pressed = ((remote.Button.Bits & mask) != 0);
//if (bit > 0) { CYAN; _tprintf(_T("|")); // seperator }
buttonOne = remote.Button.One() == 1;
buttonTwo = remote.Button.Two() == 1;
buttonHome = remote.Button.Home() == 1;
//if (pressed) {
// BRIGHT_WHITE; _tprintf(_T("%s"), button_name);
//}
//else{
// WHITE; _tprintf(_T("%*s"), _tcslen(button_name), _T(""));
//}
}
//WHITE; _tprintf(_T("]\n"));
// Acceleration:
//CYAN; _tprintf(_T(" Accel:")); WHITE;
//_tprintf(_T(" X %+2.3f Y %+2.3f Z %+2.3f \n"),remote.Acceleration.X,remote.Acceleration.Y,remote.Acceleration.Z);
// Orientation estimate (shown red if last valid update is aging):
//CYAN; _tprintf(_T(" Orient:")); WHITE; _tprintf(_T(" UpdateAge %3u "), remote.Acceleration.Orientation.UpdateAge);
// show if the last orientation update is considered out-of-date
// (using an arbitrary threshold)
//if (remote.Acceleration.Orientation.UpdateAge > 10)
// RED;
degrees = remote.Acceleration.Orientation.Pitch + startAngle;
while (degrees > 360.0) degrees -= 360.0;
while (degrees < -360.0) degrees += 360.0;
/*_tprintf(_T("Pitch:%4ddeg Roll:%4ddeg \n")
_T(" (X %+.3f Y %+.3f Z %+.3f) \n"),
(int)remote.Acceleration.Orientation.Pitch,
(int)remote.Acceleration.Orientation.Roll,
remote.Acceleration.Orientation.X,
remote.Acceleration.Orientation.Y,
remote.Acceleration.Orientation.Z);*/
// Speaker:
/*CYAN; _tprintf(_T(" Speaker:"));
WHITE;
_tprintf(_T(" %s | %s "), (remote.Speaker.bEnabled ? _T("On ") :
_T("Off")),
(remote.Speaker.bMuted ? _T("Muted") :
_T(" ")));
_tprintf(_T("Frequency %4u Hz Volume 0x%02x\n"),
wiimote::FreqLookup[remote.Speaker.Freq],
remote.Speaker.Volume);*/
}
// disconnect (auto-happens on wiimote destruction anyway, but let's play nice)
remote.Disconnect();
CloseHandle(console);
return 0;
} | 35.245614 | 128 | 0.640418 | [
"object"
] |
373d7b4e190f9c7815a2a18bdfabe594983bc1eb | 1,219 | cpp | C++ | ceppengine/src/ceppengine/components/rendering/meshrenderer.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | 2 | 2017-11-13T11:29:03.000Z | 2017-11-13T12:09:12.000Z | ceppengine/src/ceppengine/components/rendering/meshrenderer.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | ceppengine/src/ceppengine/components/rendering/meshrenderer.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | #include "meshrenderer.h"
#include "../../engine.h"
namespace cepp {
MeshRenderer::MeshRenderer()
{
}
MeshRenderer::~MeshRenderer()
{
Engine::instance()->renderModule()->removeHandler(this);
}
std::string MeshRenderer::typeName() const
{
return "MeshRenderer";
}
Mesh *MeshRenderer::mesh() const
{
return mMesh;
}
void MeshRenderer::setMesh(Mesh *mesh)
{
mMesh = mesh;
}
Material *MeshRenderer::material() const
{
return mMaterial;
}
void MeshRenderer::setMaterial(Material *material)
{
mMaterial = material;
}
void _renderMesh(Object *obj, IRenderer *renderer)
{
MeshRenderer *r = (MeshRenderer*)obj;
r->render(renderer);
}
void MeshRenderer::render(IRenderer *renderer)
{
if(!gameObject()->isActiveInHierarchy()) return;
renderer->setMesh(mMesh);
renderer->setMaterial(mMaterial);
float *lToWMat = gameObject()->localToWorldMatrix().toColumnMajorArray();
Engine::instance()->renderModule()->setGlobalShaderParam("LocalToWorldMatrix", lToWMat, 4 * 4);
renderer->applySettings();
renderer->draw();
delete lToWMat;
}
void MeshRenderer::start()
{
Engine::instance()->renderModule()->addHandler(this, _renderMesh);
}
} // namespace cepp
| 17.666667 | 99 | 0.692371 | [
"mesh",
"render",
"object"
] |
37479e9e9ca34f3355a42ffe77ac27cd84f87f13 | 1,558 | cpp | C++ | leetcode/cpp/qt_construct_binary_tree_from_preorder_and_inorder_traversal.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | leetcode/cpp/qt_construct_binary_tree_from_preorder_and_inorder_traversal.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | leetcode/cpp/qt_construct_binary_tree_from_preorder_and_inorder_traversal.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | /**
* @Author: Tian Qiao <root>
* @Date: 2016-07-12T18:48:51+08:00
* @Email: qiaotian@me.com
* @Last modified by: root
* @Last modified time: 2016-07-12T20:16:53+08:00
* @Inc: Bloomberg
* @Difficulty: Medium
*/
/**
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
*/
// 问题:runtime error 死循环,原因在于 #1 处的前序和中序在递归过程中的下标范围写错
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int pl, int pr, int il, int ir) {
if(pl>pr || il>ir) return NULL;
TreeNode *root = new TreeNode(preorder[pl]);
if(pl==pr || il==ir) return root;
// method 1
//int len = 0; //左子树长度
//while(inorder[len+il]!=preorder[pl]) len++;
// method 2
int len = find(inorder.begin() + ii,inorder.begin() + jj, preorder[pl]) - inorder.begin() -il;
// # 1
root->left = len<=0?NULL:helper(preorder, inorder, pl+1, pl+len, il, il+len-1);
root->right = len>=(pr-pl)?NULL:helper(preorder, inorder, pl+len+1, pr, il+len+1, ir);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty()) return NULL;
return helper(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
}
};
| 28.327273 | 102 | 0.601412 | [
"vector"
] |
3755c8be4cf0cb6f55e2e4dda7843d14fbdb85eb | 2,817 | cpp | C++ | CGALWrapper/Geometry/Box2_EIK.cpp | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null | CGALWrapper/Geometry/Box2_EIK.cpp | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null | CGALWrapper/Geometry/Box2_EIK.cpp | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null |
#include "Box2_EIK.h"
#include <CGAL/Iso_rectangle_2.h>
#include <CGAL/Aff_transformation_2.h>
#include <CGAL/Cartesian_converter.h>
typedef CGAL::Iso_rectangle_2<EIK> Box2;
typedef CGAL::Aff_transformation_2<EIK> Transformation2;
void* Box2_EIK_Create(const Point2d& min, const Point2d& max)
{
auto _min = min.ToCGAL<EIK>();
auto _max = max.ToCGAL<EIK>();
return new Box2(_min, _max);
}
void Box2_EIK_Release(void* ptr)
{
auto obj = static_cast<Box2*>(ptr);
if (obj != nullptr)
{
delete obj;
obj = nullptr;
}
}
Box2* CastToBox2(void* ptr)
{
return static_cast<Box2*>(ptr);
}
Box2* NewBox2()
{
return new Box2();
}
Point2d Box2_EIK_GetMin(void* ptr)
{
auto rec = CastToBox2(ptr);
return Point2d::FromCGAL<EIK>(rec->min());
}
void Box2_EIK_SetMin(void* ptr, const Point2d& point)
{
auto rec = CastToBox2(ptr);
(*rec) = Box2(point.ToCGAL<EIK>(), rec->max());
}
Point2d Box2_EIK_GetMax(void* ptr)
{
auto rec = CastToBox2(ptr);
return Point2d::FromCGAL<EIK>(rec->max());
}
void Box2_EIK_SetMax(void* ptr, const Point2d& point)
{
auto rec = CastToBox2(ptr);
(*rec) = Box2(rec->min(), point.ToCGAL<EIK>());
}
double Box2_EIK_Area(void* ptr)
{
auto rec = CastToBox2(ptr);
return CGAL::to_double(rec->area());
}
CGAL::Bounded_side Box2_EIK_BoundedSide(void* ptr, const Point2d& point)
{
auto rec = CastToBox2(ptr);
auto p = point.ToCGAL<EIK>();
return rec->bounded_side(p);
}
BOOL Box2_EIK_ContainsPoint(void* ptr, const Point2d& point, BOOL inculdeBoundary)
{
auto rec = CastToBox2(ptr);
auto side = rec->bounded_side(point.ToCGAL<EIK>());
if (inculdeBoundary && side == CGAL::Bounded_side::ON_BOUNDARY)
return true;
return side == CGAL::Bounded_side::ON_BOUNDED_SIDE;
}
BOOL Box2_EIK_IsDegenerate(void* ptr)
{
auto rec = CastToBox2(ptr);
return rec->is_degenerate();
}
void Box2_EIK_Transform(void* ptr, const Point2d& translation, double rotation, double scale)
{
auto rec = CastToBox2(ptr);
Transformation2 T(CGAL::TRANSLATION, translation.ToVector<EIK>());
Transformation2 R(CGAL::ROTATION, sin(rotation), cos(rotation));
Transformation2 S(CGAL::SCALING, scale);
(*rec) = rec->transform(T * R * S);
}
void* Box2_EIK_Copy(void* ptr)
{
auto rec = CastToBox2(ptr);
auto nrec = NewBox2();
(*nrec) = *rec;
return nrec;
}
template<class K2>
static void* Convert(Box2* rec)
{
CGAL::Cartesian_converter<EIK, K2> convert;
auto min = convert(rec->min());
auto max = convert(rec->max());
return new CGAL::Iso_rectangle_2<K2>(min, max);
}
void* Box2_EIK_Convert(void* ptr, CGAL_KERNEL k)
{
auto rec = CastToBox2(ptr);
switch (k)
{
case CGAL_KERNEL::EXACT_PREDICATES_INEXACT_CONSTRUCTION:
return Convert<EIK>(rec);
case CGAL_KERNEL::EXACT_PREDICATES_EXACT_CONSTRUCTION:
return Convert<EEK>(rec);
default:
return Convert<EIK>(rec);
}
}
| 19.978723 | 93 | 0.705715 | [
"transform"
] |
3756fb83f31eac4b0e42d7ac11c3b33a503c828c | 8,684 | hxx | C++ | main/writerfilter/source/dmapper/NumberingManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/writerfilter/source/dmapper/NumberingManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/writerfilter/source/dmapper/NumberingManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef INCLUDED_NUMBERINGMANAGER_HXX
#define INCLUDED_NUMBERINGMANAGER_HXX
#include "PropertyMap.hxx"
#include <WriterFilterDllApi.hxx>
#include <dmapper/DomainMapper.hxx>
#include <resourcemodel/LoggedResources.hxx>
#include <com/sun/star/container/XIndexReplace.hpp>
namespace writerfilter {
namespace dmapper {
class DomainMapper;
class StyleSheetEntry;
/** Class representing the numbering level properties.
*/
class ListLevel : public PropertyMap
{
sal_Int32 m_nIStartAt; //LN_ISTARTAT
sal_Int32 m_nNFC; //LN_NFC
sal_Int32 m_nJC; //LN_JC
sal_Int32 m_nFLegal; //LN_FLEGAL
sal_Int32 m_nFNoRestart; //LN_FNORESTART
sal_Int32 m_nFPrev; //LN_FPREV
sal_Int32 m_nFPrevSpace; //LN_FPREVSPACE
sal_Int32 m_nFWord6; //LN_FWORD6
::rtl::OUString m_sRGBXchNums; //LN_RGBXCHNUMS
sal_Int32 m_nXChFollow; //LN_IXCHFOLLOW
::rtl::OUString m_sBulletChar;
sal_Int32 m_nTabstop;
boost::shared_ptr< StyleSheetEntry > m_pParaStyle;
public:
typedef boost::shared_ptr< ListLevel > Pointer;
ListLevel() :
m_nIStartAt(-1)
,m_nNFC(-1)
,m_nJC(-1)
,m_nFLegal(-1)
,m_nFNoRestart(-1)
,m_nFPrev(-1)
,m_nFPrevSpace(-1)
,m_nFWord6(-1)
,m_nXChFollow(-1)
,m_nTabstop( 0 )
{}
~ListLevel( ){ }
// Setters for the import
void SetValue( Id nId, sal_Int32 nValue );
void SetBulletChar( rtl::OUString sValue ) { m_sBulletChar = sValue; };
void SetParaStyle( boost::shared_ptr< StyleSheetEntry > pStyle )
{
m_pParaStyle = pStyle;
};
void AddRGBXchNums( rtl::OUString sValue ) { m_sRGBXchNums += sValue; };
// Getters
rtl::OUString GetBulletChar( ) { return m_sBulletChar; };
boost::shared_ptr< StyleSheetEntry > GetParaStyle( ) { return m_pParaStyle; };
// UNO mapping functions
// rPrefix and rSuffix are out parameters
static sal_Int16 GetParentNumbering( rtl::OUString sText, sal_Int16 nLevel,
rtl::OUString& rPrefix, rtl::OUString& rSuffix );
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >
GetProperties( );
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue>
GetCharStyleProperties( );
private:
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >
GetLevelProperties( );
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >
GetParaProperties( );
};
class AbstractListDef
{
private:
sal_Int32 m_nTPLC; //LN_TPLC
::rtl::OUString m_sRGISTD; //LN_RGISTD
sal_Int32 m_nSimpleList; //LN_FSIMPLELIST
sal_Int32 m_nRestart; //LN_FRESTARTHDN
sal_Int32 m_nUnsigned; //LN_UNSIGNED26_2
// The ID member reflects either the abstractNumId or the numId
// depending on the use of the class
sal_Int32 m_nId;
// Properties of each level. This can also reflect the overridden
// levels of a numbering.
::std::vector< ListLevel::Pointer > m_aLevels;
// Only used during the numberings import
ListLevel::Pointer m_pCurrentLevel;
// The style name linked to.
::rtl::OUString m_sNumStyleLink;
public:
typedef boost::shared_ptr< AbstractListDef > Pointer;
AbstractListDef( );
~AbstractListDef( );
// Setters using during the import
void SetId( sal_Int32 nId ) { m_nId = nId; };
void SetValue( sal_uInt32 nSprmId, sal_Int32 nValue );
void AddRGISTD( rtl::OUString sValue ) { m_sRGISTD += sValue; };
// Accessors
sal_Int32 GetId( ) const { return m_nId; };
sal_Int16 Size( ) { return sal_Int16( m_aLevels.size( ) ); };
ListLevel::Pointer GetLevel( sal_uInt16 nLvl );
void AddLevel( );
ListLevel::Pointer GetCurrentLevel( ) const { return m_pCurrentLevel; };
virtual com::sun::star::uno::Sequence<
com::sun::star::uno::Sequence<
com::sun::star::beans::PropertyValue > > GetPropertyValues( );
void SetNumStyleLink(rtl::OUString sValue) { m_sNumStyleLink = sValue; };
::rtl::OUString GetNumStyleLink() { return m_sNumStyleLink; };
};
class ListDef : public AbstractListDef
{
private:
// Pointer to the abstract numbering
AbstractListDef::Pointer m_pAbstractDef;
// Cache for the UNO numbering rules
uno::Reference< container::XIndexReplace > m_xNumRules;
public:
typedef boost::shared_ptr< ListDef > Pointer;
ListDef( );
~ListDef( );
// Accessors
void SetAbstractDefinition( AbstractListDef::Pointer pAbstract ) { m_pAbstractDef = pAbstract; };
AbstractListDef::Pointer GetAbstractDefinition( ) { return m_pAbstractDef; };
// Mapping functions
static rtl::OUString GetStyleName( sal_Int32 nId );
com::sun::star::uno::Sequence<
com::sun::star::uno::Sequence<
com::sun::star::beans::PropertyValue > > GetPropertyValues( );
void CreateNumberingRules(
DomainMapper& rDMapper,
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory> xFactory );
::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace >
GetNumberingRules( ) { return m_xNumRules; };
};
/** This class provides access to the defined numbering styles.
*/
class ListsManager :
public LoggedProperties,
public LoggedTable
{
private:
DomainMapper& m_rDMapper;
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > m_xFactory;
// The numbering entries
std::vector< AbstractListDef::Pointer > m_aAbstractLists;
std::vector< ListDef::Pointer > m_aLists;
// These members are used for import only
AbstractListDef::Pointer m_pCurrentDefinition;
bool m_bIsLFOImport;
AbstractListDef::Pointer GetAbstractList( sal_Int32 nId );
// Properties
virtual void lcl_attribute( Id nName, Value & rVal );
virtual void lcl_sprm(Sprm & sprm);
// Table
virtual void lcl_entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref);
public:
ListsManager(
DomainMapper& rDMapper,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xFactory);
virtual ~ListsManager();
typedef boost::shared_ptr< ListsManager > Pointer;
// Config methods
void SetLFOImport( bool bLFOImport ) { m_bIsLFOImport = bLFOImport; };
// Numberings accessors
AbstractListDef::Pointer GetCurrentDef( ) { return m_pCurrentDefinition; };
sal_uInt32 Size() const
{ return sal_uInt32( m_aLists.size( ) ); };
ListDef::Pointer GetList( sal_Int32 nId );
// Mapping methods
void CreateNumberingRules( );
};
} }
#endif
| 34.054902 | 109 | 0.592008 | [
"vector"
] |
375bd9fbc31cf4738e062330631cee612a68491d | 1,594 | cpp | C++ | model/GetCountriesResponse.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | model/GetCountriesResponse.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | model/GetCountriesResponse.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | /**
* TextMagic API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2
*
*
* NOTE: This class is auto generated by the swagger code generator 2.4.8.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "GetCountriesResponse.h"
namespace com {
namespace textmagic {
namespace client {
namespace model {
GetCountriesResponse::GetCountriesResponse()
{
}
GetCountriesResponse::~GetCountriesResponse()
{
}
void GetCountriesResponse::validate()
{
// TODO: implement validation
}
web::json::value GetCountriesResponse::toJson() const
{
web::json::value val = this->null<Country>::toJson();
return val;
}
void GetCountriesResponse::fromJson(web::json::value& val)
{
this->null<Country>::fromJson(val);
}
void GetCountriesResponse::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
}
void GetCountriesResponse::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
}
}
}
}
}
| 21.540541 | 123 | 0.703262 | [
"model"
] |
376104b5466de999f9235856f8884c584596ba9e | 10,082 | cpp | C++ | app/src/main/jni/native.cpp | liaxim/RemoteDisplayNDK-android | 1b41575b786644fb2449b59711c8b1a189c0bb54 | [
"Apache-2.0"
] | 2 | 2018-10-03T02:14:39.000Z | 2020-06-06T00:06:42.000Z | app/src/main/jni/native.cpp | liaxim/RemoteDisplayNDK-android | 1b41575b786644fb2449b59711c8b1a189c0bb54 | [
"Apache-2.0"
] | null | null | null | app/src/main/jni/native.cpp | liaxim/RemoteDisplayNDK-android | 1b41575b786644fb2449b59711c8b1a189c0bb54 | [
"Apache-2.0"
] | 1 | 2019-01-25T11:49:11.000Z | 2019-01-25T11:49:11.000Z | /*
* Copyright 2016 The Android Open Source Project
*
* 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 <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <GLES2/gl2.h>
#include "Cube.h"
#define LOG_TAG "NativeRenderer"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define RD_TARGET_COUNT 2
#define ANGLE_INCREMENT 0.2f
struct remote_display_target {
GLuint remoteDisplayTexture;
GLuint remoteDisplayFrameBuffer;
bool locked;
};
jobject gPresentation = NULL;
jmethodID gRemoteRenderMethod = NULL;
jmethodID gShowGlErrorMethod = NULL;
remote_display_target remoteDisplayTargets[RD_TARGET_COUNT];
int gRemoteDisplayWidth, gRemoteDisplayHeight;
int gLocalWidth, gLocalHeight;
Cube cube;
ndk_helper::Mat4 mat_model;
ndk_helper::Mat4 mat_model_view;
ndk_helper::Mat4 mat_model_view_projection;
ndk_helper::Mat4 mat_projection;
ndk_helper::Mat4 mat_view;
ndk_helper::Mat4 mat_rotation;
float angle;
static void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
LOGI("GL %s = %s\n", name, v);
}
static void checkGlError(JNIEnv *env, const char* op) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)\n", op, error);
jstring jop = env->NewStringUTF(op);
jstring source = env->NewStringUTF("Native");
if (gPresentation) {
env->CallVoidMethod(gPresentation, gShowGlErrorMethod, source, error, jop);
}
}
}
remote_display_target initRemoteDisplayTexture(JNIEnv *env, int width, int height) {
LOGI("initRemoteDisplayTexture(), %d x %d", width, height);
remote_display_target target;
target.locked = false;
glGenTextures(1, &target.remoteDisplayTexture);
glBindTexture(GL_TEXTURE_2D, target.remoteDisplayTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
glGenFramebuffers(1, &target.remoteDisplayFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, target.remoteDisplayFrameBuffer);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target.remoteDisplayTexture, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
LOGI("initRemoteDisplayTexture(), textureId: %d", target.remoteDisplayTexture);
return target;
}
void setupViewport(int width, int height) {
glViewport( 0, 0, width, height);
checkGlError("glViewport");
// Configure perspective with field of view
float ratio = (float) width / height;
float fov = 30.0f;
float near = 1.0f;
float far = 100.0f;
float top = (float) tanf(fov * M_PI / 360.0f) * near;
float bottom = -top;
float left = ratio * bottom;
float right = ratio * top;
mat_projection = ndk_helper::Mat4::Perspective(left, right, bottom, top, near, far);
glFrontFace( GL_CCW );
glCullFace(GL_FRONT);
glEnable(GL_CULL_FACE);
}
void renderLocalFrame(JNIEnv *env, bool colorChange) {
glClearColor( 0.5f, 0.5f, 0.5f, 1.f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
mat_view = ndk_helper::Mat4::LookAt(
ndk_helper::Vec3(0.0f, 0.0f, -10.0f),
ndk_helper::Vec3(0.0f, 0.0f, 0.0f),
ndk_helper::Vec3(0.0f, 1.0f, 0.0f)
);
mat_model = ndk_helper::Mat4::Identity();
mat_model = mat_model + ndk_helper::Mat4::Translation(0.0f, -0.5f, -1.5f);
mat_rotation = ndk_helper::Mat4::Rotation(2 * angle, 0.f, 1.f, 1.f);
mat_model *= mat_rotation;
mat_model_view = mat_view * mat_model;
mat_model_view_projection = mat_projection * mat_model_view;
cube.Render(mat_model_view_projection.Ptr(), colorChange);
angle += ANGLE_INCREMENT;
}
void renderRemoteDisplayFrame(JNIEnv *env, remote_display_target target) {
glViewport( 0, 0, gRemoteDisplayWidth, gRemoteDisplayHeight);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return;
glBindFramebuffer(GL_FRAMEBUFFER, target.remoteDisplayFrameBuffer);
setupViewport(gRemoteDisplayWidth, gRemoteDisplayHeight);
renderLocalFrame(env, false);
glBindFramebuffer(GL_FRAMEBUFFER,0);
}
void notifyRemoteDisplayRenderThread(JNIEnv *env, remote_display_target target) {
env->CallVoidMethod(gPresentation, gRemoteRenderMethod, target.remoteDisplayTexture);
}
extern "C" {
JNIEXPORT void JNICALL Java_com_example_castremotedisplay_ndk_local_NativeRenderer_init
(JNIEnv * env, jclass type, jint width, jint height);
JNIEXPORT void JNICALL Java_com_example_castremotedisplay_ndk_local_NativeRenderer_renderFrame
(JNIEnv * env, jclass type);
JNIEXPORT void JNICALL Java_com_example_castremotedisplay_ndk_local_NativeRenderer_castSessionStarted
(JNIEnv *env, jclass type, jobject presentation, jint width, jint height);
JNIEXPORT void JNICALL Java_com_example_castremotedisplay_ndk_local_NativeRenderer_castSessionEnded
(JNIEnv *env, jclass type, jobject presentation);
JNIEXPORT void JNICALL Java_com_example_castremotedisplay_ndk_local_NativeRenderer_notifyRemoteFrameDone
(JNIEnv *env, jclass type, jint textureId);
};
JNIEXPORT void JNICALL
Java_com_example_castremotedisplay_ndk_local_NativeRenderer_init(JNIEnv *env, jclass type,
jint width, jint height) {
LOGI("Initialize native renderer");
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
printGLString("Extensions", GL_EXTENSIONS);
// Initialize Cube Renderer ie. load Shaders
cube.Init();
// Initialize GL state.
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
// Set anti-aliasing
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gLocalWidth = width;
gLocalHeight = height;
}
JNIEXPORT void JNICALL
Java_com_example_castremotedisplay_ndk_local_NativeRenderer_renderFrame(JNIEnv *env, jclass type) {
if(!remoteDisplayTargets[0].remoteDisplayTexture && gPresentation) {
for(int i = 0; i < RD_TARGET_COUNT; i++) {
remoteDisplayTargets[i] =
initRemoteDisplayTexture(env, gRemoteDisplayWidth, gRemoteDisplayHeight);
}
};
// Render local frame (ie. displayed on the device)
setupViewport(gLocalWidth, gLocalHeight);
renderLocalFrame(env, true);
if(remoteDisplayTargets[0].remoteDisplayTexture && gRemoteRenderMethod) {
remote_display_target target;
for(int i = 0; i < RD_TARGET_COUNT; i++) {
if (!remoteDisplayTargets[i].locked) {
target = remoteDisplayTargets[i];
}
}
if(target.remoteDisplayTexture) {
target.locked = true;
// Render remote frame (ie. to be displayed on the TV)
renderRemoteDisplayFrame(env, target);
notifyRemoteDisplayRenderThread(env, target);
} else {
LOGE("No free texture...");
}
}
}
JNIEXPORT void JNICALL
Java_com_example_castremotedisplay_ndk_local_NativeRenderer_castSessionStarted(
JNIEnv *env, jclass type, jobject presentation, jint width, jint height) {
LOGI("Got notified that Cast session started. Init.");
gRemoteDisplayWidth = width;
gRemoteDisplayHeight = height;
// Acquire refs to Java methods
gPresentation = env->NewGlobalRef(presentation);
jclass cls = env->GetObjectClass(presentation);
gRemoteRenderMethod = env->GetMethodID(cls, "renderFrameToTexture", "(I)V");
gShowGlErrorMethod = env->GetMethodID(cls,
"onGlError", "(Ljava/lang/String;ILjava/lang/String;)V");
}
JNIEXPORT void JNICALL
Java_com_example_castremotedisplay_ndk_local_NativeRenderer_castSessionEnded(JNIEnv *env,
jclass type,
jobject presentation) {
LOGI("Got notified that Cast session ended");
env->DeleteGlobalRef(gPresentation);
gPresentation = NULL;
gRemoteRenderMethod = NULL;
for(int i = 0; i < RD_TARGET_COUNT; i++) {
glDeleteFramebuffers(1, &remoteDisplayTargets[i].remoteDisplayFrameBuffer);
remoteDisplayTargets[i].remoteDisplayFrameBuffer = 0;
glDeleteTextures(1, &remoteDisplayTargets[i].remoteDisplayTexture);
remoteDisplayTargets[i].remoteDisplayTexture = 0;
}
}
JNIEXPORT void JNICALL
Java_com_example_castremotedisplay_ndk_local_NativeRenderer_notifyRemoteFrameDone(JNIEnv *env,
jclass type,
jint textureId) {
// Unlock target as RD thread has finished rendering to remote surface
for(int i = 0; i < RD_TARGET_COUNT; i++) {
if (!remoteDisplayTargets[i].remoteDisplayTexture == textureId) {
remoteDisplayTargets[i].locked = false;
}
}
}
| 34.765517 | 104 | 0.693513 | [
"render"
] |
37638475c5cee58876d3002e2e422d41b24630a5 | 23,287 | cpp | C++ | src/libSBML/src/sbml/packages/distrib/sbml/Uncertainty.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 5 | 2015-04-16T14:27:38.000Z | 2021-11-30T14:54:39.000Z | src/libSBML/src/sbml/packages/distrib/sbml/Uncertainty.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 8 | 2017-05-30T16:58:39.000Z | 2022-02-22T16:51:34.000Z | src/libSBML/src/sbml/packages/distrib/sbml/Uncertainty.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 7 | 2016-05-29T08:12:59.000Z | 2019-05-02T13:39:25.000Z | /**
* @file Uncertainty.cpp
* @brief Implementation of the Uncertainty class.
* @author SBMLTeam
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2020 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. University of Heidelberg, Heidelberg, Germany
* 3. University College London, London, UK
*
* Copyright (C) 2019 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2013-2018 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation. A copy of the license agreement is provided in the
* file named "LICENSE.txt" included with this software distribution and also
* available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*/
#include <sbml/packages/distrib/sbml/Uncertainty.h>
#include <sbml/packages/distrib/sbml/ListOfUncertainties.h>
#include <sbml/packages/distrib/validator/DistribSBMLError.h>
#include <sbml/util/ElementFilter.h>
using namespace std;
LIBSBML_CPP_NAMESPACE_BEGIN
#ifdef __cplusplus
/*
* Creates a new Uncertainty using the given SBML Level, Version and
* “distrib” package version.
*/
Uncertainty::Uncertainty(unsigned int level,
unsigned int version,
unsigned int pkgVersion)
: DistribBase(level, version, pkgVersion)
, mUncertParameters (level, version, pkgVersion)
{
setSBMLNamespacesAndOwn(new DistribPkgNamespaces(level, version,
pkgVersion));
connectToChild();
}
/*
* Creates a new Uncertainty using the given DistribPkgNamespaces object.
*/
Uncertainty::Uncertainty(DistribPkgNamespaces *distribns)
: DistribBase(distribns)
, mUncertParameters (distribns)
{
setElementNamespace(distribns->getURI());
connectToChild();
loadPlugins(distribns);
}
/*
* Copy constructor for Uncertainty.
*/
Uncertainty::Uncertainty(const Uncertainty& orig)
: DistribBase( orig )
, mUncertParameters ( orig.mUncertParameters )
{
connectToChild();
}
/*
* Assignment operator for Uncertainty.
*/
Uncertainty&
Uncertainty::operator=(const Uncertainty& rhs)
{
if (&rhs != this)
{
DistribBase::operator=(rhs);
mUncertParameters = rhs.mUncertParameters;
connectToChild();
}
return *this;
}
/*
* Creates and returns a deep copy of this Uncertainty object.
*/
Uncertainty*
Uncertainty::clone() const
{
return new Uncertainty(*this);
}
/*
* Destructor for Uncertainty.
*/
Uncertainty::~Uncertainty()
{
}
/*
* Returns the ListOfUncertParameters from this Uncertainty.
*/
const ListOfUncertParameters*
Uncertainty::getListOfUncertParameters() const
{
return &mUncertParameters;
}
/*
* Returns the ListOfUncertParameters from this Uncertainty.
*/
ListOfUncertParameters*
Uncertainty::getListOfUncertParameters()
{
return &mUncertParameters;
}
/*
* Get an UncertParameter from the Uncertainty.
*/
UncertParameter*
Uncertainty::getUncertParameter(unsigned int n)
{
return mUncertParameters.get(n);
}
/*
* Get an UncertParameter from the Uncertainty.
*/
const UncertParameter*
Uncertainty::getUncertParameter(unsigned int n) const
{
return mUncertParameters.get(n);
}
/*
* Get an UncertParameter from the Uncertainty based on the element to which it
* refers.
*/
const UncertParameter*
Uncertainty::getUncertParameterByVar(const std::string& sid) const
{
return mUncertParameters.getByVar(sid);
}
const UncertParameter*
Uncertainty::getUncertParameterByType(UncertType_t utype) const
{
return mUncertParameters.getByType(utype);
}
/*
* Get an UncertParameter from the Uncertainty based on the element to which it
* refers.
*/
UncertParameter*
Uncertainty::getUncertParameterByVar(const std::string& sid)
{
return mUncertParameters.getByVar(sid);
}
UncertParameter*
Uncertainty::getUncertParameterByType(UncertType_t utype)
{
return mUncertParameters.getByType(utype);
}
/*
* Adds a copy of the given UncertParameter to this Uncertainty.
*/
int
Uncertainty::addUncertParameter(const UncertParameter* up)
{
if (up == NULL)
{
return LIBSBML_OPERATION_FAILED;
}
else if (up->hasRequiredAttributes() == false)
{
return LIBSBML_INVALID_OBJECT;
}
else if (getLevel() != up->getLevel())
{
return LIBSBML_LEVEL_MISMATCH;
}
else if (getVersion() != up->getVersion())
{
return LIBSBML_VERSION_MISMATCH;
}
else if (matchesRequiredSBMLNamespacesForAddition(static_cast<const
SBase*>(up)) == false)
{
return LIBSBML_NAMESPACES_MISMATCH;
}
else
{
return mUncertParameters.append(up);
}
}
/*
* Adds a copy of the given UncertParameter to this Uncertainty.
*/
int
Uncertainty::addUncertSpan(const UncertSpan* up)
{
if (up == NULL)
{
return LIBSBML_OPERATION_FAILED;
}
else if (up->hasRequiredAttributes() == false)
{
return LIBSBML_INVALID_OBJECT;
}
else if (getLevel() != up->getLevel())
{
return LIBSBML_LEVEL_MISMATCH;
}
else if (getVersion() != up->getVersion())
{
return LIBSBML_VERSION_MISMATCH;
}
else if (matchesRequiredSBMLNamespacesForAddition(static_cast<const
SBase*>(up)) == false)
{
return LIBSBML_NAMESPACES_MISMATCH;
}
else
{
return mUncertParameters.append((UncertParameter*)(up));
}
}
/*
* Get the number of UncertParameter objects in this Uncertainty.
*/
unsigned int
Uncertainty::getNumUncertParameters() const
{
return mUncertParameters.size();
}
UncertParameter*
Uncertainty::createUncertParameter()
{
UncertParameter* up = NULL;
try
{
DISTRIB_CREATE_NS(distribns, getSBMLNamespaces());
up = new UncertParameter(distribns);
delete distribns;
}
catch (...)
{
}
if (up != NULL) mUncertParameters.appendAndOwn(up);
return up;
}
UncertSpan*
Uncertainty::createUncertSpan()
{
UncertSpan* up = NULL;
try
{
DISTRIB_CREATE_NS(distribns, getSBMLNamespaces());
up = new UncertSpan(distribns);
delete distribns;
}
catch (...)
{
}
if (up != NULL) mUncertParameters.appendAndOwn((UncertParameter*)(up));
return up;
}
/*
* Removes the nth UncertParameter from this Uncertainty and returns a pointer
* to it.
*/
UncertParameter*
Uncertainty::removeUncertParameter(unsigned int n)
{
return mUncertParameters.remove(n);
}
/*
* Returns the XML element name of this Uncertainty object.
*/
const std::string&
Uncertainty::getElementName() const
{
static const string name = "uncertainty";
return name;
}
/*
* Returns the libSBML type code for this Uncertainty object.
*/
int
Uncertainty::getTypeCode() const
{
return SBML_DISTRIB_UNCERTAINTY;
}
/*
* Predicate returning @c true if all the required attributes for this
* Uncertainty object have been set.
*/
bool
Uncertainty::hasRequiredAttributes() const
{
bool allPresent = DistribBase::hasRequiredAttributes();
return allPresent;
}
/*
* Predicate returning @c true if all the required elements for this
* Uncertainty object have been set.
*/
bool
Uncertainty::hasRequiredElements() const
{
bool allPresent = DistribBase::hasRequiredElements();
return allPresent;
}
/** @cond doxygenLibsbmlInternal */
/*
* Write any contained elements
*/
void
Uncertainty::writeElements(XMLOutputStream& stream) const
{
DistribBase::writeElements(stream);
for (unsigned int i = 0; i < getNumUncertParameters(); i++)
{
getUncertParameter(i)->write(stream);
}
SBase::writeExtensionElements(stream);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Accepts the given SBMLVisitor
*/
bool
Uncertainty::accept(SBMLVisitor& v) const
{
v.visit(*this);
mUncertParameters.accept(v);
v.leave(*this);
return true;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the parent SBMLDocument
*/
void
Uncertainty::setSBMLDocument(SBMLDocument* d)
{
DistribBase::setSBMLDocument(d);
mUncertParameters.setSBMLDocument(d);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Connects to child elements
*/
void
Uncertainty::connectToChild()
{
DistribBase::connectToChild();
mUncertParameters.connectToParent(this);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Enables/disables the given package with this element
*/
void
Uncertainty::enablePackageInternal(const std::string& pkgURI,
const std::string& pkgPrefix,
bool flag)
{
DistribBase::enablePackageInternal(pkgURI, pkgPrefix, flag);
mUncertParameters.enablePackageInternal(pkgURI, pkgPrefix, flag);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Updates the namespaces when setLevelVersion is used
*/
void
Uncertainty::updateSBMLNamespace(const std::string& package,
unsigned int level,
unsigned int version)
{
DistribBase::updateSBMLNamespace(package, level, version);
mUncertParameters.updateSBMLNamespace(package, level, version);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Gets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::getAttribute(const std::string& attributeName, bool& value) const
{
int return_value = DistribBase::getAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Gets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::getAttribute(const std::string& attributeName, int& value) const
{
int return_value = DistribBase::getAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Gets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::getAttribute(const std::string& attributeName,
double& value) const
{
int return_value = DistribBase::getAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Gets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::getAttribute(const std::string& attributeName,
unsigned int& value) const
{
int return_value = DistribBase::getAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Gets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::getAttribute(const std::string& attributeName,
std::string& value) const
{
int return_value = DistribBase::getAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Predicate returning @c true if this Uncertainty's attribute "attributeName"
* is set.
*/
bool
Uncertainty::isSetAttribute(const std::string& attributeName) const
{
bool value = DistribBase::isSetAttribute(attributeName);
return value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::setAttribute(const std::string& attributeName, bool value)
{
int return_value = DistribBase::setAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::setAttribute(const std::string& attributeName, int value)
{
int return_value = DistribBase::setAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::setAttribute(const std::string& attributeName, double value)
{
int return_value = DistribBase::setAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::setAttribute(const std::string& attributeName,
unsigned int value)
{
int return_value = DistribBase::setAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::setAttribute(const std::string& attributeName,
const std::string& value)
{
int return_value = DistribBase::setAttribute(attributeName, value);
return return_value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Unsets the value of the "attributeName" attribute of this Uncertainty.
*/
int
Uncertainty::unsetAttribute(const std::string& attributeName)
{
int value = DistribBase::unsetAttribute(attributeName);
return value;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Creates and returns an new "elementName" object in this Uncertainty.
*/
SBase*
Uncertainty::createChildObject(const std::string& elementName)
{
DistribBase* obj = NULL;
if (elementName == "uncertParameter")
{
return createUncertParameter();
}
return obj;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Adds a new "elementName" object to this Uncertainty.
*/
int
Uncertainty::addChildObject(const std::string& elementName,
const SBase* element)
{
if (elementName == "uncertParameter" && element->getTypeCode() ==
SBML_DISTRIB_UNCERTPARAMETER)
{
return addUncertParameter((const UncertParameter*)(element));
}
return LIBSBML_OPERATION_FAILED;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Removes and returns the new "elementName" object with the given id in this
* Uncertainty.
*/
SBase*
Uncertainty::removeChildObject(const std::string& elementName,
const std::string& id)
{
if (elementName == "uncertParameter")
{
for (unsigned int i = 0; i < getNumUncertParameters(); i++)
{
if (getUncertParameter(i)->getId() == id)
{
return removeUncertParameter(i);
}
}
}
return NULL;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Returns the number of "elementName" in this Uncertainty.
*/
unsigned int
Uncertainty::getNumObjects(const std::string& elementName)
{
unsigned int n = 0;
if (elementName == "uncertParameter")
{
return getNumUncertParameters();
}
return n;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Returns the nth object of "objectName" in this Uncertainty.
*/
SBase*
Uncertainty::getObject(const std::string& elementName, unsigned int index)
{
SBase* obj = NULL;
if (elementName == "uncertParameter")
{
return getUncertParameter(index);
}
return obj;
}
/** @endcond */
/*
* Returns the first child element that has the given @p id in the model-wide
* SId namespace, or @c NULL if no such object is found.
*/
SBase*
Uncertainty::getElementBySId(const std::string& id)
{
if (id.empty())
{
return NULL;
}
SBase* obj = NULL;
obj = mUncertParameters.getElementBySId(id);
if (obj != NULL)
{
return obj;
}
return obj;
}
/*
* Returns the first child element that has the given @p metaid, or @c NULL if
* no such object is found.
*/
SBase*
Uncertainty::getElementByMetaId(const std::string& metaid)
{
if (metaid.empty())
{
return NULL;
}
SBase* obj = NULL;
if (mUncertParameters.getMetaId() == metaid)
{
return &mUncertParameters;
}
obj = mUncertParameters.getElementByMetaId(metaid);
if (obj != NULL)
{
return obj;
}
return obj;
}
/*
* Returns a List of all child SBase objects, including those nested to an
* arbitrary depth.
*/
List*
Uncertainty::getAllElements(ElementFilter* filter)
{
List* ret = new List();
List* sublist = NULL;
ADD_FILTERED_LIST(ret, sublist, mUncertParameters, filter);
ADD_FILTERED_FROM_PLUGIN(ret, sublist, filter);
return ret;
}
/** @cond doxygenLibsbmlInternal */
/*
* Creates a new object from the next XMLToken on the XMLInputStream
*/
SBase*
Uncertainty::createObject(XMLInputStream& stream)
{
SBase* obj = DistribBase::createObject(stream);
const std::string& name = stream.peek().getName();
if (name == "uncertParameter")
{
obj = mUncertParameters.createObject(stream);
}
else if (name == "uncertSpan")
{
obj = mUncertParameters.createObject(stream);
}
connectToChild();
return obj;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Adds the expected attributes for this element
*/
void
Uncertainty::addExpectedAttributes(ExpectedAttributes& attributes)
{
DistribBase::addExpectedAttributes(attributes);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Reads the expected attributes into the member data variables
*/
void
Uncertainty::readAttributes(const XMLAttributes& attributes,
const ExpectedAttributes& expectedAttributes)
{
unsigned int level = getLevel();
unsigned int version = getVersion();
unsigned int pkgVersion = getPackageVersion();
unsigned int numErrs;
bool assigned = false;
SBMLErrorLog* log = getErrorLog();
if (log && getParentSBMLObject() &&
static_cast<ListOfUncertainties*>(getParentSBMLObject())->size() < 2)
{
numErrs = log->getNumErrors();
for (int n = numErrs-1; n >= 0; n--)
{
if (log->getError(n)->getErrorId() == UnknownPackageAttribute)
{
const std::string details = log->getError(n)->getMessage();
log->remove(UnknownPackageAttribute);
log->logPackageError("distrib", DistribUnknown, pkgVersion, level,
version, details, getLine(), getColumn());
}
else if (log->getError(n)->getErrorId() == UnknownCoreAttribute)
{
const std::string details = log->getError(n)->getMessage();
log->remove(UnknownCoreAttribute);
log->logPackageError("distrib",
DistribSBaseLOUncertaintiesAllowedCoreAttributes, pkgVersion, level,
version, details, getLine(), getColumn());
}
}
}
DistribBase::readAttributes(attributes, expectedAttributes);
if (log)
{
numErrs = log->getNumErrors();
for (int n = numErrs-1; n >= 0; n--)
{
if (log->getError(n)->getErrorId() == UnknownPackageAttribute)
{
const std::string details = log->getError(n)->getMessage();
log->remove(UnknownPackageAttribute);
log->logPackageError("distrib", DistribUnknown, pkgVersion, level,
version, details, getLine(), getColumn());
}
else if (log->getError(n)->getErrorId() == UnknownCoreAttribute)
{
const std::string details = log->getError(n)->getMessage();
log->remove(UnknownCoreAttribute);
log->logPackageError("distrib",
DistribUncertaintyAllowedCoreAttributes, pkgVersion, level, version,
details, getLine(), getColumn());
}
}
}
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Writes the attributes to the stream
*/
void
Uncertainty::writeAttributes(XMLOutputStream& stream) const
{
DistribBase::writeAttributes(stream);
SBase::writeExtensionAttributes(stream);
}
/** @endcond */
#endif /* __cplusplus */
/*
* Creates a new Uncertainty_t using the given SBML Level, Version and
* “distrib” package version.
*/
LIBSBML_EXTERN
Uncertainty_t *
Uncertainty_create(unsigned int level,
unsigned int version,
unsigned int pkgVersion)
{
return new Uncertainty(level, version, pkgVersion);
}
/*
* Creates and returns a deep copy of this Uncertainty_t object.
*/
LIBSBML_EXTERN
Uncertainty_t*
Uncertainty_clone(const Uncertainty_t* u)
{
if (u != NULL)
{
return static_cast<Uncertainty_t*>(u->clone());
}
else
{
return NULL;
}
}
/*
* Frees this Uncertainty_t object.
*/
LIBSBML_EXTERN
void
Uncertainty_free(Uncertainty_t* u)
{
if (u != NULL)
{
delete u;
}
}
/*
* Returns a ListOf_t * containing UncertParameter_t objects from this
* Uncertainty_t.
*/
LIBSBML_EXTERN
ListOf_t*
Uncertainty_getListOfUncertParameters(Uncertainty_t* u)
{
return (u != NULL) ? u->getListOfUncertParameters() : NULL;
}
/*
* Get an UncertParameter_t from the Uncertainty_t.
*/
LIBSBML_EXTERN
UncertParameter_t*
Uncertainty_getUncertParameter(Uncertainty_t* u, unsigned int n)
{
return (u != NULL) ? u->getUncertParameter(n) : NULL;
}
/*
* Get an UncertParameter_t from the Uncertainty_t based on the element to
* which it refers.
*/
LIBSBML_EXTERN
UncertParameter_t*
Uncertainty_getUncertParameterByVar(Uncertainty_t* u, const char *sid)
{
return (u != NULL && sid != NULL) ? u->getUncertParameterByVar(sid) : NULL;
}
/*
* Adds a copy of the given UncertParameter_t to this Uncertainty_t.
*/
LIBSBML_EXTERN
int
Uncertainty_addUncertParameter(Uncertainty_t* u, const UncertParameter_t* up)
{
return (u != NULL) ? u->addUncertParameter(up) : LIBSBML_INVALID_OBJECT;
}
/*
* Get the number of UncertParameter_t objects in this Uncertainty_t.
*/
LIBSBML_EXTERN
unsigned int
Uncertainty_getNumUncertParameters(Uncertainty_t* u)
{
return (u != NULL) ? u->getNumUncertParameters() : SBML_INT_MAX;
}
/*
* Removes the nth UncertParameter_t from this Uncertainty_t and returns a
* pointer to it.
*/
LIBSBML_EXTERN
UncertParameter_t*
Uncertainty_removeUncertParameter(Uncertainty_t* u, unsigned int n)
{
return (u != NULL) ? u->removeUncertParameter(n) : NULL;
}
/*
* Predicate returning @c 1 (true) if all the required attributes for this
* Uncertainty_t object have been set.
*/
LIBSBML_EXTERN
int
Uncertainty_hasRequiredAttributes(const Uncertainty_t * u)
{
return (u != NULL) ? static_cast<int>(u->hasRequiredAttributes()) : 0;
}
/*
* Predicate returning @c 1 (true) if all the required elements for this
* Uncertainty_t object have been set.
*/
LIBSBML_EXTERN
int
Uncertainty_hasRequiredElements(const Uncertainty_t * u)
{
return (u != NULL) ? static_cast<int>(u->hasRequiredElements()) : 0;
}
LIBSBML_CPP_NAMESPACE_END
| 19.634907 | 79 | 0.692232 | [
"object",
"model"
] |
37641be3e3e7a36a86b892508905fd7232873378 | 1,451 | cpp | C++ | metro/src/regression/LogUnnormalisedPosterior.cpp | gavinband/qctool | 8d8adb45151c91f953fe4a9af00498073b1132ba | [
"BSL-1.0"
] | 3 | 2021-04-21T05:42:24.000Z | 2022-01-26T14:59:43.000Z | metro/src/regression/LogUnnormalisedPosterior.cpp | gavinband/qctool | 8d8adb45151c91f953fe4a9af00498073b1132ba | [
"BSL-1.0"
] | 2 | 2020-04-09T16:11:04.000Z | 2020-11-10T11:18:56.000Z | metro/src/regression/LogUnnormalisedPosterior.cpp | gavinband/qctool | 8d8adb45151c91f953fe4a9af00498073b1132ba | [
"BSL-1.0"
] | null | null | null |
// Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <string>
#include "metro/regression/LogLikelihood.hpp"
#include "metro/SmoothFunction.hpp"
#include "metro/regression/LogUnnormalisedPosterior.hpp"
namespace metro {
namespace regression {
LogUnnormalisedPosterior::LogUnnormalisedPosterior( LogLikelihood& loglikelihood, SmoothFunction& posterior ):
m_ll( loglikelihood ),
m_prior( posterior )
{}
LogLikelihood const& LogUnnormalisedPosterior::ll() const {
return m_ll ;
}
SmoothFunction const& LogUnnormalisedPosterior::prior() const {
return m_prior ;
}
std::string LogUnnormalisedPosterior::get_summary() const {
std::string result = "LogUnnormalisedPosterior:\n" ;
result +=
" loglikelihood: " + m_ll.get_summary()
+ "\n prior: " + m_prior.get_summary()
+ "\n" ;
return result ;
}
void LogUnnormalisedPosterior::evaluate_at(
LogUnnormalisedPosterior::Vector const& parameters,
int const numberOfDerivatives
) {
m_parameters = parameters ;
evaluate( numberOfDerivatives ) ;
}
void LogUnnormalisedPosterior::evaluate(
int const numberOfDerivatives
) {
m_ll.evaluate_at( m_parameters, numberOfDerivatives ) ;
m_prior.evaluate_at( m_parameters, numberOfDerivatives ) ;
}
}
}
| 27.377358 | 112 | 0.716058 | [
"vector"
] |
376625181a4c1a9510ac4330a93729a5921cdd19 | 2,594 | hpp | C++ | source/dynarithmic/twain/options/imageinformation_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | source/dynarithmic/twain/options/imageinformation_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | source/dynarithmic/twain/options/imageinformation_options.hpp | dynarithmic/twainsave-opensource | 9aa0d43572ffd68ba28311e237c33f1ec4557534 | [
"Apache-2.0"
] | null | null | null | /*
This file is part of the Dynarithmic TWAIN Library (DTWAIN).
Copyright (c) 2002-2020 Dynarithmic Software.
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.
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
DYNARITHMIC SOFTWARE. DYNARITHMIC SOFTWARE DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS.
*/
#ifndef DTWAIN_IMAGEINFORMATION_OPTIONS_HPP
#define DTWAIN_IMAGEINFORMATION_OPTIONS_HPP
#include <string>
#include <vector>
#include <array>
#include <dynarithmic/twain/twain_values.hpp>
namespace dynarithmic
{
namespace twain
{
class imageinformation_options
{
friend class options_base;
std::string m_sAuthor;
std::string m_sCaption;
bool m_bExtImageInfo;
public:
imageinformation_options() : m_bExtImageInfo(false) {}
imageinformation_options& set_author(const std::string& s)
{ m_sAuthor = s; return *this; }
imageinformation_options& set_caption(const std::string& s)
{ m_sCaption = s; return *this; }
imageinformation_options& set_extimageinfo(bool bSet)
{ m_bExtImageInfo = bSet; return *this; }
std::string get_author() const
{ return m_sAuthor; }
std::string get_caption() const
{ return m_sCaption; }
bool get_extimageinfo() const
{ return m_bExtImageInfo;}
static const std::array<uint16_t, 5>& get_affected_caps()
{
static std::array<uint16_t, 5> affected_caps = { CAP_AUTHOR,
CAP_CAPTION,
CAP_TIMEDATE,
ICAP_EXTIMAGEINFO,
ICAP_SUPPORTEDEXTIMAGEINFO};
return affected_caps;
}
};
}
}
#endif
| 34.131579 | 96 | 0.586739 | [
"vector"
] |
377e5b83b9125473007583fa5db95627d67abe12 | 19,464 | cc | C++ | third_party/perfetto/src/ftrace_reader/cpu_reader.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/perfetto/src/ftrace_reader/cpu_reader.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/perfetto/src/ftrace_reader/cpu_reader.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ftrace_reader/cpu_reader.h"
#include <signal.h>
#include <dirent.h>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/metatrace.h"
#include "perfetto/base/utils.h"
#include "src/ftrace_reader/proto_translation_table.h"
#include "perfetto/trace/ftrace/ftrace_event.pbzero.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
namespace perfetto {
namespace {
bool ReadIntoString(const uint8_t* start,
const uint8_t* end,
uint32_t field_id,
protozero::Message* out) {
for (const uint8_t* c = start; c < end; c++) {
if (*c != '\0')
continue;
out->AppendBytes(field_id, reinterpret_cast<const char*>(start),
static_cast<uintptr_t>(c - start));
return true;
}
return false;
}
bool ReadDataLoc(const uint8_t* start,
const uint8_t* field_start,
const uint8_t* end,
const Field& field,
protozero::Message* message) {
PERFETTO_DCHECK(field.ftrace_size == 4);
// See
// https://github.com/torvalds/linux/blob/master/include/trace/trace_events.h
uint32_t data = 0;
const uint8_t* ptr = field_start;
if (!CpuReader::ReadAndAdvance(&ptr, end, &data)) {
PERFETTO_DCHECK(false);
return false;
}
const uint16_t offset = data & 0xffff;
const uint16_t len = (data >> 16) & 0xffff;
const uint8_t* const string_start = start + offset;
const uint8_t* const string_end = string_start + len;
if (string_start <= start || string_end > end) {
PERFETTO_DCHECK(false);
return false;
}
ReadIntoString(string_start, string_end, field.proto_field_id, message);
return true;
}
using BundleHandle =
protozero::MessageHandle<protos::pbzero::FtraceEventBundle>;
const std::vector<bool> BuildEnabledVector(const ProtoTranslationTable& table,
const std::set<std::string>& names) {
std::vector<bool> enabled(table.largest_id() + 1);
for (const std::string& name : names) {
const Event* event = table.GetEventByName(name);
if (!event)
continue;
enabled[event->ftrace_event_id] = true;
}
return enabled;
}
void SetBlocking(int fd, bool is_blocking) {
int flags = fcntl(fd, F_GETFL, 0);
flags = (is_blocking) ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
PERFETTO_CHECK(fcntl(fd, F_SETFL, flags) == 0);
}
// For further documentation of these constants see the kernel source:
// linux/include/linux/ring_buffer.h
// Some information about the values of these constants are exposed to user
// space at: /sys/kernel/debug/tracing/events/header_event
constexpr uint32_t kTypeDataTypeLengthMax = 28;
constexpr uint32_t kTypePadding = 29;
constexpr uint32_t kTypeTimeExtend = 30;
constexpr uint32_t kTypeTimeStamp = 31;
struct PageHeader {
uint64_t timestamp;
uint64_t size;
uint64_t overwrite;
};
struct EventHeader {
uint32_t type_or_length : 5;
uint32_t time_delta : 27;
};
struct TimeStamp {
uint64_t tv_nsec;
uint64_t tv_sec;
};
} // namespace
EventFilter::EventFilter(const ProtoTranslationTable& table,
std::set<std::string> names)
: enabled_ids_(BuildEnabledVector(table, names)),
enabled_names_(std::move(names)) {}
EventFilter::~EventFilter() = default;
CpuReader::CpuReader(const ProtoTranslationTable* table,
size_t cpu,
base::ScopedFile fd,
std::function<void()> on_data_available)
: table_(table), cpu_(cpu), trace_fd_(std::move(fd)) {
int pipe_fds[2];
PERFETTO_CHECK(pipe(&pipe_fds[0]) == 0);
staging_read_fd_.reset(pipe_fds[0]);
staging_write_fd_.reset(pipe_fds[1]);
// Make reads from the raw pipe blocking so that splice() can sleep.
PERFETTO_CHECK(trace_fd_);
SetBlocking(*trace_fd_, true);
// Reads from the staging pipe are always non-blocking.
SetBlocking(*staging_read_fd_, false);
// Note: O_NONBLOCK seems to be ignored by splice() on the target pipe. The
// blocking vs non-blocking behavior is controlled solely by the
// SPLICE_F_NONBLOCK flag passed to splice().
SetBlocking(*staging_write_fd_, false);
// We need a non-default SIGPIPE handler to make it so that the blocking
// splice() is woken up when the ~CpuReader() dtor destroys the pipes.
// Just masking out the signal would cause an implicit syscall restart and
// hence make the join() in the dtor unreliable.
struct sigaction current_act = {};
PERFETTO_CHECK(sigaction(SIGPIPE, nullptr, ¤t_act) == 0);
#pragma GCC diagnostic push
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wdisabled-macro-expansion"
#endif
if (current_act.sa_handler == SIG_DFL || current_act.sa_handler == SIG_IGN) {
struct sigaction act = {};
act.sa_sigaction = [](int, siginfo_t*, void*) {};
PERFETTO_CHECK(sigaction(SIGPIPE, &act, nullptr) == 0);
}
#pragma GCC diagnostic pop
worker_thread_ =
std::thread(std::bind(&RunWorkerThread, cpu_, *trace_fd_,
*staging_write_fd_, on_data_available, &exiting_));
}
CpuReader::~CpuReader() {
// The kernel's splice implementation for the trace pipe doesn't generate a
// SIGPIPE if the output pipe is closed (b/73807072). Instead, the call to
// close() on the pipe hangs forever. To work around this, we first close the
// trace fd (which prevents another splice from starting), raise SIGPIPE and
// wait for the worker to exit (i.e., to guarantee no splice is in progress)
// and only then close the staging pipe.
exiting_ = true;
trace_fd_.reset();
pthread_kill(worker_thread_.native_handle(), SIGPIPE);
worker_thread_.join();
}
// static
void CpuReader::RunWorkerThread(size_t cpu,
int trace_fd,
int staging_write_fd,
const std::function<void()>& on_data_available,
std::atomic<bool>* exiting) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
// This thread is responsible for moving data from the trace pipe into the
// staging pipe at least one page at a time. This is done using the splice(2)
// system call, which unlike poll/select makes it possible to block until at
// least a full page of data is ready to be read. The downside is that as the
// call is blocking we need a dedicated thread for each trace pipe (i.e.,
// CPU).
char thread_name[16];
snprintf(thread_name, sizeof(thread_name), "traced_probes%zu", cpu);
pthread_setname_np(pthread_self(), thread_name);
while (true) {
// First do a blocking splice which sleeps until there is at least one
// page of data available and enough space to write it into the staging
// pipe.
ssize_t splice_res;
{
PERFETTO_METATRACE("name", "splice_blocking", "pid", cpu);
splice_res = splice(trace_fd, nullptr, staging_write_fd, nullptr,
base::kPageSize, SPLICE_F_MOVE);
}
if (splice_res < 0) {
// The kernel ftrace code has its own splice() implementation that can
// occasionally fail with transient errors not reported in man 2 splice.
// Just try again if we see these.
if (errno == ENOMEM || errno == EBUSY || (errno == EINTR && !*exiting)) {
PERFETTO_DPLOG("Transient splice failure -- retrying");
usleep(100 * 1000);
continue;
}
PERFETTO_DPLOG("Stopping CPUReader loop for CPU %zd.", cpu);
PERFETTO_DCHECK(errno == EPIPE || errno == EINTR || errno == EBADF);
break; // ~CpuReader is waiting to join this thread.
}
// Then do as many non-blocking splices as we can. This moves any full
// pages from the trace pipe into the staging pipe as long as there is
// data in the former and space in the latter.
while (true) {
{
PERFETTO_METATRACE("name", "splice_nonblocking", "pid", cpu);
splice_res = splice(trace_fd, nullptr, staging_write_fd, nullptr,
base::kPageSize, SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
}
if (splice_res < 0) {
if (errno != EAGAIN && errno != ENOMEM && errno != EBUSY)
PERFETTO_PLOG("splice");
break;
}
}
{
PERFETTO_METATRACE("name", "splice_waitcallback", "pid", cpu);
// This callback will block until we are allowed to read more data.
on_data_available();
}
}
#else
base::ignore_result(cpu);
base::ignore_result(trace_fd);
base::ignore_result(staging_write_fd);
base::ignore_result(on_data_available);
base::ignore_result(exiting);
PERFETTO_ELOG("Supported only on Linux/Android");
#endif
}
bool CpuReader::Drain(const std::array<const EventFilter*, kMaxSinks>& filters,
const std::array<BundleHandle, kMaxSinks>& bundles,
const std::array<FtraceMetadata*, kMaxSinks>& metadatas) {
PERFETTO_DCHECK_THREAD(thread_checker_);
while (true) {
uint8_t* buffer = GetBuffer();
long bytes =
PERFETTO_EINTR(read(*staging_read_fd_, buffer, base::kPageSize));
if (bytes == -1 && errno == EAGAIN)
break;
PERFETTO_CHECK(static_cast<size_t>(bytes) == base::kPageSize);
size_t evt_size = 0;
for (size_t i = 0; i < kMaxSinks; i++) {
if (!filters[i])
break;
evt_size =
ParsePage(buffer, filters[i], &*bundles[i], table_, metadatas[i]);
PERFETTO_DCHECK(evt_size);
}
}
for (size_t i = 0; i < kMaxSinks; i++) {
if (!filters[i])
break;
bundles[i]->set_cpu(static_cast<uint32_t>(cpu_));
bundles[i]->set_overwrite_count(metadatas[i]->overwrite_count);
}
return true;
}
uint8_t* CpuReader::GetBuffer() {
PERFETTO_DCHECK_THREAD(thread_checker_);
if (!buffer_)
buffer_ = base::PageAllocator::Allocate(base::kPageSize);
return reinterpret_cast<uint8_t*>(buffer_.get());
}
// The structure of a raw trace buffer page is as follows:
// First a page header:
// 8 bytes of timestamp
// 8 bytes of page length TODO(hjd): other fields also defined here?
// // TODO(hjd): Document rest of format.
// Some information about the layout of the page header is available in user
// space at: /sys/kernel/debug/tracing/events/header_event
// This method is deliberately static so it can be tested independently.
size_t CpuReader::ParsePage(const uint8_t* ptr,
const EventFilter* filter,
protos::pbzero::FtraceEventBundle* bundle,
const ProtoTranslationTable* table,
FtraceMetadata* metadata) {
const uint8_t* const start_of_page = ptr;
const uint8_t* const end_of_page = ptr + base::kPageSize;
PageHeader page_header;
if (!ReadAndAdvance<uint64_t>(&ptr, end_of_page, &page_header.timestamp))
return 0;
// TODO(fmayer): Do kernel deepdive to double check this.
uint16_t size_bytes = table->ftrace_page_header_spec().size.size;
PERFETTO_CHECK(size_bytes >= 4);
uint32_t overwrite_and_size;
if (!ReadAndAdvance<uint32_t>(&ptr, end_of_page, &overwrite_and_size))
return 0;
page_header.size = (overwrite_and_size & 0x000000000000ffffull) >> 0;
page_header.overwrite = (overwrite_and_size & 0x00000000ff000000ull) >> 24;
metadata->overwrite_count = static_cast<uint32_t>(page_header.overwrite);
PERFETTO_DCHECK(page_header.size <= base::kPageSize);
ptr += size_bytes - 4;
const uint8_t* const end = ptr + page_header.size;
if (end > end_of_page)
return 0;
uint64_t timestamp = page_header.timestamp;
while (ptr < end) {
EventHeader event_header;
if (!ReadAndAdvance(&ptr, end, &event_header))
return 0;
timestamp += event_header.time_delta;
switch (event_header.type_or_length) {
case kTypePadding: {
// Left over page padding or discarded event.
if (event_header.time_delta == 0) {
// Not clear what the correct behaviour is in this case.
PERFETTO_DCHECK(false);
return 0;
}
uint32_t length;
if (!ReadAndAdvance<uint32_t>(&ptr, end, &length))
return 0;
ptr += length;
break;
}
case kTypeTimeExtend: {
// Extend the time delta.
uint32_t time_delta_ext;
if (!ReadAndAdvance<uint32_t>(&ptr, end, &time_delta_ext))
return 0;
// See https://goo.gl/CFBu5x
timestamp += (static_cast<uint64_t>(time_delta_ext)) << 27;
break;
}
case kTypeTimeStamp: {
// Sync time stamp with external clock.
TimeStamp time_stamp;
if (!ReadAndAdvance<TimeStamp>(&ptr, end, &time_stamp))
return 0;
// Not implemented in the kernel, nothing should generate this.
PERFETTO_DCHECK(false);
break;
}
// Data record:
default: {
PERFETTO_CHECK(event_header.type_or_length <= kTypeDataTypeLengthMax);
// type_or_length is <=28 so it represents the length of a data record.
// if == 0, this is an extended record and the size of the record is
// stored in the first uint32_t word in the payload.
// See Kernel's include/linux/ring_buffer.h
uint32_t event_size;
if (event_header.type_or_length == 0) {
if (!ReadAndAdvance<uint32_t>(&ptr, end, &event_size))
return 0;
// Size includes the size field itself.
if (event_size < 4)
return 0;
event_size -= 4;
} else {
event_size = 4 * event_header.type_or_length;
}
const uint8_t* start = ptr;
const uint8_t* next = ptr + event_size;
if (next > end)
return 0;
uint16_t ftrace_event_id;
if (!ReadAndAdvance<uint16_t>(&ptr, end, &ftrace_event_id))
return 0;
if (filter->IsEventEnabled(ftrace_event_id)) {
protos::pbzero::FtraceEvent* event = bundle->add_event();
event->set_timestamp(timestamp);
if (!ParseEvent(ftrace_event_id, start, next, table, event, metadata))
return 0;
}
// Jump to next event.
ptr = next;
}
}
}
return static_cast<size_t>(ptr - start_of_page);
}
// |start| is the start of the current event.
// |end| is the end of the buffer.
bool CpuReader::ParseEvent(uint16_t ftrace_event_id,
const uint8_t* start,
const uint8_t* end,
const ProtoTranslationTable* table,
protozero::Message* message,
FtraceMetadata* metadata) {
PERFETTO_DCHECK(start < end);
const size_t length = static_cast<size_t>(end - start);
// TODO(hjd): Rework to work even if the event is unknown.
const Event& info = *table->GetEventById(ftrace_event_id);
// TODO(hjd): Test truncated events.
// If the end of the buffer is before the end of the event give up.
if (info.size > length) {
PERFETTO_DCHECK(false);
return false;
}
bool success = true;
for (const Field& field : table->common_fields())
success &= ParseField(field, start, end, message, metadata);
protozero::Message* nested =
message->BeginNestedMessage<protozero::Message>(info.proto_field_id);
for (const Field& field : info.fields)
success &= ParseField(field, start, end, nested, metadata);
// This finalizes |nested| automatically.
message->Finalize();
metadata->FinishEvent();
return success;
}
// Caller must guarantee that the field fits in the range,
// explicitly: start + field.ftrace_offset + field.ftrace_size <= end
// The only exception is fields with strategy = kCStringToString
// where the total size isn't known up front. In this case ParseField
// will check the string terminates in the bounds and won't read past |end|.
bool CpuReader::ParseField(const Field& field,
const uint8_t* start,
const uint8_t* end,
protozero::Message* message,
FtraceMetadata* metadata) {
PERFETTO_DCHECK(start + field.ftrace_offset + field.ftrace_size <= end);
const uint8_t* field_start = start + field.ftrace_offset;
uint32_t field_id = field.proto_field_id;
switch (field.strategy) {
case kUint8ToUint32:
ReadIntoVarInt<uint8_t>(field_start, field_id, message);
return true;
case kUint16ToUint32:
ReadIntoVarInt<uint16_t>(field_start, field_id, message);
return true;
case kUint32ToUint32:
case kUint32ToUint64:
ReadIntoVarInt<uint32_t>(field_start, field_id, message);
return true;
case kUint64ToUint64:
ReadIntoVarInt<uint64_t>(field_start, field_id, message);
return true;
case kInt8ToInt32:
ReadIntoVarInt<int8_t>(field_start, field_id, message);
return true;
case kInt16ToInt32:
ReadIntoVarInt<int16_t>(field_start, field_id, message);
return true;
case kInt32ToInt32:
case kInt32ToInt64:
ReadIntoVarInt<int32_t>(field_start, field_id, message);
return true;
case kInt64ToInt64:
ReadIntoVarInt<int64_t>(field_start, field_id, message);
return true;
case kFixedCStringToString:
// TODO(hjd): Add AppendMaxLength string to protozero.
return ReadIntoString(field_start, field_start + field.ftrace_size,
field_id, message);
case kCStringToString:
// TODO(hjd): Kernel-dive to check this how size:0 char fields work.
return ReadIntoString(field_start, end, field.proto_field_id, message);
case kStringPtrToString:
// TODO(hjd): Figure out how to read these.
return true;
case kDataLocToString:
return ReadDataLoc(start, field_start, end, field, message);
case kBoolToUint32:
ReadIntoVarInt<uint32_t>(field_start, field_id, message);
return true;
case kInode32ToUint64:
ReadInode<uint32_t>(field_start, field_id, message, metadata);
return true;
case kInode64ToUint64:
ReadInode<uint64_t>(field_start, field_id, message, metadata);
return true;
case kPid32ToInt32:
ReadPid(field_start, field_id, message, metadata);
return true;
case kCommonPid32ToInt32:
ReadCommonPid(field_start, field_id, message, metadata);
return true;
case kDevId32ToUint64:
ReadDevId<uint32_t>(field_start, field_id, message, metadata);
return true;
case kDevId64ToUint64:
ReadDevId<uint64_t>(field_start, field_id, message, metadata);
return true;
}
// Not reached, for gcc.
PERFETTO_CHECK(false);
return false;
}
} // namespace perfetto
| 35.779412 | 80 | 0.660142 | [
"vector"
] |
3783b22326277bf83c3e7945303f4c3d8efb40cc | 6,143 | cpp | C++ | modules/processing/src/_processing.cpp | OpenMA/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 41 | 2016-06-28T13:51:39.000Z | 2022-01-20T16:33:00.000Z | modules/processing/src/_processing.cpp | bmswgnp/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 82 | 2016-04-09T15:19:31.000Z | 2018-11-15T18:56:12.000Z | modules/processing/src/_processing.cpp | bmswgnp/openma | 6f3b55292fd0a862b3444f11d71d0562cfe81ac1 | [
"Unlicense"
] | 9 | 2016-03-29T14:28:31.000Z | 2020-07-29T07:39:19.000Z | /*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "openma/processing.h"
#include "openma/base/timesequence.h"
#include "openma/base/logger.h"
#include "openma/math.h" // ma::math::prepare_window_processing
#include <iostream> // Used by IIRFilterDesign
#include <Eigen_openma/SignalProcessing/IIRFilterDesign.h>
#include <Eigen_openma/SignalProcessing/FiltFilt.h>
void _ma_processing_butterworth_zero_lag_filter(ma::TimeSequence* ts, const Eigen::Matrix<double, Eigen::Dynamic, 1>& b, const Eigen::Matrix<double, Eigen::Dynamic, 1>& a)
{
Eigen::Map<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>> data(ts->data(), ts->samples(), ts->components());
data = Eigen::filtfilt(b,a,data);
};
void _ma_processing_butterworth_zero_lag_filter_windowed(ma::TimeSequence* ts, const Eigen::Matrix<double, Eigen::Dynamic, 1>& b, const Eigen::Matrix<double, Eigen::Dynamic, 1>& a)
{
int cpts = ts->components()-1;
Eigen::Map<Eigen::Array<double,Eigen::Dynamic,1>> resin(ts->data()+cpts*ts->samples(), ts->samples(), 1);
Eigen::Array<double,Eigen::Dynamic,1> resout;
unsigned mwlen = 3 * std::max(a.rows(),b.rows()) - 1;
std::vector<std::array<unsigned,2>> windows;
ma::math::prepare_window_processing(resout, windows, resin, mwlen);
Eigen::Map<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>> data(ts->data(), ts->samples(), ts->components());
Eigen::Matrix<double,Eigen::Dynamic,1> temp = Eigen::Matrix<double,Eigen::Dynamic,1>::Zero(data.rows(),1);
for (int i = 0 ; i < cpts ; ++i)
{
for (const auto& w : windows)
temp.segment(w[0],w[1]) = Eigen::filtfilt(b,a,data.block(w[0],i,w[1],1));
data.col(i) = temp;
}
resin = resout;
};
namespace ma
{
namespace processing
{
/**
* Convenient function to simplify the data filtering of time sequences with a zero-lag Butterworth filter
* Internally, this function does two filtering passes (one forward followed by one backward). To respect the given final cut-off frequency (@a fc) and the final order (@a fn), these ones are adapted in consequence (see Robertson & Dowling [1] and Winter [2]).
* This function manage each component independently. In case the type of a time sequence is tagged ma::TimeSequence::Reconstructed, the filtering is managed in consequence and realized by window.
*
* @important This is the responsability of the developer to use correctly this function. It is not intended to verify if the passed time sequence(s) is(are) physically adapted to this filter. For example, the filter is adapted for time sequence with the types TimeSequence::Position and TimeSequence::Analog but might not with the types TimeSequence::Pose and TimeSequence::Wrench.
*
* @par References
* 1. Robertson D.G., Dowling J.J., <em>Design and responses of Butterworth and critically damped digital filters</em>, Journal of Electromyography and Kinesiology, 2003.
* 2. Winter D.A., <em>Biomechanics and Motor Control of Human Movement</em>, John Wiley & Sons, Inc., 2009, paragraph 3.4.4.2.
*
* @ingroup openma_processing
*/
bool filter_butterworth_zero_lag(const std::vector<TimeSequence*>& tss, Response type, double fc, int fn)
{
if (fc <= 0.0)
{
error("Impossible to have a cut-off frequency equal or lower than 0.0.");
return false;
}
if (fn <= 1)
{
error("Impossible to have an order equal or lower than 1.");
return false;
}
Eigen::BandType t = Eigen::LowPass;
switch (type)
{
case Response::LowPass:
break;
case Response::HighPass:
t = Eigen::HighPass;
break;
case Response::BandPass:
t = Eigen::BandPass;
break;
case Response::BandStop:
t = Eigen::BandStop;
break;
default:
error("Unknown band type for the Butterworth filter. Filtering aborted.");
return false;
}
for (const auto& ts : tss)
{
if (ts->sampleRate() == 0.0)
{
error("The time sequence '%s' has a null sample rate.", ts->name().c_str());
continue;
}
double wn = fc / (ts->sampleRate() / 2.0);
int n = fn;
Eigen::adjustZeroLagButterworth(n, wn);
Eigen::Matrix<double, Eigen::Dynamic, 1> a, b;
Eigen::butter(&b, &a, n, wn, t);
if ((ts->type() & TimeSequence::Reconstructed) == TimeSequence::Reconstructed)
_ma_processing_butterworth_zero_lag_filter_windowed(ts,b,a);
else
_ma_processing_butterworth_zero_lag_filter(ts,b,a);
}
return true;
};
};
}; | 45.169118 | 385 | 0.69624 | [
"vector"
] |
378942e0529aec15cf49641d334ebe6cd0b419f3 | 1,927 | cpp | C++ | ext/lazer_lines/lazer_lines.cpp | roadtrippers/lazer_lines | 68f7e0e9776f7bb656bb0f0fa90ceb098fa0af09 | [
"MIT"
] | 2 | 2015-06-30T13:17:15.000Z | 2016-04-28T18:12:17.000Z | ext/lazer_lines/lazer_lines.cpp | roadtrippers/lazer_lines | 68f7e0e9776f7bb656bb0f0fa90ceb098fa0af09 | [
"MIT"
] | 2 | 2016-03-30T15:58:48.000Z | 2021-09-01T18:02:30.000Z | ext/lazer_lines/lazer_lines.cpp | roadtrippers/lazer_lines | 68f7e0e9776f7bb656bb0f0fa90ceb098fa0af09 | [
"MIT"
] | 1 | 2015-06-30T13:17:18.000Z | 2015-06-30T13:17:18.000Z | #include <tuple>
#include <vector>
#include "flexpolyline.h"
#include "lazer_lines.h"
/* Define module "object" */
VALUE LazerLines = Qnil;
extern "C" void Init_lazer_lines() {
LazerLines = rb_define_module("LazerLines");
rb_define_singleton_method(LazerLines, "encode_with_precision", reinterpret_cast<VALUE(*)(...)>(method_encode), 2);
rb_define_singleton_method(LazerLines, "decode_with_precision", reinterpret_cast<VALUE(*)(...)>(method_decode), 2);
rb_define_singleton_method(LazerLines, "flexpolyline_decode", reinterpret_cast<VALUE(*)(...)>(method_flexpolyline_decode), 1);
}
/* Raise RangeError if precision is too large for 32-bit signed integers */
void Check_Precision(VALUE precision_digits) {
if (FIX2INT(precision_digits) >= 8) {
rb_raise(rb_eRangeError, "maximum supported precision is 7 digits");
}
}
VALUE flexpolyline_to_rb_polyline(std::vector<std::tuple<double, double, double>> polyline) {
VALUE rb_polyline = rb_ary_new2(polyline.size());
for (int index = 0; index < polyline.size(); ++index) {
std::tuple<double, double, double> point = polyline[index];
double d_lat = std::get<1>(point);
double d_lon = std::get<0>(point);
VALUE rb_lat = DBL2NUM(d_lat);
VALUE rb_lon = DBL2NUM(d_lon);
VALUE point_array = rb_ary_new3(2, rb_lat, rb_lon);
rb_ary_store(rb_polyline, index, point_array);
}
return rb_polyline;
}
VALUE method_flexpolyline_decode(VALUE self, VALUE rb_string) {
Check_Type(rb_string, T_STRING);
char* c_string = StringValueCStr(rb_string);
std::string string(c_string);
std::vector<std::tuple<double, double, double>> polyline;
auto res = hf::polyline_decode(string, [&polyline](double lat, double lng, double z) {
std::tuple<double, double, double> tuple = std::make_tuple (lat, lng, z);
polyline.push_back(tuple);
});
VALUE rb_polyline = flexpolyline_to_rb_polyline(polyline);
return rb_polyline;
}
| 32.116667 | 128 | 0.72548 | [
"object",
"vector"
] |
3790c19c114a331214ddba4567c579e9bdff0593 | 8,713 | inl | C++ | include/dbclt/postgres/statement.inl | lavoiepatrick/dbclt | e815a253ad538db34f655c3dfbbf032668ea1f15 | [
"MIT"
] | null | null | null | include/dbclt/postgres/statement.inl | lavoiepatrick/dbclt | e815a253ad538db34f655c3dfbbf032668ea1f15 | [
"MIT"
] | null | null | null | include/dbclt/postgres/statement.inl | lavoiepatrick/dbclt | e815a253ad538db34f655c3dfbbf032668ea1f15 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 Patrick Lavoie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include "../util.h"
namespace dbclt
{
template<>
struct type_traits< datetime >
{
using value_type = datetime;
using bound_type = int64_t;
};
namespace postgres
{
inline statement_impl::statement_impl( session_impl& session ) : m_conn( session.m_conn )
{
}
inline statement_impl::result_type statement_impl::execute( const std::string& stmt )
{
if( !m_conn )
throw data_exception( "Connection is not opened" );
result_ptr res( PQexec( m_conn.get( ), stmt.c_str( ) ) );
ExecStatusType status = PQresultStatus( res.get( ) );
if( status != PGRES_COMMAND_OK )
throw data_exception( "Command failed: " + stmt + " -- " + PQresStatus( status ) + " -- " +
PQerrorMessage( m_conn.get( ) ) );
return result_type( result_impl::create( res ) );
}
inline statement_impl::result_type statement_impl::execute_params( const std::string& stmt )
{
if( !m_conn )
throw data_exception( "Connection is not opened" );
result_ptr res( PQexecParams( m_conn.get( ),
stmt.c_str( ),
m_paramTypes.size( ),
&*m_paramTypes.begin( ),
&*m_paramValues.begin( ),
&*m_paramLengths.begin( ),
&*m_paramFormats.begin( ),
0 ) );
ExecStatusType status = PQresultStatus( res.get( ) );
if( status != PGRES_COMMAND_OK )
throw data_exception( "Command failed: " + stmt + " -- " + PQresStatus( status ) + " -- " +
PQerrorMessage( m_conn.get( ) ) );
return result_type( result_impl::create( res ) );
}
inline statement_impl::recordset_type statement_impl::query( const std::string& stmt )
{
if( !m_conn )
throw data_exception( "Connection is not opened" );
result_ptr res(
PQexecParams( m_conn.get( ), stmt.c_str( ), 0, nullptr, nullptr, nullptr, nullptr, 1 ) );
ExecStatusType status = PQresultStatus( res.get( ) );
if( status != PGRES_TUPLES_OK )
throw data_exception( "Command failed: " + stmt + " -- " + PQresStatus( status ) + " -- " +
PQerrorMessage( m_conn.get( ) ) );
result_type result( result_impl::create( res ) );
return *result.recordsets( ).begin( );
}
inline statement_impl::recordset_type statement_impl::query_params( const std::string& stmt )
{
if( !m_conn )
throw data_exception( "Connection is not opened" );
result_ptr res( PQexecParams( m_conn.get( ),
stmt.c_str( ),
m_paramTypes.size( ),
&*m_paramTypes.begin( ),
&*m_paramValues.begin( ),
&*m_paramLengths.begin( ),
&*m_paramFormats.begin( ),
1 ) );
ExecStatusType status = PQresultStatus( res.get( ) );
if( status != PGRES_TUPLES_OK )
throw data_exception( "Command failed: " + stmt + " -- " + PQresStatus( status ) + " -- " +
PQerrorMessage( m_conn.get( ) ) );
result_type result( result_impl::create( res ) );
return *result.recordsets( ).begin( );
}
template<>
inline void statement_impl::bind_parameter( const std::string& value, std::string& bound )
{
m_paramTypes.emplace_back( 1043 );
m_paramValues.emplace_back( bound.c_str( ) );
m_paramLengths.emplace_back( ( int )bound.length( ) );
m_paramFormats.emplace_back( 0 );
}
template<>
inline void statement_impl::bind_parameter( const std::string_view& value, std::string_view& bound )
{
m_paramTypes.emplace_back( 1043 );
m_paramValues.emplace_back( bound.data( ) );
m_paramLengths.emplace_back( ( int )bound.length( ) );
m_paramFormats.emplace_back( 0 );
}
template<>
inline void statement_impl::bind_parameter( const bool& value, bool& bound )
{
m_paramTypes.emplace_back( 16 );
m_paramValues.emplace_back( ( const char* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const int8_t& value, int8_t& bound )
{
m_paramTypes.emplace_back( 20 );
m_paramValues.emplace_back( ( const char* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const int16_t& value, int16_t& bound )
{
m_paramTypes.emplace_back( 21 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const int32_t& value, int32_t& bound )
{
m_paramTypes.emplace_back( 23 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const int64_t& value, int64_t& bound )
{
m_paramTypes.emplace_back( 20 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const float& value, float& bound )
{
m_paramTypes.emplace_back( 700 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const double& value, double& bound )
{
m_paramTypes.emplace_back( 701 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline void statement_impl::bind_parameter( const datetime& value, int64_t& bound )
{
m_paramTypes.emplace_back( 1114 );
m_paramValues.emplace_back( ( const char* )( const void* )&bound );
m_paramLengths.emplace_back( ( int )sizeof( bound ) );
m_paramFormats.emplace_back( 1 );
}
template<>
inline auto statement_impl::get_binder_traits( const int32_t& )
{
struct binder_traits
{
using user_type = int32_t;
using bound_type = int32_t;
using traits = binder_traits;
static int32_t transform( int32_t from )
{
return util::big_to_native32( from );
}
};
return binder_traits( );
}
template<>
inline auto statement_impl::get_binder_traits( const int64_t& )
{
struct binder_traits
{
using user_type = int64_t;
using bound_type = int64_t;
using traits = binder_traits;
static int64_t transform( int64_t from )
{
return util::big_to_native64( from );
}
};
return binder_traits( );
}
template<>
inline auto statement_impl::get_binder_traits( const float& )
{
struct binder_traits
{
using user_type = float;
using bound_type = float;
using traits = binder_traits;
static float transform( float from )
{
return util::big_to_native32( from );
}
};
return binder_traits( );
}
template<>
inline auto statement_impl::get_binder_traits( const double& )
{
struct binder_traits
{
using user_type = double;
using bound_type = double;
using traits = binder_traits;
static double transform( double from )
{
return util::big_to_native64( from );
}
};
return binder_traits( );
}
template<>
inline auto statement_impl::get_binder_traits( const datetime& )
{
struct binder_traits
{
using user_type = datetime;
using bound_type = int64_t;
using traits = binder_traits;
static int64_t transform( datetime from )
{
static const date::sys_days pgEpoch( date::year( 2000 ) / 1 / 1 );
return util::big_to_native64( ( from - pgEpoch ).count( ) );
}
static datetime transform( int64_t from )
{
static const date::sys_days pgEpoch( date::year( 2000 ) / 1 / 1 );
return pgEpoch + std::chrono::microseconds( util::big_to_native64( from ) );
}
};
return binder_traits( );
}
} // namespace postgres
} // namespace dbclt
| 28.567213 | 100 | 0.707908 | [
"transform"
] |
37911e1f7d1fd0c6e37d246ca2f3b82516f11fc4 | 6,783 | cpp | C++ | day-09.cpp | MarioLiebisch/Advent-of-Code-2019 | 5c353128ae61b88fd4656367d2cf0ba1287fe902 | [
"MIT"
] | null | null | null | day-09.cpp | MarioLiebisch/Advent-of-Code-2019 | 5c353128ae61b88fd4656367d2cf0ba1287fe902 | [
"MIT"
] | null | null | null | day-09.cpp | MarioLiebisch/Advent-of-Code-2019 | 5c353128ae61b88fd4656367d2cf0ba1287fe902 | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
// Yep, have to up the type size:
// 'long' on Windows x64 is still just 32 bit, but we need 64 bit
typedef long long value;
// Again this function is basically unchanged from day 7, except for the
// new op code (9) and new addressing mode (2).
void run (std::map<value, value> memory, std::function<value()> input, std::function<void(value)> output) {
std::size_t ip = 0;
std::size_t relative_base = 0;
std::map<const std::size_t, std::function<void()>> codes;
unsigned char mode1 = 0, mode2 = 0, mode3 = 0;
const std::function<value&(const std::size_t, const unsigned char)> read = [&](const std::size_t address, const unsigned char mode) -> value& {
switch (mode) {
case 2: // relative
return memory[relative_base + memory[address]];
case 1: // immediate
return memory[address];
case 0: // positional
return memory[memory[address]];
default: // unhandled
std::cerr << "Unhandled access mode: " << mode << "\n";
throw "Unhandled access mode!";
return memory[0];
}
};
// add
codes[1] = [&]() { read(ip + 3, mode3) = read(ip + 1, mode1) + read(ip + 2, mode2); ip += 4; };
// mul
codes[2] = [&]() { read(ip + 3, mode3) = read(ip + 1, mode1) * read(ip + 2, mode2); ip += 4; };
// input
codes[3] = [&]() { read(ip + 1, mode1) = input(); ip += 2; };
// output
codes[4] = [&]() { output(read(ip + 1, mode1)); ip += 2; };
// jump if true
codes[5] = [&]() { ip = read(ip + 1, mode1) ? read(ip + 2, mode2) : ip + 3; };
// jump if false
codes[6] = [&]() { ip = read(ip + 1, mode1) ? ip + 3 : read(ip + 2, mode2); };
// less than
codes[7] = [&]() { read(ip + 3, mode3) = read(ip + 1, mode1) < read(ip + 2, mode2); ip += 4; };
// equals
codes[8] = [&]() { read(ip + 3, mode3) = read(ip + 1, mode1) == read(ip + 2, mode2); ip += 4; };
// adjust relative base
codes[9] = [&]() { relative_base += read(ip + 1, mode1); ip += 2; };
// halt
codes[99] = [&]() { ip = -1; };
while (ip != -1) {
const std::size_t raw = memory[ip];
const std::size_t op = raw % 100;
const std::size_t modes = (raw / 100) % 1000;
mode1 = modes % 10;
mode2 = (modes / 10) % 10;
mode3 = (modes / 100) % 100;
const auto& ins = codes.find(op);
if (ins != codes.end()) {
ins->second();
}
else {
std::cout << "Unknown op code: " << op << std::endl;
ip = -1;
}
}
}
int main(int argc, char **argv) {
const std::vector<value> program = { 1102,34463338,34463338,63,1007,63,34463338,63,1005,63,53,1102,1,3,1000,109,988,209,12,9,1000,209,6,209,3,203,0,1008,1000,1,63,1005,63,65,1008,1000,2,63,1005,63,902,1008,1000,0,63,1005,63,58,4,25,104,0,99,4,0,104,0,99,4,17,104,0,99,0,0,1102,1,37,1007,1102,24,1,1006,1102,26,1,1012,1101,528,0,1023,1102,256,1,1027,1102,466,1,1029,1102,1,629,1024,1101,0,620,1025,1101,0,0,1020,1102,1,30,1004,1101,39,0,1003,1102,36,1,1005,1102,531,1,1022,1102,32,1,1019,1101,0,27,1000,1101,0,28,1016,1101,1,0,1021,1101,23,0,1013,1102,1,25,1015,1102,1,21,1008,1102,1,22,1018,1102,1,34,1014,1102,475,1,1028,1101,33,0,1002,1101,0,35,1011,1102,1,20,1009,1102,38,1,1017,1101,259,0,1026,1101,31,0,1010,1101,0,29,1001,109,8,21102,40,1,10,1008,1018,40,63,1005,63,203,4,187,1105,1,207,1001,64,1,64,1002,64,2,64,109,7,21108,41,41,0,1005,1015,225,4,213,1106,0,229,1001,64,1,64,1002,64,2,64,109,1,1205,5,247,4,235,1001,64,1,64,1105,1,247,1002,64,2,64,109,20,2106,0,-9,1105,1,265,4,253,1001,64,1,64,1002,64,2,64,109,-38,1202,4,1,63,1008,63,33,63,1005,63,291,4,271,1001,64,1,64,1106,0,291,1002,64,2,64,109,6,2102,1,0,63,1008,63,29,63,1005,63,315,1001,64,1,64,1106,0,317,4,297,1002,64,2,64,109,10,21102,42,1,5,1008,1019,40,63,1005,63,341,1001,64,1,64,1105,1,343,4,323,1002,64,2,64,109,-13,2101,0,5,63,1008,63,24,63,1005,63,365,4,349,1105,1,369,1001,64,1,64,1002,64,2,64,109,7,1202,-6,1,63,1008,63,36,63,1005,63,389,1105,1,395,4,375,1001,64,1,64,1002,64,2,64,109,1,2107,31,-5,63,1005,63,411,1106,0,417,4,401,1001,64,1,64,1002,64,2,64,109,3,1206,8,431,4,423,1105,1,435,1001,64,1,64,1002,64,2,64,109,-8,2108,31,0,63,1005,63,451,1105,1,457,4,441,1001,64,1,64,1002,64,2,64,109,26,2106,0,-2,4,463,1001,64,1,64,1106,0,475,1002,64,2,64,109,-33,1207,6,38,63,1005,63,491,1106,0,497,4,481,1001,64,1,64,1002,64,2,64,109,3,2108,27,0,63,1005,63,515,4,503,1105,1,519,1001,64,1,64,1002,64,2,64,109,23,2105,1,0,1106,0,537,4,525,1001,64,1,64,1002,64,2,64,109,-30,1207,7,28,63,1005,63,559,4,543,1001,64,1,64,1106,0,559,1002,64,2,64,109,20,21101,43,0,0,1008,1013,43,63,1005,63,581,4,565,1105,1,585,1001,64,1,64,1002,64,2,64,109,-14,2102,1,1,63,1008,63,27,63,1005,63,611,4,591,1001,64,1,64,1105,1,611,1002,64,2,64,109,18,2105,1,7,4,617,1001,64,1,64,1106,0,629,1002,64,2,64,109,13,1206,-9,641,1105,1,647,4,635,1001,64,1,64,1002,64,2,64,109,-18,21107,44,45,-1,1005,1011,665,4,653,1105,1,669,1001,64,1,64,1002,64,2,64,109,-2,2107,28,-9,63,1005,63,687,4,675,1106,0,691,1001,64,1,64,1002,64,2,64,1205,10,701,1106,0,707,4,695,1001,64,1,64,1002,64,2,64,109,-6,1201,2,0,63,1008,63,21,63,1005,63,731,1001,64,1,64,1106,0,733,4,713,1002,64,2,64,109,-5,1208,7,23,63,1005,63,753,1001,64,1,64,1105,1,755,4,739,1002,64,2,64,109,16,1208,-8,37,63,1005,63,777,4,761,1001,64,1,64,1106,0,777,1002,64,2,64,109,3,21107,45,44,-8,1005,1010,797,1001,64,1,64,1105,1,799,4,783,1002,64,2,64,109,-8,1201,-5,0,63,1008,63,36,63,1005,63,821,4,805,1106,0,825,1001,64,1,64,1002,64,2,64,109,-9,2101,0,1,63,1008,63,31,63,1005,63,845,1105,1,851,4,831,1001,64,1,64,1002,64,2,64,109,6,21108,46,49,3,1005,1010,867,1106,0,873,4,857,1001,64,1,64,1002,64,2,64,109,5,21101,47,0,7,1008,1019,44,63,1005,63,897,1001,64,1,64,1106,0,899,4,879,4,64,99,21101,27,0,1,21102,913,1,0,1106,0,920,21201,1,30449,1,204,1,99,109,3,1207,-2,3,63,1005,63,962,21201,-2,-1,1,21101,940,0,0,1105,1,920,21202,1,1,-1,21201,-2,-3,1,21102,1,955,0,1106,0,920,22201,1,-1,-2,1105,1,966,22102,1,-2,-2,109,-3,2105,1,0 };
// Since memory should now be "much larger" than the program, we'll
// just use a std::map, so we only access/simulate memory that's
// actually used.
std::map<value, value> memory;
std::size_t i = 0;
// Copy the program to memory
for (const value &byte : program) {
memory[i++] = byte;
}
// Running as usual
run(memory, []() -> value {
value tmp;
std::cin >> tmp;
return tmp;
}, [](value output) {
// Prints both the simple results for star 1 and star 2
std::cout << output << "\n";
});
return 0;
}
| 68.515152 | 3,429 | 0.609465 | [
"vector"
] |
3795e0b8895cb4afd35c271133ec1f27e484b691 | 843 | cpp | C++ | model/interface.cpp | ORNL-QCI/eldispacho | f9eb38c8ba05bc9b78b0516c038a92f7ca46c364 | [
"BSD-3-Clause"
] | 1 | 2020-06-18T23:10:12.000Z | 2020-06-18T23:10:12.000Z | model/interface.cpp | ORNL-QCI/eldispacho | f9eb38c8ba05bc9b78b0516c038a92f7ca46c364 | [
"BSD-3-Clause"
] | null | null | null | model/interface.cpp | ORNL-QCI/eldispacho | f9eb38c8ba05bc9b78b0516c038a92f7ca46c364 | [
"BSD-3-Clause"
] | 1 | 2020-06-18T23:10:15.000Z | 2020-06-18T23:10:15.000Z | #include "interface.hpp"
namespace model {
namespace interface {
transmitter::transmitter(base::id_t id)
: base(id) {
}
transmitter::transmitter(base::id_t id,
simulator::unit&& simulationUnit)
: base(id, std::move(simulationUnit)) {
}
transmitter::transmitter(transmitter&& old)
: base(std::move(old)) {
}
transmitter& transmitter::operator=(transmitter&& old) {
base::operator=(std::move(old));
return *this;
}
receiver::receiver(base::id_t id)
: base(id) {
}
receiver::receiver(base::id_t id,
simulator::unit&& simulationUnit)
: base(id, std::move(simulationUnit)) {
}
receiver::receiver(receiver&& old)
: base(std::move(old)) {
}
receiver& receiver::operator=(receiver&& old) {
base::operator=(std::move(old));
return *this;
}
}
}
| 19.159091 | 58 | 0.618031 | [
"model"
] |
37985499aa28a6d7fe00bdc24829d8fe175f2884 | 40,463 | cpp | C++ | Osiris/Hacks/Aimbot.cpp | justinmaks/stincheat | 7b5c85f049fad0366be72c6a8ce03a27229dc888 | [
"MIT"
] | 2 | 2020-12-07T01:52:02.000Z | 2021-02-27T13:13:11.000Z | Osiris/Hacks/Aimbot.cpp | justinmaks/stincheat | 7b5c85f049fad0366be72c6a8ce03a27229dc888 | [
"MIT"
] | null | null | null | Osiris/Hacks/Aimbot.cpp | justinmaks/stincheat | 7b5c85f049fad0366be72c6a8ce03a27229dc888 | [
"MIT"
] | 1 | 2020-11-04T07:15:51.000Z | 2020-11-04T07:15:51.000Z | #include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class xcyqcea {
public:
int kilecvcxxtjy;
xcyqcea();
bool aybdhlllttivvdhzrird(int fznlcz, int yqpjthtwddtqt);
void jwvrweqxyr(bool gwwdaiz, string ullae, string gkjadenod, int ehyktkikldllkpc, double qmofzf, double tvxerpkkju, double iiaizzmfi, string rwdhg, string zgxcijopfpfi, bool dndisoabvtkpsdd);
protected:
int nfslq;
double ksuhhthlvptgpg;
double wlzojlvbrpahan;
string ktkqbkwbojogvnldptivh(int sixjncnbc, bool dprlisa, int lwjnz, int ldparpfqj, double zsgdicmem, bool hzkuzholktmwyj, string fengyravcichwu);
void zvbhimcxaeqf(int guutfjuarregphr, int motsulpjg, double zmlfnmac, string rmipe, double jrzifcxozzhg, int ltihqplk);
void jfmqyllbncxvmo(int gpczxqlsyr, string uedxk, string acfwpfhuwjfmfn, double itbmziru, int kkqqzqh, double iiqtrrz, double mszucwtklaa, string aaojkolkwy);
string kkznkhvijhobiavnvm(double nphvogccrv, int ptykpmk, double mnwlkjcomerudax, int siifrkrrsaj, bool encwr, string slpkmanoqnov, string waskjcdxutw, double rjcmgmdxeazby, bool ezsizexzekeo, bool vndnwajef);
int fwmrikrivoiolaqquyec();
double ktoiqzvzrndmkhoziozpxj(int vosdqrpquxo, double chmvmgstj);
bool rrykrndhki(string ktxxnhnfye, double xrpxlpazurlvhhx);
bool cbfongztztnxgmmummbr(int gvlbgoox, bool wumiqsrwbkl, bool qclaajyzoctry, double ixigqocqra, bool hlfexwcimjly, string miwdx, double jvbkqil, int gzhllzde);
string pdxtlkclspxsdjxjukg(string hvwrk, string ozdjumwwgtuwvz, bool nxalczclgxjq);
string xyfyqfhrknzrrlgb(double gvtmlohccr);
private:
string mmvurkktpq;
double hvmyzezl;
double zyxufztjndacysiyuddmcxv(string qyllthrmzj, int khxjzvrjx, bool bkoid, bool cujad);
void hsxhhvktmaujigfytfzup(bool cholezphupqudl, string bbftr, double nwqvvdwxpak, int iytbuiyyatcsjy, string szakliwxyyq, string erafzfbfwvyyuvt, int gixrogmpcdd, double xkpoqcdgolt, double wbdewpjmrmhirl, int ylcwnnxilb);
string wmvtzfdjjfyidqbxrp(string oweendozdig, string hlrumpiiu, double zsdokcmm, bool hjgpzfzp, double aamed);
string rtbgbdgwvdddsabmiopmex(double lxxoxly, string cescouhfcbd, bool sybsnws, int ugcvufc, bool htczyqwfxm, string krtisycxvne);
bool elmylhsvjrhathnecsrbtdnnv(string pezelavkmgnmw, int rccxabesxrtafkk, double wcazliz, bool jnemiugs, bool rhedmbxc);
string knnhbvccjdjueczo(bool ssmuqoepfsl, double kadtkw, double zsbrw, bool ztlpzlt, bool ssqftytspongt, double woqibkghd, bool zyzbstzfaqsp, int qsimmu, bool jnctpgtohlyqgza);
bool swyxpjlxptleiszssynxm(string ddbjwvltdmunb, string yhjtis, double ailehli, int hzyfriwmwpck);
double epnhihpivmirsuvfwclfoxn(string ivalmiifsiblhev, bool pjmlez);
int ytpjeqdnjvgpd(int zusfzfgxjckt, int sgmjp, double rjmdxnxhgja, string xppjibulqlyfam, double yfmwqkwduhoaejw, double rbefsiy, int bssedkp);
int wqbzwdenuvwgnwzjireva(double cxylvuaqyk, int gtczmjlkolcgugw, double gptijxfgx);
};
double xcyqcea::zyxufztjndacysiyuddmcxv(string qyllthrmzj, int khxjzvrjx, bool bkoid, bool cujad) {
return 99887;
}
void xcyqcea::hsxhhvktmaujigfytfzup(bool cholezphupqudl, string bbftr, double nwqvvdwxpak, int iytbuiyyatcsjy, string szakliwxyyq, string erafzfbfwvyyuvt, int gixrogmpcdd, double xkpoqcdgolt, double wbdewpjmrmhirl, int ylcwnnxilb) {
bool lpqgj = false;
int ebmdswdr = 1653;
bool ybzsgwx = true;
string qompjxutcy = "fxmuravlsedadyyoiiqzruvhzwtulizvrqdtsifjojilbelbpiqlw";
double lvggdqkk = 8551;
if (8551 == 8551) {
int onpadncr;
for (onpadncr = 39; onpadncr > 0; onpadncr--) {
continue;
}
}
}
string xcyqcea::wmvtzfdjjfyidqbxrp(string oweendozdig, string hlrumpiiu, double zsdokcmm, bool hjgpzfzp, double aamed) {
string ombvvzxdfzlvd = "rljuwpevpliqeyxrcpycyuoyulsmrpomzplzmjjs";
string cqpyhvwdksd = "kimrogbrohrdowemsdwnwriplwacqdjrbkucfdunfxivp";
bool aaxlx = false;
double ljnpargwdngrh = 38851;
int ankik = 1810;
double cqbsdvuozotn = 12226;
int eemvvfm = 1711;
if (1810 == 1810) {
int lxdwsiym;
for (lxdwsiym = 25; lxdwsiym > 0; lxdwsiym--) {
continue;
}
}
if (string("kimrogbrohrdowemsdwnwriplwacqdjrbkucfdunfxivp") != string("kimrogbrohrdowemsdwnwriplwacqdjrbkucfdunfxivp")) {
int wuptbgt;
for (wuptbgt = 84; wuptbgt > 0; wuptbgt--) {
continue;
}
}
if (38851 != 38851) {
int iavkbtvgfw;
for (iavkbtvgfw = 33; iavkbtvgfw > 0; iavkbtvgfw--) {
continue;
}
}
if (1711 != 1711) {
int gs;
for (gs = 73; gs > 0; gs--) {
continue;
}
}
return string("kfq");
}
string xcyqcea::rtbgbdgwvdddsabmiopmex(double lxxoxly, string cescouhfcbd, bool sybsnws, int ugcvufc, bool htczyqwfxm, string krtisycxvne) {
string qqsauebndhvg = "nsqdccioqibopfpcfxxzkuzguxcsqhauqxflkonrviddicqoecwyomhvhpgbeoebkbluyjneuzqtv";
string jlbsgppmvfehhu = "dfbapbijn";
int goodl = 5528;
bool shcqsyzmt = true;
int sruxxvnoucd = 6226;
double wtbjnx = 4214;
bool oeljocwwt = true;
bool tmzmszrb = false;
if (true != true) {
int mz;
for (mz = 57; mz > 0; mz--) {
continue;
}
}
if (5528 != 5528) {
int fwavz;
for (fwavz = 26; fwavz > 0; fwavz--) {
continue;
}
}
if (true == true) {
int xgqbg;
for (xgqbg = 15; xgqbg > 0; xgqbg--) {
continue;
}
}
if (true != true) {
int kmmlbqct;
for (kmmlbqct = 94; kmmlbqct > 0; kmmlbqct--) {
continue;
}
}
return string("qxejpuumjcny");
}
bool xcyqcea::elmylhsvjrhathnecsrbtdnnv(string pezelavkmgnmw, int rccxabesxrtafkk, double wcazliz, bool jnemiugs, bool rhedmbxc) {
string qrwja = "xptwnbtxiecv";
double jwrjbufgpfoumt = 32312;
double mltdiovg = 37134;
string muejwqfrcoxf = "kmfeharkbgrxpcuchjjhfhotnpegobzxgjrjlxxxxqauuzapleky";
double mbbwndyfkxqq = 77952;
string sfpqtkvobk = "bykfnoyfnbqhltxacpuintvsygvkqqkbpladfebanxe";
int bhwow = 6343;
if (string("bykfnoyfnbqhltxacpuintvsygvkqqkbpladfebanxe") != string("bykfnoyfnbqhltxacpuintvsygvkqqkbpladfebanxe")) {
int odylu;
for (odylu = 16; odylu > 0; odylu--) {
continue;
}
}
return false;
}
string xcyqcea::knnhbvccjdjueczo(bool ssmuqoepfsl, double kadtkw, double zsbrw, bool ztlpzlt, bool ssqftytspongt, double woqibkghd, bool zyzbstzfaqsp, int qsimmu, bool jnctpgtohlyqgza) {
int zvwmygsjewtmmq = 274;
int uyuqska = 1331;
int tclmhnmtpjxsh = 1613;
int ypdwp = 682;
string gjjgwsijdyioux = "mftualwzdtzojs";
double rtqfrtrcctjuvc = 53018;
double ivhkvoi = 5005;
int niornki = 5713;
double goufqs = 40932;
if (40932 != 40932) {
int jvebvook;
for (jvebvook = 96; jvebvook > 0; jvebvook--) {
continue;
}
}
if (40932 == 40932) {
int ujeyejqunf;
for (ujeyejqunf = 75; ujeyejqunf > 0; ujeyejqunf--) {
continue;
}
}
return string("ajhcptcaaevmxrxrnl");
}
bool xcyqcea::swyxpjlxptleiszssynxm(string ddbjwvltdmunb, string yhjtis, double ailehli, int hzyfriwmwpck) {
bool dpbdkp = true;
if (true == true) {
int ngdovhpdq;
for (ngdovhpdq = 66; ngdovhpdq > 0; ngdovhpdq--) {
continue;
}
}
if (true == true) {
int llw;
for (llw = 3; llw > 0; llw--) {
continue;
}
}
if (true == true) {
int xlhntepibk;
for (xlhntepibk = 54; xlhntepibk > 0; xlhntepibk--) {
continue;
}
}
if (true != true) {
int rftnood;
for (rftnood = 52; rftnood > 0; rftnood--) {
continue;
}
}
return false;
}
double xcyqcea::epnhihpivmirsuvfwclfoxn(string ivalmiifsiblhev, bool pjmlez) {
bool keaqaaqjagvq = false;
string uelrogmvasnqtb = "czrytjltzwpcqkmabidgpcedcovkrkqusfzhklfpwqryhflrskflnuirgfduawxjbk";
string uasirmvecygadn = "cirbldhewtqhwuftnjxezoovtskakzpalvfbksqcfxbvua";
double ufgem = 13154;
double rrqeumqfnicnd = 17701;
double ifnitbssjejdydd = 7484;
int nguvmdwyf = 1971;
bool orahlulan = true;
bool kkiggkyss = false;
return 53874;
}
int xcyqcea::ytpjeqdnjvgpd(int zusfzfgxjckt, int sgmjp, double rjmdxnxhgja, string xppjibulqlyfam, double yfmwqkwduhoaejw, double rbefsiy, int bssedkp) {
int saseaz = 6340;
string pvgpsqfdsuullm = "qnzlbpfiglpnmycoaljld";
double tccxcttkwjgxmmk = 17915;
double ehtdoc = 24766;
double bpnpxnaefixjfl = 18759;
if (17915 == 17915) {
int gdohw;
for (gdohw = 91; gdohw > 0; gdohw--) {
continue;
}
}
return 68094;
}
int xcyqcea::wqbzwdenuvwgnwzjireva(double cxylvuaqyk, int gtczmjlkolcgugw, double gptijxfgx) {
int mpvhgpwdu = 1405;
double uhwsnemkditxlx = 8993;
string cazwqabferfazl = "obokqmmahhwiazxrtifzhvnnwlmkuvepiktysmdeiwjxygbf";
int nmgbxovtec = 4462;
int xujqjw = 273;
string rizihfa = "irvdadilimixwjfuyhlhpiqqarngdydxinbvgsmeqaljrfonjdwpqqlmyuhkrrpxsdyyrxcvxqkv";
double tvjmyfnxt = 40032;
int ipnoqj = 1432;
if (40032 != 40032) {
int fx;
for (fx = 59; fx > 0; fx--) {
continue;
}
}
return 50904;
}
string xcyqcea::ktkqbkwbojogvnldptivh(int sixjncnbc, bool dprlisa, int lwjnz, int ldparpfqj, double zsgdicmem, bool hzkuzholktmwyj, string fengyravcichwu) {
double gjydvrqxdd = 10432;
int ffulwv = 663;
double rgdwuemtsstkw = 8794;
string ftlmu = "rydqbouytimlmylkvocjefzkbqghbycpqoxmocgmnhrvdticvsyqercdfkbwaphmuvfxeiwkymqdtdscay";
double bdjkffcijff = 1413;
if (string("rydqbouytimlmylkvocjefzkbqghbycpqoxmocgmnhrvdticvsyqercdfkbwaphmuvfxeiwkymqdtdscay") != string("rydqbouytimlmylkvocjefzkbqghbycpqoxmocgmnhrvdticvsyqercdfkbwaphmuvfxeiwkymqdtdscay")) {
int nhhv;
for (nhhv = 78; nhhv > 0; nhhv--) {
continue;
}
}
return string("uc");
}
void xcyqcea::zvbhimcxaeqf(int guutfjuarregphr, int motsulpjg, double zmlfnmac, string rmipe, double jrzifcxozzhg, int ltihqplk) {
int lpkacvrr = 2599;
double bvhlsjvjl = 60236;
bool amoxu = true;
string dngef = "mlsphbjue";
int gvnxzhf = 3508;
bool iksoz = true;
if (60236 == 60236) {
int sesicoox;
for (sesicoox = 19; sesicoox > 0; sesicoox--) {
continue;
}
}
if (true == true) {
int wmagdknrnw;
for (wmagdknrnw = 84; wmagdknrnw > 0; wmagdknrnw--) {
continue;
}
}
if (3508 == 3508) {
int odtidkbyhc;
for (odtidkbyhc = 61; odtidkbyhc > 0; odtidkbyhc--) {
continue;
}
}
if (60236 == 60236) {
int ushkjvv;
for (ushkjvv = 45; ushkjvv > 0; ushkjvv--) {
continue;
}
}
if (string("mlsphbjue") == string("mlsphbjue")) {
int jksrf;
for (jksrf = 16; jksrf > 0; jksrf--) {
continue;
}
}
}
void xcyqcea::jfmqyllbncxvmo(int gpczxqlsyr, string uedxk, string acfwpfhuwjfmfn, double itbmziru, int kkqqzqh, double iiqtrrz, double mszucwtklaa, string aaojkolkwy) {
int zostigmqw = 3787;
double zbkvzuechoech = 15675;
bool tjjtrkibebvsdyy = true;
bool cvsiffhdcub = true;
if (15675 == 15675) {
int lkziqkvifa;
for (lkziqkvifa = 65; lkziqkvifa > 0; lkziqkvifa--) {
continue;
}
}
if (15675 == 15675) {
int ah;
for (ah = 50; ah > 0; ah--) {
continue;
}
}
if (true == true) {
int kbzhvga;
for (kbzhvga = 41; kbzhvga > 0; kbzhvga--) {
continue;
}
}
if (true != true) {
int dmafxhrz;
for (dmafxhrz = 5; dmafxhrz > 0; dmafxhrz--) {
continue;
}
}
if (15675 == 15675) {
int rms;
for (rms = 62; rms > 0; rms--) {
continue;
}
}
}
string xcyqcea::kkznkhvijhobiavnvm(double nphvogccrv, int ptykpmk, double mnwlkjcomerudax, int siifrkrrsaj, bool encwr, string slpkmanoqnov, string waskjcdxutw, double rjcmgmdxeazby, bool ezsizexzekeo, bool vndnwajef) {
bool bduyeipkua = false;
string kqhpsdyczc = "lozkssagopqoptketvpxcojgexobslonrekbjejusfexz";
if (string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz") != string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz")) {
int jh;
for (jh = 32; jh > 0; jh--) {
continue;
}
}
if (string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz") != string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz")) {
int yqwjeado;
for (yqwjeado = 73; yqwjeado > 0; yqwjeado--) {
continue;
}
}
if (string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz") == string("lozkssagopqoptketvpxcojgexobslonrekbjejusfexz")) {
int evrvmii;
for (evrvmii = 8; evrvmii > 0; evrvmii--) {
continue;
}
}
if (false == false) {
int xnsd;
for (xnsd = 8; xnsd > 0; xnsd--) {
continue;
}
}
return string("hfzxzxyexia");
}
int xcyqcea::fwmrikrivoiolaqquyec() {
string rohkdc = "kuqykgmpgapnemxzyajpqdcotjjbxutlrpotrwxs";
int dxvaqbzk = 1013;
string vtpiw = "cldukybcdmbssfidmnierui";
bool mclncscoyd = false;
int uflpnypyzl = 253;
string ljhlfqtcdjzucha = "sfupmqvsobobjscjbnaalxwxmbfotwppdqpogedfjxnfeubuvpjsglgwvyyztjjggaqyqzqlfiacfmrkgqkrtuokdaqbhpla";
double yhlwvo = 12601;
string akrihotmvawy = "ncftwsppsprazvzhdxecljfbquuthloqicaczevmbsvokzzhdsofseutttznlhspeywcoownulztvdhqzhvvfrvh";
bool hetoklv = true;
double ywikakqteipjnpt = 20898;
return 98693;
}
double xcyqcea::ktoiqzvzrndmkhoziozpxj(int vosdqrpquxo, double chmvmgstj) {
int fzcoqrqekvgkw = 1125;
string kjihttlsipotv = "pwzecrynkfbiusex";
bool qsouyjf = false;
string lzjldleaozkdxnh = "teomjqampzkvhqlvabhjijsqjlnupozewrfbiryqaxwdlxivuszszgsrfkoipulscdpd";
int qjuxwalyjdhpbmn = 1401;
string zaogu = "mdndpspvyrkfoeyzavvtgepalpmqdezqdacbscqzrpfsqngwr";
double pzhsuhpveolvd = 10103;
int ljhpdhdrlmf = 4414;
double vgdjvtoekgc = 21933;
return 37363;
}
bool xcyqcea::rrykrndhki(string ktxxnhnfye, double xrpxlpazurlvhhx) {
bool gfbwznwgs = false;
bool zrwvloq = true;
bool cedijz = false;
string zzxfv = "esdfuwoupscpxqamijegnrafvm";
bool zqkkqhtlmed = false;
bool zkygpqw = false;
string ivrwdhcszzvh = "owigzirwaqnfmjlovprwyxeguchfhgctzuhgfoysybbarnrbppebmgjkbxedywfx";
double ysbcjcvsjhpypg = 5938;
return false;
}
bool xcyqcea::cbfongztztnxgmmummbr(int gvlbgoox, bool wumiqsrwbkl, bool qclaajyzoctry, double ixigqocqra, bool hlfexwcimjly, string miwdx, double jvbkqil, int gzhllzde) {
string jogdc = "ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw";
int jmtebvxhocjw = 2024;
if (string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw") == string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw")) {
int igyotw;
for (igyotw = 43; igyotw > 0; igyotw--) {
continue;
}
}
if (string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw") == string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw")) {
int oi;
for (oi = 59; oi > 0; oi--) {
continue;
}
}
if (string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw") == string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw")) {
int jgy;
for (jgy = 6; jgy > 0; jgy--) {
continue;
}
}
if (string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw") != string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw")) {
int kl;
for (kl = 45; kl > 0; kl--) {
continue;
}
}
if (string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw") != string("ynuwlpwwkrouceiywpiskxzlhklyffaegfpjmgvllifcwluncqiifqkesfflmugnbzycursczsxabvtjpyw")) {
int so;
for (so = 47; so > 0; so--) {
continue;
}
}
return true;
}
string xcyqcea::pdxtlkclspxsdjxjukg(string hvwrk, string ozdjumwwgtuwvz, bool nxalczclgxjq) {
bool pecwseh = false;
double ebzwcztfpwvwes = 16878;
bool ocpxapqie = true;
if (false != false) {
int dfczx;
for (dfczx = 55; dfczx > 0; dfczx--) {
continue;
}
}
if (false == false) {
int pqqgk;
for (pqqgk = 77; pqqgk > 0; pqqgk--) {
continue;
}
}
if (16878 == 16878) {
int ggezjdo;
for (ggezjdo = 16; ggezjdo > 0; ggezjdo--) {
continue;
}
}
if (16878 != 16878) {
int ekjj;
for (ekjj = 63; ekjj > 0; ekjj--) {
continue;
}
}
return string("h");
}
string xcyqcea::xyfyqfhrknzrrlgb(double gvtmlohccr) {
double akxuphrjwfamm = 59114;
int huhqn = 262;
string ygmpvb = "jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg";
if (string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg") == string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg")) {
int iaua;
for (iaua = 40; iaua > 0; iaua--) {
continue;
}
}
if (262 == 262) {
int av;
for (av = 100; av > 0; av--) {
continue;
}
}
if (string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg") != string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg")) {
int bthbjidqb;
for (bthbjidqb = 13; bthbjidqb > 0; bthbjidqb--) {
continue;
}
}
if (string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg") != string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg")) {
int cbxfg;
for (cbxfg = 69; cbxfg > 0; cbxfg--) {
continue;
}
}
if (string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg") != string("jmksufmxsxpoogimlvsdghjlvdmqgoionaugrkbiyftmavpgylhaozsguueiqxzwcrihmhlnjdcohyqwfnvknhsgrhtfzykayelg")) {
int pubbfvdkae;
for (pubbfvdkae = 95; pubbfvdkae > 0; pubbfvdkae--) {
continue;
}
}
return string("fs");
}
bool xcyqcea::aybdhlllttivvdhzrird(int fznlcz, int yqpjthtwddtqt) {
string ndggcaoz = "yefpckqohbyinchidzzojv";
double fnqybky = 12426;
bool vtfni = false;
string jhpgrxugecaunn = "asprivtcpycjtxxgpmztonsozklwsxhkhqajwvjghtgfyrzuvxmmieaqcmhurrygjomngiqukdzmhevlmfstwg";
bool axohebqm = true;
if (12426 == 12426) {
int rymztk;
for (rymztk = 76; rymztk > 0; rymztk--) {
continue;
}
}
if (string("asprivtcpycjtxxgpmztonsozklwsxhkhqajwvjghtgfyrzuvxmmieaqcmhurrygjomngiqukdzmhevlmfstwg") == string("asprivtcpycjtxxgpmztonsozklwsxhkhqajwvjghtgfyrzuvxmmieaqcmhurrygjomngiqukdzmhevlmfstwg")) {
int mq;
for (mq = 2; mq > 0; mq--) {
continue;
}
}
if (string("yefpckqohbyinchidzzojv") != string("yefpckqohbyinchidzzojv")) {
int dsprz;
for (dsprz = 96; dsprz > 0; dsprz--) {
continue;
}
}
if (12426 == 12426) {
int dame;
for (dame = 74; dame > 0; dame--) {
continue;
}
}
return false;
}
void xcyqcea::jwvrweqxyr(bool gwwdaiz, string ullae, string gkjadenod, int ehyktkikldllkpc, double qmofzf, double tvxerpkkju, double iiaizzmfi, string rwdhg, string zgxcijopfpfi, bool dndisoabvtkpsdd) {
bool lxoqtfdxxrc = true;
int rhcpyisofxpnbm = 4221;
string ofxtbt = "gznprbxvalacbaqixetfekrsmfrjdcdplphwmvezrjzjbhjpikqviecakswow";
string wervcbo = "ghlhixebjirxxzyoohb";
double wpsqdapcmtk = 4005;
bool krnkimtpoqwgb = false;
bool odbyhbypv = true;
bool zwopfliiq = true;
bool xxbage = false;
if (true == true) {
int ncmj;
for (ncmj = 2; ncmj > 0; ncmj--) {
continue;
}
}
if (true != true) {
int eoorc;
for (eoorc = 30; eoorc > 0; eoorc--) {
continue;
}
}
}
xcyqcea::xcyqcea() {
this->aybdhlllttivvdhzrird(4404, 1015);
this->jwvrweqxyr(true, string("sxykizgkzspajkdhwjhohiuvrcjw"), string("hvedoqrsxonkmjmunzmgqsympjk"), 1349, 55244, 15409, 15779, string("aexpqtuernniwuudz"), string("nljtsaadkohqdvwcqoulenkjkrakmuihigyscfpjybopsezycrbvavmikuctfpfoqisvmgwhmpykdhxk"), false);
this->ktkqbkwbojogvnldptivh(1434, false, 570, 648, 12812, true, string("gknryfowvhidktstpqgsyrgzdmsgrdhjurxzpgndzauifzouohmcuncznlandgdwkivnuovluasnxdgjxbmtufkrgtnhjxzcc"));
this->zvbhimcxaeqf(5445, 263, 40060, string("nbduizldweotfdcklywitrpcnanenawkqiqstwkash"), 24222, 835);
this->jfmqyllbncxvmo(6867, string("gdzpfffcwujxjyozpyqijhphfrwvdetqebixkaacug"), string("sgrdiyqhdhjnvherqcnmphqmbeefoqdtsyqbfctha"), 36611, 1087, 259, 4855, string("t"));
this->kkznkhvijhobiavnvm(38049, 2986, 34723, 1403, false, string("lfjpdwydsbedsdswkbtqfozmlozvdalccenkwsmp"), string("freswrlxjqkxntkazjgykwzriwxplqrtbwmuxcxigvkjwzvgqowglu"), 49434, false, true);
this->fwmrikrivoiolaqquyec();
this->ktoiqzvzrndmkhoziozpxj(1871, 5672);
this->rrykrndhki(string("twusdfofzzfyyihwiwxhrlhkljglzfcodvaensfwdjxlncamilojuvjbmqdgrkzxydsrjsnbknoajzsiymquut"), 50373);
this->cbfongztztnxgmmummbr(121, true, false, 19420, true, string("tzokbhwlnkzwstfczxmejnlgolucyxt"), 76654, 1245);
this->pdxtlkclspxsdjxjukg(string("vjzzbjklxnruor"), string("kssfoieulmxlbskikoltlebioemspwsmtxkspexzwwfqtkcgcqdsfkdblchzzpfmsvmwxscwrahztwtgyy"), true);
this->xyfyqfhrknzrrlgb(9499);
this->zyxufztjndacysiyuddmcxv(string("xflgjxhdyfxnbewouayzusgklbi"), 5806, true, false);
this->hsxhhvktmaujigfytfzup(true, string("apdaixrmemoekaqp"), 12115, 2421, string("ygjgntbxafmfwtryogivnrabywyvcpujevpomutkdxxlow"), string("wvhvjlnrmsgulghofmwmuagudcqjnhrisjhglalhswdjnkbnwscewaubkuxsakxjdfuoqqtcnotoadurfqmawiyhbyfp"), 4497, 37504, 27187, 4979);
this->wmvtzfdjjfyidqbxrp(string("assogjwcpugexqnmvvtawjoszznhdakiovnixoviwwphphtp"), string("vzdbaneqjxhjomfotqtcaodq"), 1446, true, 27043);
this->rtbgbdgwvdddsabmiopmex(14321, string("axkysnpjdafypckdfxm"), true, 696, false, string("fhasvrviuzfztoyodjymbdayqxkuphmkxxcyumjdegytrvwcnacsuo"));
this->elmylhsvjrhathnecsrbtdnnv(string("swjrmxqfizizftzctjgixykmitcgttyuyrpvns"), 877, 27759, true, true);
this->knnhbvccjdjueczo(false, 44516, 10300, true, false, 3986, false, 529, false);
this->swyxpjlxptleiszssynxm(string("pyeyjyxckmlvvanurjbbmgkwanenwuyvmwzkwsyqqmtellmamdvjkkmztgkmbawxomcicjkoseyzludnskvue"), string("fdfnlmduntmpgcaarftpltgkemwonrcykfelwreffxadqigyjnncaxdmfopqyrummeqnclukkbhxfuoxelfojdwwpuwzgvsm"), 5290, 3828);
this->epnhihpivmirsuvfwclfoxn(string("kthiffewdfutkkpdvsmozehqzsthaijgpdwsezzbfaysmeluovrgbybaisrnaqbtvtzfebdvotljtuwwauigkohg"), true);
this->ytpjeqdnjvgpd(1737, 6140, 5532, string("ctbluks"), 1763, 7123, 815);
this->wqbzwdenuvwgnwzjireva(39469, 1176, 4758);
}
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class dloojda {
public:
bool lofcvjvlrfuomm;
bool mxsnxugppdrurmh;
bool vuakfqmxisa;
dloojda();
bool bwxggnlrdla(string qiegzhle, string meahww, double dgeheofek, int nicjpoj, int hjdyqeebvicjoey, string rjlil, int nhneyl, string jgvvt, bool hngcdwhoreed, double ikgtxyipbnwp);
protected:
int vvbjetiqae;
double hdzrkquw;
bool xldumkervnw(int hzyxkbjmd);
void vzxeimzfdhanntiiuufmgktlb(int uwihjhphv, string afeub);
int sxhmzpwomw(bool cdjrupktkwf, bool sxsfdhnm, int kzirjeh);
bool efghljedzrqxbkugtlsgzr(bool kwkxgykbhq, bool ymdgiyagnkjpzlv, int nlfeuwxwbi, bool tmtlyjp, bool kszfvrczhzus, string jtvzszkdpfdp, int bdajtjbfp);
private:
string jfdbzmroxypyfh;
double agcorw;
bool thegfaw;
double ueahjzu;
int sxpqytmxtajs;
void xoilpkxzoosrcfmqqrkbgp(double axjbluynbhikw, int kbeciehhu, int obxmbszyvaaua, string maaco, double sixlsyau, bool fksdepvkq, bool bjquntakmgxu, string mepgsqvzewv, string jgkumkoooq, double peajvfmgv);
double djshekpffqflxdkebcqvq(bool ymoauymykqiuw, double aefomqc, string xarrwaqjuszhq);
};
void dloojda::xoilpkxzoosrcfmqqrkbgp(double axjbluynbhikw, int kbeciehhu, int obxmbszyvaaua, string maaco, double sixlsyau, bool fksdepvkq, bool bjquntakmgxu, string mepgsqvzewv, string jgkumkoooq, double peajvfmgv) {
double ofhjgpbyg = 26509;
}
double dloojda::djshekpffqflxdkebcqvq(bool ymoauymykqiuw, double aefomqc, string xarrwaqjuszhq) {
bool hvtqgpltv = false;
int fjpsvhwxkbk = 4636;
double gjvnezteugelw = 10172;
int txesupsfq = 1974;
double cxafnzzwjgm = 66824;
int agwzu = 2146;
int kvrsqj = 261;
string cuifmleqsfqtj = "ulhntysywncczmvbmamnpepssgnulukrvocwiglyqtvdcgalinyknxncokbkbigttgrweawdxzngwnvjrswtrxrog";
string ycrbcpeeun = "ybvoacdzioexjwnehcanfninklwatgdcmiqmka";
string qitdzqvxmezxkhj = "kikldpqg";
if (string("kikldpqg") == string("kikldpqg")) {
int nzbs;
for (nzbs = 36; nzbs > 0; nzbs--) {
continue;
}
}
if (66824 != 66824) {
int ns;
for (ns = 54; ns > 0; ns--) {
continue;
}
}
if (4636 != 4636) {
int vwxwk;
for (vwxwk = 74; vwxwk > 0; vwxwk--) {
continue;
}
}
if (2146 != 2146) {
int xbhilm;
for (xbhilm = 91; xbhilm > 0; xbhilm--) {
continue;
}
}
return 80889;
}
bool dloojda::xldumkervnw(int hzyxkbjmd) {
string xzksraohf = "alkdlmefjkucoqdlxkkusrcbilfmvyiskzhwvyrtwgxwvm";
int htfvbkpts = 1058;
int vqiwgcbjtrnn = 2592;
string szxfwupozq = "rtphkvkxbcmisufqcg";
string dlwlowijmpcazf = "gafwjdgvlpfnjtpbydpvwcczkbvlftjfqbrsn";
bool rjwitwvhvytrtlm = true;
bool gumoaqyx = true;
if (string("alkdlmefjkucoqdlxkkusrcbilfmvyiskzhwvyrtwgxwvm") != string("alkdlmefjkucoqdlxkkusrcbilfmvyiskzhwvyrtwgxwvm")) {
int duzzm;
for (duzzm = 27; duzzm > 0; duzzm--) {
continue;
}
}
if (true == true) {
int jisq;
for (jisq = 96; jisq > 0; jisq--) {
continue;
}
}
return false;
}
void dloojda::vzxeimzfdhanntiiuufmgktlb(int uwihjhphv, string afeub) {
double yaepg = 69055;
string grihhz = "nladkuwuovogztauyqhqhkhsozxydslapdpsygrfeqwqbrqonqfmvzoveqjpzhnod";
int xchmfmndk = 2922;
int iqnligkck = 1476;
bool mqqjwlcjwjwtee = false;
string cqyozewv = "omkysqgrcxzswxbzulwsvdkoxurylrebgkaaaemoxrrcvzzvtvwzwgxvcpygxyhayiaailqfnqajxidrgheoprxwpnatea";
string zqbsahoftppjial = "abwvvqmgzghshbpnhhm";
}
int dloojda::sxhmzpwomw(bool cdjrupktkwf, bool sxsfdhnm, int kzirjeh) {
double tfyey = 75939;
if (75939 != 75939) {
int xfieag;
for (xfieag = 14; xfieag > 0; xfieag--) {
continue;
}
}
if (75939 != 75939) {
int bng;
for (bng = 61; bng > 0; bng--) {
continue;
}
}
if (75939 != 75939) {
int ujayrta;
for (ujayrta = 26; ujayrta > 0; ujayrta--) {
continue;
}
}
if (75939 != 75939) {
int nsjr;
for (nsjr = 39; nsjr > 0; nsjr--) {
continue;
}
}
if (75939 != 75939) {
int nrbiqnv;
for (nrbiqnv = 23; nrbiqnv > 0; nrbiqnv--) {
continue;
}
}
return 87315;
}
bool dloojda::efghljedzrqxbkugtlsgzr(bool kwkxgykbhq, bool ymdgiyagnkjpzlv, int nlfeuwxwbi, bool tmtlyjp, bool kszfvrczhzus, string jtvzszkdpfdp, int bdajtjbfp) {
double xiwuldvce = 6304;
int emvnrzzralwyn = 90;
if (6304 != 6304) {
int hdwqkddnft;
for (hdwqkddnft = 25; hdwqkddnft > 0; hdwqkddnft--) {
continue;
}
}
if (90 == 90) {
int cciheelqzt;
for (cciheelqzt = 87; cciheelqzt > 0; cciheelqzt--) {
continue;
}
}
if (6304 == 6304) {
int keaomd;
for (keaomd = 89; keaomd > 0; keaomd--) {
continue;
}
}
if (90 != 90) {
int ps;
for (ps = 82; ps > 0; ps--) {
continue;
}
}
return false;
}
bool dloojda::bwxggnlrdla(string qiegzhle, string meahww, double dgeheofek, int nicjpoj, int hjdyqeebvicjoey, string rjlil, int nhneyl, string jgvvt, bool hngcdwhoreed, double ikgtxyipbnwp) {
int knzgfcfrvn = 991;
double aennaesdioaetc = 14605;
double bhzdsmainfqmb = 67453;
bool ihbqurxlnzwr = true;
string doeebhipyhv = "gvxnjvvxcqphvjwedukxromymrampelpdxjdrrxxxeomwxrcfxjhkedstiyltxhupkdzzdsrnhwbqjkvfrmghrzyzevorljiaia";
int penhqknsdoa = 4581;
if (991 == 991) {
int sdazk;
for (sdazk = 83; sdazk > 0; sdazk--) {
continue;
}
}
if (true == true) {
int wci;
for (wci = 65; wci > 0; wci--) {
continue;
}
}
if (67453 == 67453) {
int dg;
for (dg = 67; dg > 0; dg--) {
continue;
}
}
if (67453 == 67453) {
int wt;
for (wt = 15; wt > 0; wt--) {
continue;
}
}
return false;
}
dloojda::dloojda() {
this->bwxggnlrdla(string("sbenarphjnyvhilexghfhthbtdmdeamfrkxjqfppkxkyiryqwbaumysqigmigilndcnusrvipqwudwlw"), string("drhmydwrvhfbriccmxnqqqtrttvxrotppvqxslgdkfpjtjsqctnhuiiicukipozlunuizbvcqavxmsiflftsftixuvnrlht"), 22577, 5914, 2255, string("vxetxxnxjsyohljoibufavkvdauhglzlyzypghedavtworemmffyszhtebephgxx"), 1588, string("wrzhesifljpxijxcwtadxbwqeoubjgpfdpylenkyutbtjfzupajqhweuuuxfmfpswi"), false, 43709);
this->xldumkervnw(5722);
this->vzxeimzfdhanntiiuufmgktlb(4274, string("bwdmhxojpdgsturgxbbowczxncwgniqpacrcfijrwasdoqoiyxeszlxdmilcywdxmwbngmh"));
this->sxhmzpwomw(true, false, 1365);
this->efghljedzrqxbkugtlsgzr(true, false, 2609, false, false, string("ugvwzofakfiujyvcpqlteqqpxuoohzuvgcypathtwgxastpmdzoadbnujactcoivrpezvcpswplhfmkmwbjygtywe"), 2690);
this->xoilpkxzoosrcfmqqrkbgp(23550, 5355, 1734, string("kxcryaoxuelizeuoacecgqbep"), 4265, true, true, string("msfmesxnzwisaxdtbetzzunhszsevcbngdvefsiupgk"), string("uzevkuiuodcqrxbbg"), 84014);
this->djshekpffqflxdkebcqvq(false, 68988, string("pzwjkheamkmkoutueaamycedyutkxprksipakrzohjyfcjlvsaenoexurge"));
}
#include "Aimbot.h"
#include "../Config.h"
#include "../Interfaces.h"
#include "../Memory.h"
#include "../SDK/Entity.h"
#include "../SDK/UserCmd.h"
#include "../SDK/Vector.h"
#include "../SDK/WeaponId.h"
#include "../SDK/GlobalVars.h"
#include "../SDK/PhysicsSurfaceProps.h"
#include "../SDK/WeaponData.h"
Vector Aimbot::calculateRelativeAngle(const Vector& source, const Vector& destination, const Vector& viewAngles) noexcept
{
return ((destination - source).toAngle() - viewAngles).normalize();
}
static float handleBulletPenetration(SurfaceData* enterSurfaceData, const Trace& enterTrace, const Vector& direction, Vector& result, float penetration, float damage) noexcept
{
Vector end;
Trace exitTrace;
__asm {
mov ecx, end
mov edx, enterTrace
}
if (!memory->traceToExit(enterTrace.endpos.x, enterTrace.endpos.y, enterTrace.endpos.z, direction.x, direction.y, direction.z, exitTrace))
return -1.0f;
SurfaceData* exitSurfaceData = interfaces->physicsSurfaceProps->getSurfaceData(exitTrace.surface.surfaceProps);
float damageModifier = 0.16f;
float penetrationModifier = (enterSurfaceData->penetrationmodifier + exitSurfaceData->penetrationmodifier) / 2.0f;
if (enterSurfaceData->material == 71 || enterSurfaceData->material == 89) {
damageModifier = 0.05f;
penetrationModifier = 3.0f;
} else if (enterTrace.contents >> 3 & 1 || enterTrace.surface.flags >> 7 & 1) {
penetrationModifier = 1.0f;
}
if (enterSurfaceData->material == exitSurfaceData->material) {
if (exitSurfaceData->material == 85 || exitSurfaceData->material == 87)
penetrationModifier = 3.0f;
else if (exitSurfaceData->material == 76)
penetrationModifier = 2.0f;
}
damage -= 11.25f / penetration / penetrationModifier + damage * damageModifier + (exitTrace.endpos - enterTrace.endpos).squareLength() / 24.0f / penetrationModifier;
result = exitTrace.endpos;
return damage;
}
static bool canScan(Entity* entity, const Vector& destination, const WeaponInfo* weaponData, int minDamage, bool allowFriendlyFire) noexcept
{
if (!localPlayer)
return false;
float damage{ static_cast<float>(weaponData->damage) };
Vector start{ localPlayer->getEyePosition() };
Vector direction{ destination - start };
direction /= direction.length();
int hitsLeft = 4;
while (damage >= 1.0f && hitsLeft) {
Trace trace;
interfaces->engineTrace->traceRay({ start, destination }, 0x4600400B, localPlayer.get(), trace);
if (!allowFriendlyFire && trace.entity && trace.entity->isPlayer() && !localPlayer->isOtherEnemy(trace.entity))
return false;
if (trace.fraction == 1.0f)
break;
if (trace.entity == entity && trace.hitgroup > HitGroup::Generic && trace.hitgroup <= HitGroup::RightLeg) {
damage = HitGroup::getDamageMultiplier(trace.hitgroup) * damage * powf(weaponData->rangeModifier, trace.fraction * weaponData->range / 500.0f);
if (float armorRatio{ weaponData->armorRatio / 2.0f }; HitGroup::isArmored(trace.hitgroup, trace.entity->hasHelmet()))
damage -= (trace.entity->armor() < damage * armorRatio / 2.0f ? trace.entity->armor() * 4.0f : damage) * (1.0f - armorRatio);
return damage >= minDamage;
}
const auto surfaceData = interfaces->physicsSurfaceProps->getSurfaceData(trace.surface.surfaceProps);
if (surfaceData->penetrationmodifier < 0.1f)
break;
damage = handleBulletPenetration(surfaceData, trace, direction, start, weaponData->penetration, damage);
hitsLeft--;
}
return false;
}
void Aimbot::run(UserCmd* cmd) noexcept
{
if (!localPlayer || localPlayer->nextAttack() > memory->globalVars->serverTime() || localPlayer->isDefusing() || localPlayer->waitForNoAttack())
return;
const auto activeWeapon = localPlayer->getActiveWeapon();
if (!activeWeapon || !activeWeapon->clip())
return;
if (localPlayer->shotsFired() > 0 && !activeWeapon->isFullAuto())
return;
auto weaponIndex = getWeaponIndex(activeWeapon->itemDefinitionIndex2());
if (!weaponIndex)
return;
auto weaponClass = getWeaponClass(activeWeapon->itemDefinitionIndex2());
if (!config->aimbot[weaponIndex].enabled)
weaponIndex = weaponClass;
if (!config->aimbot[weaponIndex].enabled)
weaponIndex = 0;
if (!config->aimbot[weaponIndex].betweenShots && activeWeapon->nextPrimaryAttack() > memory->globalVars->serverTime())
return;
if (!config->aimbot[weaponIndex].ignoreFlash && localPlayer->isFlashed())
return;
if (config->aimbot[weaponIndex].onKey) {
if (!config->aimbot[weaponIndex].keyMode) {
if (!GetAsyncKeyState(config->aimbot[weaponIndex].key))
return;
} else {
static bool toggle = true;
if (GetAsyncKeyState(config->aimbot[weaponIndex].key) & 1)
toggle = !toggle;
if (!toggle)
return;
}
}
if (config->aimbot[weaponIndex].enabled && (cmd->buttons & UserCmd::IN_ATTACK || config->aimbot[weaponIndex].autoShot || config->aimbot[weaponIndex].aimlock) && activeWeapon->getInaccuracy() <= config->aimbot[weaponIndex].maxAimInaccuracy) {
if (config->aimbot[weaponIndex].scopedOnly && activeWeapon->isSniperRifle() && !localPlayer->isScoped())
return;
auto bestFov = config->aimbot[weaponIndex].fov;
Vector bestTarget{ };
const auto localPlayerEyePosition = localPlayer->getEyePosition();
const auto aimPunch = activeWeapon->requiresRecoilControl() ? localPlayer->getAimPunch() : Vector{ };
for (int i = 1; i <= interfaces->engine->getMaxClients(); i++) {
auto entity = interfaces->entityList->getEntity(i);
if (!entity || entity == localPlayer.get() || entity->isDormant() || !entity->isAlive()
|| !entity->isOtherEnemy(localPlayer.get()) && !config->aimbot[weaponIndex].friendlyFire || entity->gunGameImmunity())
continue;
for (auto bone : { 8, 4, 3, 7, 6, 5 }) {
const auto bonePosition = entity->getBonePosition(config->aimbot[weaponIndex].bone > 1 ? 10 - config->aimbot[weaponIndex].bone : bone);
const auto angle = calculateRelativeAngle(localPlayerEyePosition, bonePosition, cmd->viewangles + aimPunch);
const auto fov = std::hypot(angle.x, angle.y);
if (fov > bestFov)
continue;
if (!config->aimbot[weaponIndex].ignoreSmoke && memory->lineGoesThroughSmoke(localPlayerEyePosition, bonePosition, 1))
continue;
if (!entity->isVisible(bonePosition) && (config->aimbot[weaponIndex].visibleOnly || !canScan(entity, bonePosition, activeWeapon->getWeaponData(), config->aimbot[weaponIndex].killshot ? entity->health() : config->aimbot[weaponIndex].minDamage, config->aimbot[weaponIndex].friendlyFire)))
continue;
if (fov < bestFov) {
bestFov = fov;
bestTarget = bonePosition;
}
if (config->aimbot[weaponIndex].bone)
break;
}
}
if (bestTarget.notNull()) {
static Vector lastAngles{ cmd->viewangles };
static int lastCommand{ };
if (lastCommand == cmd->commandNumber - 1 && lastAngles.notNull() && config->aimbot[weaponIndex].silent)
cmd->viewangles = lastAngles;
auto angle = calculateRelativeAngle(localPlayerEyePosition, bestTarget, cmd->viewangles + aimPunch);
bool clamped{ false };
if (std::abs(angle.x) > config->misc.maxAngleDelta || std::abs(angle.y) > config->misc.maxAngleDelta) {
angle.x = std::clamp(angle.x, -config->misc.maxAngleDelta, config->misc.maxAngleDelta);
angle.y = std::clamp(angle.y, -config->misc.maxAngleDelta, config->misc.maxAngleDelta);
clamped = true;
}
angle /= config->aimbot[weaponIndex].smooth;
cmd->viewangles += angle;
if (!config->aimbot[weaponIndex].silent)
interfaces->engine->setViewAngles(cmd->viewangles);
if (config->aimbot[weaponIndex].autoScope && activeWeapon->nextPrimaryAttack() <= memory->globalVars->serverTime() && activeWeapon->isSniperRifle() && !localPlayer->isScoped())
cmd->buttons |= UserCmd::IN_ATTACK2;
if (config->aimbot[weaponIndex].autoShot && activeWeapon->nextPrimaryAttack() <= memory->globalVars->serverTime() && !clamped && activeWeapon->getInaccuracy() <= config->aimbot[weaponIndex].maxShotInaccuracy)
cmd->buttons |= UserCmd::IN_ATTACK;
if (clamped)
cmd->buttons &= ~UserCmd::IN_ATTACK;
if (clamped || config->aimbot[weaponIndex].smooth > 1.0f) lastAngles = cmd->viewangles;
else lastAngles = Vector{ };
lastCommand = cmd->commandNumber;
}
}
}
| 38.683556 | 414 | 0.664706 | [
"vector"
] |
379ac52d07c462ed5f81d3b11397c7552187f055 | 10,836 | cpp | C++ | main.cpp | tom--bo/trees | 9572b923bcccef2e7725ca4eaccbd9aa6b4af732 | [
"MIT"
] | null | null | null | main.cpp | tom--bo/trees | 9572b923bcccef2e7725ca4eaccbd9aa6b4af732 | [
"MIT"
] | 2 | 2020-07-09T14:24:44.000Z | 2020-07-11T16:20:43.000Z | main.cpp | tom--bo/trees | 9572b923bcccef2e7725ca4eaccbd9aa6b4af732 | [
"MIT"
] | null | null | null | #include "bplustree.h"
#include "bstartree.h"
#include "btree.h"
#include <bits/stdc++.h>
#include <unistd.h>
using namespace std;
using namespace std::chrono;
string getTestFilename(int n) {
ios::fmtflags curret_flag = std::cout.flags();
ostringstream ss;
ss << std::setw(3) << std::setfill('0') << n;
string s(ss.str());
s = "tests/data/case_" + s + ".txt";
std::cout.flags(curret_flag);
return s;
}
string getSimpleTestFilename(int n) {
ios::fmtflags curret_flag = std::cout.flags();
ostringstream ss;
ss << std::setw(3) << std::setfill('0') << n;
string s(ss.str());
s = "tests/simple_data/case_" + s + ".txt";
std::cout.flags(curret_flag);
return s;
}
class TestManager {
public:
IndexType index_type;
TestManager(IndexType it) : index_type{it} {};
void exec_benchmark(bool debug, unsigned int lru_capa) {
cout << "=== BENCH START ===" << endl;
vector<int> t = {/*4, 8, 16, 32,*/ 64, 128, 256, 512};
bench(debug, lru_capa, t, 10, 100000, 1000, 100000, 0, 0, 100, 0);
// bench(debug, lru_capa, t, 10, 1000000, 1000, 100000, 0, 0, 90, 10);
// bench(debug, lru_capa, t, 10, 1000000, 1000, 100000, 0, 0, 80, 20);
}
void exec_test(bool debug, unsigned int lru_capa) {
cout << "=== TEST START ===" << endl;
vector<short> t = {2, 5, 10, 100};
for (unsigned int n = 0; n < t.size(); n++) {
int ng = 0;
cout << "T = " << t[n] << " ------------- " << endl;
for (int i = 0; i <= 40; i++) {
string s = getTestFilename(i);
ng += test(debug, lru_capa, s, t[n], i);
}
if (ng == 0) {
cout << "All tests passed!!" << endl;
}
}
}
void exec_simple_test(bool debug, unsigned int lru_capa) {
int ng = 0;
for (int i = 0; i <= 10; i++) {
string s = getSimpleTestFilename(i);
ng += test(debug, lru_capa, s, 2, i);
}
if (ng == 0) {
cout << "All tests passed!!" << endl;
}
}
private:
Indexable *buildTree(IndexType it, short int t, unsigned int lru_capa) {
switch (it) {
case 0:
return new Btree(t, lru_capa);
case 1:
return new Bplustree(t, lru_capa);
case 2:
return new Bstartree(t, lru_capa);
}
}
void bench(bool debug, unsigned int lru_capa, vector<int> vt, int exp_cnt,
unsigned long ope_cnt, unsigned int initial_insert, int mod,
unsigned long select_pct, unsigned long range_pct,
unsigned long insert_pct, unsigned long del_pct) {
printf("\nope_cnt: %lu, mod: %d, lru_capa: %d, select(%%): %lu, range(%%): "
"%lu, "
"insert(%%): %lu, del(%%): %lu\n",
ope_cnt, mod, lru_capa, select_pct, range_pct, insert_pct, del_pct);
cout << " T, Ave_total_time(ms)";
if (debug) {
cout << ", Ave_node_cnt, Ave_inter_node, Ave_leaf_node, Ave_root_keys, "
"Ave_inter_fill_rate, Ave_leaf_fill_rate, Ave_node_merge, "
"Ave_node_split, Ave_tree_height, Cache_hit_rate";
}
cout << endl;
// vector<short int> vt = {2, 4, 8, 16, 32, 64, 128};
for (unsigned int i = 0; i < vt.size(); i++) {
long total_time = 0;
MetricCounter total_mc = MetricCounter();
unsigned key_max;
for (int j = 0; j < exp_cnt; j++) {
// init
Indexable *tree = buildTree(index_type, vt[i], lru_capa);
key_max = tree->get_key_max();
mt19937_64 mt(j);
steady_clock::time_point start = steady_clock::now();
// start benchmark
unsigned short select_ = select_pct;
unsigned short range_ = select_ + range_pct;
unsigned short insert_ = range_ + insert_pct;
if (insert_ + del_pct != 100) {
cout << "select, range, insert, del rate setting is invalid!" << endl;
return;
}
// initial insert
for (unsigned j = 0; j < initial_insert; j++) {
unsigned long d = mt() % mod;
tree->insert(Item{d, j});
}
// operations in experiment
for (unsigned long j = 0; j < ope_cnt; j++) {
unsigned long d1 = mt() % mod;
unsigned long threshold = mt() % 100;
if (threshold < select_) {
tree->search(d1);
} else if (threshold < range_) {
unsigned long d2 = mt() % mod;
if (d1 > d2)
swap(d1, d2);
tree->count_range(d1, d2);
} else if (threshold < insert_) {
tree->insert(Item{d1, j});
} else {
tree->delete_key(d1);
}
}
steady_clock::time_point finish = steady_clock::now();
nanoseconds spent_time = duration_cast<nanoseconds>(finish - start);
long st = spent_time.count();
total_time += st;
tree->update_metric();
MetricCounter mc = tree->get_metrics();
total_mc.node_count += mc.node_count;
total_mc.root_key_count += mc.root_key_count;
total_mc.intermediate_node_cnt += mc.intermediate_node_cnt;
total_mc.intermediate_node_keys_cnt += mc.intermediate_node_keys_cnt;
total_mc.leaf_node_cnt += mc.leaf_node_cnt;
total_mc.leaf_node_keys_cnt += mc.leaf_node_keys_cnt;
total_mc.node_merge += mc.node_merge;
total_mc.node_split += mc.node_split;
total_mc.height += mc.height;
total_mc.cache_checked += mc.cache_checked;
total_mc.cache_hit_cnt += mc.cache_hit_cnt;
// end
// delete tree;
}
long ave_time = total_time / exp_cnt;
printf("%3d, %11ld.%06ld", vt[i], ave_time / 1000000, ave_time % 1000000);
if (debug) {
if (total_mc.cache_checked == 0)
total_mc.cache_checked = 1.0;
printf(
", %12.1f, %14.1f, %13.1f, %13.1f, %19.1f, %18.1f, %14.1f, %18.1f, "
"%15.1f, %10.1f",
total_mc.node_count / exp_cnt,
total_mc.intermediate_node_cnt / exp_cnt,
total_mc.leaf_node_cnt / exp_cnt, total_mc.root_key_count / exp_cnt,
total_mc.intermediate_node_keys_cnt /
total_mc.intermediate_node_cnt / key_max * 100,
total_mc.leaf_node_keys_cnt / total_mc.leaf_node_cnt / key_max *
100,
total_mc.node_merge / exp_cnt, total_mc.node_split / exp_cnt,
total_mc.height / exp_cnt,
total_mc.cache_hit_cnt / total_mc.cache_checked * 100);
}
cout << endl;
}
}
int test(bool debug, unsigned int lru_capa, string filename, short int t,
int num) {
ifstream in(filename);
cin.rdbuf(in.rdbuf());
short int flag;
unsigned long data, i = 0;
unsigned long data_max = 0;
Indexable *tr = buildTree(index_type, t, lru_capa);
auto mp = map<unsigned long, unsigned long>();
while (cin >> flag >> data) {
if (data > data_max)
data_max = data;
i++;
if (flag == 1) { // 1: add
Item item = Item{data, i};
tr->insert(item);
mp[data]++;
} else { // 2: delete
tr->delete_key(data);
if (mp[data] != 0) {
mp[data]--;
}
}
}
// check
vector<Item> c;
tr->tree_walk(&c);
// count function test
for (unsigned long i = 0; i <= data_max; i++) {
if (tr->count(i) != mp[i]) {
cout << "case " << num << " failed: count(" << i << ") is different!"
<< endl;
cout << "expected: " << mp[i] << ", returned: " << tr->count(i) << endl;
return 1;
}
}
// search test
for (unsigned long i = 1; i <= data_max; i++) {
Item a = tr->search(i);
if ((mp[i] > 0 && a.key == 0) || (mp[i] == 0 && a.key > 0)) {
cout << "case " << num << " failed: search(" << i << ") is different!"
<< endl;
cout << "expected: " << (mp[i] != 0)
<< ", returned: " << (tr->search(i).key != 0) << endl;
return 1;
}
}
// count range test
for (unsigned long i = 0; i < 10; i++) {
for (unsigned long j = 30; j < 200; j += 5) {
unsigned long tr_cnt = tr->count_range(i, j);
// count in map
unsigned long mp_cnt = 0;
for (unsigned long k = i; k <= j; k++) {
mp_cnt += mp[k];
}
if (tr_cnt != mp_cnt) {
cout << "tree_cnt: " << tr_cnt << " -- map_cnt: " << mp_cnt << endl;
return 1;
}
}
}
// data check
int diff_from = -1;
int l = c.size();
for (int i = 0; i < l; i++) {
if (diff_from == -1 && mp[c[i].key] <= 0) {
diff_from = i;
break;
}
mp[c[i].key]--;
}
for (auto i = mp.begin(); i != mp.end(); ++i) {
if (i->second != 0) {
cout << "case " << num << " failed: remaining key in map test" << endl;
return 1;
}
}
if (diff_from == -1) {
if (debug) {
cout << "case " << num << " passed!" << endl;
}
} else {
cout << "case " << num << " failed: ";
cout << "different data from " << diff_from << " -- " << endl;
}
return 0;
}
};
int main(int argc, char *argv[]) {
// get options and args
int opt;
bool bench = false, test = false, simple_test = false;
bool debug = false;
unsigned int lru_capa = 0;
while ((opt = getopt(argc, argv, "bdhl:st")) != -1) {
switch (opt) {
case 'b':
bench = true;
break;
case 'd':
debug = true;
break;
case 'l':
lru_capa = stoi(string(optarg));
break;
case 'h':
cout << "./main (-b|-t|-s) [-d] [-l (num)] (b|bp|bs) " << endl;
cout << "-h: help" << endl;
cout << "-t: Execute my test" << endl;
cout << "-s: Execute my simple test" << endl;
cout << "-b: Execute my benchmark" << endl;
cout << "-d: (Debug mode) Print additional info" << endl;
cout << "-l [num]: define LRU cache capacity (node number). If you don't "
"specify this, LRU cache is disabled (Not assumes disk storage)"
<< endl;
return 1;
case 's':
simple_test = true;
break;
case 't':
test = true;
break;
default: /* '?' */
cout << "Plz see help by -h" << endl;
return 1;
}
}
string tree = argv[optind];
IndexType index_type = B;
if (tree == "b") {
index_type = B;
cout << "<< B tree >>" << endl;
} else if (tree == "bp") {
index_type = B_PLUS;
cout << "<< Bplus tree >>" << endl;
} else if (tree == "bs") {
index_type = B_STAR;
cout << "<< Bstar tree >>" << endl;
} else {
cout << "No index type specified!!" << endl;
return 1;
}
auto tm = TestManager(index_type);
if (simple_test)
tm.exec_simple_test(debug, lru_capa);
if (test)
tm.exec_test(debug, lru_capa);
if (bench)
tm.exec_benchmark(debug, lru_capa);
return 0;
}
| 30.610169 | 80 | 0.529808 | [
"vector",
"3d"
] |
379b442878e9704423bd4ecd1f6090f6a3b6c7af | 430 | cpp | C++ | atc/abc234/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | 3 | 2022-03-30T14:14:57.000Z | 2022-03-31T04:30:32.000Z | atc/abc234/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | atc/abc234/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
typedef long long ll;
using namespace std;
vector<int> ve;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
//IO
ll k;
cin >> k;
ll a = 1;
while (a <= k) {
ve.push_back(((k & a) ? 2 : 0));
a <<= 1;
}
reverse(ve.begin(), ve.end());
for (auto v : ve)
cout << v;
return 0;
}
//19:14.17
| 13.4375 | 41 | 0.502326 | [
"vector"
] |
37adbcf4080230e08a89b4a74c459fa7d653a9f3 | 8,524 | cpp | C++ | src/geometry/CTiglPointsToBSplineInterpolation.cpp | cfsengineering/tigl | abfbb57b82dc6beac7cde212a4cd5e0aed866db8 | [
"Apache-2.0"
] | 171 | 2015-04-13T11:24:34.000Z | 2022-03-26T00:56:38.000Z | src/geometry/CTiglPointsToBSplineInterpolation.cpp | cfsengineering/tigl | abfbb57b82dc6beac7cde212a4cd5e0aed866db8 | [
"Apache-2.0"
] | 620 | 2015-01-20T08:34:36.000Z | 2022-03-30T11:05:33.000Z | src/geometry/CTiglPointsToBSplineInterpolation.cpp | cfsengineering/tigl | abfbb57b82dc6beac7cde212a4cd5e0aed866db8 | [
"Apache-2.0"
] | 56 | 2015-02-09T13:33:56.000Z | 2022-03-19T04:52:51.000Z | /*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-08-06 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglPointsToBSplineInterpolation.h"
#include "CTiglError.h"
#include "CTiglBSplineAlgorithms.h"
#include <BSplCLib.hxx>
#include <math_Gauss.hxx>
#include <GeomConvert.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <algorithm>
#include <cassert>
namespace
{
Handle(TColStd_HArray1OfReal) toArray(const std::vector<double>& vector)
{
Handle(TColStd_HArray1OfReal) array = new TColStd_HArray1OfReal(1, static_cast<int>(vector.size()));
int ipos = 1;
for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); ++it, ipos++) {
array->SetValue(ipos, *it);
}
return array;
}
void clamp(Handle(Geom_BSplineCurve) & curve, double min, double max)
{
Handle(Geom_Curve) c = new Geom_TrimmedCurve(curve, min, max);
curve = GeomConvert::CurveToBSplineCurve(c);
}
} // namespace
namespace tigl
{
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_degree(static_cast<int>(maxDegree))
, m_C2Continuous(continuousIfClosed)
{
m_params = CTiglBSplineAlgorithms::computeParamsBSplineCurve(points);
if (maxDegree < 1) {
throw CTiglError("Degree must be larger than 1 in CTiglPointsToBSplineInterpolation!");
}
if (points.IsNull()) {
throw CTiglError("No points given in CTiglPointsToBSplineInterpolation", TIGL_NULL_POINTER);
}
if (points->Length() < 2) {
throw CTiglError("Too few points in CTiglPointsToBSplineInterpolation", TIGL_MATH_ERROR);
}
}
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
const std::vector<double>& parameters,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_params(parameters)
, m_degree(static_cast<int>(maxDegree))
, m_C2Continuous(continuousIfClosed)
{
if (static_cast<int>(m_params.size()) != m_pnts->Length()) {
throw CTiglError("Number of parameters and points don't match in CTiglPointsToBSplineInterpolation");
}
if (maxDegree < 1) {
throw CTiglError("Degree must be larger than 1 in CTiglPointsToBSplineInterpolation!");
}
if (points.IsNull()) {
throw CTiglError("No points given in CTiglPointsToBSplineInterpolation", TIGL_NULL_POINTER);
}
if (points->Length() < 2) {
throw CTiglError("Too few points in CTiglPointsToBSplineInterpolation", TIGL_MATH_ERROR);
}
}
Handle(Geom_BSplineCurve) CTiglPointsToBSplineInterpolation::Curve() const
{
int degree = static_cast<int>(Degree());
std::vector<double> params = m_params;
std::vector<double> knots =
CTiglBSplineAlgorithms::knotsFromCurveParameters(params, static_cast<unsigned int>(degree), isClosed());
if (isClosed()) {
// we remove the last parameter, since it is implicitly
// included by wrapping the control points
params.pop_back();
}
math_Matrix bsplMat =
CTiglBSplineAlgorithms::bsplineBasisMat(degree, toArray(knots)->Array1(), toArray(params)->Array1());
// build left hand side of the linear system
int nParams = static_cast<int>(params.size());
math_Matrix lhs(1, nParams, 1, nParams, 0.);
for (int iCol = 1; iCol <= nParams; ++iCol) {
lhs.SetCol(iCol, bsplMat.Col(iCol));
}
if (isClosed()) {
// sets the continuity constraints for closed curves on the left hand side if requested
// by wrapping around the control points
// This is a trick to make the matrix square and enforce the endpoint conditions
for (int iCol = 1; iCol <= degree; ++iCol) {
lhs.SetCol(iCol, lhs.Col(iCol) + bsplMat.Col(nParams + iCol));
}
}
// right hand side
math_Vector rhsx(1, nParams, 0.);
math_Vector rhsy(1, nParams, 0.);
math_Vector rhsz(1, nParams, 0.);
for (int i = 1; i <= nParams; ++i) {
const gp_Pnt& p = m_pnts->Value(i);
rhsx(i) = p.X();
rhsy(i) = p.Y();
rhsz(i) = p.Z();
}
math_Gauss solver(lhs);
math_Vector cp_x(1, nParams);
math_Vector cp_y(1, nParams);
math_Vector cp_z(1, nParams);
solver.Solve(rhsx, cp_x);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsy, cp_y);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsz, cp_z);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
int nCtrPnts = static_cast<int>(m_params.size());
if (isClosed()) {
nCtrPnts += degree - 1;
}
if (needsShifting()) {
nCtrPnts += 1;
}
TColgp_Array1OfPnt poles(1, nCtrPnts);
for (Standard_Integer icp = 1; icp <= nParams; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(icp, pnt);
}
if (isClosed()) {
// wrap control points
for (Standard_Integer icp = 1; icp <= degree; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(nParams + icp, pnt);
}
}
if (needsShifting()) {
// add a new control point and knot
size_t deg = static_cast<size_t>(degree);
knots.push_back(knots.back() + knots[2 * deg + 1] - knots[2 * deg]);
poles.SetValue(nParams + degree + 1, poles.Value(degree + 1));
// shift back the knots
for (size_t iknot = 0; iknot < knots.size(); ++iknot) {
knots[iknot] -= params[0];
}
}
Handle(TColStd_HArray1OfReal) occFlatKnots = toArray(knots);
int knotsLen = BSplCLib::KnotsLength(occFlatKnots->Array1());
TColStd_Array1OfReal occKnots(1, knotsLen);
TColStd_Array1OfInteger occMults(1, knotsLen);
BSplCLib::Knots(occFlatKnots->Array1(), occKnots, occMults);
Handle(Geom_BSplineCurve) result = new Geom_BSplineCurve(poles, occKnots, occMults, degree, false);
// clamp bspline
if (isClosed()) {
clamp(result, m_params.front(), m_params.back());
}
return result;
}
double CTiglPointsToBSplineInterpolation::maxDistanceOfBoundingBox(const TColgp_Array1OfPnt& points) const
{
double maxDistance = 0.;
for (int i = points.Lower(); i <= points.Upper(); ++i) {
for (int j = points.Lower(); j <= points.Upper(); ++j) {
double dist = points.Value(i).Distance(points.Value(j));
maxDistance = std::max(maxDistance, dist);
}
}
return maxDistance;
}
bool CTiglPointsToBSplineInterpolation::isClosed() const
{
double maxDistance = maxDistanceOfBoundingBox(m_pnts->Array1());
double error = 1e-6 * maxDistance;
return m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), error) && m_C2Continuous;
}
bool CTiglPointsToBSplineInterpolation::needsShifting() const
{
return (Degree() % 2) == 0 && isClosed();
}
CTiglPointsToBSplineInterpolation::operator Handle(Geom_BSplineCurve)() const
{
return Curve();
}
const std::vector<double>& CTiglPointsToBSplineInterpolation::Parameters() const
{
return m_params;
}
unsigned int CTiglPointsToBSplineInterpolation::Degree() const
{
int maxDegree = m_pnts->Length() - 1;
if (isClosed()) {
maxDegree -= 1;
}
int degree = std::min(maxDegree, m_degree);
assert(degree > 0);
return static_cast<unsigned int>(degree);
}
} // namespace tigl
| 32.166038 | 117 | 0.643008 | [
"vector"
] |
37af62c30422c1c41904676e493a3139cb696758 | 3,704 | cpp | C++ | Registry/WorldMapRegistry.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | Registry/WorldMapRegistry.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | Registry/WorldMapRegistry.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// WorldMapRegistry.cpp
// Implementation of the Class WorldMapRegistry
// Created on: 28-mar-2008 10:36:13
// Original author: Lukas Kalinski
///////////////////////////////////////////////////////////
#include "WorldMapRegistry.h"
#include "World.h"
#include "WrapBoundaryStrategy.h"
#include "Coord2d.h"
#include "Planet.h"
#include "SpawnPoint.h"
#include "FuelItem.h"
#include <iostream>
#include <fstream>
#include <sstream>
WorldMapRegistry* WorldMapRegistry::m_singleton = 0;
WorldMapRegistry::~WorldMapRegistry() {
}
WorldMapRegistry::WorldMapRegistry(const WorldMapRegistry& registry) {
throw std::exception("WorldMapRegistry.cpp: Copy constructor called.");
}
/**
* Constructs a world map registry instance.
*/
WorldMapRegistry::WorldMapRegistry() {
}
/**
* Generates a game world instance from a given map name.
*/
World WorldMapRegistry::generateFromMap(const std::string& mapName) const {
// Open map file:
std::ifstream ff(mapName.c_str(), std::ios_base::in);
// Read a map from a file:
if (ff.is_open()) {
std::string line;
std::string token;
// First line is special and contains the world coordinates:
float world_x_coord, world_y_coord;
ff >> world_x_coord >> world_y_coord;
World world(Coord2d(0.0f, 0.0f), Coord2d(world_x_coord, world_y_coord));
WorldObjectsManager & wom = world.getWorldObjectsManager();
// For each line...
while (!ff.eof()) {
getline(ff, line);
std::stringstream ss(line); // Insert the string into a stream
std::vector<std::string> line_tokens;
// For each token in line...
for(int i=0; !ss.eof(); ++i) {
ss >> token;
line_tokens.push_back(token);
}
if(std::string("PLANET") == line_tokens[0]) {
float mass, radius, x_coord, y_coord;
Planet::planet_t planet_type;
// mass, radius, type x y
// Planet(550.0, 140.0, Planet::EARTH), Coord2d(2500.0, 2500.0)
sscanf_s(line_tokens[1].c_str(), "%f", &mass);
sscanf_s(line_tokens[2].c_str(), "%f", &radius);
sscanf_s(line_tokens[3].c_str(), "%d", &planet_type);
sscanf_s(line_tokens[4].c_str(), "%f", &x_coord);
sscanf_s(line_tokens[5].c_str(), "%f", &y_coord);
wom.insert(Planet(mass, radius, planet_type), Coord2d(x_coord, y_coord));
} else if(std::string("SPAWNPOINT") == line_tokens[0]) {
float x_coord, y_coord;
sscanf_s(line_tokens[1].c_str(), "%f", &x_coord);
sscanf_s(line_tokens[2].c_str(), "%f", &y_coord);
//wom.insert(SpawnPoint(), Coord2d(3500.0, 3500.0));
wom.insert(SpawnPoint(), Coord2d(x_coord, y_coord));
} else if(std::string("FUEL") == line_tokens[0]) {
float x_coord, y_coord;
unsigned int fuel_amount;
sscanf_s(line_tokens[1].c_str(), "%f", &x_coord);
sscanf_s(line_tokens[2].c_str(), "%f", &y_coord);
sscanf_s(line_tokens[3].c_str(), "%d", &fuel_amount);
wom.insert(FuelItem(fuel_amount), Coord2d(x_coord, y_coord));
}
}
ff.close();
return world;
} else {
throw std::exception("WorldMapRegistry::readFromMapFile(): Error opening map file.");
}
}
/**
* Returns an iterator of strings containing the names of all available maps.
*/
std::vector<std::string>::iterator WorldMapRegistry::getMaps() {
std::vector<std::string> v;
v.push_back("Map 1");
return v.begin();
}
/**
* Returns the singleton instance of the world map registry.
*/
WorldMapRegistry* WorldMapRegistry::instance() {
if (!m_singleton) {
m_singleton = new WorldMapRegistry();
}
return m_singleton;
} | 28.492308 | 88 | 0.62527 | [
"vector"
] |
37b09113bc528fe5cd030700345d81c5e6cb78a7 | 778 | cpp | C++ | 1-Introduction/1.3-Getting_Started_The_Easy_Problems/3-Medium/EdyJunior/11507.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | 1 | 2017-11-16T10:56:17.000Z | 2017-11-16T10:56:17.000Z | 1-Introduction/1.3-Getting_Started_The_Easy_Problems/3-Medium/EdyJunior/11507.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | null | null | null | 1-Introduction/1.3-Getting_Started_The_Easy_Problems/3-Medium/EdyJunior/11507.cpp | IFCE-CP/CP3-solutions | 1abcabd9a06968184a55d3b0414637019014694c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main() {
string str, pos;
int l;
vector <vector<string>> s;
string v[] = { "+x", "-x", "+y", "-y", "+z", "-z" };
s.push_back({ "+y", "-y", "+z", "-z" });
s.push_back({ "-y", "+y", "-z", "+z" });
s.push_back({ "-x", "+x", "+y", "+y" });
s.push_back({ "+x", "-x", "-y", "-y" });
s.push_back({ "+z", "+z", "-x", "+x" });
s.push_back({ "-z", "-z", "+x", "-x" });
while (cin >> l && l) {
pos = "+x";
while (--l) {
cin >> str;
if (str == "No") { continue; }
int ind = 0;
for (int i = 0; i < 6; i++)
if (v[i] == str) { ind = i; }
ind -= 2;
int indC = 0;
for (int i = 0; i < 6; i++)
if (v[i] == pos) { indC = i; }
pos = s[indC][ind];
}
cout << pos << "\n";
}
return 0;
} | 19.45 | 53 | 0.38946 | [
"vector"
] |
37b4a52f0b0c35ed53b9e84be9d458e38cc1c483 | 8,637 | cpp | C++ | src/libcore/python/struct.cpp | tizian/layer-laboratory | 008cc94b76127e9eb74227fcd3d0145da8ddec30 | [
"CNRI-Python"
] | 7 | 2020-07-24T03:19:59.000Z | 2022-03-30T10:56:12.000Z | src/libcore/python/struct.cpp | tizian/layer-laboratory | 008cc94b76127e9eb74227fcd3d0145da8ddec30 | [
"CNRI-Python"
] | 1 | 2021-04-07T22:30:23.000Z | 2021-04-08T00:55:36.000Z | src/libcore/python/struct.cpp | tizian/layer-laboratory | 008cc94b76127e9eb74227fcd3d0145da8ddec30 | [
"CNRI-Python"
] | 2 | 2020-06-08T08:25:09.000Z | 2021-04-05T22:13:08.000Z | #include <mitsuba/core/struct.h>
#include <mitsuba/core/simd.h>
#include <mitsuba/core/logger.h>
#include <mitsuba/python/python.h>
#include <pybind11/numpy.h>
/// Conversion between 'Struct' and NumPy 'dtype' data structures
py::dtype dtype_for_struct(const Struct *s) {
py::list names, offsets, formats;
for (auto field: *s) {
names.append(py::str(field.name));
offsets.append(py::int_(field.offset));
std::string format;
switch (field.type) {
case Struct::Type::Int8: format = "int8"; break;
case Struct::Type::UInt8: format = "uint8"; break;
case Struct::Type::Int16: format = "int16"; break;
case Struct::Type::UInt16: format = "uint16"; break;
case Struct::Type::Int32: format = "int32"; break;
case Struct::Type::UInt32: format = "uint32"; break;
case Struct::Type::Int64: format = "int64"; break;
case Struct::Type::UInt64: format = "uint64"; break;
case Struct::Type::Float16: format = "float16"; break;
case Struct::Type::Float32: format = "float32"; break;
case Struct::Type::Float64: format = "float64"; break;
case Struct::Type::Invalid: format = "invalid"; break;
default: Throw("Internal error.");
}
formats.append(py::str(format));
}
return py::dtype(names, formats, offsets, s->size());
}
MTS_PY_EXPORT(Struct) {
auto c = MTS_PY_CLASS(Struct, Object);
py::class_<Struct::Field> field(c, "Field", D(Struct, Field));
py::enum_<Struct::Type>(c, "Type")
.value("Int8", Struct::Type::Int8, D(Struct, Type, Int8))
.value("UInt8", Struct::Type::UInt8, D(Struct, Type, UInt8))
.value("Int16", Struct::Type::Int16, D(Struct, Type, Int16))
.value("UInt16", Struct::Type::UInt16, D(Struct, Type, UInt16))
.value("Int32", Struct::Type::Int32, D(Struct, Type, Int32))
.value("UInt32", Struct::Type::UInt32, D(Struct, Type, UInt32))
.value("Int64", Struct::Type::Int64, D(Struct, Type, Int64))
.value("UInt64", Struct::Type::UInt64, D(Struct, Type, UInt64))
.value("Float16", Struct::Type::Float16, D(Struct, Type, Float16))
.value("Float32", Struct::Type::Float32, D(Struct, Type, Float32))
.value("Float64", Struct::Type::Float64, D(Struct, Type, Float64))
.value("Invalid", Struct::Type::Invalid, D(Struct, Type, Invalid))
.def(py::init([](py::dtype dt) {
Struct::Type value = Struct::Type::Int8;
if (dt.kind() == 'i') {
switch (dt.itemsize()) {
case 1: value = Struct::Type::Int8; break;
case 2: value = Struct::Type::Int16; break;
case 4: value = Struct::Type::Int32; break;
case 8: value = Struct::Type::Int64; break;
default: throw py::type_error("Struct::Type(): Invalid integer type!");
}
} else if (dt.kind() == 'u') {
switch (dt.itemsize()) {
case 1: value = Struct::Type::UInt8; break;
case 2: value = Struct::Type::UInt16; break;
case 4: value = Struct::Type::UInt32; break;
case 8: value = Struct::Type::UInt64; break;
default: throw py::type_error("Struct::Type(): Invalid unsigned integer type!");
}
} else if (dt.kind() == 'f') {
switch (dt.itemsize()) {
case 2: value = Struct::Type::Float16; break;
case 4: value = Struct::Type::Float32; break;
case 8: value = Struct::Type::Float64; break;
default: throw py::type_error("Struct::Type(): Invalid floating point type!");
}
} else {
throw py::type_error("Struct::Type(): Invalid type!");
}
return new Struct::Type(value);
}), "dtype"_a);
py::implicitly_convertible<py::dtype, Struct::Type>();
py::enum_<Struct::Flags>(c, "Flags", py::arithmetic())
.value("Normalized", Struct::Flags::Normalized, D(Struct, Flags, Normalized))
.value("Gamma", Struct::Flags::Gamma, D(Struct, Flags, Gamma))
.value("Weight", Struct::Flags::Weight, D(Struct, Flags, Weight))
.value("Assert", Struct::Flags::Assert, D(Struct, Flags, Assert))
.value("Alpha", Struct::Flags::Alpha, D(Struct, Flags, Alpha))
.value("PremultipliedAlpha", Struct::Flags::PremultipliedAlpha, D(Struct, Flags, PremultipliedAlpha))
.value("Default", Struct::Flags::Default, D(Struct, Flags, Default))
.def(py::self | py::self)
.def(int() | py::self)
.def(int() & py::self);
py::enum_<Struct::ByteOrder>(c, "ByteOrder")
.value("LittleEndian", Struct::ByteOrder::LittleEndian,
D(Struct, ByteOrder, LittleEndian))
.value("BigEndian", Struct::ByteOrder::BigEndian,
D(Struct, ByteOrder, BigEndian))
.value("HostByteOrder", Struct::ByteOrder::HostByteOrder,
D(Struct, ByteOrder, HostByteOrder));
c.def(py::init<bool, Struct::ByteOrder>(), "pack"_a = false,
"byte_order"_a = Struct::ByteOrder::HostByteOrder,
D(Struct, Struct))
.def("append",
(Struct &(Struct::*)(const std::string&, Struct::Type, uint32_t, double)) &Struct::append,
"name"_a, "type"_a, "flags"_a = Struct::Flags::None, "default"_a = 0.0,
D(Struct, append), py::return_value_policy::reference)
.def("field", py::overload_cast<const std::string &>(&Struct::field), D(Struct, field),
py::return_value_policy::reference_internal)
.def("__getitem__", [](Struct &s, size_t i) -> Struct::Field& {
if (i >= s.field_count())
throw py::index_error();
return s[i];
}, py::return_value_policy::reference_internal)
.def("__len__", &Struct::field_count)
.def(py::self == py::self)
.def(py::self != py::self)
.def("__hash__", [](const Struct &s) { return hash(s); })
.def_method(Struct, size)
.def_method(Struct, alignment)
.def_method(Struct, byte_order)
.def_method(Struct, field_count)
.def_method(Struct, has_field)
.def_static("is_float", &Struct::is_float, D(Struct, is_float))
.def_static("is_integer", &Struct::is_integer, D(Struct, is_integer))
.def_static("is_signed", &Struct::is_signed, D(Struct, is_signed))
.def_static("is_unsigned", &Struct::is_unsigned, D(Struct, is_unsigned))
.def_static("range", &Struct::range, D(Struct, range))
.def("dtype", &dtype_for_struct, "Return a NumPy dtype corresponding to this data structure");
field.def("is_float", &Struct::Field::is_float, D(Struct, Field, is_float))
.def("is_integer", &Struct::Field::is_integer, D(Struct, Field, is_integer))
.def("is_signed", &Struct::Field::is_signed, D(Struct, Field, is_signed))
.def("is_unsigned", &Struct::Field::is_unsigned, D(Struct, Field, is_unsigned))
.def("range", &Struct::Field::range, D(Struct, Field, range))
.def(py::self == py::self)
.def(py::self != py::self)
.def("__hash__", [](const Struct::Field &f) { return hash(f); })
.def_readwrite("type", &Struct::Field::type, D(Struct, Field, type))
.def_readwrite("size", &Struct::Field::size, D(Struct, Field, size))
.def_readwrite("offset", &Struct::Field::offset, D(Struct, Field, offset))
.def_readwrite("flags", &Struct::Field::flags, D(Struct, Field, flags))
.def_readwrite("name", &Struct::Field::name, D(Struct, Field, name))
.def_readwrite("blend", &Struct::Field::blend, D(Struct, Field, blend));
MTS_PY_CLASS(StructConverter, Object)
.def(py::init<const Struct *, const Struct *, bool>(), "source"_a, "target"_a, "dither"_a = false)
.def_method(StructConverter, source)
.def_method(StructConverter, target)
.def("convert", [](const StructConverter &c, py::bytes input_) -> py::bytes {
std::string input(input_);
size_t count = input.length() / c.source()->size();
std::string result(c.target()->size() * count, '\0');
if (!c.convert(count, input.data(), (void *) result.data()))
throw std::runtime_error("Conversion failed!");
return result;
});
}
| 52.98773 | 114 | 0.572074 | [
"object"
] |
37b5f3ea891a6b22c173202d8bea29c469838935 | 6,864 | hpp | C++ | include/etl/impl/egblas/clip_value.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 210 | 2015-02-13T11:40:45.000Z | 2022-01-21T21:46:42.000Z | include/etl/impl/egblas/clip_value.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 5 | 2017-01-31T18:12:48.000Z | 2020-07-16T15:18:00.000Z | include/etl/impl/egblas/clip_value.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 25 | 2016-11-26T16:32:56.000Z | 2021-07-20T02:08:51.000Z | //=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief EGBLAS wrappers for the clip_value operation.
*/
#pragma once
#ifdef ETL_EGBLAS_MODE
#include "etl/impl/cublas/cuda.hpp"
#include "etl/util/complex_cast.hpp"
#include "etl/util/safe_cast.hpp"
#include <egblas.hpp>
#endif
namespace etl::impl::egblas {
/*!
* \brief Indicates if EGBLAS has single-precision clip_value.
*/
#ifdef EGBLAS_HAS_SCLIP_VALUE
static constexpr bool has_sclip_value = true;
#else
static constexpr bool has_sclip_value = false;
#endif
/*!
* \brief Wrappers for single-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] const float alpha,
[[maybe_unused]] float A,
[[maybe_unused]] float B,
[[maybe_unused]] float* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_SCLIP_VALUE
inc_counter("egblas");
egblas_sclip_value(n, alpha, A, B, C, ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
/*!
* \brief Indicates if EGBLAS has double-precision clip_value.
*/
#ifdef EGBLAS_HAS_DCLIP_VALUE
static constexpr bool has_dclip_value = true;
#else
static constexpr bool has_dclip_value = false;
#endif
/*!
* \brief Wrappers for double-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] double alpha,
[[maybe_unused]] double A,
[[maybe_unused]] double B,
[[maybe_unused]] double* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_DCLIP_VALUE
inc_counter("egblas");
egblas_dclip_value(n, alpha, A, B, C, ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
/*!
* \brief Indicates if EGBLAS has complex single-precision clip_value.
*/
#ifdef EGBLAS_HAS_CCLIP_VALUE
static constexpr bool has_cclip_value = true;
#else
static constexpr bool has_cclip_value = false;
#endif
/*!
* \brief Wrappers for complex single-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] const std::complex<float> alpha,
[[maybe_unused]] std::complex<float> A,
[[maybe_unused]] std::complex<float> B,
[[maybe_unused]] std::complex<float>* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_CCLIP_VALUE
inc_counter("egblas");
egblas_cclip_value(n, complex_cast(alpha), complex_cast(A), complex_cast(B), reinterpret_cast<cuComplex*>(C), ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
/*!
* \brief Wrappers for complex single-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] const etl::complex<float> alpha,
[[maybe_unused]] etl::complex<float> A,
[[maybe_unused]] etl::complex<float> B,
[[maybe_unused]] etl::complex<float>* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_CCLIP_VALUE
inc_counter("egblas");
egblas_cclip_value(n, complex_cast(alpha), complex_cast(A), complex_cast(B), reinterpret_cast<cuComplex*>(C), ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
/*!
* \brief Indicates if EGBLAS has complex double-precision clip_value.
*/
#ifdef EGBLAS_HAS_ZCLIP_VALUE
static constexpr bool has_zclip_value = true;
#else
static constexpr bool has_zclip_value = false;
#endif
/*!
* \brief Wrappers for complex double-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] const std::complex<double> alpha,
[[maybe_unused]] std::complex<double> A,
[[maybe_unused]] std::complex<double> B,
[[maybe_unused]] std::complex<double>* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_ZCLIP_VALUE
inc_counter("egblas");
egblas_zclip_value(n, complex_cast(alpha), complex_cast(A), complex_cast(B), reinterpret_cast<cuDoubleComplex*>(C), ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
/*!
* \brief Wrappers for complex double-precision egblas clip_value operation
* \param n The size of the vector
* \param alpha The scaling factor alpha
* \param A The memory of the vector a
* \param B The memory of the vector b
* \param C The memory of the vector c
* \param ldc The leading dimension of c
*/
inline void clip_value([[maybe_unused]] size_t n,
[[maybe_unused]] const etl::complex<double> alpha,
[[maybe_unused]] etl::complex<double> A,
[[maybe_unused]] etl::complex<double> B,
[[maybe_unused]] etl::complex<double>* C,
[[maybe_unused]] size_t ldc) {
#ifdef EGBLAS_HAS_ZCLIP_VALUE
inc_counter("egblas");
egblas_zclip_value(n, complex_cast(alpha), complex_cast(A), complex_cast(B), reinterpret_cast<cuDoubleComplex*>(C), ldc);
#else
cpp_unreachable("Invalid call to egblas::clip_value");
#endif
}
} //end of namespace etl::impl::egblas
| 33.980198 | 125 | 0.643794 | [
"vector"
] |
37b82466cc43d3e94aa1324a3f2a8c52159ee68f | 6,074 | cpp | C++ | t2s/src/SliceExprTree.cpp | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 24 | 2021-09-02T22:54:51.000Z | 2022-01-27T19:28:04.000Z | t2s/src/SliceExprTree.cpp | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 5 | 2021-11-08T20:10:11.000Z | 2022-03-08T01:12:57.000Z | t2s/src/SliceExprTree.cpp | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 8 | 2021-09-06T21:07:02.000Z | 2022-03-10T01:54:48.000Z | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* Licensed under the BSD-2-Clause Plus Patent License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSDplusPatent
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*******************************************************************************/
#include "./SliceExprTree.h"
#include "./DebugPrint.h"
#include "../../Halide/src/IREquality.h"
#include "../../Halide/src/IROperator.h"
#include <sstream>
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
// We do not match IntImm, UIntImm, FloatImm, StringImm, Variable, statements,
// or any Expr that a user cannot specify in the source code (e.g. Load, Store,
// Provide, Let, etc.) However, we may use IRVisitor to match their sub-expressions.
// Match an expression. Only one place is allowed to be matched.
template<typename T>
void SliceExprTree::match_expr(const T* op) {
debug(4) << "SliceExprTree: visiting Expr " << Internal::to_string(Expr(op)) << "\n";
if (expr_to_match.defined() && equal(expr_to_match, op)) {
user_assert(!matched_operand.defined())
<< error_msg_header << "Multiple matches for the expression "
<< expr_to_match << "\n";
matched_operand = op;
}
}
// Commonly, we try to match an expression. No matter it matches or not, we will
// continue to match the sub-expressions: even if a match already happens, we
// would like to check that there is only 1 match in the entire tree.
void SliceExprTree::visit(const Add *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Sub *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Mul *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Div *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Mod *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Min *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Max *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const EQ *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const NE *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const LT *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const LE *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const GT *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const GE *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const And *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Or *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Not *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Load *op) { match_expr(op); IRVisitor::visit(op); }
void SliceExprTree::visit(const Select *op) {
match_expr(op);
Expr old_condition = condition;
if (matched_operand.defined()) {
// We cannot change the matched operand, nor the condition leading to it.
// We just want to check that the sub-expressions do not have another match.
IRVisitor::visit(op);
} else {
condition = old_condition.defined() ? old_condition && op->condition : op->condition;
op->true_value.accept(this);
if (matched_operand.defined()) {
// Check that the false value does not have another match.
if (op->false_value.defined()) {
op->false_value.accept(this);
}
} else {
condition = old_condition.defined() ? old_condition && !op->condition : !op->condition;
if (op->false_value.defined()) {
op->false_value.accept(this);
if (!matched_operand.defined()) {
// Recover the original condition
condition = old_condition;
}
}
}
// Check that the Select's condition does not have a match
op->condition.accept(this);
}
}
void SliceExprTree::visit(const Call *op) {
debug(4) << "SliceExprTree: visiting call " << Internal::to_string(Expr(op)) << "\n";
if (func_to_match != "") {
if (op->name == func_to_match) {
user_assert(!matched_operand.defined())
<< error_msg_header << "Multiple matches for calling Func "
<< func_to_match << "\n";
matched_operand = op;
}
} else {
match_expr(op);
}
IRVisitor::visit(op);
}
void SliceExprTree::visit(const Let *op) {
if (!matched_operand.defined()) {
lets.push_back(op);
// No match_expr(op) because user cannot specify a Let Expr in source code.
IRVisitor::visit(op);
if (!matched_operand.defined()) {
lets.pop_back();
}
} else {
// Just check the sub_expressions does not have another match
IRVisitor::visit(op);
}
}
std::string SliceExprTree::to_string() const {
if (!matched_operand.defined()) {
return "No slice found";
} else {
Expr e = matched_operand;
for (size_t j = 0; j < lets.size(); j++) {
e = Let::make(lets[j]->name, lets[j]->value, e);
}
std::ostringstream s;
s << "Select(" << condition << ", " << e << ")";
return s.str();
}
}
}
};
| 41.889655 | 100 | 0.614257 | [
"vector"
] |
37c0d13634200b2d16aebc2365f83c27129db93b | 15,570 | cpp | C++ | src/server/services/transfers/ReuseTransfersService.cpp | cern-fts/fts3 | cf9eb5c9f52728929965edf58a86381eec0c4e88 | [
"Apache-2.0"
] | 9 | 2018-06-27T09:53:51.000Z | 2021-01-19T09:54:37.000Z | src/server/services/transfers/ReuseTransfersService.cpp | cern-fts/fts3 | cf9eb5c9f52728929965edf58a86381eec0c4e88 | [
"Apache-2.0"
] | null | null | null | src/server/services/transfers/ReuseTransfersService.cpp | cern-fts/fts3 | cf9eb5c9f52728929965edf58a86381eec0c4e88 | [
"Apache-2.0"
] | 3 | 2018-07-13T06:17:44.000Z | 2021-07-08T04:57:04.000Z | /*
* Copyright (c) CERN 2013-2015
*
* Copyright (c) Members of the EMI Collaboration. 2010-2013
* See http://www.eu-emi.eu/partners for details on the copyright
* holders.
*
* 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 "ReuseTransfersService.h"
#include <fstream>
#include "common/DaemonTools.h"
#include "config/ServerConfig.h"
#include "cred/DelegCred.h"
#include "ExecuteProcess.h"
#include "server/DrainMode.h"
#include "SingleTrStateInstance.h"
#include "CloudStorageConfig.h"
#include "ThreadSafeList.h"
#include "VoShares.h"
using namespace fts3::common;
using fts3::config::ServerConfig;
namespace fts3 {
namespace server {
extern time_t retrieveRecords;
ReuseTransfersService::ReuseTransfersService()
{
setServiceName("ReuseTransfersService");
}
void ReuseTransfersService::runService()
{
while (!boost::this_thread::interruption_requested())
{
retrieveRecords = time(0);
try
{
boost::this_thread::sleep(schedulingInterval);
if (DrainMode::instance())
{
FTS3_COMMON_LOGGER_NEWLOG(INFO)
<< "Set to drain mode, no more transfers for this instance!"
<< commit;
boost::this_thread::sleep(boost::posix_time::seconds(15));
continue;
}
executeUrlcopy();
}
catch (boost::thread_interrupted&)
{
FTS3_COMMON_LOGGER_NEWLOG(INFO) << "Thread interruption requested" << commit;
break;
}
catch (std::exception& e)
{
FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService " << e.what() << commit;
}
catch (...)
{
FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService!" << commit;
}
}
}
void ReuseTransfersService::writeJobFile(const std::string& jobId, const std::vector<std::string>& files)
{
std::ofstream fout;
try
{
std::vector<std::string>::const_iterator iter;
std::string filename = ServerConfig::instance().get<std::string>("MessagingDirectory") + "/" + jobId;
fout.open(filename.c_str(), std::ios::out);
for (iter = files.begin(); iter != files.end(); ++iter)
{
fout << *iter << std::endl;
}
}
catch (...)
{
// pass
}
}
std::map<uint64_t, std::string> ReuseTransfersService::generateJobFile(
const std::string& jobId, const std::list<TransferFile>& files)
{
std::vector<std::string> urls;
std::map<uint64_t, std::string> fileIds;
std::ostringstream line;
for (auto it = files.begin(); it != files.end(); ++it)
{
fileIds.insert(std::make_pair(it->fileId, it->jobId));
std::string fileMetadata = UrlCopyCmd::prepareMetadataString(
it->fileMetadata);
if (fileMetadata.empty())
fileMetadata = "x";
std::string bringOnlineToken = it->bringOnlineToken;
if (bringOnlineToken.empty())
bringOnlineToken = "x";
std::string checksum = it->checksum;
if (checksum.empty())
checksum = "x";
line << std::fixed << it->fileId << " " << it->sourceSurl << " "
<< it->destSurl << " " << checksum << " "
<< boost::lexical_cast<long long>(it->userFilesize) << " "
<< fileMetadata << " " << bringOnlineToken;
urls.push_back(line.str());
line.str(std::string());
}
writeJobFile(jobId, urls);
return fileIds;
}
void ReuseTransfersService::getFiles(const std::vector<QueueId>& queues, int availableUrlCopySlots)
{
auto db = DBSingleton::instance().getDBObjectInstance();
//now get files to be scheduled
std::map<std::string, std::queue<std::pair<std::string, std::list<TransferFile> > > > voQueues;
db->getReadySessionReuseTransfers(queues, voQueues);
std::map<std::string, int> slotsLeftForSource, slotsLeftForDestination;
for (auto i = queues.begin(); i != queues.end(); ++i) {
// To reduce queries, fill in one go limits as source and as destination
if (slotsLeftForDestination.count(i->destSe) == 0) {
StorageConfig seConfig = db->getStorageConfig(i->destSe);
slotsLeftForDestination[i->destSe] = seConfig.inboundMaxActive>0?seConfig.inboundMaxActive:60;
slotsLeftForSource[i->destSe] = seConfig.outboundMaxActive>0?seConfig.outboundMaxActive:60;
}
if (slotsLeftForSource.count(i->sourceSe) == 0) {
StorageConfig seConfig = db->getStorageConfig(i->sourceSe);
slotsLeftForDestination[i->sourceSe] = seConfig.inboundMaxActive>0?seConfig.inboundMaxActive:60;
slotsLeftForSource[i->sourceSe] = seConfig.outboundMaxActive>0?seConfig.outboundMaxActive:60;
}
// Once it is filled, decrement
slotsLeftForDestination[i->destSe] -= i->activeCount;
slotsLeftForSource[i->sourceSe] -= i->activeCount;
}
bool empty = false;
while (!empty)
{
empty = true;
for (auto vo_it = voQueues.begin(); vo_it != voQueues.end(); ++vo_it)
{
std::queue<std::pair<std::string, std::list<TransferFile> > > & vo_jobs =
vo_it->second;
if (!vo_jobs.empty())
{
empty = false; //< if we are here there are still some data
std::pair<std::string, std::list<TransferFile> > const job = vo_jobs.front();
vo_jobs.pop();
if (job.second.size() <= 0) {
FTS3_COMMON_LOGGER_NEWLOG(ERR)
<< "Empty job " << job.first
<< commit;
continue;
}
if (slotsLeftForDestination[job.second.front().destSe] <= 0) {
FTS3_COMMON_LOGGER_NEWLOG(WARNING)
<< "Reached limitation for destination " << job.second.front().destSe
<< commit;
}
else if (slotsLeftForSource[job.second.front().sourceSe] <= 0) {
FTS3_COMMON_LOGGER_NEWLOG(WARNING)
<< "Reached limitation for source " << job.second.front().sourceSe
<< commit;
}
else if (availableUrlCopySlots <= 0) {
FTS3_COMMON_LOGGER_NEWLOG(WARNING)
<< "Reached limitation of MaxUrlCopyProcesses"
<< commit;
return;
} else {
startUrlCopy(job.first, job.second);
--availableUrlCopySlots;
--slotsLeftForDestination[job.second.front().destSe];
--slotsLeftForSource[job.second.front().sourceSe];
}
}
}
}
}
void ReuseTransfersService::startUrlCopy(std::string const & job_id, std::list<TransferFile> const & files)
{
GenericDbIfce *db = DBSingleton::instance().getDBObjectInstance();
UrlCopyCmd cmdBuilder;
// Set log directory
std::string logsDir = ServerConfig::instance().get<std::string>("TransferLogDirectory");
cmdBuilder.setLogDir(logsDir);
// Messaging
std::string msgDir = ServerConfig::instance().get<std::string>("MessagingDirectory");
cmdBuilder.setMonitoring(monitoringMessages, msgDir);
// Set parameters from the "representative", without using the source and destination url, and other data
// that is per transfer
TransferFile const & representative = files.front();
cmdBuilder.setFromTransfer(representative, true, db->publishUserDn(representative.voName), msgDir);
// Generate the file containing the list of transfers
std::map<uint64_t, std::string> fileIds = generateJobFile(representative.jobId, files);
// Can we run?
int currentActive = 0;
if (!db->isTrAllowed(representative.sourceSe, representative.destSe, currentActive)) {
return;
}
// Set parameters
int secPerMB = db->getSecPerMb(representative.voName);
if (secPerMB > 0) {
cmdBuilder.setSecondsPerMB(secPerMB);
}
TransferFile::ProtocolParameters protocolParams = representative.getProtocolParameters();
if (representative.internalFileParams.empty()) {
protocolParams.nostreams = db->getStreamsOptimization(representative.sourceSe, representative.destSe);
protocolParams.timeout = db->getGlobalTimeout(representative.voName);
protocolParams.ipv6 = db->isProtocolIPv6(representative.sourceSe, representative.destSe);
protocolParams.udt = db->isProtocolUDT(representative.sourceSe, representative.destSe);
//protocolParams.buffersize
}
cmdBuilder.setFromProtocol(protocolParams);
std::string proxy_file = DelegCred::getProxyFile(representative.userDn, representative.credId);
if (!proxy_file.empty())
cmdBuilder.setProxy(proxy_file);
std::string cloudConfigFile = fts3::generateCloudStorageConfigFile(db, representative);
if (!cloudConfigFile.empty()) {
cmdBuilder.setOAuthFile(cloudConfigFile);
}
// Set all to ready, special case for session reuse
int updatedFiles = db->updateFileStatusReuse(representative, "READY");
if (updatedFiles <= 0)
{
FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Transfer "
<< representative.jobId << " with session reuse enabled"
<< " not updated. Probably picked by another node"
<< commit;
return;
}
// Debug level
unsigned debugLevel = db->getDebugLevel(representative.sourceSe, representative.destSe);
if (debugLevel > 0)
{
cmdBuilder.setDebugLevel(debugLevel);
}
// Infosystem
cmdBuilder.setInfosystem(infosys);
// FTS3 name
cmdBuilder.setFTSName(ftsHostName);
// Current number of actives
cmdBuilder.setNumberOfActive(currentActive);
// Number of retries and maximum number allowed
int retry_times = db->getRetryTimes(representative.jobId, representative.fileId);
cmdBuilder.setNumberOfRetries(retry_times < 0 ? 0 : retry_times);
int retry_max = db->getRetry(representative.jobId);
cmdBuilder.setMaxNumberOfRetries(retry_max < 0 ? 0 : retry_max);
// Log and run
std::string params = cmdBuilder.generateParameters();
FTS3_COMMON_LOGGER_NEWLOG(INFO) << "Transfer params: " << cmdBuilder << commit;
ExecuteProcess pr(cmd, params);
// Check if fork failed , check if execvp failed
std::string forkMessage;
if (-1 == pr.executeProcessShell(forkMessage))
{
if (forkMessage.empty())
{
FTS3_COMMON_LOGGER_NEWLOG(ERR)
<< "Transfer failed to spawn " << commit;
db->forkFailed(job_id);
}
else
{
FTS3_COMMON_LOGGER_NEWLOG(ERR)
<< "Transfer failed to spawn " << forkMessage
<< commit;
db->forkFailed(job_id);
}
}
else
{
db->setPidForJob(job_id, pr.getPid());
}
std::map<uint64_t, std::string>::const_iterator iterFileIds;
std::vector<events::Message> protoMsgs;
for (iterFileIds = fileIds.begin(); iterFileIds != fileIds.end(); ++iterFileIds)
{
fts3::events::MessageUpdater msg2;
msg2.set_job_id(job_id);
msg2.set_file_id(iterFileIds->first);
msg2.set_process_id(pr.getPid());
msg2.set_timestamp(millisecondsSinceEpoch());
ThreadSafeList::get_instance().push_back(msg2);
events::Message protoMsg;
protoMsg.set_file_id(iterFileIds->first);
protoMsg.set_transfer_status("UPDATE");
protoMsg.set_timeout(cmdBuilder.getTimeout());
protoMsg.set_buffersize(cmdBuilder.getBuffersize());
protoMsg.set_nostreams(cmdBuilder.getNoStreams());
protoMsgs.push_back(protoMsg);
}
// Set known protocol settings
db::DBSingleton::instance().getDBObjectInstance()->updateProtocol(protoMsgs);
}
/**
* Transfers in uneschedulable queues must be set to fail
*/
static void failUnschedulable(const std::vector<QueueId> &unschedulable)
{
Producer producer(config::ServerConfig::instance().get<std::string>("MessagingDirectory"));
std::map<std::string, std::queue<std::pair<std::string, std::list<TransferFile> > > > voQueues;
DBSingleton::instance().getDBObjectInstance()->getReadySessionReuseTransfers(unschedulable, voQueues);
for (auto mapIter = voQueues.begin(); mapIter != voQueues.end(); ++mapIter) {
std::queue<std::pair<std::string, std::list<TransferFile>>> &queues = mapIter->second;
while (!queues.empty()) {
std::pair<std::string, std::list<TransferFile>> &job = queues.front();
for (auto iterTransfer = job.second.begin(); iterTransfer != job.second.end(); ++iterTransfer) {
events::Message status;
status.set_transfer_status("FAILED");
status.set_timestamp(millisecondsSinceEpoch());
status.set_process_id(0);
status.set_job_id(job.first);
status.set_file_id(iterTransfer->fileId);
status.set_source_se(iterTransfer->sourceSe);
status.set_dest_se(iterTransfer->destSe);
status.set_transfer_message("No share configured for this VO");
status.set_retry(false);
status.set_errcode(EPERM);
producer.runProducerStatus(status);
}
queues.pop();
}
}
}
void ReuseTransfersService::executeUrlcopy()
{
// Bail out as soon as possible if there are too many url-copy processes
int maxUrlCopy = config::ServerConfig::instance().get<int>("MaxUrlCopyProcesses");
int urlCopyCount = countProcessesWithName("fts_url_copy");
int availableUrlCopySlots = maxUrlCopy - urlCopyCount;
if (availableUrlCopySlots <= 0) {
FTS3_COMMON_LOGGER_NEWLOG(WARNING)
<< "Reached limitation of MaxUrlCopyProcesses"
<< commit;
return;
}
try
{
std::vector<QueueId> queues, unschedulable;
DBSingleton::instance().getDBObjectInstance()->getQueuesWithSessionReusePending(queues);
// Breaking determinism. See FTS-704 for an explanation.
std::random_shuffle(queues.begin(), queues.end());
queues = applyVoShares(queues, unschedulable);
// Fail all that are unschedulable
failUnschedulable(unschedulable);
if (queues.empty()) {
return;
}
getFiles(queues, availableUrlCopySlots);
}
catch (std::exception& e)
{
FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService " << e.what() << commit;
}
catch (...)
{
FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService!" << commit;
}
}
} // end namespace server
} // end namespace fts3
| 35.067568 | 110 | 0.624791 | [
"vector"
] |
37cabec3cb2dbfbe2381c66d15d96e9ff7f63584 | 536 | cpp | C++ | 0670-Maximum Swap/0670-Maximum Swap.cpp | zhuangli1987/LeetCode-1 | e81788abf9e95e575140f32a58fe983abc97fa4a | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0601-0700/0670-Maximum Swap/0670-Maximum Swap.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0601-0700/0670-Maximum Swap/0670-Maximum Swap.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
int maximumSwap(int num) {
string str = to_string(num);
int n = str.size();
vector<int> last(10);
for (int i = 0; i < n; ++i) {
last[str[i] - '0'] = i;
}
for (int i = 0; i < n; ++i) {
for (int d = 9; d > str[i] - '0'; --d) {
if (last[d] > i) {
swap(str[i], str[last[d]]);
return stoi(str);
}
}
}
return num;
}
};
| 23.304348 | 52 | 0.333955 | [
"vector"
] |
56cd3cfeab02b2030e01b9f57b5b1fe9d163abe4 | 2,107 | hpp | C++ | AoC_2017/day13.hpp | c-goldschmidt/AoC_2017 | 6455b14bca9dc67ec6ceaf1f3c16ddb4c0b599e0 | [
"CC0-1.0"
] | null | null | null | AoC_2017/day13.hpp | c-goldschmidt/AoC_2017 | 6455b14bca9dc67ec6ceaf1f3c16ddb4c0b599e0 | [
"CC0-1.0"
] | null | null | null | AoC_2017/day13.hpp | c-goldschmidt/AoC_2017 | 6455b14bca9dc67ec6ceaf1f3c16ddb4c0b599e0 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "day_factory.hpp"
DAY(Day13)
class Scanner {
public:
Scanner(int range = 0);
~Scanner() = default;
int range;
int position;
void tick();
void reset();
private:
int direction;
};
Scanner::Scanner(int range) {
this->range = range;
position = 0;
direction = 1;
}
void Scanner::tick() {
if (this->range == 0) {
return;
}
if (this->position == this->range - 1) {
this->direction = -1;
} else if (this->position == 0) {
this->direction = 1;
}
this->position += this->direction;
}
void Scanner::reset() {
position = 0;
direction = 1;
}
class SecurityGrid {
public:
SecurityGrid(vector<string> input);
~SecurityGrid() = default;
void tickScanners();
void reset();
int scannerRangeAt(int depth);
int numLayers;
map<int, Scanner> scanners;
};
SecurityGrid::SecurityGrid(vector<string> input) {
regex rxLine("(\\d+): (\\d+)");
for (string line: input) {
smatch match;
regex_match(line, match, rxLine);
int depth = stoi(match[1]);
int range = stoi(match[2]);
scanners[depth] = Scanner(range);
numLayers = max(numLayers, depth);
}
}
void SecurityGrid::tickScanners() {
for(auto& item: scanners) {
item.second.tick();
}
}
void SecurityGrid::reset() {
for (auto& item : scanners) {
item.second.reset();
}
}
int SecurityGrid::scannerRangeAt(int depth) {
if (auto it = scanners.find(depth); it == scanners.end()) {
return 0;
}
if (scanners[depth].position == 0) {
return scanners[depth].range;
}
return 0;
}
void Day13::part1() {
SecurityGrid grid(fileContent);
int severity = 0;
for (int i = 0; i <= grid.numLayers; i++) {
severity += grid.scannerRangeAt(i) * i;
grid.tickScanners();
}
printResult(severity);
}
bool tryBreaching(SecurityGrid *grid, int delay) {
for (auto& item : grid->scanners) {
if ((item.first + delay) % ((item.second.range - 1) * 2) == 0) {
return false;
}
}
return true;
}
void Day13::part2() {
SecurityGrid grid(fileContent);
int delay = 0;
bool breached = false;
do {
delay++;
breached = tryBreaching(&grid, delay);
} while (!breached);
printResult(delay);
} | 16.590551 | 66 | 0.642145 | [
"vector"
] |
56d0a3b260e0188a6ff9d95aa53b5147fa17e5a0 | 394 | cpp | C++ | CountDownMarquee/TextMaker.cpp | FelixHauser/CountDownMarquee | ef38b1655268695dbf5d4b3e5fb0c216722d1a39 | [
"MIT"
] | null | null | null | CountDownMarquee/TextMaker.cpp | FelixHauser/CountDownMarquee | ef38b1655268695dbf5d4b3e5fb0c216722d1a39 | [
"MIT"
] | null | null | null | CountDownMarquee/TextMaker.cpp | FelixHauser/CountDownMarquee | ef38b1655268695dbf5d4b3e5fb0c216722d1a39 | [
"MIT"
] | null | null | null | #include "TextMaker.h"
RtcSetup rtC; //init Real Time Clock Object
TextMaker::TextMakerSetup (){
}
String TextMaker::composedString(){
String preString=FIRST_TEXT_TO_SCROLL;
if (COUNTDOWN==true){
preString=preString+rtC.timeString()+LAST_TEXT_TO_SCROLL;
}else{
preString=preString+LAST_TEXT_TO_SCROLL;
}
return preString;
}
| 12.709677 | 61 | 0.65736 | [
"object"
] |
56d0cba1cca2af1886b9afe3ced3ac0c849f822a | 401 | cpp | C++ | Dataset/Leetcode/train/94/421.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/94/421.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/94/421.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
void find(vector<int> & res, TreeNode* root)
{
if(root)
{
find(res, root->left);
res.push_back(root->val);
find(res, root->right);
}
else
return;
}
vector<int> XXX(TreeNode* root) {
vector<int> res;
find(res, root);
return res;
}
};
| 16.708333 | 48 | 0.431421 | [
"vector"
] |
56d6c356e4f559cdcd010940aeca63a20a1f6039 | 3,354 | cpp | C++ | 06_future/src/main.cpp | rafaelschreiber/nvs_5_jg | f0f63e7bf6ddb2e1ba51d981a56fbfcf5d0ad506 | [
"BSD-3-Clause"
] | null | null | null | 06_future/src/main.cpp | rafaelschreiber/nvs_5_jg | f0f63e7bf6ddb2e1ba51d981a56fbfcf5d0ad506 | [
"BSD-3-Clause"
] | null | null | null | 06_future/src/main.cpp | rafaelschreiber/nvs_5_jg | f0f63e7bf6ddb2e1ba51d981a56fbfcf5d0ad506 | [
"BSD-3-Clause"
] | null | null | null | /*
* Author: Rafael Schreiber (i16066)
* Project: 06_future
* File: main.cpp
* Date: 07-12-2020
*/
#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <chrono>
#include "CLI11.hpp"
#include "InfInt.h"
#include "calc_factors.h"
using namespace std;
void check_result(vector<InfInt> &factor_numbers, vector<shared_future<vector<InfInt>>> &future_primes){
int index{0};
for (auto result_future : future_primes){
InfInt factored_number{"1"};
for (auto prime : result_future.get()){
factored_number *= prime;
}
if (factor_numbers[index] != factored_number){
cerr << "An error occured, while calculating prime factors. Factoring doesn't match with original value";
}
index++;
}
}
void print_result(vector<InfInt> &factor_numbers, vector<shared_future<vector<InfInt>>> &future_primes){
int index{0};
for (auto result_future : future_primes){
cout << factor_numbers[index] << ": ";
for (auto prime : result_future.get()){
cout << prime << " ";
}
cout << endl;
index++;
}
}
vector<InfInt> convert_to_infint_vector(vector<string> s_vector){
vector<InfInt> infint_vector;
for (auto s_number : s_vector){
InfInt infint_number = s_number;
infint_vector.push_back(infint_number);
}
return infint_vector;
}
int main(int argc, char** argv) {
vector<string> factor_numbers;
bool do_async{false};
CLI::App app("Factor numbers");
app.add_option("number", factor_numbers, "numbers to factor") -> required()
-> check([](const std::string &str) {
auto is_valid = str.find_first_not_of("0123456789");
if (is_valid == string::npos){
return std::string();
} else {
return std::string(str + " contains not numeric character");
}
});
app.add_flag("-a, --async", do_async, "async");
CLI11_PARSE(app, argc, argv);
vector<InfInt> infint_factor_numbers{convert_to_infint_vector(factor_numbers)};
/* Print numbers with prime factors single threaded without async
for (auto number : infint_factor_numbers){
cout << number << ": ";
auto prime_factors = get_factors(number);
for (auto prime : prime_factors){
cout << prime << " ";
}
cout << endl;
}
cout << "Async: " << async << endl;
*/
vector<shared_future<vector<InfInt>>> future_primes_vector;
auto start = chrono::system_clock::now();
for (auto number : infint_factor_numbers){
if (do_async){
future_primes_vector.push_back(async(launch::async, get_factors, number));
} else {
future_primes_vector.push_back(async(launch::deferred, get_factors, number));
}
}
future_primes_vector.at(infint_factor_numbers.size() - 1).wait();
auto duration = chrono::duration_cast<chrono::milliseconds> (std::chrono::system_clock::now() - start);
thread t1{check_result, ref(infint_factor_numbers), ref(future_primes_vector)};
thread t2{print_result, ref(infint_factor_numbers), ref(future_primes_vector)};
t1.join();
t2.join();
cout << "Time elapsed used for factoring: " << duration.count() << "ms" << endl;
return 0;
}
| 31.055556 | 117 | 0.626714 | [
"vector"
] |
56dba89531868cab287bb4171087f84ee8d99855 | 2,485 | cpp | C++ | application.cpp | salaadas/teenie | f4976bf65cc9c68d23a57db754a79c9e45990cb9 | [
"MIT"
] | null | null | null | application.cpp | salaadas/teenie | f4976bf65cc9c68d23a57db754a79c9e45990cb9 | [
"MIT"
] | null | null | null | application.cpp | salaadas/teenie | f4976bf65cc9c68d23a57db754a79c9e45990cb9 | [
"MIT"
] | null | null | null | #include "./application.h"
#include "SDL.h"
#include "./graphics.h"
#include "./globals.h"
#include "./input.h"
#include "./texture.h"
#include "./math/linalg.h"
#include "./tiles/tilegrid.h"
namespace {
const int FPS = 60;
const uint32_t MAX_FRAME_TIME = 1000 / FPS;
}
Application::Application()
{
SDL_Init(SDL_INIT_EVERYTHING);
this->game_loop();
}
Application::~Application()
{
SDL_Quit();
}
void Application::game_loop()
{
Graphics game_graphics;
this->tiles = TileGrid(game_graphics);
Input input;
uint32_t LAST_UPDATE_TIME = SDL_GetTicks();
while (!this->quit) {
SDL_Event event = {0};
input.refresh_keys_memory();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: {
this->quit = true;
}break;
case SDL_KEYDOWN: {
input.handle_key_press(event);
}break;
case SDL_KEYUP: {
input.handle_key_release(event);
}break;
case SDL_MOUSEBUTTONDOWN: {
Vec2i m_coord = game_graphics.emit_mouse_coordinate();
SDL_GetMouseState(&m_coord.x, &m_coord.y);
if (event.button.button == SDL_BUTTON_LEFT) {
printf("left clicked at: (%d; %d)\n", m_coord.x, m_coord.y);
}
if (event.button.button == SDL_BUTTON_RIGHT) {
printf("right clicked: (%d; %d)\n", m_coord.x, m_coord.y);
}
}break;
case SDL_MOUSEBUTTONUP: {
}
}
if (input.was_key_pressed(SDL_SCANCODE_ESCAPE)) {
this->quit = true;
}
}
const uint32_t CURRENT_TIME = SDL_GetTicks();
const uint32_t ELAPSED_TIME = CURRENT_TIME - LAST_UPDATE_TIME;
this->render_all(game_graphics);
this->update_all(ELAPSED_TIME);
}
}
void Application::update_all(uint32_t elapsed_time)
{
// TODO: Implement update
elapsed_time = 0;
}
void Application::render_all(Graphics &graphics)
{
graphics.set_render_color(globals::BACKGROUND_COLOR);
graphics.clear();
// render entities/tiles after this line
this->tiles.render_tile(graphics, "grass", vec2is(200));
// everything should be rendered by the time it reaches this comment
graphics.flip();
}
| 26.72043 | 84 | 0.561368 | [
"render"
] |
56df036d16c9f27b98f89b755cfb25834b504b6a | 813 | cpp | C++ | usaco/1.1 ride.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | usaco/1.1 ride.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | usaco/1.1 ride.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | /*
ID: iamdipt1
PROG: ride
LANG: C++
*/
#include<cstdio>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
using namespace std;
int main() {
ofstream fout ("ride.out");
ifstream fin ("ride.in");
char c[7],g[7];
fin >>c >>g;
int co=1,gr=1;
int cs,gs;
cs=strlen(c);
for(int i =0;i<cs;i++)
{
co=co*(c[i]-64);
}
gs=strlen(g);
for(int i =0;i<gs;i++)
{
gr=gr*(g[i]-64);
}
co=co%47;
gr=gr%47;
if(co==gr)
fout << "GO" << endl;
else
fout << "STAY" << endl;
return 0;
}
| 14.781818 | 31 | 0.560886 | [
"vector"
] |
56e334703b236462929ca686378091237d24fe09 | 5,452 | cpp | C++ | modules/cuda_plugin/tests/functional/shared_tests_instances/single_layer_tests/tensor_iterator.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | modules/cuda_plugin/tests/functional/shared_tests_instances/single_layer_tests/tensor_iterator.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | modules/cuda_plugin/tests/functional/shared_tests_instances/single_layer_tests/tensor_iterator.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "single_layer_tests/tensor_iterator.hpp"
#include <cuda/runtime.hpp>
#include <cuda_operation_base.hpp>
#include <cuda_operation_registry.hpp>
#include <cuda_test_constants.hpp>
#include <ngraph/op/util/attr_types.hpp>
#include <vector>
#include "benchmark.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
namespace LayerTestsDefinitions {
class TensorIteratorDisabledTransformationsTest : public TensorIteratorTest {
protected:
void SetUp() override {
TensorIteratorTest::SetUp();
configuration[CUDA_CONFIG_KEY(DISABLE_TENSORITERATOR_TRANSFORM)] = CUDA_CONFIG_VALUE(YES);
}
};
TEST_P(TensorIteratorDisabledTransformationsTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
auto params = GetParam();
Run();
}
} // namespace LayerTestsDefinitions
namespace {
std::vector<bool> should_decompose = {false};
std::vector<size_t> smoke_seq_lengths_clip_non_zero{20};
std::vector<size_t> batch{1, 10};
std::vector<size_t> hidden_size{1, 10, 384, 512, 768};
std::vector<size_t> sequence_axis{0, 1};
std::vector<ngraph::helpers::TensorIteratorBody> body_type = {ngraph::helpers::TensorIteratorBody::LSTM};
std::vector<float> clip_zeros{0.f};
std::vector<ngraph::op::RecurrentSequenceDirection> direction = {
ngraph::op::RecurrentSequenceDirection::FORWARD,
ngraph::op::RecurrentSequenceDirection::REVERSE,
};
std::vector<InferenceEngine::Precision> netPrecisions = {InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16};
INSTANTIATE_TEST_CASE_P(
smoke_TensorIteratorNoClip,
TensorIteratorDisabledTransformationsTest,
::testing::Combine(::testing::ValuesIn(should_decompose),
::testing::ValuesIn(smoke_seq_lengths_clip_non_zero),
::testing::ValuesIn(batch),
::testing::ValuesIn(hidden_size),
//::testing::ValuesIn(input_size), // hardcoded to 10 due to Combine supports up to 10 args
::testing::ValuesIn(sequence_axis),
::testing::ValuesIn(clip_zeros),
::testing::ValuesIn(body_type),
::testing::ValuesIn(direction),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CUDA)),
TensorIteratorDisabledTransformationsTest::getTestCaseName);
std::vector<size_t> seq_lengths_clip_non_zero{1000};
INSTANTIATE_TEST_CASE_P(
TensorIteratorNoClip,
TensorIteratorDisabledTransformationsTest,
::testing::Combine(::testing::ValuesIn(should_decompose),
::testing::ValuesIn(seq_lengths_clip_non_zero),
::testing::ValuesIn(batch),
::testing::ValuesIn(hidden_size),
//::testing::ValuesIn(input_size), // hardcoded to 10 due to Combine supports up to 10 args
::testing::ValuesIn(sequence_axis),
::testing::ValuesIn(clip_zeros),
::testing::ValuesIn(body_type),
::testing::ValuesIn(direction),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CUDA)),
TensorIteratorDisabledTransformationsTest::getTestCaseName);
// ------------- Benchmark -------------
namespace benchmark {
struct TensorIteratorBenchmarkTest : BenchmarkLayerTest<TensorIteratorDisabledTransformationsTest> {};
TEST_P(TensorIteratorBenchmarkTest, DISABLED_benchmark) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
Run("TensorIterator", std::chrono::milliseconds(2000), 100);
}
std::vector<bool> should_decompose = {false};
std::vector<size_t> seq_lengths_clip_non_zero{20};
std::vector<size_t> batch{1, 10};
std::vector<size_t> hidden_size{1, 10};
std::vector<size_t> sequence_axis{0, 1};
std::vector<ngraph::helpers::TensorIteratorBody> body_type = {ngraph::helpers::TensorIteratorBody::LSTM};
std::vector<float> clip_zeros{0.f};
std::vector<ngraph::op::RecurrentSequenceDirection> direction = {
ngraph::op::RecurrentSequenceDirection::FORWARD,
ngraph::op::RecurrentSequenceDirection::REVERSE,
};
std::vector<InferenceEngine::Precision> netPrecisions = {InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16};
INSTANTIATE_TEST_CASE_P(
smoke_TensorIteratorNoClip,
TensorIteratorBenchmarkTest,
::testing::Combine(::testing::ValuesIn(should_decompose),
::testing::ValuesIn(seq_lengths_clip_non_zero),
::testing::ValuesIn(batch),
::testing::ValuesIn(hidden_size),
//::testing::ValuesIn(input_size), // hardcoded to 10 due to Combine supports up to 10 args
::testing::ValuesIn(sequence_axis),
::testing::ValuesIn(clip_zeros),
::testing::ValuesIn(body_type),
::testing::ValuesIn(direction),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CUDA)),
TensorIteratorBenchmarkTest::getTestCaseName);
} // namespace benchmark
} // namespace
| 41.30303 | 114 | 0.659024 | [
"vector"
] |
56e3ee274ce89f3bdcb7964054f153ae90b65a67 | 4,875 | cpp | C++ | Tests/InterprocessEngineTest/main.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 232 | 2016-08-29T00:33:32.000Z | 2022-03-29T22:39:51.000Z | Tests/InterprocessEngineTest/main.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 10 | 2021-01-02T12:40:49.000Z | 2021-08-31T06:31:04.000Z | Tests/InterprocessEngineTest/main.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 40 | 2017-12-18T06:14:39.000Z | 2022-01-29T16:35:23.000Z |
#include <TestUtils/WindowsSampleWrapper.h>
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <cassert>
#include <sstream>
#pragma comment( lib, "dxguid.lib" )
#pragma comment( lib, "dinput8.lib" )
TCHAR szName[] = TEXT( "Local\\RenderHookSharedMemory" );
TCHAR event_name[] = TEXT( "Local\\RenderHookInitDeviceEvent" );
TCHAR render_start_event[] = TEXT( "Local\\RenderHookRenderStartEvent" );
TCHAR render_finish_event[] = TEXT( "Local\\RenderHookRenderFinishEvent" );
TCHAR init_finish_event[] = TEXT( "Local\\RenderHookInitFinishEvent" );
#define SHARED_MEMORY_SIZE 1024 * 1024 * 1024
class DisplayModeTest : public rh::tests::TestSample
{
public:
DisplayModeTest( rh::engine::RenderingAPI api, HINSTANCE inst )
: rh::tests::TestSample( api, inst )
{
}
bool Initialize( void *wnd ) override
{
STARTUPINFOA start_info{};
start_info.cb = sizeof( start_info );
PROCESS_INFORMATION proc_info{};
std::stringstream cmd_args;
cmd_args << "C:\\Users\\peter\\Documents\\Visual Studio 2015\\Projects\\gtaRenderHook\\build\\rw_x64_render_driver\\rw_x64_render_driver.exe";
auto cmd_args_str = cmd_args.str();
char cmd_args_cstr[512];
strcpy_s( cmd_args_cstr, cmd_args_str.c_str() );
_SECURITY_ATTRIBUTES eventsecattr{};
eventsecattr.nLength = sizeof( _SECURITY_ATTRIBUTES );
eventsecattr.bInheritHandle = true;
hEventHandle = CreateEvent( &eventsecattr, TRUE, FALSE, event_name );
mRenderStart =
CreateEvent( &eventsecattr, TRUE, FALSE, render_start_event );
mRenderFinish =
CreateEvent( &eventsecattr, TRUE, FALSE, render_finish_event );
mInitEvent =
CreateEvent( &eventsecattr, TRUE, FALSE, init_finish_event );
BOOL result =
CreateProcessA( nullptr, cmd_args_cstr, nullptr, nullptr, false, 0,
nullptr, nullptr, &start_info, &proc_info );
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
SHARED_MEMORY_SIZE, // maximum object size (low-order DWORD)
szName ); // name of mapping object
if ( hMapFile == NULL )
{
_tprintf( TEXT( "Could not open file mapping object (%d).\n" ),
static_cast<int>( GetLastError() ) );
return 1;
}
mSharedMemory =
MapViewOfFile( hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0, 0, SHARED_MEMORY_SIZE );
if ( mSharedMemory == NULL )
{
_tprintf( TEXT( "Could not map view of file (%d).\n" ),
static_cast<int>( GetLastError() ) );
CloseHandle( hMapFile );
return 1;
}
CopyMemory( mSharedMemory, &wnd, sizeof( HWND ) );
SetEvent( hEventHandle );
WaitForSingleObject( mInitEvent, INFINITE );
return true;
}
private:
// TestSample interface
HANDLE hMapFile;
HANDLE hEventHandle;
LPVOID mSharedMemory;
HANDLE mRenderStart;
HANDLE mRenderFinish;
HANDLE mInitEvent;
public:
void CustomShutdown() override
{
UnmapViewOfFile( mSharedMemory );
CloseHandle( hMapFile );
}
// TestSample interface
public:
void CustomRender() override {
struct render_color
{
float r, g, b, a;
};
render_color color{0.1f, 0.0f, float( rand() % 100 ) / 100.0f, 1.0f};
CopyMemory( mSharedMemory, &color, sizeof( render_color ) );
SetEvent( mRenderStart );
WaitForSingleObject( mRenderFinish, INFINITE );
ResetEvent( mRenderFinish );
}
};
int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPWSTR lpCmdLine, int nCmdShow )
{
UNREFERENCED_PARAMETER( hPrevInstance );
UNREFERENCED_PARAMETER( lpCmdLine );
UNREFERENCED_PARAMETER( nCmdShow );
// Window params initialization
rh::tests::WindowsSampleParams initParams;
initParams.instance = hInstance;
initParams.sampleTitle = TEXT( "DisplayModeTest" );
initParams.windowClass = TEXT( "DISPLAYMODETEST" );
rh::tests::WindowsSampleWrapper sample(
initParams, std::make_unique<DisplayModeTest>(
rh::engine::RenderingAPI::Vulkan, hInstance ) );
// Initialize test sample.
if ( !sample.Init() )
return FALSE;
// Run test sample!
sample.Run();
return TRUE;
}
| 33.62069 | 150 | 0.610051 | [
"object"
] |
56ead0597fe5afcd9313c2170afc2a96dac8d4a8 | 2,265 | cpp | C++ | main.cpp | rufus-stone/mobius | 752d0c8ea09bd0c80e7e467c9d2784e4c94495fd | [
"MIT"
] | 1 | 2020-04-20T17:15:58.000Z | 2020-04-20T17:15:58.000Z | main.cpp | rufus-stone/mobius | 752d0c8ea09bd0c80e7e467c9d2784e4c94495fd | [
"MIT"
] | null | null | null | main.cpp | rufus-stone/mobius | 752d0c8ea09bd0c80e7e467c9d2784e4c94495fd | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "mobius.hpp"
#include "examples/demo.hpp"
int main()
{
std::cout << "-----------------------------------------------\n";
std::cout << "Demonstrating vanilla state engine operation...\n\n";
// Create a new vanilla state engine
auto engine = mobius::new_engine();
// Push an example state to the top of the stack
engine->push<demo::vanilla_state_one>();
std::cout << "The size of state engine stack is now: " << engine->size() << '\n';;
// Handle some input event against the state at the top of the state (in this case vanilla_state_one) - for example purposes, this will cause us to enter vanilla_state_two
engine->handle_input('a');
std::cout << "The size of state engine stack is now: " << engine->size() << '\n';
// Handle some input event against the state at the top of the state (in this case vanilla_state_two) - for example purposes, this will pop vanilla_state_two and restore vanilla_state_one
engine->handle_input('a');
std::cout << "The size of state engine stack is now: " << engine->size() << '\n';
// Handle some input event against the state at the top of the state (in this case vanilla_state_one) - for example purposes, this will pop vanilla_state_one leaving the state stack empty
engine->handle_input('q');
std::cout << "The size of state engine stack is now: " << engine->size() << "\n\n\n";
std::cout << "------------------------------------------------\n";
std::cout << "Demonstrating enhanced state engine operation...\n\n";
// Create an enhanced engine with a vector as it's business logic object, and initialize it with two strings
auto game_engine = mobius::new_enhanced_engine<std::vector<std::string>>("one", "two");
// We can interact with the internal logic object like this
game_engine->logic().push_back("three");
std::cout << "Internal logic vector now has size: " << game_engine->logic().size() << '\n'; // Internal logic vector now has size: 3
// The rest of the functionality is the same as a vanilla state engine
game_engine->push<demo::enhanced_state_one>();
game_engine->handle_input('p');
game_engine->handle_input('a');
game_engine->handle_input('q');
return 0;
}
| 41.181818 | 190 | 0.66755 | [
"object",
"vector"
] |
56f93b4a189766d7ebf2b23141f80bc90ba72103 | 1,837 | cpp | C++ | main.cpp | the-real-atomic/classes | 0190cd012e8fd4de21291e75c2cf8c1dd9db7756 | [
"Unlicense"
] | null | null | null | main.cpp | the-real-atomic/classes | 0190cd012e8fd4de21291e75c2cf8c1dd9db7756 | [
"Unlicense"
] | null | null | null | main.cpp | the-real-atomic/classes | 0190cd012e8fd4de21291e75c2cf8c1dd9db7756 | [
"Unlicense"
] | null | null | null | #include <string>
#include <vector>
// TODO: Move this code somewhere else...
class PlayerSave {
public:
std::string NName; //Is the name the player wants to enter in for the new game save.
std::string setName(std::string NName, std::string PS); //Will get the private string that's the name of the save and set the new name of the save.
private:
std::string Psave1; //Player Save 1
std::string Psave2; //Player Save 2
std::string Psave3; //Player Save 3
};
class PlayerInfo {
public:
double PHealth = 100; //Players Health
double PShield = 50; //Players shield
double PStamina = 200; //Players Stamina
double StaminaRegenRate = .1; //Stamina Regen tic rate
private:
};
class PlayerWeapon {
public:
void ChoosePrimary(); //Player chooses there primary weapon
void ChooseSecondary(); //Player chooses there secondary weapon
void PrimaryAmmoPickup(); //Function that will add random amount of bullets to the local player current amount of primary ammo
void SecondaryAmmoPickup(); //Function that will add random amount of bullets to the local player current amount of secondary ammo
int PA = 0; //Players Primary Weapon ammo amount
int SA = 0; //Players Secondary Weapon ammo amount
int SAmmo = SA; //Players Secondary Ammo
int PAmmo = PA; //Players Primary ammo
private:
};
class PlayerPickup : PlayerInfo {
public:
double HealthPickup(); //Adds Health to the local players current Health
double ShieldPickup(); //Adds Shield to the local players current shield
double StaminaRegenPickup(); //Adds a increase to the stamina regen rate for a short period of time
};
int main() {
std::vector<PlayerSave> save_slots;
return 0;
}
| 32.22807 | 155 | 0.672292 | [
"vector"
] |
56fa6401097980e687c90db748c024b0cbee2d41 | 558 | hpp | C++ | src/Avokii/Graphics/FrameBuffer.hpp | Katipo007/avokii | 3a3d1ff244b078b1f1014726b554ce021c0ce488 | [
"MIT"
] | 1 | 2021-06-28T11:24:42.000Z | 2021-06-28T11:24:42.000Z | src/Avokii/Graphics/FrameBuffer.hpp | Katipo007/avokii | 3a3d1ff244b078b1f1014726b554ce021c0ce488 | [
"MIT"
] | null | null | null | src/Avokii/Graphics/FrameBuffer.hpp | Katipo007/avokii | 3a3d1ff244b078b1f1014726b554ce021c0ce488 | [
"MIT"
] | null | null | null | #pragma once
#include <cinttypes>
#include "Avokii/Geometry/Size.hpp"
namespace Avokii::Graphics
{
struct FrameBufferSpecification
{
Size<uint32_t> size{ 0, 0 };
uint32_t samples{ 1 };
bool swap_chain_target{ false };
};
class FrameBuffer
{
public:
virtual ~FrameBuffer() = default;
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual void Resize( uint32_t width, uint32_t height ) = 0;
virtual const FrameBufferSpecification& GetSpecification() const = 0;
virtual uint32_t GetNativeColourAttachment() const = 0;
};
}
| 18.6 | 71 | 0.71147 | [
"geometry"
] |
7117be1625d36c3801cb7894a2ab06d9a83a0702 | 5,063 | cpp | C++ | src/QtAIV/AIV/nHeaderViewConnector.cpp | Vladimir-Lin/QtAIV | a96b52a1df9c85dbadfc1dfcfc38d60948462c89 | [
"MIT"
] | null | null | null | src/QtAIV/AIV/nHeaderViewConnector.cpp | Vladimir-Lin/QtAIV | a96b52a1df9c85dbadfc1dfcfc38d60948462c89 | [
"MIT"
] | null | null | null | src/QtAIV/AIV/nHeaderViewConnector.cpp | Vladimir-Lin/QtAIV | a96b52a1df9c85dbadfc1dfcfc38d60948462c89 | [
"MIT"
] | null | null | null | #include <qtaiv.h>
N::HeaderViewConnector:: HeaderViewConnector (Qt::Orientation orientation,QObject * parent)
: QObject ( parent)
{
cAdjustSectionSizePending = true;
cOrientation = orientation;
}
N::HeaderViewConnector::~HeaderViewConnector(void)
{
}
void N::HeaderViewConnector::append(QHeaderView* view)
{
if (view->orientation() != cOrientation){
return;
}
cHeaderViewList.append(view);
connect(view, SIGNAL(destroyed(QObject*)), this, SLOT(viewDestroyed(QObject*)));
connect(view, SIGNAL(sectionMoved(int,int,int)), this, SLOT(sectionMoved(int,int,int)));
connect(view, SIGNAL(sectionResized(int,int,int)), this, SLOT(sectionResized(int,int,int)));
connect(view, SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(sortIndicatorChanged(int,Qt::SortOrder)));
if (cOrientation == Qt::Horizontal){
QTableView* mView = qobject_cast<QTableView*>(view->parentWidget());
if (mView){
connect(mView->horizontalScrollBar(), SIGNAL(rangeChanged(int,int)), this, SLOT(scrollBarRangeChanged(int,int)));
connect(mView->horizontalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(scrollBarSilderMoved(int)));
connect(mView->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrollBarSilderMoved(int)));
}
}
}
void N::HeaderViewConnector::adjustSectionSize()
{
cAdjustSectionSizePending = false;
int mWidth = 0;
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView){
if (mWidth < mHeaderView->width()){
mWidth = mHeaderView->width();
}
}
}
if (mWidth > 0){
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView){
mHeaderView->blockSignals(true);
mHeaderView->setFixedWidth(mWidth);
mHeaderView->blockSignals(false);
}
}
}
}
void N::HeaderViewConnector::scrollBarRangeChanged(int min, int max)
{
if (cOrientation == Qt::Vertical){
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView && mHeaderView){
QTableView* mTableView = qobject_cast<QTableView*>(mHeaderView->parentWidget());
if (mTableView){
if (mTableView->verticalScrollBar()->isVisible()){
}
}
}
}
}
// QHeaderView* mSender = qobject_cast<QHeaderView*>(sender());
// Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
// if (mHeaderView && mHeaderView != mSender){
// QTableView* mTableView = qobject_cast<QTableView*>(mHeaderView->parentWidget());
// if (mTableView){
// if (cOrientation == Qt::Horizontal){
// mTableView->horizontalScrollBar()->setRange(min, max);
// }
// }
// }
// }
}
void N::HeaderViewConnector::scrollBarSilderMoved(int value)
{
QHeaderView* mSender = qobject_cast<QHeaderView*>(sender());
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView && mHeaderView != mSender){
QTableView* mTableView = qobject_cast<QTableView*>(mHeaderView->parentWidget());
if (mTableView){
if (cOrientation == Qt::Horizontal){
mTableView->horizontalScrollBar()->setValue(value);
}
}
}
}
}
void N::HeaderViewConnector::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
Q_UNUSED(logicalIndex);
QHeaderView* mSender = qobject_cast<QHeaderView*>(sender());
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView && mHeaderView != mSender){
mHeaderView->blockSignals(true);
mHeaderView->moveSection(oldVisualIndex, newVisualIndex);
mHeaderView->blockSignals(false);
}
}
}
void N::HeaderViewConnector::sectionResized(int logicalIndex, int oldSize, int newSize)
{
Q_UNUSED(oldSize);
QHeaderView* mSender = qobject_cast<QHeaderView*>(sender());
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView && mHeaderView != mSender){
mHeaderView->resizeSection(logicalIndex, newSize);
}
}
if (cAdjustSectionSizePending){
adjustSectionSize();
}
}
void N::HeaderViewConnector::sortIndicatorChanged(int logicalIndex, Qt::SortOrder order)
{
QHeaderView* mSender = qobject_cast<QHeaderView*>(sender());
Q_FOREACH(QHeaderView* mHeaderView, cHeaderViewList){
if (mHeaderView && mHeaderView != mSender){
mHeaderView->blockSignals(true);
mHeaderView->setSortIndicator(logicalIndex, order);
mHeaderView->blockSignals(false);
}
}
}
void N::HeaderViewConnector::viewDestroyed(QObject* object)
{
cHeaderViewList.removeAt(cHeaderViewList.indexOf(qobject_cast<QHeaderView*>(object)));
}
| 35.65493 | 125 | 0.629271 | [
"object"
] |
711c260b7be1a1563c5223e5414546f7e96c8184 | 9,463 | cpp | C++ | src/AsmvarBaseStat/StatsMain.cpp | bioinformatics-centre/AsmVar | 5abd91a47feedfbd39b89ec3e2d6d20c02fe5a5e | [
"MIT"
] | 17 | 2015-12-25T10:58:03.000Z | 2021-05-06T01:56:40.000Z | src/AsmvarBaseStat/StatsMain.cpp | bioinformatics-centre/AsmVar | 5abd91a47feedfbd39b89ec3e2d6d20c02fe5a5e | [
"MIT"
] | 3 | 2017-07-20T22:12:16.000Z | 2021-04-19T14:37:14.000Z | src/AsmvarBaseStat/StatsMain.cpp | bioinformatics-centre/AsmVar | 5abd91a47feedfbd39b89ec3e2d6d20c02fe5a5e | [
"MIT"
] | 3 | 2018-01-26T02:03:04.000Z | 2020-08-07T08:01:20.000Z | /*
* Author : Shujia Huang & Siyang Liu
* Date : 2013-11-22 14:37:13
*
* Modfiy from '~/Bin/software_pip/Reapr/Reapr_1.0.16/src/task_stats.cpp' wrote by Matin Hunt
* 2013-11-26 23:02:07 I shift to calculate the read coverage instead of fragment coverage!!
*
*/
#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <cstring>
#include <string>
#include <list>
#include <getopt.h>
#include <algorithm>
#include "Stats.h"
struct CmdLineOptions {
uint16_t minMapQuality; // ignore reads mapped with quality less than this
uint32_t minAlignScore;
uint32_t iniReadLength; // Just use to init the size of coverage deque
string bamInfile;
string gapInfile;
string refGCfile;
string gc2covfile;
};
// deals with command line options: fills the options struct
void ParseOptions(int argc, char** argv, CmdLineOptions& ops);
void Usage ( const char* prog );
int main ( int argc, char** argv ) {
CmdLineOptions ops;
ParseOptions(argc, argv, ops);
cerr << "\nCommand Important Parameters: -q " << ops.minMapQuality << " -a " << ops.minAlignScore << " -l " << ops.iniReadLength << "\n" << endl;
Stats stats;
map<string, list<pair<long,long> > > refgaps;
LoadGaps (ops.gapInfile, refgaps);
//GetInsersizeFromBam (ops.bamInfile , stats.insert);
//Tabix tigc(ops.refGCfile);
//LoadGC2Cov(ops.gc2covfile, stats.gc2cov);
// Go through input bam file getting local stats
cerr << "************ Go through input bam file getting local stats **********\n" << endl;
BamReader bamReader;
SamHeader header;
RefVector references;
if (!bamReader.Open(ops.bamInfile)) {
cerr << ERROR_PREFIX << "Error opening bam file '" << ops.bamInfile << "'" << endl;
return 1;
}
header = bamReader.GetHeader();
references = bamReader.GetReferenceData();
bool firstRecord (true);
int32_t currentRefID(-1);
//int32_t alignScore;
uint32_t alignScore;
//int32_t isToosmall, isToobig;
string currentRefIDstring, rg, sa;
BamAlignment al;
unsigned long num = 0;
//cout << "#CHROM\tPOS\tTOTAL_COV\tPROPER_PAIR_COV\tLOW_ALIGN_SCORE_PROPER_PAIR\tBAD_INSERT_COV\tWRONG_ORIETATION_COV\tSINGLE_END_COV\t"
// << "CLIP_AND_SA_COV\tEXPECTED_COV(Correct by GC contain)\n";
cout << "#CHROM\tPOS\tTOTAL_COV\tPROPER_PAIR_COV\tLOW_ALIGN_SCORE_PROPER_PAIR\tCROSS_READ_COV\tBAD_INSERT_COV\tWRONG_ORIETATION_COV\tSINGLE_END_COV\t"
<< "CLIP_AND_SA_COV\n";
while ( bamReader.GetNextAlignment(al) ) {
++num; if ( num % 1000000 == 0 ) cerr << ">>> Reading lines number : " << num << endl;
if ( !al.IsMapped() || al.IsDuplicate() || al.MapQuality < ops.minMapQuality ) continue;
//al.GetTag("AS", alignScore);
//cerr << "alignScore: " << alignScore << "\t# " << al.GetTag("AS", alignScore) << "\t# " << al.HasTag("AS") << endl;
if (!al.GetTag("AS", alignScore)) { cerr << "Read " << al.Name << " doesn't have an alignment score AS:... Cannot continue" << endl; exit(1); }
if (!al.GetTag("RG", rg)) { cerr << "Read " << al.Name << " doesn't have an alignment score RG:... Cannot continue " << endl; exit(1); }
//if (!stats.insert.count(rg)) {
// cerr << "Read " << al.Name << " doesn't have a RG id( " << rg << " ) at bam header ... Cannot continue " << endl; exit(1);
//}
// Deal with the case when we find a new reference sequence in the bam
if ( currentRefID != al.RefID ) {
if ( firstRecord ) {
firstRecord = false;
} else {
OutputStats( currentRefIDstring, references[currentRefID].RefLength + 1, stats, refgaps );
}
currentRefID = al.RefID;
currentRefIDstring = references[al.RefID].RefName;
unsigned long startPos = 1;
stats.properPair = Coverage( ops.iniReadLength, startPos );
stats.pLowAlignScore = Coverage( ops.iniReadLength, startPos );
stats.crossSignal = Coverage( ops.iniReadLength, startPos ); // to be a cross signal reads then the reads must be a proper-pair first!
stats.badInserSizePair = Coverage( ops.iniReadLength, startPos );
stats.wrongOrientation = Coverage( ops.iniReadLength, startPos );
stats.single = Coverage( ops.iniReadLength, startPos );
stats.clipAlign = Coverage( ops.iniReadLength, startPos );
//LoadGC(tigc, currentRefIDstring, stats.refGC);
}
// print all stats to left 100bp of current read mapped position
// It's very important to keep away from the current mapped position 100bp, this distance is for reads clip situation!
OutputStats ( currentRefIDstring, al.Position - 100, stats, refgaps ); // Acturally I dn't have to set -100 now! 2013-11-26 22:57:32
// Now the coordinate in Coverage should equal to al.Position
//isToosmall = stats.insert[rg].first - 3 * stats.insert[rg].second; if ( isToosmall < 0 ) isToosmall = 1;
//isToobig = stats.insert[rg].first + 3 * stats.insert[rg].second;
// Caution: Bamtools give the 0-base coordinate system which interval is half closed '(]', I shift it to 1-base
// coordinate system which interval is closed '[]' below.
// al.Position is 0-base;
// al.GetEndPosition() is 1-base by default
if ( al.CigarData[0].Type == 'S' && (al.Position+1) > 1 ) stats.clipAlign.Add((al.Position+1) - 1);
if ( al.CigarData.back().Type == 'S' && al.GetEndPosition()+1 <= references[al.RefID].RefLength ) stats.clipAlign.Add(al.GetEndPosition() + 1);
short pairOrientation = GetPairOrientation( al );
if ( !al.IsMateMapped() || pairOrientation == UNPAIRED || pairOrientation == DIFF_CHROM ) {
stats.single.Add (al.Position + 1, al.GetEndPosition()); // al.Position is 0-base, shift to 1-base
} else if ( pairOrientation == INNER ) { //Correct orientation but the insertsize could be good or bad
if ( al.IsProperPair() ) {
if ( alignScore >= ops.minAlignScore ) { // stats.properPair
// Should consider cross signal first!
map< char, vector<pair<int32_t,int32_t> > > indelSignal = IndelSignalRefPos(al.Position + 1, al.CigarData);
if ( indelSignal.count('I') ) {
for ( size_t i(0); i < indelSignal['I'].size(); ++i )
stats.crossSignal.Add( indelSignal['I'][i].first, indelSignal['I'][i].second );
}
if ( indelSignal.count('D') ) {
for ( size_t i(0); i < indelSignal['D'].size(); ++i )
stats.crossSignal.Add( indelSignal['D'][i].first, indelSignal['D'][i].second );
}
if ( !indelSignal.count('I') && !indelSignal.count('D') ) stats.properPair.Add ( al.Position + 1, al.GetEndPosition() );
} else { // stats.pLowAlignScore
stats.pLowAlignScore.Add( al.Position + 1, al.GetEndPosition() ); // read coverage
}
} else {
stats.badInserSizePair.Add ( al.Position + 1, al.GetEndPosition() );
}
} else if ( pairOrientation == SAME || pairOrientation == OUTTER ) { // Wrong Orientation
stats.wrongOrientation.Add ( (al.Position + 1), al.GetEndPosition() );
} else {
cerr << ERROR_PREFIX << "Didn't expect this to happen... " << al.Name << endl; exit(1);
}
}
bamReader.Close();
cerr << ">>> Total lines number in bamInfile : " << num << endl;
// print the remaining stats from the last ref sequence in the bam
OutputStats( currentRefIDstring, references[currentRefID].RefLength + 1, stats, refgaps );
cerr << "***************************** All Done ******************************\n" << endl;
return 0;
}
void ParseOptions(int argc, char** argv, CmdLineOptions& ops) {
// Set Default
ops.minMapQuality = 30;
ops.minAlignScore = 90;
ops.iniReadLength = 1000;
char c;
while ( (c = getopt(argc, argv, "b:a:l:q:r:g:c:h") ) != -1 ) {
switch ( c ) {
case 'b' : ops.bamInfile = optarg; break;
case 'r' : ops.refGCfile = optarg; break;
case 'g' : ops.gapInfile = optarg; break;
case 'c' : ops.gc2covfile = optarg; break; // gc contain to coverage
case 'q' : ops.minMapQuality = atoi(optarg); break;
case 'a' : ops.minAlignScore = atoi(optarg); break;
case 'l' : ops.iniReadLength = atoi(optarg); break;
case 'h' : Usage( argv[0] );
default :
cerr << "\n[ERROR]Unknow option: -" << c << "\n" << endl; exit(1);
}
}
//if ( ops.bamInfile.empty() || ops.refGCfile.empty() || ops.gc2covfile.empty() || ops.gapInfile.empty() ) Usage ( argv[0] );
if ( ops.bamInfile.empty() || ops.gapInfile.empty() ) Usage ( argv[0] );
}
void Usage ( const char* prog ) {
cerr << "\nVersion : 0.0.0 (2013-11-25 22:33:53) \n"
<< "Author : Shujia Huang \n\n"
<< "\nUsage : " << prog << " [Option] [-b bamInfile] > Output \n\n"
<< " Options : \n\n"
<< " -b bam input file. Required! \n"
//<< " -r File of reference's GC contain. Required! \n"
<< " -g File of reference gap' regions. Required! \n"
//<< " -c File of GC contain vs coverage. Required! \n"
<< " -q Min Mapped quality. [30] \n"
<< " -a Min alignment score. [90] \n"
<< " -l Init fragment length.[1000] Not Suggest to change this parameter.\n"
<< " -h Show this help. \n" << endl;
exit(1);
}
| 43.408257 | 151 | 0.611434 | [
"vector"
] |
711cd5cbf8ba30ae6bdf4fbd094f654caded9f15 | 8,269 | cpp | C++ | ros_ign_bridge/src/factories/geometry_msgs.cpp | gezp/ros_ign | bfacf1a378f19f69e711f651a0d589fdb5e9b1f4 | [
"Apache-2.0"
] | null | null | null | ros_ign_bridge/src/factories/geometry_msgs.cpp | gezp/ros_ign | bfacf1a378f19f69e711f651a0d589fdb5e9b1f4 | [
"Apache-2.0"
] | null | null | null | ros_ign_bridge/src/factories/geometry_msgs.cpp | gezp/ros_ign | bfacf1a378f19f69e711f651a0d589fdb5e9b1f4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "factories/geometry_msgs.hpp"
#include <memory>
#include <string>
#include "factory.hpp"
#include "ros_ign_bridge/convert/geometry_msgs.hpp"
namespace ros_ign_bridge
{
std::shared_ptr<FactoryInterface>
get_factory__geometry_msgs(
const std::string & ros_type_name,
const std::string & ign_type_name)
{
if ((ros_type_name == "geometry_msgs/msg/Quaternion" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Quaternion")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Quaternion,
ignition::msgs::Quaternion
>
>("geometry_msgs/msg/Quaternion", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/Vector3" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Vector3d")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Vector3,
ignition::msgs::Vector3d
>
>("geometry_msgs/msg/Vector3", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/Point" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Vector3d")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Point,
ignition::msgs::Vector3d
>
>("geometry_msgs/msg/Point", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/Pose" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Pose")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Pose,
ignition::msgs::Pose
>
>("geometry_msgs/msg/Pose", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/PoseStamped" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Pose")
{
return std::make_shared<
Factory<
geometry_msgs::msg::PoseStamped,
ignition::msgs::Pose
>
>("geometry_msgs/msg/PoseStamped", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/Transform" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Pose")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Transform,
ignition::msgs::Pose
>
>("geometry_msgs/msg/Transform", ign_type_name);
}
if ((ros_type_name == "geometry_msgs/msg/TransformStamped" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Pose")
{
return std::make_shared<
Factory<
geometry_msgs::msg::TransformStamped,
ignition::msgs::Pose
>
>("geometry_msgs/msg/TransformStamped", ign_type_name);
}
if (
(ros_type_name == "geometry_msgs/msg/Twist" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Twist")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Twist,
ignition::msgs::Twist
>
>("geometry_msgs/msg/Twist", ign_type_name);
}
if (
(ros_type_name == "geometry_msgs/msg/Wrench" || ros_type_name.empty()) &&
ign_type_name == "ignition.msgs.Wrench")
{
return std::make_shared<
Factory<
geometry_msgs::msg::Wrench,
ignition::msgs::Wrench
>
>("geometry_msgs/msg/Wrench", ign_type_name);
}
return nullptr;
}
template<>
void
Factory<
geometry_msgs::msg::Quaternion,
ignition::msgs::Quaternion
>::convert_ros_to_ign(
const geometry_msgs::msg::Quaternion & ros_msg,
ignition::msgs::Quaternion & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Quaternion,
ignition::msgs::Quaternion
>::convert_ign_to_ros(
const ignition::msgs::Quaternion & ign_msg,
geometry_msgs::msg::Quaternion & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Vector3,
ignition::msgs::Vector3d
>::convert_ros_to_ign(
const geometry_msgs::msg::Vector3 & ros_msg,
ignition::msgs::Vector3d & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Vector3,
ignition::msgs::Vector3d
>::convert_ign_to_ros(
const ignition::msgs::Vector3d & ign_msg,
geometry_msgs::msg::Vector3 & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Point,
ignition::msgs::Vector3d
>::convert_ros_to_ign(
const geometry_msgs::msg::Point & ros_msg,
ignition::msgs::Vector3d & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Point,
ignition::msgs::Vector3d
>::convert_ign_to_ros(
const ignition::msgs::Vector3d & ign_msg,
geometry_msgs::msg::Point & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Pose,
ignition::msgs::Pose
>::convert_ros_to_ign(
const geometry_msgs::msg::Pose & ros_msg,
ignition::msgs::Pose & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Pose,
ignition::msgs::Pose
>::convert_ign_to_ros(
const ignition::msgs::Pose & ign_msg,
geometry_msgs::msg::Pose & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::PoseStamped,
ignition::msgs::Pose
>::convert_ros_to_ign(
const geometry_msgs::msg::PoseStamped & ros_msg,
ignition::msgs::Pose & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::PoseStamped,
ignition::msgs::Pose
>::convert_ign_to_ros(
const ignition::msgs::Pose & ign_msg,
geometry_msgs::msg::PoseStamped & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Transform,
ignition::msgs::Pose
>::convert_ros_to_ign(
const geometry_msgs::msg::Transform & ros_msg,
ignition::msgs::Pose & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Transform,
ignition::msgs::Pose
>::convert_ign_to_ros(
const ignition::msgs::Pose & ign_msg,
geometry_msgs::msg::Transform & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::TransformStamped,
ignition::msgs::Pose
>::convert_ros_to_ign(
const geometry_msgs::msg::TransformStamped & ros_msg,
ignition::msgs::Pose & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::TransformStamped,
ignition::msgs::Pose
>::convert_ign_to_ros(
const ignition::msgs::Pose & ign_msg,
geometry_msgs::msg::TransformStamped & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Twist,
ignition::msgs::Twist
>::convert_ros_to_ign(
const geometry_msgs::msg::Twist & ros_msg,
ignition::msgs::Twist & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Twist,
ignition::msgs::Twist
>::convert_ign_to_ros(
const ignition::msgs::Twist & ign_msg,
geometry_msgs::msg::Twist & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Wrench,
ignition::msgs::Wrench
>::convert_ros_to_ign(
const geometry_msgs::msg::Wrench & ros_msg,
ignition::msgs::Wrench & ign_msg)
{
ros_ign_bridge::convert_ros_to_ign(ros_msg, ign_msg);
}
template<>
void
Factory<
geometry_msgs::msg::Wrench,
ignition::msgs::Wrench
>::convert_ign_to_ros(
const ignition::msgs::Wrench & ign_msg,
geometry_msgs::msg::Wrench & ros_msg)
{
ros_ign_bridge::convert_ign_to_ros(ign_msg, ros_msg);
}
} // namespace ros_ign_bridge
| 24.107872 | 89 | 0.706494 | [
"transform"
] |
7132107230c34ca7b94245468c9740058f8005a6 | 816 | cpp | C++ | sliding window/239 Sliding Window Maximum.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | sliding window/239 Sliding Window Maximum.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | sliding window/239 Sliding Window Maximum.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | //
// 239 Sliding Window Maximum.cpp
// Leetcode
//
// Created by Quinn on 2021/1/2.
// Copyright © 2021 Quinn. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
deque<int> q;
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
if (!q.empty() && i - q.front() + 1 > k)
{
q.pop_front();
}
while (!q.empty() && nums[q.back()] <= nums[i])
{
q.pop_back();
}
q.push_back(i);
if (i + 1 >= k)
{
res.push_back(nums[q.front()]);
}
}
return res;
}
};
| 18.133333 | 59 | 0.433824 | [
"vector"
] |
71428396f6f4b6a21b3e3811160e730867915fbb | 7,118 | cpp | C++ | tests/e2e/extended_exchange_messages_test.cpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | tests/e2e/extended_exchange_messages_test.cpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | tests/e2e/extended_exchange_messages_test.cpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | #include <catch2/catch_test_macros.hpp>
#include <zmq_addon.hpp>
#include <boost/asio.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <cassert>
#include <icon/endpoint/endpoint_config.hpp>
#include <icon/client/basic_client.hpp>
#include <fmt/format.h>
#include <iostream>
#include <sstream>
#include <random>
#include <atomic>
#include <mutex>
struct Info
{
std::string thread_id;
std::vector<std::string> endpoints;
std::vector<std::string> clients;
};
constexpr auto NumberOfThreads{ 4 };
constexpr auto NumberOfEndpoints{ 10 };
constexpr auto NumberOfClientsPerThread{ 8 };
constexpr auto NumberOfMessagesPerClient{ 50 };
constexpr auto MaxExecutionTime{ std::chrono::minutes(5) };
constexpr auto ExpectedProocessedMessages = NumberOfClientsPerThread * NumberOfThreads * NumberOfMessagesPerClient;
std::atomic<size_t> ProcessedMessages{ 0 };
std::vector<std::string> addresses;
std::vector<boost::asio::io_context*> contexts{};
std::mutex contexts_mtx{};
std::vector<Info> infos;
std::mutex info_mtx;
using boost::asio::awaitable;
using boost::asio::co_spawn;
using boost::asio::detached;
using boost::asio::use_awaitable;
void add_info(Info info)
{
auto lock = std::scoped_lock{ info_mtx };
infos.push_back(std::move(info));
}
void dump_info(const Info& info)
{
icon::utils::get_logger()->debug("Dump infor for thread: {}", info.thread_id);
for (const auto& e : info.endpoints) {
icon::utils::get_logger()->debug("-- Endpoint bind : {}", e);
}
for (const auto& c : info.clients) {
icon::utils::get_logger()->debug("-- Client connected: {}", c);
}
icon::utils::get_logger()->debug("------------------------------------");
}
void add_context(boost::asio::io_context* ctx)
{
auto lock = std::scoped_lock{ contexts_mtx };
icon::utils::get_logger()->debug("Add context");
contexts.emplace_back(ctx);
}
size_t rnd(const size_t min, const size_t max)
{
static auto rd = std::random_device{};
static auto gen = std::mt19937{ rd() };
auto dist = std::uniform_int_distribution<size_t>(min, max);
return dist(gen);
}
auto create_endpoint(boost::asio::io_context& bctx, zmq::context_t& zctx, const std::string& address)
{
using namespace icon;
using namespace icon::details;
return icon::setup_default_endpoint(
icon::use_services(bctx, zctx),
icon::address(address),
icon::consumer<TestSeqReq>(
[](MessageContext<TestSeqReq> context) -> awaitable<void> {
auto& req = context.message();
auto seq_req = req.seq();
auto seq_rsp = seq_req + 1;
auto rsp = TestSeqCfm{};
rsp.set_seq(seq_rsp);
co_await context.async_respond(std::move(rsp));
}))
.build();
}
awaitable<void> run_client(icon::BasicClient& client, const std::string endpoint)
{
co_await client.async_connect(endpoint.c_str());
for (size_t i = 0; i < NumberOfMessagesPerClient; i++) {
auto seq_req = icon::TestSeqReq{};
seq_req.set_seq(i);
icon::utils::get_logger()->debug("Client send...");
auto rsp = co_await client.async_send(std::move(seq_req));
assert(rsp.is<icon::TestSeqCfm>());
const auto msg = rsp.get<icon::TestSeqCfm>();
icon::utils::get_logger()->debug("Client received...");
++ProcessedMessages;
assert(msg.seq() == i + 1);
}
}
void worker_thread(std::vector<std::string> endpoint_addresses)
{
auto bctx = boost::asio::io_context{};
auto zctx = zmq::context_t{};
using work_guard_type =
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
work_guard_type work_guard(bctx.get_executor());
add_context(&bctx);
auto endpoints = std::vector<std::unique_ptr<icon::Endpoint>>{};
auto clients = std::vector<std::unique_ptr<icon::BasicClient>>{};
auto info = Info{};
info.thread_id = "Undefined";
// Initialize endpoints
for (const auto& addr : endpoint_addresses) {
info.endpoints.push_back(addr);
endpoints.push_back(create_endpoint(bctx, zctx, addr));
}
// Initialize clients
for (size_t i = 0; i < NumberOfClientsPerThread; i++) {
clients.push_back(std::make_unique<icon::BasicClient>(zctx, bctx));
}
// Run endpoints
for (auto& e : endpoints) {
co_spawn(bctx, e->run(), detached);
}
// Run clients
for (auto& c : clients) {
auto addr = addresses[rnd(0, addresses.size() - 1)];
info.clients.push_back(addr);
co_spawn(bctx, run_client(*c, addr), detached);
}
add_info(std::move(info));
bctx.run();
}
void generate_addresses(size_t i)
{
addresses.resize(i);
std::generate(addresses.begin(), addresses.end(), [n = 5555]() mutable {
return fmt::format("tcp://127.0.0.1:{}", n++);
});
}
auto get_add(size_t i, size_t m, std::deque<std::string>& addr)
{
auto ret = std::vector<std::string>{};
auto cp = [&ret, &addr](size_t n) {
for (size_t idx = 0; idx < n; ++idx) {
ret.push_back(addr.front());
addr.pop_front();
}
return ret;
};
if (addr.empty()) {
return ret;
}
if (i < m) {
cp(rnd(1, addr.size()));
}
if (i == m) {
cp(addr.size());
}
return ret;
}
void guard_thread()
{
auto now = std::chrono::system_clock::now();
auto deadline = now + MaxExecutionTime;
while (true) {
if (std::chrono::system_clock::now() > deadline) {
icon::utils::get_logger()->error("Timeout reached. Terminate.");
std::terminate();
}
if (ProcessedMessages == ExpectedProocessedMessages) {
break;
} else {
std::this_thread::sleep_for(std::chrono::seconds(5));
icon::utils::get_logger()->debug("ProcessedMessages: {}", ProcessedMessages);
}
}
for (auto* ctx : contexts) {
ctx->stop();
}
}
void print_summary()
{
icon::utils::get_logger()->debug("Running on {} threads", NumberOfThreads);
icon::utils::get_logger()->debug("Total endpoints: {}", NumberOfEndpoints);
icon::utils::get_logger()->debug("Total clients: {}", NumberOfClientsPerThread * NumberOfThreads);
icon::utils::get_logger()->debug("Expected messages: {}", ExpectedProocessedMessages);
icon::utils::get_logger()->debug("Processed messages: {}", ProcessedMessages);
for (const auto& info : infos) {
dump_info(info);
}
}
TEST_CASE("Multiple endpooints and clients spawned in multiple threads are exchanging messages.")
{
spdlog::set_level(spdlog::level::debug);
generate_addresses(NumberOfEndpoints);
auto d = std::deque<std::string>{};
for (auto& a : addresses) {
d.push_back(a);
}
auto addr_per_th = std::vector<std::vector<std::string>>{};
for (size_t i = 1; i <= NumberOfThreads; i++) {
auto addr = get_add(i, NumberOfThreads, d);
for (auto& a : addr) {
fmt::print("Addr for: {}, {}\n", i, a);
}
addr_per_th.push_back(addr);
}
auto threads = std::vector<std::thread>{};
// Push Worker threads
for (size_t i = 0; i < NumberOfThreads; i++) {
threads.push_back(std::thread(worker_thread, addr_per_th[i]));
}
// Push guard thread
threads.push_back(std::thread(guard_thread));
for (auto& th : threads) {
th.join();
}
print_summary();
}
| 24.629758 | 115 | 0.658191 | [
"vector"
] |
7144f1fda4bb046d2c935a8b15fea91cbcef30fa | 7,446 | cpp | C++ | src/hasher.cpp | snaury/hasher | 23825e7208dffee6578f25e294497a8afbe266e1 | [
"MIT"
] | null | null | null | src/hasher.cpp | snaury/hasher | 23825e7208dffee6578f25e294497a8afbe266e1 | [
"MIT"
] | null | null | null | src/hasher.cpp | snaury/hasher | 23825e7208dffee6578f25e294497a8afbe266e1 | [
"MIT"
] | null | null | null | #include <system_error>
#include <iostream>
#include <memory>
#include <list>
#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <boost/atomic.hpp>
#include <boost/thread.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/timer/timer.hpp>
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
#include <stdint.h>
#include <fcntl.h>
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#include <io.h>
typedef int ssize_t;
#else
#include <unistd.h>
#define O_BINARY 0
#endif
/** Buffer for a single chunk of data
*/
class buffer : boost::noncopyable
{
boost::scoped_array<uint8_t> m_data;
boost::atomic<int> m_refcount;
size_t m_maxsize;
size_t m_size;
public:
typedef boost::shared_ptr<buffer> ptr;
buffer(int maxsize)
: m_data(new uint8_t[maxsize]),
m_refcount(0),
m_maxsize(maxsize),
m_size(0)
{ }
void acquire(int count = 1) {
// memory order can be relaxed since synchronization
// will be used for cross-thread comunication anyway
m_refcount.fetch_add(count, boost::memory_order_relaxed);
}
bool release(int count = 1) {
if (m_refcount.fetch_sub(count, boost::memory_order_release) <= count) {
boost::atomic_thread_fence(boost::memory_order_acquire);
return true;
}
return false;
}
uint8_t* get() const {
return m_data.get();
}
size_t maxsize() const {
return m_maxsize;
}
void size(size_t newsize) {
m_size = std::min(newsize, m_maxsize);
}
size_t size() const {
return m_size;
}
};
/** Thread-safe queue
*/
template<class T>
class safe_queue
{
bool m_done;
std::list<T> m_queue;
boost::mutex m_mutex;
boost::condition_variable m_not_empty;
public:
typedef boost::shared_ptr<safe_queue> ptr;
safe_queue()
: m_done(false)
{ }
void push(const T& value) {
boost::unique_lock<boost::mutex> lock(m_mutex);
m_queue.push_back(value);
m_not_empty.notify_one();
}
bool pop(T& value) {
boost::unique_lock<boost::mutex> lock(m_mutex);
while (m_queue.empty()) {
if (m_done) {
return false;
}
m_not_empty.wait(lock);
}
value = m_queue.front();
m_queue.pop_front();
return true;
}
void done() {
boost::unique_lock<boost::mutex> lock(m_mutex);
m_done = true;
m_not_empty.notify_all();
}
};
/** Base class for threads that calculate hashes
*/
class hash_thread_base
{
std::string m_name;
safe_queue<buffer::ptr> m_input;
safe_queue<buffer::ptr>::ptr m_freequeue;
protected:
hash_thread_base(const std::string& name, safe_queue<buffer::ptr>::ptr freequeue)
: m_name(name), m_freequeue(freequeue)
{
}
bool pop(buffer::ptr& chunk) {
return m_input.pop(chunk);
}
void release(buffer::ptr chunk) {
if (chunk->release()) {
m_freequeue->push(chunk);
}
}
public:
typedef boost::shared_ptr<hash_thread_base> ptr;
std::string name() const {
return m_name;
}
void push(buffer::ptr chunk) {
m_input.push(chunk);
}
void done() {
m_input.done();
}
virtual void start() = 0;
virtual void join() = 0;
virtual std::string hexdigest() = 0;
};
/** Implementation of hash_thread for a particular algorithm
*/
template<class HashAlgorithm>
class hash_thread : public hash_thread_base
{
HashAlgorithm m_hash;
boost::thread m_thread;
void worker() {
buffer::ptr chunk;
while (pop(chunk)) {
m_hash.Update(chunk->get(), chunk->size());
release(chunk);
}
}
public:
hash_thread(const std::string& name, safe_queue<buffer::ptr>::ptr freequeue)
: hash_thread_base(name, freequeue)
{ }
virtual void start() override {
boost::thread thread(&hash_thread::worker, this);
m_thread.swap(thread);
}
virtual void join() override {
m_thread.join();
}
virtual std::string hexdigest() override {
boost::scoped_array<uint8_t> digest(new uint8_t[m_hash.DigestSize()]);
m_hash.Final(digest.get());
std::string hexdigest(m_hash.DigestSize() * 2, 0);
for (size_t i = 0, j = 0; i < m_hash.DigestSize(); ++i) {
uint8_t k = digest[i];
hexdigest[j++] = "0123456789abcdef"[k >> 4];
hexdigest[j++] = "0123456789abcdef"[k & 15];
}
return hexdigest;
}
};
/** Low-level file IO with less overhead
*/
class iofile : boost::noncopyable
{
private:
int m_fd;
public:
bool operator!() const {
return m_fd == -1;
}
iofile()
: m_fd(-1)
{ }
iofile(const char* filename, int flags)
: m_fd(-1)
{
open(filename, flags);
}
~iofile() {
close();
}
bool open(const char* filename, int flags) {
if (m_fd != -1) {
::close(m_fd);
m_fd = -1;
}
m_fd = ::open(filename, flags);
return m_fd != -1;
}
void close() {
if (m_fd != -1) {
::close(m_fd);
m_fd = -1;
}
}
ssize_t read(void* buf, size_t count) {
return ::read(m_fd, buf, count);
}
ssize_t write(const void* buf, size_t count) {
return ::write(m_fd, buf, count);
}
};
int main(int argc, char** argv)
{
bool errors = false;
const size_t chunk_size = 65536;
const size_t readahead_size = 1048576;
for (int i = 1; i < argc; ++i) {
const char* filename = argv[i];
std::cout << filename << "...";
iofile fd(filename, O_RDONLY | O_BINARY);
if (!fd) {
std::error_code ec(errno, std::system_category());
std::cout << " error opening file: " << ec.message() << std::endl;
errors = true;
continue;
}
safe_queue<buffer::ptr>::ptr buffers = boost::make_shared< safe_queue<buffer::ptr> >();
for (size_t i = 0; i < readahead_size / chunk_size; ++i) {
buffers->push(boost::make_shared<buffer>(chunk_size));
}
std::vector<hash_thread_base::ptr> hash_threads;
hash_threads.push_back(boost::make_shared< hash_thread<CryptoPP::Weak::MD5> >("md5", buffers));
hash_threads.push_back(boost::make_shared< hash_thread<CryptoPP::SHA1> >("sha1", buffers));
hash_threads.push_back(boost::make_shared< hash_thread<CryptoPP::SHA256> >("sha256", buffers));
hash_threads.push_back(boost::make_shared< hash_thread<CryptoPP::SHA512> >("sha512", buffers));
for (const auto& hthread : hash_threads) {
hthread->start();
}
bool ok = true;
buffer::ptr chunk;
uint64_t filesize = 0;
boost::timer::cpu_timer timer;
while (buffers->pop(chunk)) {
ssize_t nbytes = fd.read(chunk->get(), chunk->maxsize());
if (nbytes == 0)
break;
if (nbytes < 0) {
std::error_code ec(errno, std::system_category());
std::cout << " error reading file: " << ec.message() << std::endl;
errors = true;
ok = false;
break;
}
chunk->size(nbytes);
chunk->acquire(hash_threads.size());
for (const auto& hthread : hash_threads) {
hthread->push(chunk);
}
filesize += nbytes;
}
for (const auto& hthread : hash_threads) {
hthread->done();
hthread->join();
}
if (!ok) {
continue;
}
boost::timer::cpu_times times = timer.elapsed();
std::cout << boost::format(" %d bytes (%.2fMB/s)") % filesize % ((double)filesize / 1048576.0 / (times.wall / 1000000000.0)) << std::endl;
for (const auto& hthread : hash_threads) {
std::cout << "\t" << hthread->name() << "\t" << hthread->hexdigest() << std::endl;
}
}
if (errors) {
return 1;
}
return 0;
}
| 22.226866 | 142 | 0.624631 | [
"vector"
] |
71480a225ffaa6789a5c689edc4b1b05adadad08 | 149 | cpp | C++ | src/c++/node_xz.cpp | robey/node-xz | 63ff8818be86ce6663d8e853116cfbcb7906545a | [
"Apache-2.0"
] | 19 | 2015-03-12T06:21:48.000Z | 2022-03-26T08:31:18.000Z | deps/xz/src/c++/node_xz.cpp | nullxx/clusperri-installer | 1112b5c65f930c47fcb841fb07e5dac32d041597 | [
"MIT"
] | 12 | 2015-08-21T02:45:22.000Z | 2021-08-31T22:49:28.000Z | src/c++/node_xz.cpp | robey/node-xz | 63ff8818be86ce6663d8e853116cfbcb7906545a | [
"Apache-2.0"
] | 5 | 2015-08-05T10:50:44.000Z | 2021-06-21T16:54:30.000Z | #include "engine.h"
Napi::Object init(Napi::Env env, Napi::Object exports) {
return Engine::Init(env, exports);
}
NODE_API_MODULE(node_xz, init)
| 18.625 | 56 | 0.718121 | [
"object"
] |
714f75102e8b70b8cfa74a3d2654de8ee5daf765 | 70,032 | cpp | C++ | extern/TGUI-0.7.8/src/TGUI/Widgets/EditBox.cpp | towzeur/PLT_2021 | c2598b387929f76ec8766e4e4741efc1a0c0379d | [
"MIT"
] | 4 | 2020-10-06T12:48:22.000Z | 2020-12-09T16:08:47.000Z | extern/TGUI-0.7.8/src/TGUI/Widgets/EditBox.cpp | towzeur/PLT_2021 | c2598b387929f76ec8766e4e4741efc1a0c0379d | [
"MIT"
] | 1 | 2020-11-24T15:41:11.000Z | 2020-11-24T15:41:11.000Z | extern/TGUI-0.7.8/src/TGUI/Widgets/EditBox.cpp | towzeur/PLT_2021 | c2598b387929f76ec8766e4e4741efc1a0c0379d | [
"MIT"
] | 2 | 2020-11-19T20:29:14.000Z | 2020-12-02T12:55:58.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus's Graphical User Interface
// Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <TGUI/Container.hpp>
#include <TGUI/Widgets/EditBox.hpp>
#include <TGUI/Loading/Theme.hpp>
#include <TGUI/Clipboard.hpp>
#include <TGUI/Clipping.hpp>
#include <cmath>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string EditBox::Validator::Int = "[+-]?[0-9]*";
std::string EditBox::Validator::UInt = "[0-9]*";
std::string EditBox::Validator::Float = "[+-]?[0-9]*\\.?[0-9]*";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EditBox::EditBox()
{
m_callback.widgetType = "EditBox";
m_draggableWidget = true;
m_allowFocus = true;
addSignal<sf::String>("TextChanged");
addSignal<sf::String>("ReturnKeyPressed");
m_defaultText.setStyle(sf::Text::Italic);
m_caret.setSize({1, 0});
m_renderer = std::make_shared<EditBoxRenderer>(this);
reload();
setSize({240, 30});
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EditBox::Ptr EditBox::create()
{
return std::make_shared<EditBox>();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EditBox::Ptr EditBox::copy(EditBox::ConstPtr editBox)
{
if (editBox)
return std::static_pointer_cast<EditBox>(editBox->clone());
else
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setPosition(const Layout2d& position)
{
Widget::setPosition(position);
getRenderer()->m_textureHover.setPosition(getPosition());
getRenderer()->m_textureNormal.setPosition(getPosition());
getRenderer()->m_textureFocused.setPosition(getPosition());
recalculateTextPositions();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setSize(const Layout2d& size)
{
Widget::setSize(size);
// Recalculate the text size when auto scaling
if (m_textSize == 0)
setText(m_text);
getRenderer()->m_textureHover.setSize(getSize());
getRenderer()->m_textureNormal.setSize(getSize());
getRenderer()->m_textureFocused.setSize(getSize());
// Set the size of the caret
m_caret.setSize({m_caret.getSize().x,
getSize().y - getRenderer()->getScaledPadding().bottom - getRenderer()->getScaledPadding().top});
// Recalculate the position of the images and texts
updatePosition();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sf::Vector2f EditBox::getFullSize() const
{
return {getSize().x + getRenderer()->getBorders().left + getRenderer()->getBorders().right,
getSize().y + getRenderer()->getBorders().top + getRenderer()->getBorders().bottom};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setFont(const Font& font)
{
Widget::setFont(font);
if (font.getFont())
{
m_textBeforeSelection.setFont(*font.getFont());
m_textSelection.setFont(*font.getFont());
m_textAfterSelection.setFont(*font.getFont());
m_textFull.setFont(*font.getFont());
m_defaultText.setFont(*font.getFont());
}
// Recalculate the text size and position
setText(m_text);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setText(const sf::String& text)
{
// Check if the text is auto sized
if (m_textSize == 0)
{
m_textFull.setCharacterSize(findBestTextSize(getFont(), (getSize().y - getRenderer()->getScaledPadding().bottom - getRenderer()->getScaledPadding().top) * 0.85f));
m_textBeforeSelection.setCharacterSize(m_textFull.getCharacterSize());
m_textSelection.setCharacterSize(m_textFull.getCharacterSize());
m_textAfterSelection.setCharacterSize(m_textFull.getCharacterSize());
m_defaultText.setCharacterSize(m_textFull.getCharacterSize());
}
else // When the text has a fixed size
{
m_textFull.setCharacterSize(m_textSize);
m_textBeforeSelection.setCharacterSize(m_textSize);
m_textSelection.setCharacterSize(m_textSize);
m_textAfterSelection.setCharacterSize(m_textSize);
m_defaultText.setCharacterSize(m_textSize);
}
// Change the text if allowed
if (m_regexString == ".*")
m_text = text;
else if (std::regex_match(text.toAnsiString(), m_regex))
m_text = text.toAnsiString(); // Unicode is not supported when using regex because it can't be checked
else // Clear the text
m_text = "";
m_displayedText = m_text;
// If there is a character limit then check if it is exeeded
if ((m_maxChars > 0) && (m_displayedText.getSize() > m_maxChars))
{
// Remove all the excess characters
m_text.erase(m_maxChars, sf::String::InvalidPos);
m_displayedText.erase(m_maxChars, sf::String::InvalidPos);
}
// Check if there is a password character
if (m_passwordChar != '\0')
{
// Loop every character and change it
for (std::size_t i = 0; i < m_text.getSize(); ++i)
m_displayedText[i] = m_passwordChar;
}
// Set the texts
m_textBeforeSelection.setString(m_displayedText);
m_textSelection.setString("");
m_textAfterSelection.setString("");
m_textFull.setString(m_displayedText);
float width = getVisibleEditBoxWidth();
// Check if there is a text width limit
if (m_limitTextWidth)
{
// Now check if the text fits into the EditBox
while (m_textBeforeSelection.findCharacterPos(m_textBeforeSelection.getString().getSize()).x - m_textBeforeSelection.getPosition().x > width)
{
// The text doesn't fit inside the EditBox, so the last character must be deleted.
m_text.erase(m_text.getSize()-1);
m_displayedText.erase(m_displayedText.getSize()-1);
// Set the new text
m_textBeforeSelection.setString(m_displayedText);
}
// Set the full text again
m_textFull.setString(m_displayedText);
}
else // There is no text cropping
{
// Calculate the text width
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
// If the text can be moved to the right then do so
if (textWidth > width)
{
if (textWidth - m_textCropPosition < width)
m_textCropPosition = static_cast<unsigned int>(textWidth - width);
}
else
m_textCropPosition = 0;
}
// Set the caret behind the last character
setCaretPosition(m_displayedText.getSize());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setDefaultText(const sf::String& text)
{
m_defaultText.setString(text);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sf::String EditBox::getSelectedText() const
{
if (m_selStart < m_selEnd)
return m_text.substring(m_selStart, m_selChars);
else if (m_selStart > m_selEnd)
return m_text.substring(m_selEnd, m_selChars);
else
return "";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setTextSize(unsigned int size)
{
// Change the text size
m_textSize = size;
// Call setText to re-position the text
setText(m_text);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setPasswordCharacter(char passwordChar)
{
// Change the password character
m_passwordChar = passwordChar;
// Recalculate the text position
setText(m_text);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setMaximumCharacters(unsigned int maxChars)
{
// Set the new character limit ( 0 to disable the limit )
m_maxChars = maxChars;
// If there is a character limit then check if it is exceeded
if ((m_maxChars > 0) && (m_displayedText.getSize() > m_maxChars))
{
// Remove all the excess characters
m_text.erase(m_maxChars, sf::String::InvalidPos);
m_displayedText.erase(m_maxChars, sf::String::InvalidPos);
// If we passed here then the text has changed.
m_textBeforeSelection.setString(m_displayedText);
m_textSelection.setString("");
m_textAfterSelection.setString("");
m_textFull.setString(m_displayedText);
// Set the caret behind the last character
setCaretPosition(m_displayedText.getSize());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setAlignment(Alignment alignment)
{
m_textAlignment = alignment;
setText(m_text);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::limitTextWidth(bool limitWidth)
{
m_limitTextWidth = limitWidth;
// Check if the width is being limited
if (m_limitTextWidth)
{
// Now check if the text fits into the EditBox
float width = getVisibleEditBoxWidth();
while (m_textBeforeSelection.findCharacterPos(m_displayedText.getSize()).x - m_textBeforeSelection.getPosition().x > width)
{
// The text doesn't fit inside the EditBox, so the last character must be deleted.
m_text.erase(m_text.getSize()-1);
m_displayedText.erase(m_displayedText.getSize()-1);
m_textBeforeSelection.setString(m_displayedText);
}
// The full text might have changed
m_textFull.setString(m_displayedText);
// There is no clipping
m_textCropPosition = 0;
// If the caret was behind the limit, then set it at the end
if (m_selEnd > m_displayedText.getSize())
setCaretPosition(m_selEnd);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setCaretPosition(std::size_t charactersBeforeCaret)
{
// The caret position has to stay inside the string
if (charactersBeforeCaret > m_text.getSize())
charactersBeforeCaret = m_text.getSize();
// Set the caret to the correct position
m_selChars = 0;
m_selStart = charactersBeforeCaret;
m_selEnd = charactersBeforeCaret;
// Change our texts
m_textBeforeSelection.setString(m_displayedText);
m_textSelection.setString("");
m_textAfterSelection.setString("");
m_textFull.setString(m_displayedText);
// Check if scrolling is enabled
if (!m_limitTextWidth)
{
// Find out the position of the caret
float caretPosition = m_textFull.findCharacterPos(m_selEnd).x;
if (m_selEnd == m_displayedText.getSize())
caretPosition += m_textFull.getCharacterSize() / 10.f;
// If the caret is too far on the right then adjust the cropping
if (m_textCropPosition + getVisibleEditBoxWidth() < caretPosition)
m_textCropPosition = static_cast<unsigned int>(caretPosition - getVisibleEditBoxWidth());
// If the caret is too far on the left then adjust the cropping
if (m_textCropPosition > caretPosition)
m_textCropPosition = static_cast<unsigned int>(caretPosition);
}
recalculateTextPositions();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::size_t EditBox::getCaretPosition() const
{
return m_selEnd;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setCaretWidth(float width)
{
m_caret.setPosition(m_caret.getPosition().x + ((m_caret.getSize().x - width) / 2.0f), m_caret.getPosition().y);
m_caret.setSize({width, getSize().y - getRenderer()->getScaledPadding().bottom - getRenderer()->getScaledPadding().top});
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setInputValidator(const std::string& regex)
{
#if defined(__clang__) || !defined(__GNUC__) || ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 9)))
m_regexString = regex;
m_regex = m_regexString;
setText(m_text);
#else
throw Exception{"EditBox::setInputValidator can't be used on GCC < 4.9"};
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const std::string& EditBox::getInputValidator()
{
return m_regexString;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::selectText()
{
m_selStart = 0;
m_selEnd = m_text.getSize();
updateSelection();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::setOpacity(float opacity)
{
ClickableWidget::setOpacity(opacity);
getRenderer()->m_textureNormal.setColor({getRenderer()->m_textureNormal.getColor().r, getRenderer()->m_textureNormal.getColor().g, getRenderer()->m_textureNormal.getColor().b, static_cast<sf::Uint8>(m_opacity * 255)});
getRenderer()->m_textureHover.setColor({getRenderer()->m_textureHover.getColor().r, getRenderer()->m_textureHover.getColor().g, getRenderer()->m_textureHover.getColor().b, static_cast<sf::Uint8>(m_opacity * 255)});
getRenderer()->m_textureFocused.setColor({getRenderer()->m_textureFocused.getColor().r, getRenderer()->m_textureFocused.getColor().g, getRenderer()->m_textureFocused.getColor().b, static_cast<sf::Uint8>(m_opacity * 255)});
#if SFML_VERSION_MAJOR > 2 || (SFML_VERSION_MAJOR == 2 && SFML_VERSION_MINOR >= 4)
m_textBeforeSelection.setFillColor(calcColorOpacity(getRenderer()->m_textColor, getOpacity()));
m_textAfterSelection.setFillColor(calcColorOpacity(getRenderer()->m_textColor, getOpacity()));
m_textSelection.setFillColor(calcColorOpacity(getRenderer()->m_selectedTextColor, getOpacity()));
m_selectedTextBackground.setFillColor(calcColorOpacity(getRenderer()->m_selectedTextBackgroundColor, getOpacity()));
m_defaultText.setFillColor(calcColorOpacity(getRenderer()->m_defaultTextColor, getOpacity()));
#else
m_textBeforeSelection.setColor(calcColorOpacity(getRenderer()->m_textColor, getOpacity()));
m_textAfterSelection.setColor(calcColorOpacity(getRenderer()->m_textColor, getOpacity()));
m_textSelection.setColor(calcColorOpacity(getRenderer()->m_selectedTextColor, getOpacity()));
m_selectedTextBackground.setFillColor(calcColorOpacity(getRenderer()->m_selectedTextBackgroundColor, getOpacity()));
m_defaultText.setColor(calcColorOpacity(getRenderer()->m_defaultTextColor, getOpacity()));
#endif
m_caret.setFillColor(calcColorOpacity(getRenderer()->m_caretColor, getOpacity()));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sf::Vector2f EditBox::getWidgetOffset() const
{
return {getRenderer()->getBorders().left, getRenderer()->getBorders().top};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::leftMousePressed(float x, float y)
{
// Find the caret position
float positionX = x - getPosition().x - getRenderer()->getScaledPadding().left;
std::size_t caretPosition = findCaretPosition(positionX);
// When clicking on the left of the first character, move the caret to the left
if ((positionX < 0) && (caretPosition > 0))
--caretPosition;
// When clicking on the right of the right character, move the caret to the right
else if ((positionX > getVisibleEditBoxWidth()) && (caretPosition < m_displayedText.getSize()))
++caretPosition;
// Check if this is a double click
if ((m_possibleDoubleClick) && (m_selChars == 0) && (caretPosition == m_selEnd))
{
// The next click is going to be a normal one again
m_possibleDoubleClick = false;
// Set the caret at the end of the text
setCaretPosition(m_displayedText.getSize());
// Select the whole text
m_selStart = 0;
m_selEnd = m_text.getSize();
updateSelection();
}
else // No double clicking
{
// Set the new caret
setCaretPosition(caretPosition);
// If the next click comes soon enough then it will be a double click
m_possibleDoubleClick = true;
}
// Set the mouse down flag
m_mouseDown = true;
m_callback.mouse.x = static_cast<int>(x - getPosition().x);
m_callback.mouse.y = static_cast<int>(y - getPosition().y);
sendSignal("MousePressed", sf::Vector2f{x - getPosition().x, y - getPosition().y});
// The caret should be visible
m_caretVisible = true;
m_animationTimeElapsed = {};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::mouseMoved(float x, float)
{
if (!m_mouseHover)
mouseEnteredWidget();
// The mouse has moved so a double click is no longer possible
m_possibleDoubleClick = false;
// Check if the mouse is hold down (we are selecting multiple characters)
if (m_mouseDown)
{
// Check if there is a text width limit
if (m_limitTextWidth)
{
// Find out between which characters the mouse is standing
m_selEnd = findCaretPosition(x - getPosition().x - getRenderer()->getScaledPadding().left);
}
else // Scrolling is enabled
{
float width = getVisibleEditBoxWidth();
// Check if the mouse is on the left of the text
if (x - getPosition().x < getRenderer()->getScaledPadding().left)
{
// Move the text by a few pixels
if (m_textFull.getCharacterSize() > 10)
{
if (m_textCropPosition > m_textFull.getCharacterSize() / 10)
m_textCropPosition -= static_cast<unsigned int>(std::floor(m_textFull.getCharacterSize() / 10.f + 0.5f));
else
m_textCropPosition = 0;
}
else
{
if (m_textCropPosition)
--m_textCropPosition;
}
}
// Check if the mouse is on the right of the text AND there is a possibility to scroll
else if ((x - getPosition().x > getRenderer()->getScaledPadding().left + width) && (m_textFull.findCharacterPos(m_displayedText.getSize()).x > width))
{
// Move the text by a few pixels
if (m_textFull.getCharacterSize() > 10)
{
if (m_textCropPosition + width < m_textFull.findCharacterPos(m_displayedText.getSize()).x + (m_textFull.getCharacterSize() / 10))
m_textCropPosition += static_cast<unsigned int>(std::floor(m_textFull.getCharacterSize() / 10.f + 0.5f));
else
m_textCropPosition = static_cast<unsigned int>(m_textFull.findCharacterPos(m_displayedText.getSize()).x + (m_textFull.getCharacterSize() / 10) - width);
}
else
{
if (m_textCropPosition + width < m_textFull.findCharacterPos(m_displayedText.getSize()).x)
++m_textCropPosition;
}
}
// Find out between which characters the mouse is standing
m_selEnd = findCaretPosition(x - getPosition().x - getRenderer()->getScaledPadding().left);
}
updateSelection();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::keyPressed(const sf::Event::KeyEvent& event)
{
// Check if one of the correct keys was pressed
if (event.code == sf::Keyboard::Left)
{
if (event.shift)
{
if (m_selEnd > 0)
{
m_selEnd--;
updateSelection();
}
}
else // Shift key is not being held down
{
// Check if we have selected some text
if (m_selChars > 0)
{
// We will not move the caret, but just undo the selection
if (m_selStart < m_selEnd)
setCaretPosition(m_selStart);
else
setCaretPosition(m_selEnd);
}
else // When we did not select any text
{
// Move the caret to the left
if (m_selEnd > 0)
setCaretPosition(m_selEnd - 1);
}
}
// Our caret has moved, it should be visible
m_caretVisible = true;
m_animationTimeElapsed = {};
}
else if (event.code == sf::Keyboard::Right)
{
if (event.shift)
{
if (m_selEnd < m_displayedText.getSize())
{
m_selEnd++;
updateSelection();
}
}
else // Shift key is not being held down
{
// Check if we have selected some text
if (m_selChars > 0)
{
// We will not move the caret, but just undo the selection
if (m_selStart < m_selEnd)
setCaretPosition(m_selEnd);
else
setCaretPosition(m_selStart);
}
else // When we did not select any text
{
// Move the caret to the right
if (m_selEnd < m_displayedText.getSize())
setCaretPosition(m_selEnd + 1);
}
}
// Our caret has moved, it should be visible
m_caretVisible = true;
m_animationTimeElapsed = {};
}
else if (event.code == sf::Keyboard::Home)
{
if (event.shift)
{
m_selEnd = 0;
updateSelection();
}
else // Shift key is not being held down
{
// Set the caret to the beginning of the text
setCaretPosition(0);
}
// Our caret has moved, it should be visible
m_caretVisible = true;
m_animationTimeElapsed = {};
}
else if (event.code == sf::Keyboard::End)
{
if (event.shift)
{
m_selEnd = m_text.getSize();
updateSelection();
}
else // Shift key is not being held down
{
// Set the caret behind the text
setCaretPosition(m_text.getSize());
}
// Our caret has moved, it should be visible
m_caretVisible = true;
m_animationTimeElapsed = {};
}
else if (event.code == sf::Keyboard::Return)
{
m_callback.text = m_text;
sendSignal("ReturnKeyPressed", getText());
}
else if (event.code == sf::Keyboard::BackSpace)
{
// Make sure that we did not select any characters
if (m_selChars == 0)
{
// We can't delete any characters when you are at the beginning of the string
if (m_selEnd == 0)
return;
// Erase the character
m_text.erase(m_selEnd-1, 1);
m_displayedText.erase(m_selEnd-1, 1);
// Set the caret back on the correct position
setCaretPosition(m_selEnd - 1);
float width = getVisibleEditBoxWidth();
// Calculate the text width
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
// If the text can be moved to the right then do so
if (textWidth > width)
{
if (textWidth - m_textCropPosition < width)
m_textCropPosition = static_cast<unsigned int>(textWidth - width);
}
else
m_textCropPosition = 0;
}
else // When you did select some characters, delete them
deleteSelectedCharacters();
// The caret should be visible again
m_caretVisible = true;
m_animationTimeElapsed = {};
m_callback.text = m_text;
sendSignal("TextChanged", getText());
}
else if (event.code == sf::Keyboard::Delete)
{
// Make sure that no text is selected
if (m_selChars == 0)
{
// When the caret is at the end of the line then you can't delete anything
if (m_selEnd == m_text.getSize())
return;
// Erase the character
m_text.erase(m_selEnd, 1);
m_displayedText.erase(m_selEnd, 1);
// Set the caret back on the correct position
setCaretPosition(m_selEnd);
// Calculate the text width
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
// If the text can be moved to the right then do so
float width = getVisibleEditBoxWidth();
if (textWidth > width)
{
if (textWidth - m_textCropPosition < width)
m_textCropPosition = static_cast<unsigned int>(textWidth - width);
}
else
m_textCropPosition = 0;
}
else // You did select some characters, delete them
deleteSelectedCharacters();
// The caret should be visible again
m_caretVisible = true;
m_animationTimeElapsed = {};
m_callback.text = m_text;
sendSignal("TextChanged", getText());
}
else
{
// Check if you are copying, pasting or cutting text
if (event.control && !event.alt && !event.shift && !event.system)
{
if (event.code == sf::Keyboard::C)
{
Clipboard::set(m_textSelection.getString());
}
else if (event.code == sf::Keyboard::V)
{
auto clipboardContents = Clipboard::get();
// Only continue pasting if you actually have to do something
if ((m_selChars > 0) || (clipboardContents.getSize() > 0))
{
deleteSelectedCharacters();
std::size_t oldCaretPos = m_selEnd;
if (m_text.getSize() > m_selEnd)
setText(m_text.toWideString().substr(0, m_selEnd) + Clipboard::get() + m_text.toWideString().substr(m_selEnd, m_text.getSize() - m_selEnd));
else
setText(m_text + clipboardContents);
setCaretPosition(oldCaretPos + clipboardContents.getSize());
m_callback.text = m_text;
sendSignal("TextChanged", getText());
}
}
else if (event.code == sf::Keyboard::X)
{
Clipboard::set(m_textSelection.getString());
deleteSelectedCharacters();
m_callback.text = m_text;
sendSignal("TextChanged", getText());
}
else if (event.code == sf::Keyboard::A)
{
selectText();
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::textEntered(sf::Uint32 key)
{
// Only add the character when the regex matches
if (m_regexString != ".*")
{
sf::String text = m_text;
if (m_selChars == 0)
text.insert(m_selEnd, key);
else
{
const std::size_t pos = std::min(m_selStart, m_selEnd);
text.erase(pos, m_selChars);
text.insert(pos, key);
}
// The character has to match the regex
if (!std::regex_match(text.toAnsiString(), m_regex))
return;
}
// If there are selected characters then delete them first
if (m_selChars > 0)
deleteSelectedCharacters();
// Make sure we don't exceed our maximum characters limit
if ((m_maxChars > 0) && (m_text.getSize() + 1 > m_maxChars))
return;
// Insert our character
m_text.insert(m_selEnd, key);
// Change the displayed text
if (m_passwordChar != '\0')
m_displayedText.insert(m_selEnd, m_passwordChar);
else
m_displayedText.insert(m_selEnd, key);
// Append the character to the text
m_textFull.setString(m_displayedText);
// When there is a text width limit then reverse what we just did
if (m_limitTextWidth)
{
// Now check if the text fits into the EditBox
if (m_textFull.findCharacterPos(m_displayedText.getSize()).x > getVisibleEditBoxWidth())
{
// If the text does not fit in the EditBox then delete the added character
m_text.erase(m_selEnd, 1);
m_displayedText.erase(m_selEnd, 1);
return;
}
}
// Move our caret forward
setCaretPosition(m_selEnd + 1);
// The caret should be visible again
m_caretVisible = true;
m_animationTimeElapsed = {};
m_callback.text = m_text;
sendSignal("TextChanged", getText());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::widgetFocused()
{
#if defined (SFML_SYSTEM_ANDROID) || defined (SFML_SYSTEM_IOS)
sf::Keyboard::setVirtualKeyboardVisible(true);
#endif
Widget::widgetFocused();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::widgetUnfocused()
{
// If there is a selection then undo it now
if (m_selChars)
setCaretPosition(m_selEnd);
#if defined (SFML_SYSTEM_ANDROID) || defined (SFML_SYSTEM_IOS)
sf::Keyboard::setVirtualKeyboardVisible(false);
#endif
Widget::widgetUnfocused();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::reload(const std::string& primary, const std::string& secondary, bool force)
{
#if SFML_VERSION_MAJOR > 2 || (SFML_VERSION_MAJOR == 2 && SFML_VERSION_MINOR >= 4)
m_textBeforeSelection.setFillColor({0, 0, 0});
m_textSelection.setFillColor({255, 255, 255});
m_textAfterSelection.setFillColor({0, 0, 0});
m_defaultText.setFillColor({160, 160, 160});
#else
m_textBeforeSelection.setColor({0, 0, 0});
m_textSelection.setColor({255, 255, 255});
m_textAfterSelection.setColor({0, 0, 0});
m_defaultText.setColor({160, 160, 160});
#endif
m_caret.setFillColor({0, 0, 0});
m_selectedTextBackground.setFillColor({0, 110, 255});
getRenderer()->setBorders({2, 2, 2, 2});
getRenderer()->setPadding({4, 2, 4, 2});
getRenderer()->setBorderColor({0, 0, 0});
getRenderer()->setBackgroundColorNormal({245, 245, 245});
getRenderer()->setBackgroundColorHover({255, 255, 255});
getRenderer()->setNormalTexture({});
getRenderer()->setHoverTexture({});
getRenderer()->setFocusTexture({});
if (m_theme && primary != "")
{
getRenderer()->setBorders({0, 0, 0, 0});
Widget::reload(primary, secondary, force);
if (force)
{
if (getRenderer()->m_textureNormal.isLoaded())
setSize(getRenderer()->m_textureNormal.getImageSize());
}
// Call setText to re-position the text
setText(m_text);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float EditBox::getVisibleEditBoxWidth()
{
return std::max(0.f, getSize().x - getRenderer()->getScaledPadding().left - getRenderer()->getScaledPadding().right);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::size_t EditBox::findCaretPosition(float posX)
{
// This code will crash when the editbox is empty. We need to avoid this.
if (m_displayedText.isEmpty())
return 0;
// Take the part outside the edit box into account when the text does not fit inside it
posX += m_textCropPosition;
// If the text is centered or aligned to the right then the position has to be corrected when the edit box is not entirely full
if (m_textAlignment != Alignment::Left)
{
float editBoxWidth = getVisibleEditBoxWidth();
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
if (textWidth < editBoxWidth)
{
// Set the number of pixels to move
if (m_textAlignment == Alignment::Center)
posX -= (editBoxWidth - textWidth) / 2.f;
else // if (textAlignment == Alignment::Right)
posX -= editBoxWidth - textWidth;
}
}
float width = 0;
sf::Uint32 prevChar = 0;
unsigned int textSize = getTextSize();
bool bold = false; /// TODO: (getRenderer()->getTextStyle() & sf::Text::Bold) != 0;
std::size_t index;
for (index = 0; index < m_text.getSize(); ++index)
{
float charWidth;
sf::Uint32 curChar = m_text[index];
if (curChar == '\n')
{
// This should not happen as edit box is for single line text, but lets try the next line anyway since we haven't found the position yet
width = 0;
prevChar = 0;
continue;
}
else if (curChar == '\t')
charWidth = static_cast<float>(getFont()->getGlyph(' ', textSize, bold).advance) * 4;
else
charWidth = static_cast<float>(getFont()->getGlyph(curChar, textSize, bold).advance);
float kerning = static_cast<float>(getFont()->getKerning(prevChar, curChar, textSize));
if (width + charWidth < posX)
width += charWidth + kerning;
else
{
// If the mouse is on the second halve of the character then the caret should be on the right of it
if (width + charWidth - posX < charWidth / 2.f)
index++;
break;
}
prevChar = curChar;
}
return index;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::deleteSelectedCharacters()
{
// Nothing to delete when no text was selected
if (m_selChars == 0)
return;
// Check if the characters were selected from left to right
if (m_selStart < m_selEnd)
{
// Erase the characters
m_text.erase(m_selStart, m_selChars);
m_displayedText.erase(m_selStart, m_selChars);
// Set the caret back on the correct position
setCaretPosition(m_selStart);
}
else // When the text is selected from right to left
{
// Erase the characters
m_text.erase(m_selEnd, m_selChars);
m_displayedText.erase(m_selEnd, m_selChars);
// Set the caret back on the correct position
setCaretPosition(m_selEnd);
}
// Calculate the text width
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
// If the text can be moved to the right then do so
float width = getVisibleEditBoxWidth();
if (textWidth > width)
{
if (textWidth - m_textCropPosition < width)
m_textCropPosition = static_cast<unsigned int>(textWidth - width);
}
else
m_textCropPosition = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::recalculateTextPositions()
{
Padding padding = getRenderer()->getScaledPadding();
float textX = getPosition().x + padding.left - m_textCropPosition;
float textY = 0;
if (getFont())
{
textY = std::round((getPosition().y + padding.top - getTextVerticalCorrection(getFont(), getTextSize()))
+ ((getSize().y - padding.bottom - padding.top) - getFont()->getLineSpacing(getTextSize())) / 2.f);
}
// Check if the layout wasn't left
if (m_textAlignment != Alignment::Left)
{
// Calculate the text width
float textWidth = m_textFull.findCharacterPos(m_displayedText.getSize()).x;
// Check if a layout would make sense
if (textWidth < getVisibleEditBoxWidth())
{
// Put the text on the correct position
if (m_textAlignment == Alignment::Center)
textX += (getVisibleEditBoxWidth() - textWidth) / 2.f;
else // if (textAlignment == Alignment::Right)
textX += getVisibleEditBoxWidth() - textWidth;
}
}
float caretLeft = textX;
// Set the text before the selection on the correct position
m_textBeforeSelection.setPosition(std::floor(textX + 0.5f), textY);
m_defaultText.setPosition(std::floor(textX + 0.5f), textY);
// Check if there is a selection
if (m_selChars != 0)
{
// Watch out for the kerning
if (m_textBeforeSelection.getString().getSize() > 0)
textX += m_font->getKerning(m_displayedText[m_textBeforeSelection.getString().getSize() - 1], m_displayedText[m_textBeforeSelection.getString().getSize()], m_textBeforeSelection.getCharacterSize());
textX += m_textBeforeSelection.findCharacterPos(m_textBeforeSelection.getString().getSize()).x - m_textBeforeSelection.getPosition().x;
// Set the position and size of the rectangle that gets drawn behind the selected text
m_selectedTextBackground.setSize({m_textSelection.findCharacterPos(m_textSelection.getString().getSize()).x - m_textSelection.getPosition().x,
getSize().y - padding.top - padding.bottom});
m_selectedTextBackground.setPosition(std::floor(textX + 0.5f), std::floor(getPosition().y + padding.top + 0.5f));
// Set the text selected text on the correct position
m_textSelection.setPosition(std::floor(textX + 0.5f), textY);
// Watch out for kerning
if (m_displayedText.getSize() > m_textBeforeSelection.getString().getSize() + m_textSelection.getString().getSize())
textX += m_font->getKerning(m_displayedText[m_textBeforeSelection.getString().getSize() + m_textSelection.getString().getSize() - 1], m_displayedText[m_textBeforeSelection.getString().getSize() + m_textSelection.getString().getSize()], m_textBeforeSelection.getCharacterSize());
// Set the text selected text on the correct position
textX += m_textSelection.findCharacterPos(m_textSelection.getString().getSize()).x - m_textSelection.getPosition().x;
m_textAfterSelection.setPosition(std::floor(textX + 0.5f), textY);
}
// Set the position of the caret
caretLeft += m_textFull.findCharacterPos(m_selEnd).x - (m_caret.getSize().x * 0.5f);
m_caret.setPosition(std::floor(caretLeft + 0.5f), std::floor(padding.top + getPosition().y + 0.5f));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::updateSelection()
{
bool recalculationNeeded = false;
// Check if we are selecting text from left to right
if (m_selEnd > m_selStart)
{
// There is no need to redo everything when nothing changed
if (m_selChars != (m_selEnd - m_selStart))
{
// Adjust the number of characters that are selected
m_selChars = m_selEnd - m_selStart;
// Change our three texts
m_textBeforeSelection.setString(m_displayedText.toWideString().substr(0, m_selStart));
m_textSelection.setString(m_displayedText.toWideString().substr(m_selStart, m_selChars));
m_textAfterSelection.setString(m_displayedText.toWideString().substr(m_selEnd));
recalculationNeeded = true;
}
}
else if (m_selEnd < m_selStart)
{
// There is no need to redo everything when nothing changed
if (m_selChars != (m_selStart - m_selEnd))
{
// Adjust the number of characters that are selected
m_selChars = m_selStart - m_selEnd;
// Change our three texts
m_textBeforeSelection.setString(m_displayedText.toWideString().substr(0, m_selEnd));
m_textSelection.setString(m_displayedText.toWideString().substr(m_selEnd, m_selChars));
m_textAfterSelection.setString(m_displayedText.toWideString().substr(m_selStart));
recalculationNeeded = true;
}
}
else if (m_selChars > 0)
{
// Adjust the number of characters that are selected
m_selChars = 0;
// Change our three texts
m_textBeforeSelection.setString(m_displayedText);
m_textSelection.setString("");
m_textAfterSelection.setString("");
recalculationNeeded = true;
}
if (recalculationNeeded)
{
// Check if scrolling is enabled
if (!m_limitTextWidth)
{
// Find out the position of the caret
float caretPosition = m_textFull.findCharacterPos(m_selEnd).x;
if (m_selEnd == m_displayedText.getSize())
caretPosition += m_textFull.getCharacterSize() / 10.f;
// If the caret is too far on the right then adjust the cropping
if (m_textCropPosition + getVisibleEditBoxWidth() < caretPosition)
m_textCropPosition = static_cast<unsigned int>(caretPosition - getVisibleEditBoxWidth());
// If the caret is too far on the left then adjust the cropping
if (m_textCropPosition > caretPosition)
m_textCropPosition = static_cast<unsigned int>(caretPosition);
}
recalculateTextPositions();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::update(sf::Time elapsedTime)
{
Widget::update(elapsedTime);
// Only show/hide the caret every half second
if (m_animationTimeElapsed >= sf::milliseconds(500))
{
// Reset the elapsed time
m_animationTimeElapsed = {};
// Switch the value of the visible flag
m_caretVisible = !m_caretVisible;
// Too slow for double clicking
m_possibleDoubleClick = false;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBox::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
// Draw the background
getRenderer()->draw(target, states);
// Set the clipping for all draw calls that happen until this clipping object goes out of scope
Padding padding = getRenderer()->getScaledPadding();
Clipping clipping{target, states, {getPosition().x + padding.left, getPosition().y + padding.top}, {getSize().x - padding.left - padding.right, getSize().y - padding.top - padding.bottom}};
if ((m_textBeforeSelection.getString() != "") || (m_textSelection.getString() != ""))
{
target.draw(m_textBeforeSelection, states);
if (m_textSelection.getString() != "")
{
target.draw(m_selectedTextBackground, states);
target.draw(m_textSelection, states);
target.draw(m_textAfterSelection, states);
}
}
else if (m_defaultText.getString() != "")
{
target.draw(m_defaultText, states);
}
// Draw the caret
if ((m_focused) && (m_caretVisible))
target.draw(m_caret, states);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setProperty(std::string property, const std::string& value)
{
property = toLower(property);
if (property == "padding")
setPadding(Deserializer::deserialize(ObjectConverter::Type::Borders, value).getBorders());
else if (property == "borders")
setBorders(Deserializer::deserialize(ObjectConverter::Type::Borders, value).getBorders());
else if (property == "caretwidth")
m_editBox->setCaretWidth(Deserializer::deserialize(ObjectConverter::Type::Number, value).getNumber());
else if (property == "textcolor")
setTextColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "selectedtextcolor")
setSelectedTextColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "selectedtextbackgroundcolor")
setSelectedTextBackgroundColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "defaulttextcolor")
setDefaultTextColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "caretcolor")
setCaretColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "backgroundcolor")
setBackgroundColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "backgroundcolornormal")
setBackgroundColorNormal(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "backgroundcolorhover")
setBackgroundColorHover(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "bordercolor")
setBorderColor(Deserializer::deserialize(ObjectConverter::Type::Color, value).getColor());
else if (property == "normalimage")
setNormalTexture(Deserializer::deserialize(ObjectConverter::Type::Texture, value).getTexture());
else if (property == "hoverimage")
setHoverTexture(Deserializer::deserialize(ObjectConverter::Type::Texture, value).getTexture());
else if (property == "focusedimage")
setFocusTexture(Deserializer::deserialize(ObjectConverter::Type::Texture, value).getTexture());
else
WidgetRenderer::setProperty(property, value);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setProperty(std::string property, ObjectConverter&& value)
{
property = toLower(property);
if (value.getType() == ObjectConverter::Type::Borders)
{
if (property == "padding")
setPadding(value.getBorders());
else if (property == "borders")
setBorders(value.getBorders());
else
WidgetRenderer::setProperty(property, std::move(value));
}
else if (value.getType() == ObjectConverter::Type::Color)
{
if (property == "textcolor")
setTextColor(value.getColor());
else if (property == "selectedtextcolor")
setSelectedTextColor(value.getColor());
else if (property == "selectedtextbackgroundcolor")
setSelectedTextBackgroundColor(value.getColor());
else if (property == "defaulttextcolor")
setDefaultTextColor(value.getColor());
else if (property == "caretcolor")
setCaretColor(value.getColor());
else if (property == "backgroundcolor")
setBackgroundColor(value.getColor());
else if (property == "backgroundcolornormal")
setBackgroundColorNormal(value.getColor());
else if (property == "backgroundcolorhover")
setBackgroundColorHover(value.getColor());
else if (property == "bordercolor")
setBorderColor(value.getColor());
else
WidgetRenderer::setProperty(property, std::move(value));
}
else if (value.getType() == ObjectConverter::Type::Texture)
{
if (property == "normalimage")
setNormalTexture(value.getTexture());
else if (property == "hoverimage")
setHoverTexture(value.getTexture());
else if (property == "focusedimage")
setFocusTexture(value.getTexture());
else
WidgetRenderer::setProperty(property, std::move(value));
}
else if (value.getType() == ObjectConverter::Type::Number)
{
if (property == "caretwidth")
m_editBox->setCaretWidth(value.getNumber());
}
else
WidgetRenderer::setProperty(property, std::move(value));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ObjectConverter EditBoxRenderer::getProperty(std::string property) const
{
property = toLower(property);
if (property == "padding")
return m_padding;
else if (property == "borders")
return m_borders;
else if (property == "caretwidth")
return m_editBox->getCaretWidth();
else if (property == "textcolor")
return m_textColor;
else if (property == "selectedtextcolor")
return m_selectedTextColor;
else if (property == "selectedtextbackgroundcolor")
return m_selectedTextBackgroundColor;
else if (property == "defaulttextcolor")
return m_defaultTextColor;
else if (property == "caretcolor")
return m_caretColor;
else if (property == "backgroundcolor")
return m_backgroundColorNormal;
else if (property == "backgroundcolornormal")
return m_backgroundColorNormal;
else if (property == "backgroundcolorhover")
return m_backgroundColorHover;
else if (property == "bordercolor")
return m_borderColor;
else if (property == "normalimage")
return m_textureNormal;
else if (property == "hoverimage")
return m_textureHover;
else if (property == "focusedimage")
return m_textureFocused;
else
return WidgetRenderer::getProperty(property);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map<std::string, ObjectConverter> EditBoxRenderer::getPropertyValuePairs() const
{
auto pairs = WidgetRenderer::getPropertyValuePairs();
if (m_textureNormal.isLoaded())
{
pairs["NormalImage"] = m_textureNormal;
if (m_textureHover.isLoaded())
pairs["HoverImage"] = m_textureHover;
if (m_textureFocused.isLoaded())
pairs["FocusedImage"] = m_textureFocused;
}
else
{
pairs["BackgroundColorNormal"] = m_backgroundColorNormal;
pairs["BackgroundColorHover"] = m_backgroundColorHover;
}
pairs["CaretWidth"] = m_editBox->getCaretWidth();
pairs["TextColor"] = m_textColor;
pairs["SelectedTextColor"] = m_selectedTextColor;
pairs["SelectedTextBackgroundColor"] = m_selectedTextBackgroundColor;
pairs["DefaultTextColor"] = m_defaultTextColor;
pairs["CaretColor"] = m_caretColor;
pairs["BorderColor"] = m_borderColor;
pairs["Borders"] = m_borders;
pairs["Padding"] = m_padding;
return pairs;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setPadding(const Padding& padding)
{
WidgetPadding::setPadding(padding);
// Recalculate the text size
m_editBox->setText(m_editBox->m_text);
// Set the size of the caret
m_editBox->m_caret.setSize({m_editBox->m_caret.getSize().x,
m_editBox->getSize().y - getScaledPadding().bottom - getScaledPadding().top});
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setCaretWidth(float width)
{
m_editBox->setCaretWidth(width);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setTextColor(const Color& textColor)
{
m_textColor = textColor;
#if SFML_VERSION_MAJOR > 2 || (SFML_VERSION_MAJOR == 2 && SFML_VERSION_MINOR >= 4)
m_editBox->m_textBeforeSelection.setFillColor(calcColorOpacity(m_textColor, m_editBox->getOpacity()));
m_editBox->m_textAfterSelection.setFillColor(calcColorOpacity(m_textColor, m_editBox->getOpacity()));
#else
m_editBox->m_textBeforeSelection.setColor(calcColorOpacity(m_textColor, m_editBox->getOpacity()));
m_editBox->m_textAfterSelection.setColor(calcColorOpacity(m_textColor, m_editBox->getOpacity()));
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setSelectedTextColor(const Color& selectedTextColor)
{
m_selectedTextColor = selectedTextColor;
#if SFML_VERSION_MAJOR > 2 || (SFML_VERSION_MAJOR == 2 && SFML_VERSION_MINOR >= 4)
m_editBox->m_textSelection.setFillColor(calcColorOpacity(m_selectedTextColor, m_editBox->getOpacity()));
#else
m_editBox->m_textSelection.setColor(calcColorOpacity(m_selectedTextColor, m_editBox->getOpacity()));
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setSelectedTextBackgroundColor(const Color& selectedTextBackgroundColor)
{
m_selectedTextBackgroundColor = selectedTextBackgroundColor;
m_editBox->m_selectedTextBackground.setFillColor(calcColorOpacity(m_selectedTextBackgroundColor, m_editBox->getOpacity()));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setDefaultTextColor(const Color& defaultTextColor)
{
m_defaultTextColor = defaultTextColor;
#if SFML_VERSION_MAJOR > 2 || (SFML_VERSION_MAJOR == 2 && SFML_VERSION_MINOR >= 4)
m_editBox->m_defaultText.setFillColor(calcColorOpacity(m_defaultTextColor, m_editBox->getOpacity()));
#else
m_editBox->m_defaultText.setColor(calcColorOpacity(m_defaultTextColor, m_editBox->getOpacity()));
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setBackgroundColor(const Color& color)
{
setBackgroundColorNormal(color);
setBackgroundColorHover(color);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setBackgroundColorNormal(const Color& color)
{
m_backgroundColorNormal = color;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setBackgroundColorHover(const Color& color)
{
m_backgroundColorHover = color;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setCaretColor(const Color& caretColor)
{
m_caretColor = caretColor;
m_editBox->m_caret.setFillColor(calcColorOpacity(m_caretColor, m_editBox->getOpacity()));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setBorderColor(const Color& color)
{
m_borderColor = color;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setNormalTexture(const Texture& texture)
{
m_textureNormal = texture;
if (m_textureNormal.isLoaded())
{
m_textureNormal.setPosition(m_editBox->getPosition());
m_textureNormal.setSize(m_editBox->getSize());
m_textureNormal.setColor({m_textureNormal.getColor().r, m_textureNormal.getColor().g, m_textureNormal.getColor().b, static_cast<sf::Uint8>(m_editBox->getOpacity() * 255)});
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setHoverTexture(const Texture& texture)
{
m_textureHover = texture;
if (m_textureHover.isLoaded())
{
m_textureHover.setPosition(m_editBox->getPosition());
m_textureHover.setSize(m_editBox->getSize());
m_textureHover.setColor({m_textureHover.getColor().r, m_textureHover.getColor().g, m_textureHover.getColor().b, static_cast<sf::Uint8>(m_editBox->getOpacity() * 255)});
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setFocusTexture(const Texture& texture)
{
m_textureFocused = texture;
if (m_textureFocused.isLoaded())
{
m_textureFocused.setPosition(m_editBox->getPosition());
m_textureFocused.setSize(m_editBox->getSize());
m_textureFocused.setColor({m_textureFocused.getColor().r, m_textureFocused.getColor().g, m_textureFocused.getColor().b, static_cast<sf::Uint8>(m_editBox->getOpacity() * 255)});
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::setDefaultTextStyle(sf::Uint32 style)
{
m_editBox->m_defaultText.setStyle(style);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void EditBoxRenderer::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
// Check if there is a background texture
if (m_textureNormal.isLoaded())
{
if (m_editBox->m_mouseHover && m_textureHover.isLoaded())
target.draw(m_textureHover, states);
else
target.draw(m_textureNormal, states);
// When the edit box is focused then draw an extra image
if (m_editBox->m_focused && m_textureFocused.isLoaded())
target.draw(m_textureFocused, states);
}
else // There is no background texture
{
sf::RectangleShape editBox(m_editBox->getSize());
editBox.setPosition(m_editBox->getPosition());
if (m_editBox->m_mouseHover)
editBox.setFillColor(calcColorOpacity(m_backgroundColorHover, m_editBox->getOpacity()));
else
editBox.setFillColor(calcColorOpacity(m_backgroundColorNormal, m_editBox->getOpacity()));
target.draw(editBox, states);
}
// Draw the borders around the edit box
if (m_borders != Borders{0, 0, 0, 0})
{
sf::Vector2f position = m_editBox->getPosition();
sf::Vector2f size = m_editBox->getSize();
// Draw left border
sf::RectangleShape border({m_borders.left, size.y + m_borders.top});
border.setPosition(position.x - m_borders.left, position.y - m_borders.top);
border.setFillColor(calcColorOpacity(m_borderColor, m_editBox->getOpacity()));
target.draw(border, states);
// Draw top border
border.setSize({size.x + m_borders.right, m_borders.top});
border.setPosition(position.x, position.y - m_borders.top);
target.draw(border, states);
// Draw right border
border.setSize({m_borders.right, size.y + m_borders.bottom});
border.setPosition(position.x + size.x, position.y);
target.draw(border, states);
// Draw bottom border
border.setSize({size.x + m_borders.left, m_borders.bottom});
border.setPosition(position.x - m_borders.left, position.y + size.y);
target.draw(border, states);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Padding EditBoxRenderer::getScaledPadding() const
{
Padding padding = getPadding();
Padding scaledPadding = padding;
auto& texture = m_textureNormal;
if (texture.isLoaded())
{
switch (texture.getScalingType())
{
case Texture::ScalingType::Normal:
scaledPadding.left = padding.left * (texture.getSize().x / texture.getImageSize().x);
scaledPadding.right = padding.right * (texture.getSize().x / texture.getImageSize().x);
scaledPadding.top = padding.top * (texture.getSize().y / texture.getImageSize().y);
scaledPadding.bottom = padding.bottom * (texture.getSize().y / texture.getImageSize().y);
break;
case Texture::ScalingType::Horizontal:
scaledPadding.left = padding.left * (texture.getSize().y / texture.getImageSize().y);
scaledPadding.right = padding.right * (texture.getSize().y / texture.getImageSize().y);
scaledPadding.top = padding.top * (texture.getSize().y / texture.getImageSize().y);
scaledPadding.bottom = padding.bottom * (texture.getSize().y / texture.getImageSize().y);
break;
case Texture::ScalingType::Vertical:
scaledPadding.left = padding.left * (texture.getSize().x / texture.getImageSize().x);
scaledPadding.right = padding.right * (texture.getSize().x / texture.getImageSize().x);
scaledPadding.top = padding.top * (texture.getSize().x / texture.getImageSize().x);
scaledPadding.bottom = padding.bottom * (texture.getSize().x / texture.getImageSize().x);
break;
case Texture::ScalingType::NineSlice:
break;
}
}
return scaledPadding;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<WidgetRenderer> EditBoxRenderer::clone(Widget* widget)
{
auto renderer = std::make_shared<EditBoxRenderer>(*this);
renderer->m_editBox = static_cast<EditBox*>(widget);
return renderer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 41.341204 | 294 | 0.515878 | [
"object"
] |
715270e752f5ab625816ed76329737978b9da889 | 1,101 | cpp | C++ | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/10_Judge_Assignment_1_(26_May_2018)/02_mod_sum.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/10_Judge_Assignment_1_(26_May_2018)/02_mod_sum.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/10_Judge_Assignment_1_(26_May_2018)/02_mod_sum.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
using std::vector;
vector<int> splitStringToIntVector(string inputString, char delimiter);
int main() {
int n = 0; cin >> n;
int m = 0; cin >> m;
cin.ignore();
// LOGIC
vector<int> resultVect(m, 0);
for (int i = 0; i < n; i++) {
string inputString = ""; getline(cin, inputString);
vector<int> inputVect = splitStringToIntVector(inputString, ' ');
for (int j = 0; j < m; j++) {
resultVect[j] += inputVect[j];
}
}
int mod = 0; cin >> mod;
for (int i = 0; i < m; i++) {
cout << resultVect[i] % mod << " ";
}
return 0;
}
vector<int> splitStringToIntVector(string inputString, char delimiter) {
vector<int> intVect;
string element = "";
int inputStringLength = inputString.length();
for (int i = 0; i < inputStringLength; i++) {
if (inputString[i] == delimiter) {
intVect.push_back(stoi(element));
element = "";
}
else {
element += inputString[i];
}
}
intVect.push_back(stoi(element));
return intVect;
} | 18.982759 | 72 | 0.62852 | [
"vector"
] |
715b3a6ce1edf7b8e42ed2c295cf4df5f8406cf4 | 1,229 | cpp | C++ | CLRS/DynamicProgramming/ProductofArrayExceptSelf.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/DynamicProgramming/ProductofArrayExceptSelf.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/DynamicProgramming/ProductofArrayExceptSelf.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | /*
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
*/
// Using the concept of prefix product and suffix product
#if 0
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> output(nums.size(),1);
for ( int i = nums.size()-2; i >= 0; i-- )
{
output[i] = output[i+1] * nums[i+1];
}
int mul = 1;
for ( int i = 1; i < nums.size(); i++ )
{
mul *= nums[i-1];
output[i] = output[i] * mul;
}
return output;
}
};
#endif
#include "../Common/common_api.h"
int main()
{
int8_t x1 = 5, x2 = -5;
printf("x1 = %d(%x), x2 = %d(%x)\n",x1,x1,x2,x2);
}
| 26.717391 | 158 | 0.600488 | [
"vector"
] |
7164d571791e2fda8bca6ad8333518b43c4805d9 | 29,978 | cpp | C++ | hphp/runtime/base/multi-val.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/base/multi-val.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/base/multi-val.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | #include "hphp/runtime/base/multi-val.h"
#include "hphp/runtime/vm/native.h"
#include "hphp/runtime/ext/std/ext_std_variable.h"
#include "hphp/runtime/base/array-iterator.h"
#include "hphp/runtime/vm/member-operations.h"
#include "hphp/runtime/base/tv-helpers.h"
#include "fstream"
#include "set"
namespace HPHP {
//#define MUL_DETAIL_DEBUG
extern std::ofstream debug_log;
static inline void
castToStringInPlace(TypedValue* v) {
cheng_assert(v->m_type == KindOfStaticString);
auto str_ptr = v->m_data.pstr;
v->m_type = KindOfString;
v->m_data.pstr = StringData::Make(str_ptr, CopyString);
tvRefcountedIncRef(v);
}
static inline void
checkAdjustType(MultiVal* mv, TypedValue* adding_val) {
auto m_multi_type = mv->getType();
// some casting:
// int => Double
if (m_multi_type == KindOfDouble && adding_val->m_type == KindOfInt64) {
tvCastToDoubleInPlace(adding_val);
}
else if (m_multi_type == KindOfString && adding_val->m_type == KindOfStaticString) {
castToStringInPlace(adding_val);
}
// promote the multi-val from Int to Double
if (m_multi_type == KindOfInt64 && adding_val->m_type == KindOfDouble) {
// change the previous Int into Double
for (int i = 0; i < mv->valSize(); i++) {
tvCastToDoubleInPlace(mv->getByVal(i));
}
mv->setType(KindOfDouble);
m_multi_type = KindOfDouble;
}
// promote the multi-val from StaticString to String
else if (m_multi_type == KindOfStaticString && adding_val->m_type == KindOfString) {
// change the previous StaticString to String
for (int i = 0; i < mv->valSize(); i++) {
castToStringInPlace(mv->getByVal(i));
}
mv->setType(KindOfString);
m_multi_type = KindOfString;
}
// if m_multi_type is KindOfUninit, we accept NULL/Uninit and whatever
// if m_multi_type is decided, we accept NULL/Uninit and THAT TYPE
#ifdef CHENG_CHECK
if ( m_multi_type != KindOfUninit
&& (adding_val->m_type != KindOfUninit && adding_val->m_type != KindOfNull)
&& m_multi_type != adding_val->m_type) {
TypedValue tmp;
tmp.m_type = KindOfMulti;
tmp.m_data.pmulti = mv;
std::cout << "\n === AddValue Warning ===\nOriginal MultiVal:\n";
std::cout << " === Elements:\n";
for (auto it : *mv) {
std::cout << it->pretty() << "\n";
}
HHVM_FN(print_r)(tvAsVariant(&tmp));
std::cout << "\nAdding element:\n " << adding_val->pretty() << "\n";
always_assert(false);
}
// Allow NULL with other data
always_assert(m_multi_type == KindOfUninit || m_multi_type == KindOfNull ||
m_multi_type == adding_val->m_type || adding_val->m_type == KindOfNull || adding_val->m_type == KindOfUninit);
#endif
if ((m_multi_type == KindOfUninit || m_multi_type == KindOfNull)
&& (adding_val->m_type != KindOfUninit && adding_val->m_type != KindOfNull) ) {
mv->setType(adding_val->m_type);
}
}
void
MultiVal::addValueNoInc(const struct TypedValue& ov) {
TypedValue v = ov;
checkAdjustType(this, &v);
values->push_back(v);
}
void
MultiVal::addValue(const struct TypedValue& v) {
addValueNoInc(v);
tvRefcountedIncRef(&v);
}
void
MultiVal::setValById(int index, const TypedValue& tv, bool setType=false) {
cheng_assert(index < values->size());
TypedValue v = tv;
checkAdjustType(this, &v);
(*values)[index] = v;
tvRefcountedIncRef(&v);
}
TypedValue
MultiVal::popValById(int index) {
cheng_assert(index < values->size());
TypedValue ret = *getByVal(index);
values->erase(values->begin() + index);
return ret;
}
bool
MultiVal::valid() {
#ifdef CHENG_CHECK
// check the same type
//for (int i = 0; i < valSize(); i++) {
// always_assert(m_multi_type == getByVal(i)->m_type);
//}
#endif
return true;
}
TypedValue*
MultiValIter::operator * () {
return m_multi->getByVal(m_pos);
}
struct TypedValue
MultiVal::makeMultiVal() {
TypedValue v;
v.m_type = KindOfMulti;
v.m_data.pmulti = new (MM().smartMallocSizeLogged(sizeof(MultiVal)))
MultiVal();
return v;
}
struct TypedValue
MultiVal::copy() {
TypedValue new_tv = makeMultiVal();
for (auto it : *values) {
new_tv.m_data.pmulti->addValue(it);
}
return new_tv;
}
void
MultiVal::release() {
this->~MultiVal();
MM().smartFreeSizeLogged(this, sizeof(MultiVal));
}
//======================================
//=========== Helper function ==========
//======================================
// why do we need clone multivalue itself?
struct TypedValue
MultiVal::cloneMultiVal(TypedValue *tv) {
#ifdef CHENG_CHECK
always_assert(tv->m_type == KindOfMulti);
#endif
auto multi = tv->m_data.pmulti;
TypedValue ret = makeMultiVal();
auto ret_multi = ret.m_data.pmulti;
// CHECK: is this correct?
ret_multi->setRefCount(multi->getCount());
for (auto it : *multi) {
TypedValue new_val;
new_val.m_type = it->m_type;
TypedValue *inner;
switch (it->m_type) {
case KindOfRef:
// Make a new copy of the inner value, and reference it
// FIXME: shared references?
inner = it->m_data.pref->tv();
tvCopy(*inner, new_val);
tvBox(&new_val);
ret_multi->addValue(new_val);
break;
case KindOfArray:
// Copy the array
new_val.m_data.parr = it->m_data.parr->copy();
ret_multi->addValue(new_val);
break;
case KindOfString:
// Strings are immutable, so copying and incrementing a reference should be okay?
ret_multi->addValue(*it);
tvRefcountedIncRef(it);
break;
case KindOfObject:
new_val.m_data.pobj = it->m_data.pobj->clone();
ret_multi->addValueNoInc(new_val);
break;
default:
ret_multi->addValue(*it);
tvRefcountedIncRef(it);
break;
}
}
return ret;
}
struct TypedValue
MultiVal::splitArray(TypedValue& tv, int size) {
#ifdef CHENG_CHECK
always_assert(tv.m_type == KindOfArray);
#endif
// check whether we can do it fast
int multi_size = containMultiVal(&tv);
bool no_multi_val = (0 == multi_size);
TypedValue ret = makeMultiVal();
auto ret_multi = ret.m_data.pmulti;
if (no_multi_val) {
ArrayData *arr = tv.m_data.parr;
for (int i = 0; i < size; i++) {
TypedValue new_arr;
// For split ref-array, we need all the field including gap field to be the same
// After that, we copy the ArrayData
memcpy(&new_arr, &tv, sizeof(TypedValue));
new_arr.m_data.parr = arr->copy();
ret_multi->addValue(new_arr); // FIXME: the count seems not right
}
} else {
cheng_assert(size == multi_size);
// In order to fix multi-multi-value problem, we need to
// only get ith elements from current array
for (int i = 0; i < size; i++) {
auto ith_tv = selectIthVal(tv, i, true);
ret_multi->addValue(ith_tv);
}
}
// FIXME: check refcounts and decref if necessary, fix invariants
#ifdef CHENG_CHECK
always_assert(size == ret_multi->valSize());
#endif
return ret;
}
struct TypedValue
MultiVal::splitObject(TypedValue& tv, int size) {
#ifdef CHENG_CHECK
always_assert(tv.m_type == KindOfObject);
#endif
auto obj = tv.m_data.pobj;
TypedValue ret = makeMultiVal();
auto ret_multi = ret.m_data.pmulti;
for (int i = 0; i < size; i++) {
TypedValue new_obj;
// For split ref-obj, we need all the field including gap field to be the same
// After that, we copy the ObjectData
memcpy(&new_obj, &tv, sizeof(TypedValue));
new_obj.m_data.pobj = obj->clone();
ret_multi->addValue(new_obj);
}
// FIXME: check refcounts and decref if necessary, fix invariants
#ifdef CHENG_CHECK
always_assert(size == ret_multi->valSize());
#endif
return ret;
}
static inline TypedValue
buildUninitMultiVal(int size) {
// build uninitial multi-val
TypedValue uninit_mv = MultiVal::makeMultiVal();
TypedValue uninit;
uninit.m_type = KindOfUninit;
for (int i=0; i<size; i++) {
uninit_mv.m_data.pmulti->addValue(uninit);
}
return uninit_mv;
}
TypedValue
MultiVal::invertTransferArray(TypedValue marr) {
#ifdef CHENG_CHECK
always_assert(marr.m_type == KindOfMulti && marr.m_data.pmulti->getType() == KindOfArray);
#endif
// get the multi_size
int multi_size = marr.m_data.pmulti->valSize();
// create the return array
auto parr = staticEmptyArray(); // FIXME
for (int i=0; i<multi_size; i++) {
// fetch each of the array
auto it = marr.m_data.pmulti->getByVal(i);
ArrayIter ait(it->m_data.parr);
while(!ait.end()) {
auto key = ait.first(); // Variant
auto value = ait.nvSecond(); // TypedValue*
// if this key exists, get the multi-value
// and put into the i-th location
// if this key doesn't exist, add one uninit-multivalue,
// and put the value to i-th location
if (parr->exists(key)) {
auto val = parr->get(key);
val.m_data.pmulti->setValById(i, *value);
} else {
auto tmp = buildUninitMultiVal(multi_size);
tmp.m_data.pmulti->setValById(i, *value);
parr = parr->set(key, tvAsVariant(&tmp), false);
}
ait.next();
}
}
ArrayIter ait(parr);
while(!ait.end()) {
auto key = ait.first();
auto value = ait.second();
// Shrink the same multi-val
// NOTE: this can be costy
auto single = value.m_data.pmulti->shrinkToSingle();
if (single != nullptr) {
parr =parr->set(key, tvAsVariant(single), false);
}
// NOTE(1): we cannot do continue merging in the no-mv-in-container world
// since this function is only used by FCallArray, which need one layer merge
#ifdef MV_IN_CONTAINER_WORLD
// Merge the additional multi-arr/obj
else if (value.m_data.pmulti->getType() == KindOfArray) {
auto ret = invertTransferArray(value);
parr = parr->set(key, tvAsVariant(&ret), false);
} else if (value.m_data.pmulti->getType() == KindOfObject) {
auto ret = invertTransferObj(value);
parr = parr->set(key, tvAsVariant(&ret), false);
}
#endif
ait.next();
}
TypedValue ret;
ret.m_type = KindOfArray;
ret.m_data.parr = parr;
tvRefcountedIncRef(&ret);
return ret;
}
struct TypedValue
MultiVal::transferArray(TypedValue tv) {
#ifdef CHENG_CHECK
always_assert(tv.m_type == KindOfArray);
#endif
// MIC_to_MC the inner element first
ArrayIter ait(tv.m_data.parr);
while(!ait.end()) {
auto value = ait.second();
if (value.m_type == KindOfArray) {
if (0 != containMultiVal(value.asTypedValue())) {
auto mc = transferArray(value);
tv.m_data.parr = tv.m_data.parr->set(ait.first(), tvAsVariant(&mc), true);
}
} else if (value.m_type == KindOfObject) {
if (0 != containMultiVal(value.asTypedValue())) {
auto mc = transferObj(value);
tv.m_data.parr = tv.m_data.parr->set(ait.first(), tvAsVariant(&mc), true);
}
}
ait.next();
}
// get the multivalue size
int multi_size = containMultiVal(&tv);
#ifdef CHENG_CHECK
always_assert(multi_size != 0);
#endif
// do split first
TypedValue new_tv = splitArray(tv, multi_size);
// replace all the multi_value with corresponding single value
for (int i = 0; i < multi_size; i++) {
TypedValue *tmp_arr = new_tv.m_data.pmulti->getByVal(i);
#ifdef CHENG_CHECK
always_assert(tmp_arr->m_type == KindOfArray);
#endif
ArrayIter tmp_ait(tmp_arr->m_data.parr);
while(!tmp_ait.end()) {
auto key = tmp_ait.first();
auto value = tmp_ait.second();
if (value.m_type == KindOfMulti) {
// this is the i'th array, which needs i'th element
TypedValue *single_val = value.m_data.pmulti->getByVal(i);
// NOTE: this should never cause escalation
tmp_arr->m_data.parr = tmp_arr->m_data.parr->set(key, tvAsVariant(single_val), false);
}
tmp_ait.next();
}
}
return new_tv;
}
// If tv does not conatin multival, it will return tv itself
struct TypedValue
MultiVal::selectIthVal(TypedValue tv, int i, bool skip_obj /*=false*/) {
int multi_num = containMultiVal(&tv);
// either not multi-v; or i within multi-v size
always_assert(multi_num == 0 || i < multi_num);
// if this is not multi-value, return directly
// FIXME: is this correct?
if (multi_num == 0) return tv;
if (tv.m_type == KindOfArray) {
auto new_arr = staticEmptyArray(); // FIXME
// create a new array, but all elements will be ith
ArrayIter ait(tv.m_data.parr);
while(!ait.end()) {
auto key = ait.first();
auto value = ait.second();
auto ith_val = selectIthVal(value, i, skip_obj);
// add to array
new_arr = new_arr->set(key, tvAsVariant(&ith_val), false);
ait.next();
}
TypedValue ret;
ret.m_type = KindOfArray;
ret.m_data.parr = new_arr;
tvRefcountedIncRef(&ret);
return ret;
} else if (tv.m_type == KindOfObject) {
if (skip_obj) return tv;
// create a new obj, but all elements will be ith
auto obj = tv.m_data.pobj->clone();
// FIXME: ugly copy/paste from iterObjElemsAndReplace
// should be uniformed
// loop through all properties of obj
auto cls = obj->getVMClass();
do {
auto c_name = cls->nameStr();
Array arr = obj->o_toIterArray(c_name);
ArrayIter it(arr);
while(!it.end()) {
auto key = it.first();
auto val = it.secondRef().asTypedValue();
auto ith_val = selectIthVal(*val, i, skip_obj);
if (ith_val.m_type != KindOfUninit) {
obj->setProp(cls, key.getStringData(), &ith_val);
}
it.next();
}
cls = cls->parent();
} while(cls);
TypedValue ret;
ret.m_type = KindOfObject;
ret.m_data.pobj = obj;
tvRefcountedIncRef(&ret);
return ret;
} else if (tv.m_type == KindOfMulti) {
auto ith_tv = *tv.m_data.pmulti->getByVal(i);
return selectIthVal(ith_tv, i, skip_obj);
}
// else
return tv;
}
// NOTE: the public elements may be iterated more than once!
static void
iterObjElemsAndReplace(std::function <TypedValue (TypedValue*)> f, TypedValue *obj) {
auto cls = obj->m_data.pobj->getVMClass();
do {
auto c_name = cls->nameStr();
Array arr = obj->m_data.pobj->o_toIterArray(c_name);
ArrayIter it(arr);
while(!it.end()) {
auto key = it.first();
auto val = it.secondRef().asTypedValue();
auto new_v = f((TypedValue*)val);
if (new_v.m_type != KindOfUninit) {
obj->m_data.pobj->setProp(cls, key.getStringData(), &new_v);
}
it.next();
}
cls = cls->parent();
} while(cls);
}
// MC to MIC
struct TypedValue
MultiVal::invertTransferObj(TypedValue obj) {
#ifdef CHENG_CHECK
always_assert(obj.m_type == KindOfMulti && obj.m_data.pmulti->getType() == KindOfObject);
#endif
// (1) Create empty object, and assign each key/value to it
// (2) check the container whehter they are multi, and do the same thing
int multi_size = containMultiVal(&obj);
auto obj_cls = obj.m_data.pmulti->getByVal(0)->m_data.pobj->getVMClass();
auto ret_obj = newInstance(obj_cls);
for (int i=0; i<multi_size; i++) {
auto tmp_obj = obj.m_data.pmulti->getByVal(i)->m_data.pobj;
auto cls = tmp_obj->getVMClass();
do {
auto c_name = cls->nameStr();
Array arr = tmp_obj->o_toIterArray(c_name);
ArrayIter it(arr);
while(!it.end()) {
auto key = it.first();
auto val = it.secondRef().asTypedValue();
auto look_up = ret_obj->getProp(cls, key.getStringData());
auto prop = look_up.prop;
if (prop && prop->m_type != KindOfNull && prop->m_type != KindOfUninit) {
// if the prop exists
cheng_assert(prop->m_type == KindOfMulti);
prop->m_data.pmulti->setValById(i, *val);
} else {
// if prop does not exist
auto tmp = buildUninitMultiVal(multi_size);
tmp.m_data.pmulti->setValById(i, *val);
ret_obj->setProp(cls, key.getStringData(), &tmp);
}
it.next();
}
cls = cls->parent();
} while(cls);
}
// (2) shrink and recursively call invert
auto cls = ret_obj->getVMClass();
do {
auto c_name = cls->nameStr();
Array arr = ret_obj->o_toIterArray(c_name);
ArrayIter it(arr);
while(!it.end()) {
auto key = it.first();
auto val = it.secondRef().asTypedValue();
auto single = val->m_data.pmulti->shrinkToSingle();
if (single != nullptr) {
ret_obj->setProp(cls, key.getStringData(), single);
}
// See NOTE(1)
#ifdef MV_IN_CONTAINER_WORLD
// Merge the additional multi-arr/obj
else if (val->m_data.pmulti->getType() == KindOfArray) {
auto ret = invertTransferArray(*val);
ret_obj->setProp(cls, key.getStringData(), &ret);
} else if (val->m_data.pmulti->getType() == KindOfObject) {
auto ret = invertTransferObj(*val);
ret_obj->setProp(cls, key.getStringData(), &ret);
}
#endif
it.next();
}
cls = cls->parent();
} while(cls);
TypedValue result;
result.m_type = KindOfObject;
result.m_data.pobj = ret_obj;
return result;
}
// MIC to MC
// (1) search contained elements, if multi, split
// (2) split the object itself, and assign each element to the correct location
struct TypedValue
MultiVal::transferObj(TypedValue tv) {
#ifdef CHENG_CHECK
always_assert(tv.m_type == KindOfObject);
#endif
auto f = [] (TypedValue* value) {
TypedValue ret;
ret.m_type = KindOfUninit;
if (value->m_type == KindOfArray) {
if (containMultiVal(value)) {
ret = transferArray(*value);
}
} else if (value->m_type == KindOfObject) {
if (containMultiVal(value)) {
ret = transferObj(*value);
}
}
return ret;
};
iterObjElemsAndReplace(f, &tv);
// get the multivalue size
int multi_size = containMultiVal(&tv);
#ifdef CHENG_CHECK
cheng_assert(multi_size != 0);
#endif
// do split first
TypedValue new_tv = splitObject(tv, multi_size);
// replace all the multi_value with corresponding single value
for (int i = 0; i < multi_size; i++) {
TypedValue *tmp_obj = new_tv.m_data.pmulti->getByVal(i);
#ifdef CHENG_CHECK
always_assert(tmp_obj->m_type == KindOfObject);
#endif
auto f2 = [i] (TypedValue *value) {
TypedValue ret;
ret.m_type = KindOfUninit;
if (value->m_type == KindOfMulti) {
ret = *value->m_data.pmulti->getByVal(i);
}
return ret;
};
iterObjElemsAndReplace(f2 ,tmp_obj);
}
return new_tv;
}
// cycle-breaker: in PHP only obj can have cycle, remember all the obj in a set.
// if meet it again, just return
#define TRACK_MAX_DEPTH 10
// the return value is the size of the multi-value
// 0 indicates there is no multi-value
// FIXME: not touch depth for now
thread_local std::set<ObjectData*> met_obj;
int MultiVal::containMultiVal(TypedValue* v, int depth) {
if (depth == 0) { met_obj.clear(); }
if (depth > (TRACK_MAX_DEPTH) ) return false; // prohibit the cycle-ref
switch(v->m_type) {
case KindOfNull:
case KindOfUninit:
case KindOfInt64:
case KindOfDouble:
case KindOfBoolean:
case KindOfClass:
case KindOfResource:
case KindOfString:
case KindOfStaticString:
return 0;
case KindOfRef:
return containMultiVal(tvToCell(v), depth+1);
case KindOfMulti:
return v->m_data.pmulti->valSize();
case KindOfArray:
{
ArrayIter it(v->m_data.parr);
while(!it.end()) {
auto val = it.second();
int size = containMultiVal(val.asTypedValue(), depth+1);
if (size != 0) {
return size;
}
it.next();
}
return 0;
}
case KindOfObject:
{
// check if we've ever seen this obj
if (met_obj.find(v->m_data.pobj) != met_obj.end()) {
// we've seen this obj, just return
return 0;
} else {
// this is a new object, push it to set
met_obj.insert(v->m_data.pobj);
}
auto cls = v->m_data.pobj->getVMClass();
do {
auto c_name = cls->nameStr();
Array arr = v->m_data.pobj->o_toIterArray(c_name);
ArrayIter it(arr);
while(!it.end()) {
auto val = it.second();
int size = containMultiVal(val.asTypedValue(), depth+1);
if (size != 0) {
return size;
}
it.next();
}
cls = cls->parent();
} while(cls);
return 0;
}
}
// should never been here
not_reached();
}
static int64_t prime = 179424691L;
static inline int64_t addToHash(int64_t hash, int64_t op) {
return hash*prime + op;
}
static int64_t calValHash(TypedValue* v) {
int64_t hash = 1;
hash = addToHash(hash, (int64_t) (v->m_type));
int64_t tmp_hash;
switch(v->m_type) {
case KindOfNull:
case KindOfUninit:
return hash;
// these are compared by value
case KindOfInt64:
case KindOfDouble:
case KindOfBoolean:
// these are compared by ptr
case KindOfClass:
case KindOfResource:
hash = addToHash(hash, v->m_data.num); // resource to see their address
return hash;
case KindOfRef:
tmp_hash = calValHash(v->m_data.pref->tv());
if (tmp_hash == INTMAX_MAX) return INTMAX_MAX;
hash = addToHash(hash, tmp_hash);
return hash;
case KindOfString:
case KindOfStaticString:
tmp_hash = std::hash<std::string>{}(v->m_data.pstr->toCppString());
hash = addToHash(hash, tmp_hash);
return hash;
case KindOfMulti:
return INTMAX_MAX; // this is a single to not merge
case KindOfArray: {
ArrayIter it(v->m_data.parr);
while(!it.end()) {
auto key = it.first();
auto key_hash = calValHash(key.asTypedValue());
if (key_hash == INTMAX_MAX) return INTMAX_MAX;
hash = addToHash(hash, key_hash);
auto val = it.second();
auto val_hash = calValHash(key.asTypedValue());
if (val_hash == INTMAX_MAX) return INTMAX_MAX;
hash = addToHash(hash, val_hash);
it.next();
}
return hash;
}
case KindOfObject:
hash = addToHash(hash, (int64_t)v->m_data.pobj);
return hash;
}
// should never been here
not_reached();
}
static bool isSameVal (TypedValue* v1, TypedValue* v2) {
if (v1->m_type != v2->m_type) {
return false;
}
Array a1, a2;
switch(v1->m_type) {
case KindOfNull:
case KindOfUninit:
return true;
// these are compared by value
case KindOfInt64:
case KindOfDouble:
case KindOfBoolean:
// these are compared by ptr
case KindOfClass:
case KindOfResource:
if (v1->m_data.num == v2->m_data.num) {
return true;
} else {
return false;
}
case KindOfRef:
if (v1->m_data.pref->tv() == v2->m_data.pref->tv()) {
return true;
} else {
return false;
}
case KindOfString:
case KindOfStaticString:
if (v1->m_data.pstr->toCppString() == v2->m_data.pstr->toCppString()) {
return true;
} else {
return false;
}
case KindOfMulti:
// FIXME: it is possible to have multival in multival
// for example: multi-array->single-obj->multi-val
//std::cout << "FATAL ERROR: there is a multi-val inside another multi-val\n";
//HHVM_FN(debug_print_backtrace)();
//always_assert(false);
return false;
// compare all the elements recursively, this may very costy!
// FIXME: assume the sequence of the attributes are the same
case KindOfArray: {
ArrayIter it1(v1->m_data.parr), it2(v2->m_data.parr);
while(!it1.end() && !it2.end()) {
auto key1 = it1.first();
auto key2 = it2.first();
auto val1 = it1.second();
auto val2 = it2.second();
if (!isSameVal(&key1, &key2) || !isSameVal(&val1, &val2)) {
return false;
}
it1.next();
it2.next();
}
if (it1.end() != it2.end()) {
return false;
}
return true;
}
case KindOfObject:
#ifdef MV_IN_CONTAINER_WORLD
// FIXME: how to fix cycle reference problem? i.e. $a->b == $b && $b->a = a
// There will be an infinite loop
auto class1 = v1->m_data.pobj->getVMClass();
auto class2 = v2->m_data.pobj->getVMClass();
do {
auto c1_name = class1->nameStr();
auto c2_name = class2->nameStr();
a1 = v1->m_data.pobj->o_toIterArray(c1_name);
a2 = v2->m_data.pobj->o_toIterArray(c2_name);
#ifdef MUL_DETAIL_DEBUG
debug_log << "!!!!!!!!!!!!!! Class Name [" << c1_name.c_str() << "]!!!!!!!!!!!!!!!!!!!!!\n";
#endif
ArrayIter it1(a1), it2(a2);
while(!it1.end() && !it2.end()) {
auto key1 = it1.first();
auto key2 = it2.first();
auto val1 = it1.second();
auto val2 = it2.second();
#ifdef MUL_DETAIL_DEBUG
debug_log << "!!!!!!!!!!!!!! KindOf Array or Obj !!!!!!!!!!!!!!!!!!!!!\n";
auto key1_txt = HHVM_FN(print_r)(tvAsVariant(&key1),true);
auto key2_txt = HHVM_FN(print_r)(tvAsVariant(&key2),true);
auto val1_txt = HHVM_FN(print_r)(tvAsVariant(&val1),true);
auto val2_txt = HHVM_FN(print_r)(tvAsVariant(&val2),true);
debug_log << " -- compare two val:\n";
debug_log << " key1:{{" << key1_txt.toString().toCppString() << "}}\n";
debug_log << " key2:{{" << key2_txt.toString().toCppString() << "}}\n";
debug_log << " val1:{{" << val1_txt.toString().toCppString() << "}}\n";
debug_log << " val2:{{" << val2_txt.toString().toCppString() << "}}\n";
#endif
if (!isSameVal(&key1, &key2) || !isSameVal(&val1, &val2)) {
return false;
}
it1.next();
it2.next();
}
if (it1.end() != it2.end()) {
return false;
}
class1 = class1->parent();
class2 = class2->parent();
always_assert( (class1!=nullptr) == (class2!=nullptr) );
} while(class1);
return true;
#else
if (v1->m_data.pobj == v2->m_data.pobj) {
return true;
} else {
return false;
}
#endif
}
// should never been here
not_reached();
}
TypedValue*
MultiVal::shrinkToSingle() {
// check if every elements are the same
auto half_indx = valSize() / 2;
auto first = getByVal(0);
auto half = getByVal(half_indx);
auto last = getByVal(valSize()-1);
bool compare_val_impl = false;
if (compare_val_impl) {
int64_t first_hash = calValHash(first);
int64_t half_hash = calValHash(half);
// INTMAX_MAX indicates there is MultiVal within
if (first_hash == INTMAX_MAX || half_hash == INTMAX_MAX || first_hash != half_hash) {
return nullptr;
}
int64_t last_hash = calValHash(last);
if (last_hash == INTMAX_MAX || first_hash != last_hash) {
return nullptr;
}
for (int i = 1; i < valSize(); i++) {
auto cur_hash = calValHash(getByVal(i));
if (cur_hash == INTMAX_MAX || first_hash != cur_hash) {
return nullptr;
}
}
return first;
} else {
// optimization: try to quit quickly
if (!isSameVal(first, half)) {
return nullptr;
}
if (!isSameVal(first, last)) {
return nullptr;
}
for (int i = 1; i < valSize(); i++) {
// std::cout << "first: " << first->pretty() << " now: " << getByVal(i)->pretty() << "\n";
// if (first->m_data.num != getByVal(i)->m_data.num) {
if (!isSameVal(first, getByVal(i))) {
return nullptr;
}
}
return first;
}
not_reached();
}
// used for debug
static std::string
typeToString(DataType d) {
switch (d) {
case KindOfInt64: return "Int";
case KindOfDouble: return "Double";
case KindOfString: return "String";
case KindOfUninit: return "Uninit";
case KindOfArray: return "Array";
case KindOfMulti: return "MultiVal";
case KindOfNull: return "Null";
case KindOfBoolean: return "Bool";
case KindOfObject: return "Obj";
case KindOfResource: return "Res";
case KindOfClass: return "Class";
case KindOfStaticString: return "StaticString";
case KindOfRef: return "Ref";
}
return "UNKOWN";
}
std::string
MultiVal::dumpElem(TypedValue* v, int nested) {
std::stringstream ss;
if (nested > TRACK_MAX_DEPTH) {
return "\nXXX: [too deep to display...]\n";
}
ss << v->pretty() << ": ";
switch (v->m_type) {
case KindOfMulti:
// NOTE: might have infinite loop
if (nested == 0) {
ss << v->m_data.pmulti->dump("");
} else {
ss << "[*] MultiVal (\n";
int counter = 0;
for (auto it : *v->m_data.pmulti) {
ss << " <" << counter++ << ">:: " << it->pretty() << "\n";
}
ss << ")\n";
}
break;
case KindOfRef:
ss << "(" << v->m_data.pref->var()->getRefCount()
<< ") -> " << dumpElem(tvToCell(v), nested+1);
break;
case KindOfArray: {
ArrayIter ait(v->m_data.parr);
ss << "Array (\n";
while(!ait.end()) {
auto key = ait.first();
auto val = ait.nvSecond();
ss << " [" << key.toString().toCppString() << "] => "
<< dumpElem((TypedValue*)val, nested+1) << "\n";
ait.next();
}
ss << ")\n";
} break;
case KindOfString:
case KindOfStaticString:
case KindOfObject: {
auto txt = HHVM_FN(print_r)(tvAsVariant(v), true);
ss << txt.toString().toCppString()
<< "(" << (uint32_t)v->m_data.pstr->getCount() << ")";
} break;
default: {
auto txt = HHVM_FN(print_r)(tvAsVariant(v), true);
ss << " : {{ " << txt.toString().toCppString() << "}}";
}
}
return ss.str();
}
std::string
MultiVal::dump(std::string prefix) {
std::stringstream ss;
ss << prefix << "MultiVal, type: " << typeToString(m_multi_type);
ss << " valSize: " << valSize() << " ref-count: " << m_count << "\n";
ss << prefix << " elements: {\n";
int counter = 0;
for (auto it : *this) {
ss << prefix << " <" << counter++ << ">:: {{" << dumpElem(it, 1) << " }}\n";
}
ss << prefix << " }\n";
return ss.str();
}
// end of HPHP
}
| 28.334594 | 125 | 0.615518 | [
"object"
] |
716c19518573a01bbef6d15d0e87af23f5343483 | 1,648 | cpp | C++ | src/tiled/GLTmxRenderer.cpp | SgtCoDFish/APG | 23c45601e1c96ab8d1192f4d1095e2c481999780 | [
"libtiff",
"Apache-2.0",
"MIT",
"ECL-2.0",
"Libpng",
"BSD-3-Clause"
] | 1 | 2015-01-05T16:57:56.000Z | 2015-01-05T16:57:56.000Z | src/tiled/GLTmxRenderer.cpp | SgtCoDFish/APG | 23c45601e1c96ab8d1192f4d1095e2c481999780 | [
"libtiff",
"Apache-2.0",
"MIT",
"ECL-2.0",
"Libpng",
"BSD-3-Clause"
] | 18 | 2015-07-04T21:49:23.000Z | 2018-07-30T09:19:32.000Z | src/tiled/GLTmxRenderer.cpp | SgtCoDFish/APG | 23c45601e1c96ab8d1192f4d1095e2c481999780 | [
"libtiff",
"Apache-2.0",
"MIT",
"ECL-2.0",
"Libpng",
"BSD-3-Clause"
] | null | null | null | #ifndef APG_NO_SDL
#ifndef APG_NO_GL
#include <glm/vec2.hpp>
#include "Tmx.h"
#include "APG/graphics/Sprite.hpp"
#include "APG/tiled/GLTmxRenderer.hpp"
#include "APG/internal/Assert.hpp"
namespace APG {
std::unordered_map<std::string, std::shared_ptr<Tileset>> GLTmxRenderer::tmxTilesets;
GLTmxRenderer::GLTmxRenderer(Tmx::Map *const map, SpriteBatch *const batch) :
GLTmxRenderer(std::unique_ptr<Tmx::Map>(map), batch) {
}
GLTmxRenderer::GLTmxRenderer(std::unique_ptr<Tmx::Map> &&map, SpriteBatch *const batch) :
TmxRenderer(std::move(map)),
batch{batch} {
}
GLTmxRenderer::GLTmxRenderer(const std::string &fileName, SpriteBatch *const batch) :
TmxRenderer(fileName),
batch{batch} {
}
void GLTmxRenderer::renderAll(float deltaTime) {
batch->begin();
TmxRenderer<GLTmxRenderer>::renderAll(deltaTime);
batch->end();
}
void GLTmxRenderer::renderLayerImpl(const Tmx::TileLayer *layer) {
const uint32_t tileWidth = map->GetTileWidth();
const uint32_t tileHeight = map->GetTileHeight();
for (int y = 0; y < layer->GetHeight(); y++) {
for (int x = 0; x < layer->GetWidth(); x++) {
const uint32_t tileX = position.x + x * tileWidth;
const uint32_t tileY = position.y + y * tileHeight;
const auto &tile = layer->GetTile(x, y);
if (tile.tilesetId == -1) {
continue;
}
const auto tileHash = tile.gid;
const auto ourSprite = sprites[tileHash];
batch->draw(ourSprite, tileX, tileY);
}
}
}
void GLTmxRenderer::renderObjectGroupImpl(const std::vector<TiledObject> &objects) {
for (const auto &obj : objects) {
batch->draw(obj.sprite, obj.position.x, obj.position.y);
}
}
}
#endif
#endif
| 22.575342 | 89 | 0.701456 | [
"vector"
] |
71721a73e95b3bf3af386ea02fcf1f8cb4e7ebfb | 13,803 | cpp | C++ | tftp_client.cpp | dembanakh/ServerClientTFTP | fdaf325b1ba929e56bf448b4b88dbef8662886d1 | [
"MIT"
] | null | null | null | tftp_client.cpp | dembanakh/ServerClientTFTP | fdaf325b1ba929e56bf448b4b88dbef8662886d1 | [
"MIT"
] | null | null | null | tftp_client.cpp | dembanakh/ServerClientTFTP | fdaf325b1ba929e56bf448b4b88dbef8662886d1 | [
"MIT"
] | null | null | null | // vim:ts=4:sts=4:sw=4:expandtab
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <chrono>
#include <cmath>
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
namespace po = boost::program_options;
using namespace std;
#define RRQ 1
#define WRQ 2
#define DATA 3
#define ACK 4
#define ERROR 5
#define OACK 6
#define NETASCII 1
#define OCTET 2
#define BLKSIZE "blksize"
#define WINDOWSIZE "windowsize"
#define TIMEOUT_ALPHA 0.125
#define TIMEOUT_BETA 0.25
#define TIMEOUT_MULTIPLIER 1.2
#define CLOCK_GRANULARITY 100
#define TIMEOUT_K 4
#define USE_TIMEOUT 0
struct rrequest {
int type;
int mode;
string filename;
vector<string> options;
int bsize = 512;
int wsize = 1;
};
class ClientHandler {
bool error = false;
rrequest r;
int fd;
sockaddr_in addr;
socklen_t addr_size;
FILE * f;
unsigned short block_number;
unsigned short last_block = 0;
bool last_packet_sent = false;
bool last_packet_received = false;
int current_rto = 1000;
int srtt;
int rttvar;
bool first_measurement = true;
bool timer_is_set = false;
chrono::time_point<chrono::system_clock> last_sending_time;
void updateRTT() {
auto current_time = chrono::system_clock::now();
int difference = chrono::duration_cast<chrono::milliseconds>(current_time - last_sending_time).count();
timer_is_set = false;
if (first_measurement) {
first_measurement = false;
srtt = difference;
rttvar = difference / 2;
current_rto = srtt + max(CLOCK_GRANULARITY, TIMEOUT_K * rttvar);
return;
}
rttvar = (1 - TIMEOUT_BETA) * rttvar + TIMEOUT_BETA * abs(srtt - difference);
srtt = (1 - TIMEOUT_ALPHA) * srtt + TIMEOUT_ALPHA * difference;
current_rto = srtt + max(CLOCK_GRANULARITY, TIMEOUT_K * rttvar);
current_rto = max(current_rto, 1000);
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = TIMEOUT_MULTIPLIER * current_rto * 1000;
if (USE_TIMEOUT && setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) < 0) {
perror("setsockopt failed");
error = true;
return;
}
}
void _sendRequest() {
int filename_len = r.filename.length();
string mode = (r.mode == NETASCII) ? "netascii" : "octet";
int mode_len = mode.length();
int bytes_length = 2 + (filename_len + 1) + (mode_len + 1);
string str_bsize;
int blksize_len;
string blksize_title;
int blksize_title_len;
if (find(r.options.begin(), r.options.end(), BLKSIZE) != r.options.end()) {
str_bsize = to_string(r.bsize);
blksize_len = str_bsize.length();
blksize_title = BLKSIZE;
blksize_title_len = blksize_title.length();
bytes_length += blksize_len + blksize_title_len + 2;
}
string str_wsize;
int wdwsize_len;
string wdwsize_title;
int wdwsize_title_len;
if (find(r.options.begin(), r.options.end(), WINDOWSIZE) != r.options.end()) {
str_wsize = to_string(r.wsize);
wdwsize_len = str_wsize.length();
wdwsize_title = WINDOWSIZE;
wdwsize_title_len = wdwsize_title.length();
bytes_length += wdwsize_len + wdwsize_title_len + 2;
}
unsigned char bytes[bytes_length];
unsigned char * current_byte = bytes;
*current_byte = 0; ++current_byte;
*current_byte = r.type; ++current_byte;
for (int i = 0; i < filename_len; ++i) {
*current_byte = r.filename[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
for (int i = 0; i < mode_len; ++i) {
*current_byte = mode[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
if (find(r.options.begin(), r.options.end(), BLKSIZE) != r.options.end()) {
for (int i = 0; i < blksize_title_len; ++i) {
*current_byte = blksize_title[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
for (int i = 0; i < blksize_len; ++i) {
*current_byte = str_bsize[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
}
if (find(r.options.begin(), r.options.end(), WINDOWSIZE) != r.options.end()) {
for (int i = 0; i < wdwsize_title_len; ++i) {
*current_byte = wdwsize_title[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
for (int i = 0; i < wdwsize_len; ++i) {
*current_byte = str_wsize[i];
++current_byte;
}
*current_byte = 0; ++current_byte;
}
if (!timer_is_set) {
timer_is_set = true;
last_sending_time = chrono::system_clock::now();
}
sendto(fd, bytes, bytes_length, 0, (sockaddr*)&addr, addr_size);
}
bool _receiveOACK() {
int buf_size = max(r.bsize + 4, 25);
char bytes[buf_size];
int nread = recvfrom(fd, bytes, buf_size, 0, (sockaddr*)&addr, &addr_size);
updateRTT();
if (bytes[0] != 0) return false;
if (bytes[1] == OACK) {
cout << "client: Received OACK" << endl;
char * zero = (char*) memchr(bytes + 2, 0, nread - 2);
if (zero == nullptr) {
cout << "OACK packet: bad format" << endl;
return false;
}
zero = bytes + 2;
while (zero != bytes + (nread - 1)) {
zero = (char*) memchr(zero + 1, 0, nread - (zero-bytes) - 1);
if (zero == nullptr) {
cout << "OACK packet: bad format" << endl;
return false;
}
string blksize = BLKSIZE;
string wdwsize = WINDOWSIZE;
if (!strncmp(zero - blksize.length(), blksize.c_str(), blksize.length())) {
if (find(r.options.begin(), r.options.end(), blksize) == r.options.end()) {
cout << "OACK packet: bad option" << endl;
return false;
}
if (zero == bytes + (nread - 1)) {
cout << "OACK packet: bad format" << endl;
return false;
}
r.bsize = strtol(zero+1, NULL, 10);
zero = (char*) memchr(zero + 1, 0, nread - (zero-bytes) - 1);
if (zero == nullptr) {
cout << "OACK packet: bad format" << endl;
return false;
}
} else if (!strncmp(zero - wdwsize.length(), wdwsize.c_str(), wdwsize.length())) {
if (find(r.options.begin(), r.options.end(), wdwsize) == r.options.end()) {
cout << "OACK packet: bad option" << endl;
return false;
}
if (zero == bytes + (nread - 1)) {
cout << "OACK packet: bad format" << endl;
return false;
}
r.wsize = strtol(zero+1, NULL, 10);
zero = (char*) memchr(zero + 1, 0, nread - (zero-bytes) - 1);
if (zero == nullptr) {
cout << "OACK packet: bad format" << endl;
return false;
}
} else; // other options
}
return true;
} else {
cout << "client: didn't received OACK - continue with default options" << endl;
r.bsize = 512;
if (bytes[1] == ACK && r.type == WRQ) {
if (nread == 4) {
unsigned short ackled_block = (bytes[2] << 8) + bytes[3];
if (ackled_block != 0) {
cout << "ACK packet: bad tid" << endl;
return false;
}
last_block = 0;
block_number = 1;
return true;
} else {
cout << "ACK packet: bad size" << endl;
return false;
}
} else if (bytes[1] == DATA && r.type == RRQ) {
for (int i = 0; i < r.wsize; ++i) {
if (nread >= 2) {
unsigned short recvd_block = (bytes[2] << 8) + bytes[3];
if (last_block + 1 == recvd_block) last_block = recvd_block;
else {
cout << "DATA packet: bad tid" << endl;
return false;
}
if (nread < r.bsize + 4) {
last_packet_received = last_packet_sent = true;
break;
}
} else {
cout << "DATA packet: bad size" << endl;
return false;
}
}
block_number = last_block;
return true;
} else return false;
}
}
void _receiveACK() {
char buf[4] {};
auto size = recvfrom(fd, buf, 4, 0, (sockaddr*)&addr, &addr_size);
if (size < 0) {
return;
}
updateRTT();
if (size == 4 && buf[0] == 0 && buf[1] == ACK) {
unsigned short ackled_block = (buf[2] << 8) + buf[3];
if ((ackled_block == 0) || (last_block + r.wsize >= ackled_block && last_block < ackled_block)) {
last_block = ackled_block;
block_number = ackled_block + 1;
} else {
//TODO sth went wrong
error = true;
return;
}
if (last_packet_sent) {
last_packet_received = true;
}
} else {
error = true;
}
}
void _sendACK() {
char buf[4];
buf[0] = 0;
buf[1] = ACK;
buf[2] = (block_number >> 8) & 255;
buf[3] = block_number & 255;
if (!timer_is_set) {
timer_is_set = true;
last_sending_time = chrono::system_clock::now();
}
sendto(fd, buf, 4, 0, (sockaddr*)&addr, addr_size);
}
void _receiveData() {
for (int i = 0; i < r.wsize; ++i) {
char buf[r.bsize+4] {};
int size = recvfrom(fd, buf, r.bsize + 4, 0, (sockaddr*)&addr, &addr_size);
if (size < 0) {
return;
}
updateRTT();
if (size >= 2 && buf[0] == 0 && buf[1] == DATA) {
unsigned short recvd_block = (buf[2] << 8) + buf[3];
if (last_block + 1 == recvd_block) last_block = recvd_block;
else {
--i;
continue;
}
fwrite(buf + 4, sizeof(char), size - 4, f);
if (size < r.bsize + 4) {
last_packet_received = last_packet_sent = true;
break;
}
} else {
cout << "client: DATA packet: bad format" << endl;
error = true;
return;
}
}
block_number = last_block;
}
void _sendData() {
for (int i = 0; i < r.wsize; ++i) {
char buf[r.bsize + 4] {};
buf[0] = 0;
buf[1] = DATA;
buf[2] = (block_number >> 8) & 255;
buf[3] = block_number & 255;
fseek(f, r.bsize*(block_number - 1), SEEK_SET);
int size = fread(buf + 4, sizeof(char), r.bsize, f);
if (size < 0) {
cout << "Error while reading from file " << r.filename << endl;
error = true;
return;
}
if (!timer_is_set) {
timer_is_set = true;
last_sending_time = chrono::system_clock::now();
}
sendto(fd, buf, size + 4, 0, (sockaddr*)&addr, addr_size);
cout << "client: Sent DATA " << block_number << endl;
if (size < r.bsize) {
last_packet_sent = true;
break;
}
++block_number;
}
}
public:
ClientHandler(rrequest & _r, string & local_filename, int port, string ip_addr) {
r = _r;
fd = socket(AF_INET, SOCK_DGRAM, 0);
addr_size = sizeof(addr);
memset(&addr, 0, addr_size);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_aton(ip_addr.c_str(), &addr.sin_addr);
//fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
char mode[2] {};
mode[0] = (r.type == RRQ) ? 'w' : 'r';
mode[1] = (r.mode == NETASCII) ? 't' : 'b';
f = fopen(local_filename.c_str(), mode);
block_number = 1;
last_block = 0;
}
~ClientHandler() { fclose(f); close(fd); }
bool request() {
_sendRequest();
if (r.options.size() == 0) {
if (r.type == RRQ) _receiveData();
else _receiveACK();
return true;
}
if (r.type == RRQ) block_number = 0;
return _receiveOACK();
}
void handle() {
if (r.type == RRQ) {
while (!error) {
_sendACK();
if (last_packet_received) return;
_receiveData();
}
} else {
while (!error) {
if (last_packet_sent) return;
_sendData();
_receiveACK();
//break;
}
}
if (error) {
cout << "client: Fatal error - aborting communication" << endl;
}
}
};
int main(int argc, char** argv) {
int PORT = 6969;
string ip_addr = "40.87.143.114";
rrequest r;
string local_filename;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("port", po::value<int>(), "port")
("ip", po::value<string>(), "ip")
("r", "read from remote server")
("w", "write to remote server")
("local", po::value<string>(), "local filename")
("remote", po::value<string>(), "remote filename")
("mode", po::value<string>(), "mode (netascii/octet)")
("blocksize", po::value<int>(), "single datagram size")
("windowsize", po::value<int>(), "size of DATA packets' window");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help")) {
cout << desc << endl;
return 1;
}
if (vm.count("port")) {
PORT = vm["port"].as<int>();
}
if (vm.count("ip")) {
ip_addr = vm["ip"].as<string>();
}
if ((vm.count("r") && vm.count("w")) || (!vm.count("r") && !vm.count("w"))) {
cout << "It is not clear whether this request is read or write!" << endl;
return 1;
}
if (vm.count("r")) r.type = RRQ;
else r.type = WRQ;
if (vm.count("remote")) {
r.filename = vm["remote"].as<std::string>();
} else {
if (r.type == RRQ) {
std::cout << "File name must be specified!" << std::endl;
return 1;
} else {
if (vm.count("local")) r.filename = vm["local"].as<string>();
else {
cout << "Either local or remote file must be specified" << endl;
return 1;
}
}
}
if (vm.count("local")) {
local_filename = vm["local"].as<string>();
} else {
if (r.type == WRQ) {
cout << "File name must be specified!" << endl;
return 1;
} else {
local_filename = r.filename;
}
}
if (vm.count("mode")) {
r.mode = (vm["mode"].as<string>()[0] == 'n') ? NETASCII : OCTET;
} else {
cout << "Mode must be specified!" << std::endl;
return 1;
}
if (vm.count("blocksize")) {
r.options.push_back(BLKSIZE);
r.bsize = vm["blocksize"].as<int>();
}
if (vm.count("windowsize")) {
r.options.push_back(WINDOWSIZE);
r.wsize = vm["windowsize"].as<int>();
}
ClientHandler handler(r, local_filename, PORT, ip_addr);
if (handler.request()) {
handler.handle();
} else {
cout << "server rejected the request" << endl;
return 1;
}
return 0;
}
| 26.544231 | 105 | 0.594726 | [
"vector"
] |
71799b890e79e3bc8133b799c69159b38be710cb | 1,186 | cpp | C++ | p190e/reverse_bits.cpp | l33tdaima/l33tdaima | 0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90 | [
"MIT"
] | 1 | 2020-02-20T12:04:46.000Z | 2020-02-20T12:04:46.000Z | p190e/reverse_bits.cpp | l33tdaima/l33tdaima | 0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90 | [
"MIT"
] | null | null | null | p190e/reverse_bits.cpp | l33tdaima/l33tdaima | 0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90 | [
"MIT"
] | null | null | null | // g++ -std=c++11 *.cpp -o test && ./test && rm -f test
#include <bitset>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int rev = 0;
for (int i = 0; i < 32; ++i) {
rev = (rev << 1) | (n & 1);
n >>= 1;
}
return rev;
}
uint32_t reverseBitsV2(uint32_t n) {
bitset<32> bset(n);
for (int i = 0; i < 32 / 2; ++i) {
bool temp = bset[i];
bset[i] = bset[bset.size() - 1 - i];
bset[bset.size() - 1 - i] = temp;
}
return (uint32_t) bset.to_ulong();
}
};
// TEST
struct Test {
uint32_t n;
uint32_t exp;
void run() {
Solution sol;
uint32_t act = sol.reverseBits(n);
cout << "Reverse bits " << bitset<32>(n) << " -> "
<< bitset<32>(act) << endl;
assert(act == exp);
assert(act == sol.reverseBitsV2(n));
}
};
int main(int argc, char const *argv[])
{
vector<Test> tests = {
{0, 0},
{43261596, 964176192},
{4294967293, 3221225471}
};
for (auto& t: tests) t.run();
return 0;
}
| 22.377358 | 59 | 0.473862 | [
"vector"
] |
7179b925a3b22c3d353231a9a3bab36589c364a9 | 10,388 | cpp | C++ | tests/push_tests.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | null | null | null | tests/push_tests.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | null | null | null | tests/push_tests.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | 1 | 2017-12-28T11:37:42.000Z | 2017-12-28T11:37:42.000Z | #define BOOST_TEST_MODULE PushTests
#include <boost/test/unit_test.hpp>
#include <zip.h>
#include <map>
#include <vector>
#include <zipfile.h>
#include "fstream"
#include "logging.h"
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include "test_utils.hpp"
#include <workingcopy.h>
#include <assetsextractor.h>
#include <commit.h>
#include <create.h>
#include <clean.h>
#include <checkout.h>
#include <reset.h>
#include <treeenumerator.h>
#include <treeindexenumerator.h>
#include "test_utils.hpp"
#include <artdeployartifacthandlers.h>
#include <artdeployartifactchecksumhandlers.h>
#include <gavcquery.h>
#include <mavenpom.h>
#include <artbaseconstants.h>
#define DBOOST_AUTO_TEST_CASE(x) void x(void)
namespace cmd=piel::cmd;
namespace lib=piel::lib;
namespace fs=boost::filesystem;
namespace tst=lib::test_utils;
static std::string artifact_name_1 = "artifact_1";
static std::string artifact_name_2 = "artifact_2";
static const char* server_api_access_token_ = "";
static const char* server_url_ = "";
static const char* server_repository_ = "";
static const std::string query_str = "test_dir:push_test:5";
void upload_checksums(art::lib::ArtDeployArtifactHandlers *deploy_handlers, std::string checksum_name)
{
art::lib::ArtDeployArtifactCheckSumHandlers deploy_checksum_handlers(deploy_handlers, checksum_name);
piel::lib::CurlEasyClient<art::lib::ArtDeployArtifactHandlers>
upload_checksum_client(deploy_checksum_handlers.gen_uri(), &deploy_checksum_handlers);
LOGD << "Upload checksum: " << " to: " << deploy_checksum_handlers.gen_uri() << ELOG;
if (!(upload_checksum_client.perform()))
{
LOGE << "Error on upload file!" << ELOG;
LOGE << upload_checksum_client.curl_error().presentation() << ELOG;
}
}
void deploy_pom(const art::lib::GavcQuery& query_)
{
piel::lib::MavenPom pom;
pom.set_group(query_.group());
pom.set_name(query_.name());
pom.set_version(query_.version());
std::ostringstream os;
pom.store(os);
LOGI << "POM: " << os.str() << ELOG;
art::lib::ArtDeployArtifactHandlers deploy_handlers(server_api_access_token_);
deploy_handlers.set_url(server_url_);
deploy_handlers.set_repo(server_repository_);
deploy_handlers.set_path(query_.group_path());
deploy_handlers.set_name(query_.name());
deploy_handlers.set_version(query_.version());
deploy_handlers.set_classifier(art::lib::ArtBaseConstants::pom_classifier);
deploy_handlers.push_input_stream(boost::shared_ptr<std::istream>(new std::istringstream(os.str())));
piel::lib::CurlEasyClient<art::lib::ArtDeployArtifactHandlers> upload_client(deploy_handlers.gen_uri(), &deploy_handlers);
LOGD << "Upload pom to: " << deploy_handlers.gen_uri() << ELOG;
if (!upload_client.perform())
{
LOGE << "Error on upload pom!" << ELOG;
LOGE << upload_client.curl_error().presentation() << ELOG;
}
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_md5);
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_sha1);
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_sha256);
}
bool upload(const art::lib::GavcQuery& query_, const std::string& classifier, const std::string& file_name)
{
bool no_errors = true;
LOGI << query_.to_string() << ELOG;
{
art::lib::ArtDeployArtifactHandlers deploy_handlers(server_api_access_token_);
deploy_handlers.set_url(server_url_);
deploy_handlers.set_repo(server_repository_);
deploy_handlers.set_path(query_.group_path());
deploy_handlers.set_name(query_.name());
deploy_handlers.set_version(query_.version());
deploy_handlers.set_classifier(classifier);
deploy_handlers.file(file_name);
piel::lib::CurlEasyClient<art::lib::ArtDeployArtifactHandlers> upload_client(deploy_handlers.gen_uri(), &deploy_handlers);
LOGD << "Upload: " << file_name << " as " << classifier << " to: " << deploy_handlers.gen_uri() << ELOG;
if (!(no_errors &= upload_client.perform()))
{
LOGE << "Error on upload file!" << ELOG;
LOGE << upload_client.curl_error().presentation() << ELOG;
}
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_md5);
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_sha1);
upload_checksums(&deploy_handlers, art::lib::ArtBaseConstants::checksums_sha256);
}
return no_errors;
}
bool create_reference(lib::WorkingCopy::Ptr working_copy, const std::string& new_ref_)
{
if (piel::lib::AssetId::empty != working_copy->local_storage()->resolve(new_ref_))
{
LOGE << "" << ELOG;
return false;
}
piel::lib::TreeIndex::Ptr initial_tree_index(new piel::lib::TreeIndex());
initial_tree_index->initial_for(new_ref_);
working_copy->local_storage()->put(initial_tree_index->assets());
piel::lib::AssetId new_tree_id = initial_tree_index->self().id();
working_copy->local_storage()->create_reference(piel::lib::refs::Ref(new_ref_, new_tree_id));
working_copy->setup_current_tree(new_ref_, initial_tree_index);
LOGI << "Created new tree: " << new_ref_ << ":" << new_tree_id.string() << ELOG;
return true;
}
BOOST_AUTO_TEST_CASE(Push_test_1)
{
LOGI << "---start Push_test_1---" << ELOG;
// Generate zip file
tst::TempFileHolder::Ptr wc_path = tst::create_temp_dir();
//tst::TempFileHolder::Ptr zip_path = tst::create_temp_dir(0);
//*********************************
// Artifact 1
LOGI << " generate state for " << artifact_name_1 << ELOG;
tst::DirState state_artifact_1;
state_artifact_1["artifact_1_file_1"] = "artifact_1 file 1 content 1";
state_artifact_1["artifact_1_file_2"] = "artifact_1 file 2 content 2";
state_artifact_1["artifact_1_file_3"] = "artifact_1 file 3 content 3";
state_artifact_1["artifact_1_file_4"] = "artifact_1 file 4 content 4";
state_artifact_1["artifact_1_1/artifact_1_file_5"] = "artifact_1_1/artifact_1 file 5 content 5";
state_artifact_1["artifact_1_2/artifact_1_file_6"] = "artifact_1_2/artifact_1 file 6 content 6";
state_artifact_1["artifact_1_3/artifact_1_file_7"] = "artifact_1_3/artifact_1 file 7 content 7";
// Init workspace
lib::WorkingCopy::Ptr wc = lib::WorkingCopy::init(wc_path->first, artifact_name_1);
tst::make_directory_state(wc->working_dir(), wc->metadata_dir(), state_artifact_1);
cmd::Commit commit_1(wc);
commit_1.set_message("Commit for " + artifact_name_1);
std::string artifact_1_state_id = commit_1();
LOGI << " artifact_1_state_id:" << artifact_1_state_id << ELOG;
//*********************************
// Artifact 2
LOGI << " generate state for " << artifact_name_2 << ELOG;
create_reference(wc, artifact_name_2);
tst::DirState state_artifact_2;
state_artifact_2["artifact_2_file_1"] = "artifact_2 file 1 content 1";
state_artifact_2["artifact_2_file_2"] = "artifact_2 file 2 content 2";
state_artifact_2["artifact_2_file_3"] = "artifact_2 file 3 content 3";
state_artifact_2["artifact_2_file_4"] = "artifact_2 file 4 content 4";
state_artifact_2["artifact_2_1/artifact_2_file_5"] = "artifact_2_1/artifact_2 file 5 content 5";
state_artifact_2["artifact_2_2/artifact_2_file_6"] = "artifact_2_2/artifact_2 file 6 content 6";
state_artifact_2["artifact_2_3/artifact_2_file_7"] = "artifact_2_3/artifact_2 file 7 content 7";
tst::make_directory_state(wc->working_dir(), wc->metadata_dir(), state_artifact_2);
cmd::Commit commit_2(wc);
commit_2.set_message("Commit for " + artifact_name_2);
std::string artifact_2_state_id = commit_2();
LOGI << " artifact_2_state_id:" << artifact_2_state_id << ELOG;
LOGI << "\n\n\n\n" << ELOG;
//*********************************
// Generate zip files for all artifacts
LOGI << " Make ZIP::" << ELOG;
LOGI << "Trees:::" << ELOG;
std::set<piel::lib::refs::Ref> all_refs = wc->local_storage()->references();
for(std::set<piel::lib::refs::Ref>::const_iterator i = all_refs.begin(), end = all_refs.end(); i != end; ++i)
{
std::string log_str;
if (wc->current_tree_name() == i->first)
log_str = "*" + i->first;
else
log_str = " " + i->first;
LOGI << log_str << ":" << i->second.string();
LOGI << ELOG;
piel::lib::TreeIndex::Ptr reference_index = piel::lib::TreeIndex::from_ref(wc->local_storage(), i->first);
lib::TreeIndexEnumerator enumerator(reference_index);
LOGI << "reference_index->self().id().string():" << reference_index->self().id().string() << ELOG;
boost::filesystem::path zip_path_fs = wc_path->first / (i->first + ".zip");
std::string zip_path = zip_path_fs.string();
lib::ZipFile::FilePtr zip = lib::ZipFile::create(zip_path);
while (enumerator.next())
{
LOGI << "\t" << enumerator.path << ":"
<< enumerator.asset.id().string() << ELOG;
LOGI << "\"" << lib::test_utils::istream_content(enumerator.asset.istream()) << "\"" << ELOG;
zip->add_istream(enumerator.path, enumerator.asset.istream());
}
}
//*********************************
// Publishing to the artifactory server
LOGI << " Publishing::" << ELOG;
art::lib::GavcQuery query_;
boost::optional<art::lib::GavcQuery> query_opt = art::lib::GavcQuery::parse(query_str);
BOOST_CHECK(query_opt);
if (!query_opt) {
LOGE << "Wrong query " << query_str << ELOG;
return;
}
query_ = query_opt.get();
bool no_errors = true;
for(std::set<piel::lib::refs::Ref>::const_iterator i = all_refs.begin(), end = all_refs.end(); i != end; ++i)
{
boost::filesystem::path zip_path_fs = wc_path->first / (i->first + ".zip");
std::string zip_path = zip_path_fs.string();
LOGI << " Publishing " << zip_path << " as " << i->first << ELOG;
no_errors &= upload(query_, i->first + ".zip", zip_path);
}
if (no_errors)
{
deploy_pom(query_);
}
//*********************************
LOGI << "---FINISH Push_test_1---" << ELOG;
}
| 36.967972 | 130 | 0.661533 | [
"vector"
] |
718345a5e18268d4957f66b65fd648fdbe1d56a1 | 64,020 | cpp | C++ | ChessBattle.cpp | elsewhat/gtav-mod-battlechess | 76c5fef1337e45dc13b6447354ffe96a1099b22b | [
"Apache-2.0"
] | null | null | null | ChessBattle.cpp | elsewhat/gtav-mod-battlechess | 76c5fef1337e45dc13b6447354ffe96a1099b22b | [
"Apache-2.0"
] | 1 | 2020-09-01T17:48:04.000Z | 2020-09-01T18:28:22.000Z | ChessBattle.cpp | elsewhat/gtav-mod-battlechess | 76c5fef1337e45dc13b6447354ffe96a1099b22b | [
"Apache-2.0"
] | null | null | null | #include "ChessBattle.h"
#include "inc\natives.h"
#include "Utils.h"
#include "GTAUtils.h"
ChessBattle::ChessBattle(ChessMove chessMove, ChessBoard* chessBoard)
{
ChessBoardSquare* squareTo = chessMove.getSquareTo();
mActionGoToEndSquare = std::make_shared<ActionGoToSquare>(ActionGoToSquare(squareTo, squareTo->getHeading(chessMove.getAttacker()->getSide()), 1.0));
}
void ChessBattle::setMessage(std::string msg, DWORD length) {
mMsgBattle = msg;
mMsgTicksLength = length;
mMsgTicksStarted = GetTickCount();
}
void ChessBattle::drawMessage(ChessBoard* chessBoard) {
if (mMsgTicksLength > 0 && GetTickCount() - mMsgTicksStarted < mMsgTicksLength) {
chessBoard->drawBigMessage(strdup(mMsgBattle.c_str()));
}
}
void ChessBattle::initializeBattle(ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
std::vector<ChessPiece*> activePieces = { attacker, defender };
chessBoard->freezeAllExcept(activePieces);
attacker->setPedCanBeDamaged(false);
defender->setPedCanBeDamaged(true);
mIsMovingToSquare = false;
mNrMovementChecks = 0;
setMessage(attacker->getPieceTypeString() + " vs. " + defender->getPieceTypeString(), 3000);
}
ChessBattleFirePrimaryWeapon::ChessBattleFirePrimaryWeapon(ChessMove chessMove, ChessBoard* chessBoard) : ChessBattle(chessMove, chessBoard)
{
mFiringPattern = "FIRING_PATTERN_SINGLE_SHOT";
}
ChessBattleFirePrimaryWeapon::ChessBattleFirePrimaryWeapon(ChessMove chessMove, ChessBoard* chessBoard, std::string firingPattern) : ChessBattle(chessMove, chessBoard)
{
mFiringPattern = firingPattern;
}
void ChessBattleFirePrimaryWeapon::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard* chessBoard)
{
Logger::logDebug("ChessBattleFirePrimaryWeapon::startExecution");
mTicksStarted = ticksStart;
//worst case is that two shots take 18 damage
defender->setHealth(300);
equipWeapon(chessMove);
AI::TASK_SHOOT_AT_ENTITY(attacker->getPed() , defender->getPed(), -1, GAMEPLAY::GET_HASH_KEY(strdup(mFiringPattern.c_str())));
Logger::logDebug("startExecution Defender health " + std::to_string(ENTITY::GET_ENTITY_HEALTH(defender->getPed())));
}
bool ChessBattleFirePrimaryWeapon::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard* chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (defender->isPedDeadOrDying()) {
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard, true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (ticksNow - mTicksStarted > 5000) {
Logger::logDebug("ChessBattleFirePrimaryWeapon::More than 5000 ticks since started. Retriggering");
Logger::logDebug("Defender health " + std::to_string(ENTITY::GET_ENTITY_HEALTH(defender->getPed())));
attacker->removeWeapons();
equipWeapon(chessMove);
AI::CLEAR_PED_TASKS_IMMEDIATELY(attacker->getPed());
AI::TASK_SHOOT_AT_ENTITY(attacker->getPed(), defender->getPed(), -1, GAMEPLAY::GET_HASH_KEY(strdup(mFiringPattern.c_str())));
Logger::logDebug("ENTITY::DOES_ENTITY_EXIST(defender->getPed()) " + std::to_string(ENTITY::DOES_ENTITY_EXIST(defender->getPed())));
//walkaround for issues with task_shoot_at_entity
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
mTicksStarted = ticksNow;
}
return false;
}
void ChessBattleFirePrimaryWeapon::equipWeapon(ChessMove chessMove)
{
chessMove.getAttacker()->equipPrimaryWeapon();
}
ChessBattleFireSecondaryWeapon::ChessBattleFireSecondaryWeapon(ChessMove chessMove, ChessBoard* chessBoard) :ChessBattleFirePrimaryWeapon(chessMove, chessBoard)
{
}
ChessBattleFireSecondaryWeapon::ChessBattleFireSecondaryWeapon(ChessMove chessMove, ChessBoard* chessBoard, std::string firingPattern) : ChessBattleFirePrimaryWeapon(chessMove, chessBoard, firingPattern)
{
}
void ChessBattleFireSecondaryWeapon::equipWeapon(ChessMove chessMove)
{
chessMove.getAttacker()->equipSecondaryWeapon();
chessMove.getDefender()->setHealth(115);
}
ChessBattleSyncedAnimation::ChessBattleSyncedAnimation(ChessMove chessMove, ChessBoard* chessBoard, std::shared_ptr<SyncedAnimation> syncedAnimation, bool killAfterwards, bool useDefenderLocation,Vector3 locationOffset) : ChessBattle(chessMove, chessBoard)
{
mSyncedAnimation = syncedAnimation;
mKillAfterwards = killAfterwards;
mUseDefenderLocation = useDefenderLocation;
mLocationOffset = locationOffset;
}
void ChessBattleSyncedAnimation::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleSyncedAnimation::startExecution " + mSyncedAnimation->getTitle());
std::vector<ChessPiece*> actors = { attacker, defender };
Vector3 startLocation = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
if (mUseDefenderLocation) {
startLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), true);
}
startLocation.x = startLocation.x+ mLocationOffset.x;
startLocation.y = startLocation.y + mLocationOffset.y;
startLocation.z = startLocation.z + mLocationOffset.z;
mSyncedAnimation->executeSyncedAnimation(true, actors, false, startLocation, false, true, false);
}
bool ChessBattleSyncedAnimation::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (mSyncedAnimation->isCompleted()) {
mSyncedAnimation->cleanupAfterExecution(true, false);
if (!defender->isPedDeadOrDying()) {
Logger::logDebug("Defender is not dead. Exploding head death");
if (mKillAfterwards) {
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
else {
defender->removePed();
}
}
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard,true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else {
return false;
}
}
ChessBattleManualPlacedSyncedAnimation::ChessBattleManualPlacedSyncedAnimation(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
//default to be overriddden by subclasses
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("takedown_front_headbutt 2266");
mSpeedBeforeImpact = 2.0;
mForceHeading = false;
mTicksBeforeAction = 700;
}
ChessBattleHeadbutt::ChessBattleHeadbutt(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattleManualPlacedSyncedAnimation(chessMove, chessBoard)
{
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("takedown_front_headbutt 2266");
mSpeedBeforeImpact = 2.0;
mForceHeading = false;
mTicksBeforeAction = 700;
}
void ChessBattleManualPlacedSyncedAnimation::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleManualPlacedSyncedAnimation::startExecution " + mSyncedAnimation->getTitle());
//1. Move to square ahead of defender
//2. Start running to square of defender
//3. After a few hundred ms trigger synched anim
//4. Wait for synched anim to complete
//5. Move to target square
//6. Wait for getting close to target square
mIsMovingIntoPosition = true;
mSquareSetup = chessBoard->getSquareInFrontOf(chessMove.getSquareTo(), attacker->getSide());
Vector3 squareToLocation = mSquareSetup->getLocation();
AI::TASK_GO_STRAIGHT_TO_COORD(attacker->getPed(), squareToLocation.x, squareToLocation.y, squareToLocation.z, 1.0, -1, mSquareSetup->getHeading(attacker->getSide()), 0.5f);
}
bool ChessBattleManualPlacedSyncedAnimation::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsMovingIntoPosition) {
Vector3 currentLocation = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
Vector3 squareToLocation = mSquareSetup->getLocation();
float distanceToTarget = SYSTEM::VDIST(squareToLocation.x, squareToLocation.y, squareToLocation.z, currentLocation.x, currentLocation.y, currentLocation.z);
if (distanceToTarget < 1.5) {
mIsMovingIntoPosition = false;
Vector3 squareToLocation = chessMove.getSquareTo()->getLocation();
AI::TASK_GO_STRAIGHT_TO_COORD(attacker->getPed(), squareToLocation.x, squareToLocation.y, squareToLocation.z, mSpeedBeforeImpact, -1, mSquareSetup->getHeading(attacker->getSide()), 0.5f);
mIsWaitingForTriggeringSynced = true;
mTicksStarted = ticksNow;
}
return false;
}
else if (mIsWaitingForTriggeringSynced) {
if (ticksNow - mTicksStarted > mTicksBeforeAction) {
mIsWaitingForTriggeringSynced = false;
std::vector<ChessPiece*> actors = { attacker, defender };
Vector3 startLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), true);
startLocation.x = startLocation.x + 0.0;
startLocation.y = startLocation.y + 0.0;
startLocation.z = startLocation.z + 0.0;
if (mForceHeading) {
ENTITY::SET_ENTITY_HEADING(attacker->getPed(), mSquareSetup->getHeading(attacker->getSide()));
}
mSyncedAnimation->executeSyncedAnimation(true, actors, false, startLocation, false, true, false);
}
return false;
}
else if (mSyncedAnimation->isCompleted()) {
mSyncedAnimation->cleanupAfterExecution(true, false);
if (!defender->isPedDeadOrDying()) {
defender->removePed();
}
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
return false;
}
ChessBattleSyncedAnimationChained::ChessBattleSyncedAnimationChained(ChessMove chessMove, ChessBoard * chessBoard,std::shared_ptr<SyncedAnimation> firstSyncedAnimation, std::shared_ptr<SyncedAnimation> secondSyncedAnimation, bool killAfterwards, bool useDefenderLocation, Vector3 locationOffset, bool hasDefenderWeapon, std::string defenderWeapon) : ChessBattle(chessMove, chessBoard)
{
mFirstSyncedAnimation = firstSyncedAnimation;
mSecondSyncedAnimation = secondSyncedAnimation;
mKillAfterwards = killAfterwards;
mUseDefenderLocation = useDefenderLocation;
mLocationOffset = locationOffset;
mHasDefenderWeapon = hasDefenderWeapon;
mDefenderWeapon = defenderWeapon;
}
void ChessBattleSyncedAnimationChained::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleSyncedAnimation::startExecution " + mFirstSyncedAnimation->getTitle());
if (mHasDefenderWeapon) {
defender->equipWeapon(mDefenderWeapon);
}
std::vector<ChessPiece*> actors = { attacker, defender };
mStartLocation = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
if (mUseDefenderLocation) {
mStartLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), true);
}
mStartLocation.x = mStartLocation.x + mLocationOffset.x;
mStartLocation.y = mStartLocation.y + mLocationOffset.y;
mStartLocation.z = mStartLocation.z + mLocationOffset.z;
mFirstSyncedAnimation->executeSyncedAnimation(true, actors, false, mStartLocation, false, true, false);
mIsFirstCompleted = false;
}
bool ChessBattleSyncedAnimationChained::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (mIsFirstCompleted && mSecondSyncedAnimation->isCompleted()) {
Logger::logDebug("ChessBattleSyncedAnimationChained:: Second sync animation complete");
mSecondSyncedAnimation->cleanupAfterExecution(true, false);
if (!defender->isPedDeadOrDying()) {
Logger::logDebug("Defender is not dead. Exploding head death");
if (mKillAfterwards) {
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
else {
defender->removePed();
}
}
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard,true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (!mIsFirstCompleted && mFirstSyncedAnimation->isCompleted()) {
Logger::logDebug("ChessBattleSyncedAnimationChained:: First sync animation complete");
mFirstSyncedAnimation->cleanupAfterExecution(true, false);
std::vector<ChessPiece*> actors = { chessMove.getAttacker(), chessMove.getDefender() };
mSecondSyncedAnimation->executeSyncedAnimation(true, actors, false, mStartLocation, false, true, false);
mIsFirstCompleted = true;
return false;
}
else {
return false;
}
}
ChessBattleKnifeStruggle::ChessBattleKnifeStruggle(ChessMove chessMove, ChessBoard * chessBoard, std::shared_ptr<SyncedAnimation> firstSyncedAnimation, std::shared_ptr<SyncedAnimation> secondSyncedAnimation, bool killAfterwards, bool useDefenderLocation, Vector3 locationOffset, bool hasDefenderWeapon, std::string defenderWeapon) : ChessBattleSyncedAnimationChained(chessMove, chessBoard, firstSyncedAnimation, secondSyncedAnimation, killAfterwards, useDefenderLocation, locationOffset, hasDefenderWeapon, defenderWeapon)
{
}
bool ChessBattleKnifeStruggle::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (mIsFirstCompleted && mSecondSyncedAnimation->isCompleted()) {
Logger::logDebug("ChessBattleSyncedAnimationChained:: Second sync animation complete");
mSecondSyncedAnimation->cleanupAfterExecution(true, false);
if (!defender->isPedDeadOrDying()) {
Logger::logDebug("Defender is not dead. Exploding head death");
if (mKillAfterwards) {
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
else {
defender->removePed();
}
}
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard, true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (!mIsFirstCompleted && mFirstSyncedAnimation->isCompleted()) {
Logger::logDebug("ChessBattleSyncedAnimationChained:: First sync animation complete");
mFirstSyncedAnimation->cleanupAfterExecution(true, false);
std::vector<ChessPiece*> actors = { chessMove.getAttacker(), chessMove.getDefender() };
mSecondSyncedAnimation->executeSyncedAnimation(true, actors, false, mStartLocation, false, true, false);
mIsFirstCompleted = true;
return false;
}
else {
return false;
}
}
ChessBattleStealthKill::ChessBattleStealthKill(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
}
void ChessBattleStealthKill::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleStealthKill::startExecution");
mTicksStarted = ticksStart;
//AI::TASK_STEALTH_KILL(attacker->getPed(), defender->getPed(), GAMEPLAY::GET_HASH_KEY("AR_stealth_kill_knife"), 1.0f, 0);
AI::TASK_STEALTH_KILL(attacker->getPed(), defender->getPed(), GAMEPLAY::GET_HASH_KEY("AR_stealth_kill_a"), 10.0f, 1);
}
bool ChessBattleStealthKill::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (defender->isPedDeadOrDying()) {
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard,true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (ticksNow - mTicksStarted > 10000) {
Logger::logDebug("ChessBattleStealthKill::More than 10000 ticks since started. Retriggering");
//walkaround for issues with task_shoot_at_entity
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleDeathByCop::ChessBattleDeathByCop(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
}
void ChessBattleDeathByCop::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleStealthKill::startExecution");
mTicksStarted = ticksStart;
/*
FireDepartment = 3,
Paramedics = 5,
Police = 7,
PedsInCavalcades = 11,
Merryweather = 14
*/
mIncidentId = 0;
GAMEPLAY::CREATE_INCIDENT_WITH_ENTITY(14, defender->getPed(),4, 0.0f, &mIncidentId);
GAMEPLAY::CREATE_INCIDENT_WITH_ENTITY(11, defender->getPed(), 4, 0.0f, &mIncidentId2);
AI::TASK_USE_MOBILE_PHONE_TIMED(attacker->getPed(), 7000);
AUDIO::_PLAY_AMBIENT_SPEECH_WITH_VOICE(attacker->getPed(), "PHONE_CALL_COPS", "A_M_M_GOLFER_01_WHITE_MINI_01", "SPEECH_PARAMS_STANDARD",0);
setMessage("Death by cops", 3000);
}
bool ChessBattleDeathByCop::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (defender->isPedDeadOrDying()) {
mIsMovingToSquare = true;
Logger::logDebug("GAMEPLAY::DELETE_INCIDENT");
GAMEPLAY::DELETE_INCIDENT(&mIncidentId);
GAMEPLAY::DELETE_INCIDENT(&mIncidentId2);
attacker->startMovement(chessMove, chessBoard,true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (ticksNow - mTicksStarted > 40000) {
Logger::logDebug("ChessBattleStealthKill::More than 40000 ticks since started. Retriggering");
//walkaround for issues with task_shoot_at_entity
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleJerryCan::ChessBattleJerryCan(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
ChessBoardSquare* squareBehind = chessBoard->getSquareBehind(chessMove.getSquareTo(), chessMove.getAttacker()->getSide());
//only Pawn can use this move with this
ChessBoardSquare* squareOneStep = chessBoard->getSquareInFrontOf(chessMove.getSquareFrom(), chessMove.getDefender()->getSide());
ChessBoardSquare* squareTwoStep = chessBoard->getSquareInFrontOf(squareOneStep, chessMove.getDefender()->getSide());
mCoordsToSneak.push_back(std::make_shared<ActionGoToCoord>(ActionGoToCoord(squareTwoStep->getLocation(), chessMove.getSquareTo()->getHeading(chessMove.getAttacker()->getSide()), 1.0)));
mCoordsToSneak.push_back(std::make_shared<ActionGoToCoord>(ActionGoToCoord(squareBehind->getLocation(), chessMove.getSquareTo()->getHeading(chessMove.getDefender()->getSide()), 1.0)));
std::shared_ptr<ActionGoToCoord> lastAction = std::make_shared<ActionGoToCoord>(ActionGoToCoord(chessMove.getSquareTo()->getLocation(), chessMove.getSquareTo()->getHeading(chessMove.getAttacker()->getSide()), 1.0));
lastAction->setMinDistance(1.1);
mCoordsToSneak.push_back(lastAction);
mActionShootingLocation = std::make_shared<ActionGoToCoord>(ActionGoToCoord(squareTwoStep->getLocation(), chessMove.getSquareTo()->getHeading(chessMove.getDefender()->getSide()), 1.0));
}
void ChessBattleJerryCan::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
mIsPouring = false;
Logger::logDebug("ChessBattleJerryCan::startExecution");
//Make defender ignore gunshots
PED::SET_BLOCKING_OF_NON_TEMPORARY_EVENTS(defender->getPed(), true);
PED::SET_BLOCKING_OF_NON_TEMPORARY_EVENTS(attacker->getPed(), true);
STREAMING::REQUEST_CLIP_SET("move_ped_wpn_jerrycan_generic");
while (!STREAMING::HAS_CLIP_SET_LOADED("move_ped_wpn_jerrycan_generic"))
{
WAIT(0);
if (GetTickCount() - ticksStart > 5000) {
Logger::logDebug("Failed to load move_ped_wpn_jerrycan_generic");
return;
}
}
mCoordsToSneak[mCoordsToSneakIndex]->start(ticksStart, attacker, defender, chessMove, chessBoard);
}
bool ChessBattleJerryCan::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsShooting) {
if (AI::GET_SEQUENCE_PROGRESS(attacker->getPed()) == -1) {
if (!defender->isPedDeadOrDying()) {
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return true;
}
else if (ticksNow - mTicksStarted > 600) {
FIRE::START_ENTITY_FIRE(defender->getPed());
mTicksStarted = mTicksStarted + mTicksStarted;
}
}
else if (mIsPouring) {
if (AI::GET_SEQUENCE_PROGRESS(attacker->getPed()) == -1) {
mIsPouring = false;
mLocationPetrol = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
mLocationPetrol.z = mLocationPetrol.z - 1.0;
mActionShootingLocation->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
}
else if (mActionShootingLocation->hasBeenStarted()) {
if (mActionShootingLocation->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
mIsShooting = true;
PED::SET_PED_STEALTH_MOVEMENT(chessMove.getAttacker()->getPed(), 0, 0);
TaskSequence taskSequence = 100;
AI::OPEN_SEQUENCE_TASK(&taskSequence);
chessMove.getAttacker()->equipPrimaryWeapon();
AI::TASK_SHOOT_AT_COORD(0, mLocationPetrol.x, mLocationPetrol.y, mLocationPetrol.z, 2000, 3337513804);
AI::CLOSE_SEQUENCE_TASK(taskSequence);
AI::TASK_PERFORM_SEQUENCE(attacker->getPed(), taskSequence);
AI::CLEAR_SEQUENCE_TASK(&taskSequence);
mTicksStarted = ticksNow;
return false;
}
}
else if (mCoordsToSneak[mCoordsToSneakIndex]->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
if (mCoordsToSneakIndex == 0) {
chessMove.getAttacker()->equipWeapon("WEAPON_PETROLCAN");
PED::SET_PED_WEAPON_MOVEMENT_CLIPSET(chessMove.getAttacker()->getPed(), "move_ped_wpn_jerrycan_generic");
PED::SET_PED_STEALTH_MOVEMENT(chessMove.getAttacker()->getPed(), 1, 0);
PED::FORCE_PED_MOTION_STATE(chessMove.getAttacker()->getPed(), 1110276645, false, 0, 0);
PED::_0x2208438012482A1A(chessMove.getAttacker()->getPed(), 0, 0);
UNK1::_0x81CBAE94390F9F89();
PED::SET_PED_MOVEMENT_CLIPSET(chessMove.getAttacker()->getPed(), "move_ped_crouched", 1.0);
}
mCoordsToSneakIndex++;
if (mCoordsToSneakIndex < mCoordsToSneak.size()) {
mCoordsToSneak[mCoordsToSneakIndex]->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else {
mIsPouring = true;
mPourTaskSequence = 99;
AI::OPEN_SEQUENCE_TASK(&mPourTaskSequence);
Logger::logDebug("Pouring petrol for 5000 ms", true);
AI::TASK_SHOOT_AT_COORD(0, 0.0, 0.0, 0.0, 5000, 3337513804);
AI::CLOSE_SEQUENCE_TASK(mPourTaskSequence);
AI::TASK_PERFORM_SEQUENCE(attacker->getPed(), mPourTaskSequence);
AI::CLEAR_SEQUENCE_TASK(&mPourTaskSequence);
return false;
}
}
return false;
}
ChessBattleHandToHandWeapon::ChessBattleHandToHandWeapon(ChessMove chessMove, ChessBoard * chessBoard,std::string handToHandWeaponAttacker, std::string handToHandWeaponDefender, bool defenderIsUnarmed, int defenderHealth) : ChessBattle(chessMove, chessBoard)
{
mHandToHandWeaponAttacker = handToHandWeaponAttacker;
mHandToHandWeaponDefender = handToHandWeaponDefender;
mDefenderIsUnarmed = defenderIsUnarmed;
mDefenderHealth = defenderHealth;
}
void ChessBattleHandToHandWeapon::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleHandToHandWeapon::startExecution");
mTicksStarted = ticksStart;
attacker->removeWeapons();
attacker->equipWeapon(mHandToHandWeaponAttacker);
defender->removeWeapons();
if (!mDefenderIsUnarmed) {
defender->equipWeapon(mHandToHandWeaponDefender);
}
defender->setHealth(mDefenderHealth);
AI::TASK_COMBAT_PED(attacker->getPed(), defender->getPed(), 0, 16);
AI::TASK_COMBAT_PED(defender->getPed(), attacker->getPed(), 0, 16);
}
bool ChessBattleHandToHandWeapon::isExecutionCompleted(DWORD ticksNow, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mIsMovingToSquare) {
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (defender->isPedDeadOrDying()) {
mIsMovingToSquare = true;
attacker->startMovement(chessMove, chessBoard,true);
return attacker->isMovementCompleted(chessMove, mNrMovementChecks++);
}
else if (ticksNow - mTicksStarted > 20000) {
Logger::logDebug("ChessBattleHandToHandWeapon::More than 20000 ticks since started.");
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleFiringSquad::ChessBattleFiringSquad(ChessMove chessMove, ChessBoard * chessBoard, std::string weapon, bool isThrowingWeapon, Animation animation): ChessBattle(chessMove,chessBoard)
{
mWeapon = weapon;
mAnimation = animation;
mIsThrowingWeapon = isThrowingWeapon;
ChessPiece* attacker = chessMove.getAttacker();
Ped pedAttacker = attacker->getPed();
std::array<ChessPiece*, 16> pieces = chessBoard->getChessSet(attacker->getSide())->getPieces();
for (auto piece : pieces) {
if (piece->getPed() != pedAttacker) {
mSquad.push_back(piece);
piece->setPedCanBeDamaged(false);
}
}
//special case
if (mSquad.size() == 0) {
mSquad.push_back(attacker);
}
ENTITY::SET_ENTITY_INVINCIBLE(chessMove.getDefender()->getPed(), false);
ENTITY::SET_ENTITY_PROOFS(chessMove.getDefender()->getPed(), false, false, false, false, false, false, false, false);
chessMove.getDefender()->setHealth(150);
}
void ChessBattleFiringSquad::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
for (auto piece : mSquad) {
piece->equipWeapon(mWeapon);
}
for (auto piece : mSquad) {
Vector3 targetLocation = chessMove.getSquareTo()->getLocation();
if (mIsThrowingWeapon) {
AI::TASK_THROW_PROJECTILE(piece->getPed(), targetLocation.x, targetLocation.y, targetLocation.z);
}
else {
AI::TASK_SHOOT_AT_ENTITY(piece->getPed(), defender->getPed(), -1, GAMEPLAY::GET_HASH_KEY("FIRING_PATTERN_SINGLE_SHOT"));
}
}
if (mSquad[0]->getPed() != attacker->getPed()) {
GTAModUtils::playAnimation(attacker->getPed(), mAnimation);
}
mTicksStarted = ticksStart;
}
bool ChessBattleFiringSquad::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (defender->isPedDeadOrDying()) {
/*for (auto piece : mSquad) {
AI::CLEAR_PED_TASKS(piece->getPed());
}*/
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else if (ticksNow - mTicksStarted > 10000) {
Logger::logDebug("ChessBattleFiringSquad::More than 10000 ticks since started");
//Kill defender
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
return false;
}
ChessBattleTank::ChessBattleTank(ChessMove chessMove, ChessBoard * chessBoard):ChessBattle(chessMove,chessBoard)
{
}
void ChessBattleTank::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleTank::startExecution");
mTicksStarted = GetTickCount();
Hash hashTankModel = GAMEPLAY::GET_HASH_KEY("rhino");
STREAMING::REQUEST_MODEL(hashTankModel);
while (!STREAMING::HAS_MODEL_LOADED(hashTankModel))
{
WAIT(0);
if (GetTickCount() > mTicksStarted + 5000) {
//duration will be 0 if it's not loaded
Logger::logError("ChessBattleTank::startExecution tankModel not loaded after 5000 ticks");
return;
}
}
Vector3 tankLocation = chessBoard->getVehicleSpawnZone(attacker->getSide());
float heading = 90.0;
if (attacker->getSide() == ChessSide::BLACK) {
heading = 270.0;
}
mVehicle = VEHICLE::CREATE_VEHICLE(hashTankModel, tankLocation.x, tankLocation.y, tankLocation.z, heading, 1, 1);
VEHICLE::SET_VEHICLE_ON_GROUND_PROPERLY(mVehicle);
Vector3 otherLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), 1);
heading = GAMEPLAY::GET_HEADING_FROM_VECTOR_2D(otherLocation.x - tankLocation.x, otherLocation.y - tankLocation.y);
ENTITY::SET_ENTITY_HEADING(mVehicle, heading);
mActionEnterTank = std::make_shared<ActionEnterVehicle>(ActionEnterVehicle(mVehicle, 2.0f, 15000));
mActionEnterTank->start(ticksStart, attacker, defender, chessMove, chessBoard);
mTicksStarted = GetTickCount();
}
bool ChessBattleTank::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (defender->isPedDeadOrDying()) {
Logger::logDebug("ChessBattleTank defender is dead has entered tank");
AI::TASK_LEAVE_VEHICLE(attacker->getPed(), mVehicle, 0);
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else if (ticksNow - mTicksStarted > 25000) {
Logger::logDebug("ChessBattleTank::More than 25000 ticks since started");
//Kill defender
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
else if (mActionEnterTank->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
Logger::logDebug("ChessBattleTank attacker has entered tank");
mTicksStarted = ticksNow;
TaskSequence taskSequence = 100;
AI::OPEN_SEQUENCE_TASK(&taskSequence);
AI::TASK_VEHICLE_AIM_AT_PED(0, defender->getPed());
AI::TASK_VEHICLE_SHOOT_AT_PED(0, defender->getPed(), 1101004800);
AI::CLOSE_SEQUENCE_TASK(taskSequence);
AI::TASK_PERFORM_SEQUENCE(attacker->getPed(), taskSequence);
AI::CLEAR_SEQUENCE_TASK(&taskSequence);
//https://www.se7ensins.com/forums/threads/how-to-get-hidden-weapons-like-remote-sniper-in-sp.1174186/
//WEAPON::SET_CURRENT_PED_VEHICLE_WEAPON(pilot, GAMEPLAY::GET_HASH_KEY("VEHICLE_WEAPON_TANK"));
VEHICLE::SET_VEHICLE_SHOOT_AT_TARGET(attacker->getPed(), defender->getPed(), 0.0, 0.0, 0.0);
}
return false;
}
ChessBattleSlap::ChessBattleSlap(ChessMove chessMove, ChessBoard * chessBoard): ChessBattleManualPlacedSyncedAnimation(chessMove, chessBoard)
{
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("takedown_front_slap 2399");
mSpeedBeforeImpact = 1.0;
}
ChessBattleNeedBiggerGun::ChessBattleNeedBiggerGun(ChessMove chessMove, ChessBoard * chessBoard, std::string weapon1, std::string firingPattern1, std::string weapon2, std::string firingPattern2, DWORD ticksBeforeSwitch): ChessBattle (chessMove,chessBoard)
{
mWeapon1 = weapon1;
mFiringPattern1 = firingPattern1;
mWeapon2 = weapon2;
mFiringPattern2 = firingPattern2;
mTicksBeforeSwitch = ticksBeforeSwitch;
}
void ChessBattleNeedBiggerGun::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleNeedBiggerGun::startExecution");
mTicksStarted = ticksStart;
attacker->equipWeapon(mWeapon1);
defender->equipWeapon(mWeapon1);
//defender cannot be damaged with first weapon
defender->setPedCanBeDamaged(false);
mFirstWeaponEquipped = true;
AI::TASK_SHOOT_AT_ENTITY(attacker->getPed(), defender->getPed(), -1, GAMEPLAY::GET_HASH_KEY(strdup(mFiringPattern1.c_str())));
AI::TASK_SHOOT_AT_ENTITY(defender->getPed(), attacker->getPed(), -1, GAMEPLAY::GET_HASH_KEY(strdup(mFiringPattern1.c_str())));
}
bool ChessBattleNeedBiggerGun::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (defender->isPedDeadOrDying()) {
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else if (mFirstWeaponEquipped && ticksNow - mTicksStarted > mTicksBeforeSwitch) {
defender->setPedCanBeDamaged(true);
mFirstWeaponEquipped = false;
attacker->equipWeapon(mWeapon2);
AI::TASK_SHOOT_AT_ENTITY(attacker->getPed(), defender->getPed(), -1, GAMEPLAY::GET_HASH_KEY(strdup(mFiringPattern2.c_str())));
mTicksStarted = ticksNow;
}
else if (ticksNow - mTicksStarted > 20000) {
Logger::logDebug("ChessBattleNeedBiggerGun::More than 25000 ticks since started");
//Kill defender
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
return false;
}
ChessBattleTurnIntoAnimal::ChessBattleTurnIntoAnimal(ChessMove chessMove, ChessBoard * chessBoard, std::string animalModel, Animation animation, DWORD waitTimeAfterAnimation): ChessBattle(chessMove,chessBoard)
{
mAnimalModelName = animalModel;
mAnimation = animation;
mWaitTimeAfterAnimation = waitTimeAfterAnimation;
}
void ChessBattleTurnIntoAnimal::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleTurnIntoAnimal::startExecution");
mTicksStarted = ticksStart;
mAnimalModelHash = GAMEPLAY::GET_HASH_KEY(strdup(mAnimalModelName.c_str()));
STREAMING::REQUEST_MODEL(mAnimalModelHash);
while (!STREAMING::HAS_MODEL_LOADED(mAnimalModelHash)) {
WAIT(0);
if (GetTickCount() - ticksStart > 15000) {
Logger::logDebug("Failed to load " + mAnimalModelName);
break;
}
}
attacker->forceFaceHeadingTowards(defender);
GTAModUtils::playAnimation(attacker->getPed(), mAnimation);
mIsWaitingAfterAnimation = true;
}
bool ChessBattleTurnIntoAnimal::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
if (mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
return true;
}
}
else if (!mIsWaitingAfterAnimation) {
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else if (mIsWaitingAfterAnimation && ticksNow - mTicksStarted > mWaitTimeAfterAnimation) {
mIsWaitingAfterAnimation = false;
Vector3 location = ENTITY::GET_ENTITY_COORDS(defender->getPed(), 1);
float heading = ENTITY::GET_ENTITY_HEADING(defender->getPed());
mAnimalPed = PED::CREATE_PED(28, mAnimalModelHash, location.x, location.y, location.z, heading, false, true);
defender->removePed();
defender->setPed(mAnimalPed);
Vector3 fleeLocation = chessBoard->getVehicleSpawnZone(defender->getSide());
AI::TASK_GO_STRAIGHT_TO_COORD(mAnimalPed, fleeLocation.x, fleeLocation.y, fleeLocation.z, 2.0, -1, heading, 0.0);
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleShootOut::ChessBattleShootOut(ChessMove chessMove, ChessBoard * chessBoard): ChessBattleManualPlacedSyncedAnimation(chessMove,chessBoard)
{
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("Shoot out");
mSpeedBeforeImpact = 1.0;
mForceHeading = true;
}
void ChessBattleShootOut::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleShootOut::startExecution " + mSyncedAnimation->getTitle());
attacker->setPedFreezed(true);
attacker->equipPrimaryWeapon();
defender->equipPrimaryWeapon();
attacker->forceFaceHeadingTowards(defender);
defender->forceFaceHeadingTowards(attacker);
//mIsMovingIntoPosition = true;
//mSquareSetup = chessBoard->getSquareInFrontOf(chessMove.getSquareTo(), attacker->getSide());
//mSquareSetup = chessBoard->getSquareInFrontOf(mSquareSetup, attacker->getSide());
//Vector3 squareToLocation = mSquareSetup->getLocation();
//AI::TASK_GO_STRAIGHT_TO_COORD(attacker->getPed(), squareToLocation.x, squareToLocation.y, squareToLocation.z, 1.0, -1, attacker->getSide(), 0.5f);
std::vector<ChessPiece*> actors = {defender,attacker };
Vector3 startLocation = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
mSyncedAnimation->executeSyncedAnimation(true, actors, false, startLocation, false, true, false);
mHasDefenderFired = false;
mHasAttackerFired = false;
}
bool ChessBattleShootOut::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mSyncedAnimation->isCompleted()) {
mSyncedAnimation->cleanupAfterExecution(true, false);
if (!defender->isPedDeadOrDying()) {
defender->removePed();
}
attacker->setPedFreezed(false);
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
Logger::logDebug("mSyncedAnimation->getProgress() " +std::to_string(mSyncedAnimation->getProgress()));
if (!mHasAttackerFired && mSyncedAnimation->getProgress() >= 0.6 &&mSyncedAnimation->getProgress() <= 0.7) {
Logger::logDebug("ChessBattleShootOut attacker firing: " );
Vector3 weaponImpact = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), 1);
PED::SET_PED_SHOOTS_AT_COORD(defender->getPed(), weaponImpact.x, weaponImpact.y, weaponImpact.z, 1);
mHasAttackerFired = true;
}
if (!mHasDefenderFired && mSyncedAnimation->getProgress() >= 0.4 &&mSyncedAnimation->getProgress() <= 0.5) {
Logger::logDebug("ChessBattleShootOut defender firing");
Vector3 weaponImpact = ENTITY::GET_ENTITY_COORDS(defender->getPed(), 1);
PED::SET_PED_SHOOTS_AT_COORD(attacker->getPed(), weaponImpact.x, weaponImpact.y, weaponImpact.z, 1);
mHasDefenderFired = true;
}
return false;
}
ChessBattleHatchetFront::ChessBattleHatchetFront(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattleManualPlacedSyncedAnimation(chessMove, chessBoard)
{
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("Hatchet takedown front");
mSpeedBeforeImpact = 1.0;
mForceHeading = true;
mTicksBeforeAction = 1100;
}
void ChessBattleHatchetFront::startExecution(DWORD ticksStart, ChessPiece* attacker, ChessPiece* defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleHatchetFront::startExecution " + mSyncedAnimation->getTitle());
//1. Move to square ahead of defender
//2. Start running to square of defender
//3. After a few hundred ms trigger synched anim
//4. Wait for synched anim to complete
//5. Move to target square
//6. Wait for getting close to target square
attacker->equipWeapon("WEAPON_HATCHET");
mIsMovingIntoPosition = true;
mSquareSetup = chessBoard->getSquareInFrontOf(chessMove.getSquareTo(), attacker->getSide());
Vector3 squareToLocation = mSquareSetup->getLocation();
AI::TASK_GO_STRAIGHT_TO_COORD(attacker->getPed(), squareToLocation.x, squareToLocation.y, squareToLocation.z, 1.0, -1, attacker->getSide(), 0.5f);
}
ChessBattleThrowGrenade::ChessBattleThrowGrenade(ChessMove chessMove, ChessBoard * chessBoard, std::string grenadeName):ChessBattle(chessMove,chessBoard)
{
mGrenadeName = grenadeName;
mActionThrowGrenade = std::make_shared<ActionThrowGrenade>(ActionThrowGrenade(grenadeName, 7000));
}
void ChessBattleThrowGrenade::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
attacker->equipWeapon(mGrenadeName);
mTicksStarted = ticksStart;
}
bool ChessBattleThrowGrenade::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
if (mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
return true;
}
}
else if (defender->isPedDeadOrDying()) {
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
else if (mActionThrowGrenade->hasBeenStarted()) {
if (mActionThrowGrenade->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
if (!defender->isPedDeadOrDying()) {
//Kill defender
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
}
return false;
}
}
else if (!mActionThrowGrenade->hasBeenStarted() && ticksNow - mTicksStarted > 700) {
mActionThrowGrenade->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
return false;
}
ChessBattleShoryuken::ChessBattleShoryuken(ChessMove chessMove, ChessBoard * chessBoard):ChessBattleManualPlacedSyncedAnimation(chessMove,chessBoard)
{
//default to be overriddden by subclasses
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("Melee takedown front uppercut");
mSpeedBeforeImpact = 1.0;
mForceHeading = true;
mTicksBeforeAction = 650;
mDoneMegaPunch = false;
}
bool ChessBattleShoryuken::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (!mDoneMegaPunch & mSyncedAnimation->getProgress() >= 0.23) {
Logger::logDebug("ChessBattleShoryuken mega punch");
Vector3 force = ENTITY::GET_ENTITY_FORWARD_VECTOR(attacker->getPed());
//Vector3 force;
float sideMultiplier = 1.0f;
if (attacker->getSide() == ChessSide::BLACK) {
sideMultiplier = -1.0f;
}
force.x = force.x* 0.8 * 1000.0;
force.y = force.y* 0.8 * 1000.0;
force.z = 0.3 * 1000.0;
Vector3 rotation;
Logger::logDebug("Force " + std::to_string(force.x) + "," + std::to_string(force.y) + "," + std::to_string(force.z) + ",");
//AI::CLEAR_PED_TASKS(defender->getPed());
ENTITY::APPLY_FORCE_TO_ENTITY(defender->getPed(), 3, force.x, force.y, force.z, rotation.x, rotation.y, rotation.z, false, false, true, true, false, true);
//PED::SET_PED_TO_RAGDOLL(defender->getPed(), 5000, 5000, 0, false, false, false);
//defender->setHealth(0);
mDoneMegaPunch = true;
mDoneRagdoll = false;
mTicksStarted = ticksNow;
}
if (!mDoneRagdoll && mDoneMegaPunch && ticksNow - mTicksStarted > 200) {
Logger::logDebug("ChessBattleShoryuken ragdoll");
mDoneRagdoll = true;
AI::SET_HIGH_FALL_TASK(defender->getPed(), 10000, 30000, 0);
//defender->setHealth(0);
AUDIO::_PLAY_AMBIENT_SPEECH_WITH_VOICE(defender->getPed(), "SCREAM_TERROR", "WAVELOAD_PAIN_MALE", "SPEECH_PARAMS_STANDARD", 0);
//PED::SET_PED_TO_RAGDOLL(defender->getPed(), 10000, 10000, 0, false, false, false);
}
if (mActionGoToEndSquare->hasBeenStarted()) {
if (mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard)) {
defender->setHealth(0);
return true;
}
}
else if (mIsMovingIntoPosition) {
Vector3 currentLocation = ENTITY::GET_ENTITY_COORDS(attacker->getPed(), true);
Vector3 squareToLocation = mSquareSetup->getLocation();
float distanceToTarget = SYSTEM::VDIST(squareToLocation.x, squareToLocation.y, squareToLocation.z, currentLocation.x, currentLocation.y, currentLocation.z);
if (distanceToTarget < 1.5) {
mIsMovingIntoPosition = false;
Vector3 squareToLocation = chessMove.getSquareTo()->getLocation();
AI::TASK_GO_STRAIGHT_TO_COORD(attacker->getPed(), squareToLocation.x, squareToLocation.y, squareToLocation.z, mSpeedBeforeImpact, -1, mSquareSetup->getHeading(attacker->getSide()), 0.5f);
mIsWaitingForTriggeringSynced = true;
mTicksStarted = ticksNow;
}
return false;
}
else if (mIsWaitingForTriggeringSynced) {
if (ticksNow - mTicksStarted > mTicksBeforeAction) {
mIsWaitingForTriggeringSynced = false;
std::vector<ChessPiece*> actors = { attacker };
Vector3 startLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), true);
startLocation.x = startLocation.x + 0.0;
startLocation.y = startLocation.y + 0.0;
startLocation.z = startLocation.z + 0.0;
if (mForceHeading) {
ENTITY::SET_ENTITY_HEADING(attacker->getPed(), mSquareSetup->getHeading(attacker->getSide()));
}
mSyncedAnimation->executeSyncedAnimation(true, actors, false, startLocation, false, true, false);
//Animation defenderAnimation = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(6702);
//GTAModUtils::playAnimation(defender->getPed(), defenderAnimation);
}
return false;
}
else if (mSyncedAnimation->isCompleted() && ticksNow - mTicksStarted > 20000) {
mSyncedAnimation->cleanupAfterExecution(true, false);
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
return false;
}
return false;
}
ChessBattleAttackedByAnimals::ChessBattleAttackedByAnimals(ChessMove chessMove, ChessBoard * chessBoard, std::string animalName, int nrOfAnimalsPrSide): ChessBattle(chessMove,chessBoard)
{
mNrOfAnimalsPrSide = nrOfAnimalsPrSide;
mAnimalName = animalName;
}
void ChessBattleAttackedByAnimals::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleAttackedByAnimals::startExecution");
Hash mAnimalHash = GAMEPLAY::GET_HASH_KEY(strdup(mAnimalName.c_str()));
STREAMING::REQUEST_MODEL(mAnimalHash);
while (!STREAMING::HAS_MODEL_LOADED(mAnimalHash)) {
if (GetTickCount() - ticksStart > 5000) {
Logger::logDebug("Failed to load " + mAnimalName);
return;
}
WAIT(0);
}
//05089 facials@p_m_zero@variations@elkcall mood_elkcal_1 3633
Animation elkCallAnimation = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(5089);
GTAModUtils::playAnimation(attacker->getPed(), elkCallAnimation);
//Audio.PlaySoundFromEntity("Franklin_Whistle_For_Chop", Game.Player.Character, "SPEECH_RELATED_SOUNDS");
AUDIO::PLAY_SOUND_FROM_ENTITY(-1, "Franklin_Whistle_For_Chop", attacker->getPed(), "SPEECH_RELATED_SOUNDS", 0, 0);
//TODO player.Task.PlayAnimation("facials@p_m_zero@variations@elkcall", "mood_elkcal_1");
Vector3 otherLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), 1);
Vector3 location = chessBoard->getVehicleSpawnZone(ChessSide::WHITE);
float heading = GAMEPLAY::GET_HEADING_FROM_VECTOR_2D(otherLocation.x - location.x, otherLocation.y - location.y);
for (int i = 0; i < mNrOfAnimalsPrSide *2 ; i++) {
if (i == mNrOfAnimalsPrSide) {
location = chessBoard->getVehicleSpawnZone(ChessSide::BLACK);
heading = GAMEPLAY::GET_HEADING_FROM_VECTOR_2D(otherLocation.x - location.x, otherLocation.y - location.y);
}
Ped animalPed = PED::CREATE_PED(4, mAnimalHash, location.x, location.y, location.z, heading, false, true);
//never flee
PED::SET_PED_COMBAT_ATTRIBUTES(animalPed, 46, true);
//fight with melee weapons
PED::SET_PED_COMBAT_ATTRIBUTES(animalPed, 5, true);
ENTITY::SET_ENTITY_CAN_BE_DAMAGED(animalPed, false);
ENTITY::SET_ENTITY_INVINCIBLE(animalPed,true);
ENTITY::SET_ENTITY_PROOFS(animalPed, 1, 1, 1, 1, 1, 1, 1, 1);
PED::SET_PED_SEEING_RANGE(animalPed, 100.0f);
PED::SET_PED_HEARING_RANGE(animalPed, 100.0f);
PED::SET_PED_ALERTNESS(animalPed, 3);
PED::SET_PED_COMBAT_RANGE(animalPed, 2);
mAnimals.push_back(animalPed);
}
for (auto animal : mAnimals) {
AI::TASK_COMBAT_PED(animal, defender->getPed(), 0, 16);
}
mIsWaitingForAnimalsToAttack = true;
mRemovedAnimals = false;
mTicksStarted = ticksStart;
}
bool ChessBattleAttackedByAnimals::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
if (mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard) && ticksNow - mTicksStarted > 15000) {
if (!mRemovedAnimals) {
Logger::logDebug("ChessBattleAttackedByAnimals Removing animals");
mRemovedAnimals = true;
for (auto animal : mAnimals) {
if (ENTITY::DOES_ENTITY_EXIST(animal))
{
PED::DELETE_PED(&animal);
}
}
}
return true;
}
else {
return false;
}
}
else if (defender->isPedDeadOrDying()) {
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
mIsWaitingForAnimalsToAttack = false;
for (auto animal : mAnimals) {
Vector3 location = chessBoard->getVehicleSpawnZone(ChessSide::WHITE);
AI::TASK_GO_STRAIGHT_TO_COORD(animal, location.x, location.y, location.z, 1.0, -1, 1.0, 0.0);
}
mTicksStarted = ticksNow;
return false;
}
else if (mIsWaitingForAnimalsToAttack && ticksNow - mTicksStarted > 20000) {
Logger::logDebug("ChessBattleAttackedByAnimals killing defender after 20000 ticks");
PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
return false;
}
}
ChessBattleAttackOfTheClones::ChessBattleAttackOfTheClones(ChessMove chessMove, ChessBoard * chessBoard):ChessBattle(chessMove, chessBoard)
{
mAnimation = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(2925);
}
void ChessBattleAttackOfTheClones::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleAttackOfTheClones::startExecution");
mTicksStarted = ticksStart;
mIsCloning = true;
Vector3 location = chessMove.getSquareTo()->getLocation();
location.x = location.x - 2.0;
defender->setHealth(135);
GTAModUtils::playAnimation(attacker->getPed(), mAnimation);
createClone(attacker, location, ENTITY::GET_ENTITY_COORDS(defender->getPed(), true));
mCloningIndex++;
mWaitingForClonesToAttack = false;
defender->equipSecondaryWeapon();
}
bool ChessBattleAttackOfTheClones::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
if (mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard) && ticksNow - mTicksStarted > 15000) {
if (!mHasRemovedClones) {
Logger::logDebug("ChessBattleAttackOfTheClones Removing clones");
mHasRemovedClones = true;
for (auto clone : mClones) {
if (ENTITY::DOES_ENTITY_EXIST(clone))
{
PED::DELETE_PED(&clone);
}
}
}
return true;
}
else {
return false;
}
}
else if (defender->isPedDeadOrDying()) {
Logger::logDebug("ChessBattleAttackOfTheClones isPedDeadOrDying");
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
mWaitingForClonesToAttack = false;
for (auto clone : mClones) {
Vector3 location = chessBoard->getVehicleSpawnZone(ChessSide::WHITE);
AI::TASK_GO_STRAIGHT_TO_COORD(clone, location.x, location.y, location.z, 1.0, -1, 1.0, 0.0);
}
mTicksStarted = ticksNow;
return false;
}
else if (mWaitingForClonesToAttack && ticksNow - mTicksStarted > 1500) {
Logger::logDebug("ChessBattleAttackOfTheClones mWaitingForClonesToAttack");
//PED::EXPLODE_PED_HEAD(defender->getPed(), 0x5FC3C11);
for (auto clone : mClones) {
AI::TASK_PUT_PED_DIRECTLY_INTO_MELEE(clone, defender->getPed(), 0.0, -1.0, 0.0, 0);
}
mWaitingForClonesToAttack = false;
return false;
}
else if (mIsCloning && ticksNow - mTicksStarted > 3000) {
Logger::logDebug("ChessBattleAttackOfTheClones mIsCloning " + std::to_string(mCloningIndex));
Vector3 location = chessMove.getSquareTo()->getLocation();
if (mCloningIndex == 1) {
location.y = location.y + 2.0;
}
else if(mCloningIndex == 2){
location.x = location.x + 2.0;
}
GTAModUtils::playAnimation(attacker->getPed(), mAnimation);
createClone(attacker, location, ENTITY::GET_ENTITY_COORDS(defender->getPed(),true));
mCloningIndex++;
if (mCloningIndex >= 3) {
mIsCloning = false;
mWaitingForClonesToAttack = true;
}
mTicksStarted = ticksNow;
}
return false;
}
void ChessBattleAttackOfTheClones::createClone(ChessPiece* chessPiece, Vector3 location, Vector3 faceLocation)
{
float heading = heading = GAMEPLAY::GET_HEADING_FROM_VECTOR_2D(faceLocation.x - location.x, faceLocation.y - location.y);
Ped clonedPed = PED::CLONE_PED(chessPiece->getPed(), heading, false, true);
ENTITY::SET_ENTITY_COORDS_NO_OFFSET(clonedPed, location.x, location.y, location.z, 0, 0, 1);
ENTITY::SET_ENTITY_HEADING(clonedPed, heading);
mClones.push_back(clonedPed);
}
ChessBattleSharkAttack::ChessBattleSharkAttack(ChessMove chessMove, ChessBoard * chessBoard): ChessBattle(chessMove,chessBoard)
{
Logger::logDebug("ChessBattleSharkAttack::constructor");
mSyncedAnimation = chessBoard->getSyncedAnimationFactory()->getByTitle("Shark attack");
mAnimation = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(2925);
}
void ChessBattleSharkAttack::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
Logger::logDebug("ChessBattleSharkAttack::startExecution " + mSyncedAnimation->getTitle());
mAnimalHash = GAMEPLAY::GET_HASH_KEY("a_c_sharktiger");
STREAMING::REQUEST_MODEL(mAnimalHash);
while (!STREAMING::HAS_MODEL_LOADED(mAnimalHash)) {
if (GetTickCount() - ticksStart > 5000) {
Logger::logDebug("Failed to load a_c_sharktiger");
return;
}
WAIT(0);
}
GTAModUtils::playAnimation(attacker->getPed(), mAnimation);
mTicksStarted = ticksStart;
}
bool ChessBattleSharkAttack::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mSyncedAnimation->isActive() && mSyncedAnimation->isCompleted()) {
Logger::logDebug("ChessBattleAttackOfTheClones mSyncedAnimation is complete");
mSyncedAnimation->cleanupAfterExecution(true, false);
defender->removePed();
if (ENTITY::DOES_ENTITY_EXIST(mSharkPed))
{
PED::DELETE_PED(&mSharkPed);
}
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mSyncedAnimation->isActive() && ticksNow - mTicksStarted > 4000) {
Logger::logDebug("ChessBattleAttackOfTheClones creating shark");
Vector3 startLocation = ENTITY::GET_ENTITY_COORDS(defender->getPed(), true);
startLocation.z = startLocation.z+1.2f;
mSharkPed = PED::CREATE_PED(4, mAnimalHash, startLocation.x, startLocation.y, startLocation.z+20.0, 0.0f, false, true);
//never flee
PED::SET_PED_COMBAT_ATTRIBUTES(mSharkPed, 46, true);
//fight with melee weapons
PED::SET_PED_COMBAT_ATTRIBUTES(mSharkPed, 5, true);
ENTITY::SET_ENTITY_CAN_BE_DAMAGED(mSharkPed, false);
ENTITY::SET_ENTITY_INVINCIBLE(mSharkPed, true);
mSyncedAnimation->setPitch(270.0f);
mSyncedAnimation->setSpeed(250.0f);
//ENTITY::SET_ENTITY_ROTATION(mSharkPed, 90.0, 0.0, 0.0, 0, true);
std::vector<Ped> peds = { defender->getPed(), mSharkPed };
mSyncedAnimation->executeSyncedAnimation(true, peds, false, startLocation, false, true, false);
}
return false;
}
ChessBattleDeathByMusician::ChessBattleDeathByMusician(ChessMove chessMove, ChessBoard * chessBoard): ChessBattle(chessMove,chessBoard)
{
Logger::logDebug("ChessBattleDeathByMusician::constructor");
//14018 mp_suicide pill 6833
//14019 mp_suicide pistol 2433
mAnimationSuicide = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(14018);
}
void ChessBattleDeathByMusician::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
mTicksStarted = ticksStart;
AI::TASK_START_SCENARIO_IN_PLACE(attacker->getPed(), "WORLD_HUMAN_MUSICIAN", 0, 0);
mIsWaitingForSuicide = true;
}
bool ChessBattleDeathByMusician::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mIsWaitingForSuicide && ticksNow - mTicksStarted > 6600) {
Logger::logDebug("ChessBattleDeathByMusician animation complete");
defender->removePed();
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsWaitingForSuicide && ticksNow - mTicksStarted > 7000) {
Logger::logDebug("ChessBattleDeathByMusician creating shark");
GTAModUtils::playAnimation(defender->getPed(), mAnimationSuicide);
mIsWaitingForSuicide = false;
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleDeathByYoga::ChessBattleDeathByYoga(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
Logger::logDebug("ChessBattleDeathByYoga::constructor");
//03878 creatures@cow@getup getup_l 4266
//03879 creatures@cow@getup getup_r 4266
//04146 creatures@fish@move turn_l_medium 10666
//04147 creatures@fish@move turn_l_small 2400
//04148 creatures@fish@move turn_r_medium 12266
//04149 creatures@fish@move turn_r_small 2399
//04695 creatures@shark@move attack 7500
mAnimationDeath= chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(4148);
}
void ChessBattleDeathByYoga::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
mTicksStarted = ticksStart;
AI::TASK_START_SCENARIO_IN_PLACE(attacker->getPed(), "WORLD_HUMAN_YOGA", 0, 0);
mIsWaitingForYoga = true;
setMessage("Yoga face-off", 3000);
}
bool ChessBattleDeathByYoga::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mIsWaitingForDeath && !mIsWaitingForYoga && ticksNow - mTicksStarted > 8000) {
Logger::logDebug("ChessBattleDeathByYoga mActionGoToEndSquare");
defender->removePed();
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsWaitingForDeath && ticksNow - mTicksStarted > 10000) {
Logger::logDebug("ChessBattleDeathByYoga mIsWaitingForDeath");
//PedType probably needs to be animal
//AI::TASK_START_SCENARIO_IN_PLACE(defender->getPed(), "WORLD_HEN_FLEE", 0, 0);
GTAModUtils::playAnimation(defender->getPed(), mAnimationDeath);
mIsWaitingForDeath = false;
mTicksStarted = ticksNow;
}
else if (mIsWaitingForYoga && ticksNow - mTicksStarted > 1000) {
Logger::logDebug("ChessBattleDeathByYoga mIsWaitingForYoga");
AI::TASK_START_SCENARIO_IN_PLACE(defender->getPed(), "WORLD_HUMAN_YOGA", 0, 0);
mIsWaitingForYoga = false;
mIsWaitingForDeath = true;
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleScaredByFlex::ChessBattleScaredByFlex(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
Logger::logDebug("ChessBattleScaredByFlex::constructor");
}
void ChessBattleScaredByFlex::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
mTicksStarted = ticksStart;
AI::TASK_START_SCENARIO_IN_PLACE(attacker->getPed(), "WORLD_HUMAN_MUSCLE_FLEX", 0, 0);
mIsWaitingForFlee = true;
}
bool ChessBattleScaredByFlex::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mIsWaitingForFlee && ticksNow - mTicksStarted > 7000) {
Logger::logDebug("ChessBattleScaredByFlex complete");
defender->removePed();
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsWaitingForFlee && ticksNow - mTicksStarted > 7000) {
Logger::logDebug("ChessBattleScaredByFlex mIsWaitingForFlee");
mIsWaitingForFlee = false;
AI::TASK_REACT_AND_FLEE_PED(defender->getPed(), attacker->getPed());
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleMagicTouch::ChessBattleMagicTouch(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
Logger::logDebug("ChessBattleMagicTouch::constructor");
mAnimationMagicTouch = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(2925);
}
void ChessBattleMagicTouch::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
GTAModUtils::playAnimation(attacker->getPed(), mAnimationMagicTouch);
mTicksStarted = ticksStart;
mIsWaiting = true;
}
bool ChessBattleMagicTouch::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mIsWaiting && ticksNow - mTicksStarted > 3500) {
Logger::logDebug("ChessBattleMagicTouch mActionGoToEndSquare");
defender->removePed();
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsWaiting && ticksNow - mTicksStarted > 4000) {
Logger::logDebug("ChessBattleMagicTouch mIsWaiting");
mIsWaiting = false;
PED::SET_PED_TO_RAGDOLL(defender->getPed(), 10000, 10000, 1, true, true, false);
mTicksStarted = ticksNow;
}
return false;
}
ChessBattleMagicUndress::ChessBattleMagicUndress(ChessMove chessMove, ChessBoard * chessBoard) : ChessBattle(chessMove, chessBoard)
{
Logger::logDebug("ChessBattleMagicUndress::constructor");
mAnimationMagicTouch = chessBoard->getAnimationFactory()->getAnimationForShortcutIndex(2925);
}
void ChessBattleMagicUndress::startExecution(DWORD ticksStart, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
GTAModUtils::playAnimation(attacker->getPed(), mAnimationMagicTouch);
mTicksStarted = ticksStart;
mIsWaiting = true;
mIsChanging = false;
}
bool ChessBattleMagicUndress::isExecutionCompleted(DWORD ticksNow, ChessPiece * attacker, ChessPiece * defender, ChessMove chessMove, ChessBoard * chessBoard)
{
drawMessage(chessBoard);
if (mActionGoToEndSquare->hasBeenStarted()) {
return mActionGoToEndSquare->checkForCompletion(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (!mIsWaiting && !mIsChanging &&ticksNow - mTicksStarted > 8000) {
Logger::logDebug("ChessBattleMagicTouch mActionGoToEndSquare");
defender->removePed();
mActionGoToEndSquare->start(ticksNow, attacker, defender, chessMove, chessBoard);
}
else if (mIsChanging && ticksNow - mTicksStarted > mChangesDelta) {
Logger::logDebug("ChessBattleMagicTouch mIsChanging");
PED::SET_PED_RANDOM_COMPONENT_VARIATION(defender->getPed(), false);
PED::SET_PED_RANDOM_PROPS(defender->getPed());
mChanges++;
mChangesDelta = mChangesDelta - 200;
if (mChanges > 7) {
AI::TASK_REACT_AND_FLEE_PED(defender->getPed(), attacker->getPed());
mIsChanging = false;
}
if (mChanges == 4) {//play again
GTAModUtils::playAnimation(attacker->getPed(), mAnimationMagicTouch);
}
mTicksStarted = ticksNow;
}
else if (mIsWaiting && ticksNow - mTicksStarted > 300) {
Logger::logDebug("ChessBattleMagicTouch mIsWaiting");
mTicksStarted = ticksNow;
mIsWaiting = false;
mIsChanging = true;
mChanges = 0;
mChangesDelta = 1500;
}
return false;
}
| 39.71464 | 522 | 0.772274 | [
"vector"
] |
718807940335fd50274c6b09c07affc27909398b | 2,253 | cpp | C++ | RectObject.cpp | Excelsus4/Eat-emAll | 5f701e764e9d7a27542ae9c88b20f26497090232 | [
"MIT"
] | null | null | null | RectObject.cpp | Excelsus4/Eat-emAll | 5f701e764e9d7a27542ae9c88b20f26497090232 | [
"MIT"
] | null | null | null | RectObject.cpp | Excelsus4/Eat-emAll | 5f701e764e9d7a27542ae9c88b20f26497090232 | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
#include "RectObject.h"
#include "Random.h"
RectObject::RectObject(D3DXVECTOR3 p, float s, D3DXVECTOR3 c, Vertex* v) :
pos(p), size(s), color(c), vertices(v), alive(true)
{
}
RectObject::RectObject(Vertex* v):
vertices(v), alive(false){
}
RectObject::~RectObject()
{
}
bool RectObject::CollisionCheck(const RectObject & target) const
{
if (!target.alive)
return false;
if (pos.x + size > target.pos.x - size &&
pos.x - size < target.pos.x + size &&
pos.y + size > target.pos.y - size &&
pos.y - size < target.pos.y + size) {
return true;
}
return false;
}
void RectObject::Consume(const RectObject & food)
{
// TOTAL AREA BASED MIXTURE SYSTEM
float area = pow(food.size, 2);
D3DXVECTOR3 foodPaint = food.color * area;
float original = pow(size, 2);
D3DXVECTOR3 myPaint = color * original;
float newArea = area + original;
D3DXVECTOR3 totalPaint = foodPaint + myPaint;
size = sqrt(newArea);
color = totalPaint / newArea;
}
void RectObject::SetVertex()
{
vertices[0].Position = D3DXVECTOR3(pos.x - size, pos.y - size, 0.0f);
vertices[1].Position = D3DXVECTOR3(pos.x - size, pos.y + size, 0.0f);
vertices[2].Position = D3DXVECTOR3(pos.x + size, pos.y - size, 0.0f);
vertices[3].Position = D3DXVECTOR3(pos.x + size, pos.y - size, 0.0f);
vertices[4].Position = D3DXVECTOR3(pos.x - size, pos.y + size, 0.0f);
vertices[5].Position = D3DXVECTOR3(pos.x + size, pos.y + size, 0.0f);
vertices[0].Color = color;
vertices[1].Color = color;
vertices[2].Color = color;
vertices[3].Color = color;
vertices[4].Color = color;
vertices[5].Color = color;
}
void RectObject::Translate(const D3DXVECTOR3 vector)
{
pos += vector;
}
void RectObject::DisableVertex()
{
size = 0;
alive = false;
SetVertex();
}
void RectObject::Randomize()
{
uniform_real_distribution<float> colorDice(0, 1);
uniform_real_distribution<float> sizeDice(10.0f, 40.0f);
uniform_real_distribution<float> XposDice(0, Width);
uniform_real_distribution<float> YposDice(0, Height);
pos = D3DXVECTOR3(XposDice(*Random::gen), YposDice(*Random::gen), 0);
size = sizeDice(*Random::gen);
color = D3DXVECTOR3(colorDice(*Random::gen), colorDice(*Random::gen), colorDice(*Random::gen));
alive = true;
SetVertex();
}
| 24.758242 | 96 | 0.689303 | [
"vector"
] |
718fc81baae382e1f112fa1e32364dda21c9b3dc | 3,651 | cpp | C++ | cradle/src/alia/layout/system.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/src/alia/layout/system.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/src/alia/layout/system.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | 4 | 2018-09-28T17:12:54.000Z | 2022-03-20T14:22:29.000Z | #include <alia/layout/system.hpp>
#include <alia/layout/utilities.hpp>
namespace alia {
static void initialize_traversal(
layout_system& system, layout_traversal& traversal,
bool is_refresh, geometry_context* geometry, layout_style_info* style,
vector<2,float> const& ppi)
{
traversal.system = &system;
traversal.active_container = 0;
traversal.next_ptr = &system.root_node;
traversal.is_refresh_pass = is_refresh;
traversal.refresh_counter = system.refresh_counter;
traversal.geometry = geometry;
traversal.style_info = style;
traversal.ppi = ppi;
style->font_size = 0;
style->character_size = make_vector<float>(0, 0);
style->x_height = 0;
style->padding_size = make_layout_vector(0, 0);
style->magnification = 1;
}
void scoped_layout_traversal::begin(
layout_system& system, layout_traversal& traversal,
geometry_context& geometry, vector<2,float> const& ppi)
{
initialize_traversal(system, traversal, false, &geometry,
&dummy_style_info_, ppi);
}
void scoped_layout_refresh::begin(
layout_system& system, layout_traversal& traversal,
vector<2,float> const& ppi)
{
initialize_traversal(system, traversal, true, 0, &dummy_style_info_, ppi);
}
// scoped_layout_calculation_context sets up a calculation context for a
// layout system.
struct scoped_layout_calculation_context
{
scoped_layout_calculation_context() {}
scoped_layout_calculation_context(
data_graph& cache, layout_calculation_context& ctx)
{ begin(cache, ctx); }
~scoped_layout_calculation_context() { end(); }
void begin(data_graph& cache, layout_calculation_context& ctx);
void end();
private:
scoped_data_traversal data_;
};
void scoped_layout_calculation_context::begin(
data_graph& cache, layout_calculation_context& ctx)
{
data_.begin(cache, ctx.data);
ctx.map = retrieve_naming_map(ctx.data);
ctx.for_measurement = false;
}
void scoped_layout_calculation_context::end()
{
data_.end();
}
void resolve_layout(layout_node* root_node, data_graph& cache,
layout_vector const& size)
{
if (root_node)
{
layout_calculation_context ctx;
scoped_layout_calculation_context slcc(cache, ctx);
get_horizontal_requirements(ctx, *root_node);
layout_requirements y =
get_vertical_requirements(ctx, *root_node, size[0]);
set_relative_assignment(ctx, *root_node,
relative_layout_assignment(
layout_box(make_layout_vector(0, 0), size), y.ascent));
}
}
void resolve_layout(layout_system& system, layout_vector const& size)
{
resolve_layout(system.root_node, system.calculation_cache, size);
// Increment the refresh counter immediately after resolving layout so
// that any changes detected after this will be associated with the new
// counter value and thus cause a recalculation.
++system.refresh_counter;
}
layout_vector get_minimum_size(layout_node* root_node, data_graph& cache)
{
if (root_node)
{
layout_calculation_context ctx;
scoped_layout_calculation_context slcc(cache, ctx);
ctx.for_measurement = true;
layout_requirements horizontal =
get_horizontal_requirements(ctx, *root_node);
layout_requirements vertical =
get_vertical_requirements(ctx, *root_node, horizontal.size);
return make_layout_vector(horizontal.size, vertical.size);
}
else
return make_layout_vector(0, 0);
}
layout_vector get_minimum_size(layout_system& system)
{
return get_minimum_size(system.root_node, system.calculation_cache);
}
}
| 30.425 | 78 | 0.723637 | [
"geometry",
"vector"
] |
7191d43025b934175e5b3b3e96ff736351f86962 | 10,711 | cpp | C++ | src/fft_enhance.cpp | wuyongchn/FingerprintLivenessDetection | 06860deef9d0259c2feed2d84100c67b425a36ba | [
"MIT"
] | 1 | 2019-02-13T13:34:32.000Z | 2019-02-13T13:34:32.000Z | src/fft_enhance.cpp | wuyongchn/FingerprintLivenessDetection | 06860deef9d0259c2feed2d84100c67b425a36ba | [
"MIT"
] | null | null | null | src/fft_enhance.cpp | wuyongchn/FingerprintLivenessDetection | 06860deef9d0259c2feed2d84100c67b425a36ba | [
"MIT"
] | 1 | 2021-06-01T05:37:08.000Z | 2021-06-01T05:37:08.000Z | //
// Created by wuyong on 19-1-24.
//
#include "fft_enhance.hpp"
FFTEnhancer::FFTEnhancer(const std::string& pi_2_yml, const std::string& pi_4_yml) {
cv::FileStorage angf(pi_2_yml, cv::FileStorage::READ);
if (!angf.isOpened()) {
std::cout << "can not read" << pi_2_yml << std::endl;
}
angf["angf"] >> angf_pi_2_;
angf.release();
angf.open(pi_4_yml, cv::FileStorage::READ);
if (!angf.isOpened()) {
std::cout << "can not read" << pi_4_yml << std::endl;
}
angf["angf"] >> angf_pi_4_;
angf.release();
}
cv::Mat FFTEnhancer::EnhancedFpt(const cv::Mat &img_src) {
assert(img_src.channels() == 1);
cv::Mat img;
img_src.convertTo(img, CV_64F);
auto block_height = int(floor(img.rows - 2 * kOverlap_) / kBlockSize_);
auto block_width = int(floor(img.cols - 2 * kOverlap_) / kBlockSize_);
cv::Mat fft_src = cv::Mat::zeros(block_height*block_width, kFFTSize_*kFFTSize_, CV_64FC2);
int window_size = kBlockSize_ + 2 * kOverlap_;
// outputs
cv::Mat oimg = cv::Mat::zeros(block_height, block_width, CV_64F);
cv::Mat eimg = cv::Mat::zeros(block_height, block_width, CV_64F);
cv::Mat enhimg = cv::Mat::zeros(img_src.size(), CV_64F);
// precomputations
cv::Mat d_mult(window_size, window_size, CV_64F);
for (int i = 0; i < window_size; ++i)
for (int j = 0; j < window_size; ++j)
d_mult.at<double>(i, j) = pow(-1, (i+j));
cv::Mat r(kFFTSize_, kFFTSize_, CV_64F);
for (int i = 0; i < kFFTSize_; ++i)
for (int j = 0; j < kFFTSize_; ++j)
r.at<double>(i, j) = sqrt(pow(-kFFTSize_/2+i, 2) + pow(-kFFTSize_/2+j, 2)) + eps_;
cv::Mat th(kFFTSize_, kFFTSize_, CV_64F);
for (int i = 0; i < kFFTSize_; ++i)
for (int j = 0; j < kFFTSize_; ++j) {
double tmp = atan2(-kFFTSize_/2+i, -kFFTSize_/2+j); // atan2(y, x)
if (tmp < 0)
tmp += CV_PI;
th.at<double>(i, j) = tmp;
}
cv::Mat w = RaisedCosineWindow(kBlockSize_, kOverlap_);
// Bandpass Filter
double frq_low = kFFTSize_ / double(kRidgeMax_);
double frq_high = kFFTSize_ / double(kRidgeMin_);
cv::Mat dr_low(r.rows, r.cols, CV_64F), dr_high(r.rows, r.cols, CV_64F);
for (int i = 0; i < r.rows; ++i) {
for (int j = 0; j < r.cols; ++j) {
double r_value = r.at<double>(i, j);
dr_low.at<double>(i, j) = 1.0 / (1 + pow(r_value / frq_high, 4));
dr_high.at<double>(i, j) = 1.0 / (1 + pow(frq_low / r_value, 4));
}
}
cv::Mat db_pass = dr_low.mul(dr_high);
std::vector<cv::Mat> planes;
planes.clear();
planes.push_back(db_pass.clone()); planes.push_back(db_pass.clone());
cv::merge(planes, db_pass);
// FFT Analysis
for (int i = 0; i < block_height; ++i) {
int row = i * kBlockSize_ + kOverlap_ + 1;
for (int j = 0; j < block_width; ++j) {
int col = j * kBlockSize_ + kOverlap_ + 1;
// Extracting Local Block
cv::Mat block = img(cv::Rect(
col - kOverlap_ - 1, row - kOverlap_ - 1, window_size, window_size)).clone(); // Rect(x, y, w, h)
cv::Scalar mean = cv::mean(block);
block -= mean[0];
block = block.mul(w);
// Do Pre-filtering
cv::Mat block_fft = MatlabFFT2(block.mul(d_mult), cv::Size(kFFTSize_, kFFTSize_));
block_fft = block_fft.mul(db_pass);
planes.clear();
cv::split(block_fft, planes);
cv::Mat d_energy;
cv::magnitude(planes[0], planes[1], d_energy);
planes.clear();
planes.push_back(d_energy.clone()); planes.push_back(d_energy.clone());
cv::merge(planes, d_energy);
block_fft = block_fft.mul(d_energy);
for (int k = 0; k < kFFTSize_*kFFTSize_; ++k)
fft_src.at<cv::Vec2d>(block_width*i+j, k) = block_fft.at<cv::Vec2d>(k%kFFTSize_, k/kFFTSize_);
planes.clear();
cv::split(block_fft, planes);
cv::magnitude(planes[0], planes[1], d_energy);
d_energy = d_energy.mul(d_energy);
// Compute Statistics
mean = cv::mean(d_energy);
oimg.at<double>(i, j) = ComputeMeanAngle(d_energy, th);
eimg.at<double>(i, j) = log(mean[0] + eps_);
}
}
// PreComputations
cv::resize(d_mult, d_mult, cv::Size(kFFTSize_, kFFTSize_));
for (int i = -kFFTSize_/2; i < kFFTSize_/2; ++i)
for (int j = -kFFTSize_/2; j < kFFTSize_/2; ++j)
d_mult.at<double>(i+16, j+16) = pow(-1, i+j);
// Precoss the Result Maps
for (int i = 0; i < 3; ++i)
oimg = SmoothenOrientationImage(oimg);
cv::Mat cimg = ComputeCoherence(oimg);
cv::Mat bwimg = GetAngularBWImage(cimg);
// FFT reconstruction
for (int i = 0; i < block_height; ++i) {
for (int j = 0; j < block_width; ++j) {
int row = i * kBlockSize_ + kOverlap_;
int col = j * kBlockSize_ + kOverlap_;
cv::Mat blkfft(kFFTSize_, kFFTSize_, CV_64FC2);
for (int k = 0; k< kFFTSize_*kFFTSize_; ++k)
blkfft.at<cv::Vec2d>(k%32, k/32) = fft_src.at<cv::Vec2d>(i*block_width+j, k);
cv::Mat af = GetAngularFilter(oimg.at<double>(i, j), bwimg.at<double>(i, j));
planes.clear();
planes.push_back(af.clone()); planes.push_back(af.clone());
cv::merge(planes, af);
blkfft = blkfft.mul(af);
blkfft = MatlabIFFT2(blkfft);
planes.clear();
cv::split(blkfft, planes);
blkfft = planes[0].mul(d_mult);
blkfft(cv::Rect(kOverlap_, kOverlap_, kBlockSize_, kBlockSize_)).copyTo(
enhimg(cv::Rect(col, row, kBlockSize_, kBlockSize_)));
}
}
for (int i = 0; i < enhimg.rows; ++i) {
for (int j = 0; j < enhimg.cols; ++j) {
double value = enhimg.at<double>(i, j);
enhimg.at<double>(i, j) = value >= 0 ? sqrt(value) : -sqrt(-value);
}
}
cv::normalize(enhimg, enhimg, 0, 255, cv::NORM_MINMAX);
enhimg.convertTo(enhimg, CV_8U);
cv::resize(eimg, eimg, enhimg.size());
for (int i = 0; i < enhimg.rows; ++i)
for (int j = 0; j < enhimg.cols; ++j)
if (eimg.at<double>(i, j) < kEnergyThresh_)
enhimg.at<uchar>(i, j) = 128;
return enhimg;
}
cv::Mat FFTEnhancer::RaisedCosineWindow(const int block_size, const int overlap) {
int window_size = block_size + 2 * overlap;
std::vector<double> y(window_size, 0);
for (int i = 0; i < window_size; ++i) {
double x = abs(window_size / 2 - i);
if (x < double(block_size) / 2)
y[i] = 1;
else
y[i] = 0.5 * (cos(CV_PI * (x - double(block_size) / 2) / overlap) + 1);
}
cv::Mat vec(y);
cv::Mat w = vec * vec.t();
return w;
}
cv::Mat FFTEnhancer::MatlabFFT2(const cv::Mat &src, const cv::Size &size) {
int nrows = cv::getOptimalDFTSize(size.height);
int ncols = cv::getOptimalDFTSize(size.width);
cv::Mat padded = cv::Mat::zeros(nrows, ncols, src.type());
src.copyTo(padded(cv::Rect(0, 0, src.cols, src.rows)));
if (padded.channels() == 1) {
cv::Mat planes[] = {cv::Mat_<double>(padded), cv::Mat::zeros(padded.size(), CV_64F)};
cv::merge(planes, 2, padded);
}
cv::dft(padded, padded);
return padded;
}
cv::Mat FFTEnhancer::MatlabIFFT2(const cv::Mat& src) {
cv::Mat dst;
src.copyTo(dst);
cv::idft(dst, dst, cv::DFT_INVERSE+cv::DFT_SCALE);
return dst;
}
double FFTEnhancer::ComputeMeanAngle(const cv::Mat& energy, const cv::Mat& th) {
cv::Mat sth(th.size(), CV_64F), cth(th.size(), CV_64F);
for (int i = 0; i < th.rows; ++i) {
for (int j = 0; j < th.cols; ++j) {
double value = th.at<double>(i, j);
sth.at<double>(i, j) = sin(2*value);
cth.at<double>(i, j) = cos(2*value);
}
}
cv::Scalar num = cv::sum(energy.mul(sth));
cv::Scalar den = cv::sum(energy.mul(cth));
double mth = 0.5 * atan2(num[0], den[0]);
if (mth < 0)
mth += CV_PI;
return mth;
}
cv::Mat FFTEnhancer::GetGaussianKernel(const int kernel_size, const double sigma0) {
int halfSize = (kernel_size-1)/ 2;
cv::Mat kernel(kernel_size, kernel_size, CV_64F);
double s2 = 2.0 * sigma0 * sigma0;
for(int i = (-halfSize); i <= halfSize; i++) {
int m = i + halfSize;
for (int j = (-halfSize); j <= halfSize; j++) {
int n = j + halfSize;
double v = exp(-(1.0*i*i + 1.0*j*j) / s2);
kernel.at<double>(m, n) = v;
}
}
cv::Scalar all = cv::sum(kernel);
kernel.convertTo(kernel, CV_64F, (1/all[0]));
return kernel;
}
cv::Mat FFTEnhancer::SmoothenOrientationImage(const cv::Mat& oimg) {
cv::Mat gx(oimg.size(), CV_64F), gy(oimg.size(), CV_64F);
for (int i = 0; i < oimg.rows; ++i) {
for (int j = 0; j < oimg.cols; ++j) {
double value = oimg.at<double>(i, j);
gy.at<double>(i, j) = sin(2*value);
gx.at<double>(i, j) = cos(2*value);
}
}
cv::Mat kernel = GetGaussianKernel(5, 0.5);
cv::filter2D(gx, gx, gx.depth(), kernel, cv::Point(-1, -1), 0, cv::BORDER_REFLECT);
cv::filter2D(gy, gy, gy.depth(), kernel, cv::Point(-1, -1), 0, cv::BORDER_REFLECT);
cv::Mat noimg(oimg.size(), CV_64F);
for (int i = 0; i < oimg.rows; ++i) {
for (int j = 0; j < oimg.cols; ++j) {
double nth = atan2(gy.at<double>(i, j), gx.at<double>(i, j));
if (nth < 0)
nth += 2 * CV_PI;
noimg.at<double>(i, j) = 0.5 * nth;
}
}
return noimg;
}
cv::Mat FFTEnhancer::ComputeCoherence(const cv::Mat& oimg) {
cv::Mat cimg(oimg.size(), CV_64F);
cv::Mat padded = cv::Mat::zeros(oimg.rows+4, oimg.cols+4, CV_64F);
cv::copyMakeBorder(oimg, padded, 2, 2, 2, 2, cv::BORDER_REFLECT);
for (int i = 3; i < padded.rows-1; ++i){
for (int j = 3; j < padded.cols-1; ++j) {
double th = padded.at<double>(i-1, j-1);
cv::Mat block = padded(cv::Rect(j-3, i-3, 5, 5)).clone();
block = abs(block - th);
for (int k = 0; k < 25; ++k)
block.at<double>(k/5, k%5) = cv::fast_abs(cos(block.at<double>(k/5, k%5)));
cimg.at<double>(i-3, j-3) = cv::mean(block)[0];
}
}
return cimg;
}
cv::Mat FFTEnhancer::GetAngularBWImage(const cv::Mat& cimg) {
cv::Mat bwimg = cv::Mat::zeros(cimg.size(), CV_64F);
bwimg += cv::Scalar::all(CV_PI / 2);
for (int i = 0; i < bwimg.rows; ++i){
for (int j = 0; j < bwimg.cols; ++j) {
double value = cimg.at<double>(i, j);
if (value <= 0.7)
bwimg.at<double>(i, j) = CV_PI;
else if (value >= 0.9)
bwimg.at<double>(i, j) = CV_PI / 4;
}
}
return bwimg;
}
cv::Mat FFTEnhancer::GetAngularFilter(const double to, const double bw) {
int steps = angf_pi_2_.cols;
double delta = CV_PI / steps;
int i = int(floor((to + delta / 2) / delta)) % steps + 1;
cv::Mat r = cv::Mat::zeros(kFFTSize_, kFFTSize_, CV_64F);
if (bw == CV_PI / 4) {
for (int k = 0; k < angf_pi_4_.rows; ++k)
r.at<double>(k/kFFTSize_, k%kFFTSize_) = angf_pi_4_.at<double>(k, i-1);
} else if (bw == CV_PI / 2){
for (int k = 0; k < angf_pi_2_.rows; ++k)
r.at<double>(k/kFFTSize_, k%kFFTSize_) = angf_pi_2_.at<double>(k, i-1);
} else
r += cv::Scalar::all(1);
return r;
} | 36.681507 | 107 | 0.592008 | [
"vector"
] |
7196216b34143b7e4b2cc8d93d9da87148f8be09 | 3,469 | cc | C++ | python/embed/main1.cc | guoxiaoyong/simple-useful | 63f483250cc5e96ef112aac7499ab9e3a35572a8 | [
"CC0-1.0"
] | null | null | null | python/embed/main1.cc | guoxiaoyong/simple-useful | 63f483250cc5e96ef112aac7499ab9e3a35572a8 | [
"CC0-1.0"
] | null | null | null | python/embed/main1.cc | guoxiaoyong/simple-useful | 63f483250cc5e96ef112aac7499ab9e3a35572a8 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <boost/python.hpp>
enum Side {
BUY,
SELL,
};
struct Order {
std::string symbol;
Side side;
int size;
double price;
int order_id;
};
// forward declaration
class StrategyInstance;
class StrategyServer {
public:
void sendOrder(
StrategyInstance&,
const std::string& symbol,
Side, int size, double price);
private:
int _next_order_id = 0;
};
class StrategyInstance {
public:
StrategyInstance(StrategyServer&);
virtual ~StrategyInstance() = default;
virtual void eval() = 0;
virtual void onOrder(const Order&) = 0;
void sendOrder(
const std::string& symbol, Side, int size, double price);
private:
StrategyServer& _server;
};
///////////////////////////////////
// implementation
void StrategyServer::sendOrder(
StrategyInstance& instance,
const std::string& symbol, Side side, int size, double price) {
// simulate sending an order, receiving an acknowledgement
// and calling back to the strategy instance
std::cout << "sending order to market\n";
Order order { symbol, side, size, price, ++_next_order_id };
instance.onOrder(order);
}
///////////////////////////////////
StrategyInstance::StrategyInstance(StrategyServer& server)
: _server(server) {}
void StrategyInstance::sendOrder(
const std::string& symbol, Side side, int size, double price) {
_server.sendOrder(*this, symbol, side, size, price);
}
////////////////////////////////////
// export to python
namespace bp = boost::python;
class PyStrategyInstance final
: public StrategyInstance,
public bp::wrapper<StrategyInstance> {
using StrategyInstance::StrategyInstance;
void eval() override {
get_override("eval")();
}
void onOrder(const Order& order) override {
get_override("on_order")(order);
}
};
BOOST_PYTHON_MODULE(StrategyFramework) {
bp::enum_<Side>("Side")
.value("BUY", BUY)
.value("SELL", SELL)
;
bp::class_<Order>("Order")
.def_readonly("symbol", &Order::symbol)
.def_readonly("side", &Order::side)
.def_readwrite("size", &Order::size)
.def_readwrite("price", &Order::price)
.def_readonly("order_id", &Order::order_id)
;
bp::class_<StrategyServer>("StrategyServer")
;
bp::class_<PyStrategyInstance, boost::noncopyable>("StrategyInstance", bp::init<StrategyServer&>())
.def("send_order", &StrategyInstance::sendOrder)
;
}
bp::object import(
const std::string& module,
const std::string& path,
bp::object& globals) {
bp::dict locals;
locals["module_name"] = module;
locals["path"] = path;
bp::exec("import imp\n"
"new_module = imp.load_module(module_name, open(path), path, ('py', 'U', imp.PY_SOURCE))\n",
globals, locals);
return locals["new_module"];
}
//////////////////////////////////
int main() {
try {
Py_Initialize();
PyImport_AppendInittab("StrategyFramework", &initStrategyFramework);
StrategyServer server;
bp::object main = bp::import("__main__");
bp::object globals = main.attr("__dict__");
bp::object module = import("strategy", "strategy.py", globals);
bp::object Strategy = module.attr("Strategy");
bp::object strategy = Strategy(server);
strategy.attr("eval")();
return 0;
} catch(const bp::error_already_set&) {
std::cerr << ">>> Error! Uncaught exception:\n";
PyErr_Print();
return 1;
}
}
| 24.956835 | 103 | 0.629865 | [
"object"
] |
71b34feae745f19ada41e31864cf4a2ada8ae4a0 | 914 | cpp | C++ | list/appl_node_iterator.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | list/appl_node_iterator.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | list/appl_node_iterator.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | /* See LICENSE for license details */
/*
*/
#include <appl_status.h>
#include <appl_types.h>
#include <object/appl_object.h>
#include <list/appl_node.h>
#include <list/appl_node_iterator.h>
/* Assert compiler */
#include <misc/appl_assert_cplusplus.h>
//
//
//
appl_node_iterator::appl_node_iterator(
class appl_node * const
p_node) :
p_cur(
p_node),
p_end(
p_node)
{
}
//
//
//
appl_node_iterator::~appl_node_iterator()
{
}
//
//
//
bool
appl_node_iterator::next(void)
{
bool
b_result;
p_cur =
p_cur->p_next;
b_result =
(p_cur != p_end);
return
b_result;
} // next()
//
//
//
bool
appl_node_iterator::prev(void)
{
bool
b_result;
p_cur =
p_cur->p_prev;
b_result =
(p_cur != p_end);
return
b_result;
} // prev()
/* end-of-file: appl_node_iterator.cpp */
| 11.283951 | 41 | 0.573304 | [
"object"
] |
71baa838f6de1117f00bae8816664dc292a1525e | 1,738 | cpp | C++ | XJ Contests/2020/10.5/koizumi/test.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2020/10.5/koizumi/test.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2020/10.5/koizumi/test.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int N=82;
int n,a[5];
namespace solver1{
void main(){
if(a[2]==0&&n==2) n--;
if(n==1){
if(a[1]==1) puts("Lose");
else printf("1\n");
}
else{
if(a[2]==a[1]-1) puts("Lose");
else{
int x=a[1],y=a[2];
if(x==y) y--;
else x=y+1;
printf("%d %d\n",x,y);
}
}
}
}
struct PRIOR{
int x,y,z;
PRIOR(){}
PRIOR(int x,int y,int z):x(x),y(y),z(z){}
bool operator < (const PRIOR &rhs)const{
return z<rhs.z;
}
}pre[N][N][N];
vector<PRIOR> A;
namespace solver2{
int dp[N][N][N];
int dfs(int a1,int a2,int a3){
if(a1==1&&a2==0&&a3==0) return dp[1][0][0]=0;
if(dp[a1][a2][a3]!=-1) return dp[a1][a2][a3];
int flag=0;
for(int i=a1-1;i>=1;i--){
int x=i,y=min(i,a2),z=min(i,a3);
if(!dfs(x,y,z)) pre[a1][a2][a3]=PRIOR(x,y,z),flag=1;
}
for(int i=a2-1;i>=0;i--){
int x=a1,y=i,z=min(i,a3);
if(!dfs(x,y,z)) pre[a1][a2][a3]=PRIOR(x,y,z),flag=1;
}
for(int i=a3-1;i>=0;i--){
int x=a1,y=a2,z=i;
if(!dfs(x,y,z)) pre[a1][a2][a3]=PRIOR(x,y,z),flag=1;
}
if(!flag) A.push_back(PRIOR(a1,a2,a3));
return dp[a1][a2][a3]=flag;
}
void main(){
memset(dp,-1,sizeof(dp));
dfs(80,80,80);
sort(A.begin(),A.end());
for(int i=0;i<(int)A.size();i++) cout<<A[i].x<<" "<<A[i].y<<" "<<A[i].z<<endl;
}
}
void solve(){
solver2::main();
}
int main(){
int T=1; //scanf("%d",&T);
while(T--){
solve();
}
} | 23.808219 | 86 | 0.415995 | [
"vector"
] |
71bdc76c40ff20c95c3bc609aaf509f540568259 | 1,523 | cc | C++ | m68000/main.cc | galibert/retrofpga | 2a0c36bedc7284870b013a8680f1c7100b32c205 | [
"BSD-2-Clause"
] | 9 | 2020-04-10T14:10:46.000Z | 2021-02-24T06:39:55.000Z | m68000/main.cc | galibert/retrofpga | 2a0c36bedc7284870b013a8680f1c7100b32c205 | [
"BSD-2-Clause"
] | null | null | null | m68000/main.cc | galibert/retrofpga | 2a0c36bedc7284870b013a8680f1c7100b32c205 | [
"BSD-2-Clause"
] | 1 | 2022-01-04T18:10:13.000Z | 2022-01-04T18:10:13.000Z | #define CXXRTL_INCLUDE_VCD_CAPI_IMPL
#include "m68000.cc"
using namespace cxxrtl;
cxxrtl_design::p_m68000 m68000;
debug_items ditems;
const debug_item *clk, *pclk, *nclk;
const debug_item *o_e;
void stepp()
{
pclk->next[0] = 1;
clk->next[0] = 0;
m68000.step();
clk->next[0] = 1;
m68000.step();
pclk->next[0] = 0;
}
void stepn()
{
nclk->next[0] = 1;
clk->next[0] = 0;
m68000.step();
clk->next[0] = 1;
m68000.step();
nclk->next[0] = 0;
}
void reset()
{
auto &res = ditems["rst"];
res.next[0] = 1;
stepp();
stepn();
res.next[0] = 0;
}
int main(int argc, char **argv)
{
m68000.debug_info(ditems, "");
clk = &ditems["clk"];
pclk = &ditems["i_pclk"];
nclk = &ditems["i_nclk"];
o_e = &ditems["o_e"];
auto &state = ditems["eclock estate"];
auto &lfsr = ditems["eclock elfsr"];
auto &nlfsr = ditems["eclock enlfsr"];
auto &ereset = ditems["eclock ereset"];
auto &ma = ditems["i_ma"];
auto µ = ditems["o_micro"];
auto &nano = ditems["o_nano"];
auto &eu_w = ditems["i_eu_w"];
auto &eu_r = ditems["i_eu_r"];
reset();
for(int i=0; i != 0x400; i++) {
ma.next[0] = i;
// printf("%3d: %d (%x %x) -> %x reset=%x\n", i, o_e->curr[0], lfsr.curr[0], nlfsr.curr[0], state.curr[0], ereset.curr[0]);
eu_r.next[0] = 1;
stepp();
eu_r.next[0] = 0;
eu_w.next[0] = 1;
stepn();
eu_w.next[0] = 0;
printf("%03x %05x %x%08x%08x\n",
i,
micro.curr[0],
nano.curr[2],
nano.curr[1],
nano.curr[0]);
}
return 0;
}
| 18.573171 | 130 | 0.564675 | [
"3d"
] |
71c079359dfff436c5c54378f3ed583ea7f9865e | 3,768 | cpp | C++ | src/core/search/AutoSuggestion.cpp | demonatic/Skilo | adc73692dfa41c11b74ce02bfc657a5692156187 | [
"MIT"
] | 3 | 2020-05-10T16:52:35.000Z | 2021-03-12T08:06:06.000Z | src/core/search/AutoSuggestion.cpp | demonatic/Skilo | adc73692dfa41c11b74ce02bfc657a5692156187 | [
"MIT"
] | null | null | null | src/core/search/AutoSuggestion.cpp | demonatic/Skilo | adc73692dfa41c11b74ce02bfc657a5692156187 | [
"MIT"
] | null | null | null | #include "AutoSuggestion.h"
#include "utility/Exception.h"
namespace Skilo {
namespace Search{
AutoSuggestor::AutoSuggestor(const size_t suggestion_num,const size_t min_gram,const size_t max_gram,const size_t max_query_len):
_suggestion_num(suggestion_num),_max_query_len(max_query_len),_min_gram(min_gram),_max_gram(max_gram)
{
}
void AutoSuggestor::update(const std::string &content)
{
if(content.length()>_max_query_len){
return;
}
//increase query frequency
size_t query_freq=_query_freq_map[content];
_query_freq_map[content]=++query_freq;
std::vector<std::string_view> edge_ngrams=this->edge_ngram(content);
for(auto &&gram:edge_ngrams){
auto list_it=_suggest_map.find(gram);
if(list_it!=_suggest_map.end()){
SuggestionList &sug=list_it->second;
size_t sug_min_freq=sug.front().freq;
if(sug.size()>=_suggestion_num&&query_freq<sug_min_freq){
continue;
}
SuggestNode node{content,query_freq};
size_t node_index=lower_bound(sug.begin(),sug.end(),node)-sug.begin();
int pre_index=node_index-1;
while(pre_index>=0&&sug[pre_index].freq==query_freq-1){ //find if query entry already exist
if(sug[pre_index].query==content){
break;
}
--pre_index;
}
if(pre_index>=0&&sug[pre_index].query==content){ //query entry already in, increase its frequency by 1
sug[pre_index].freq++;
while(pre_index+1<sug.size()&&sug[pre_index].freq>sug[pre_index+1].freq){ //move it to right position
std::swap(sug[pre_index],sug[pre_index+1]);
pre_index++;
}
}
else if(sug.size()<_suggestion_num){ // add as a new suggestion node
sug.push_back({});
size_t i=sug.size()-1;
for(;i>node_index&&sug[i-1].freq>query_freq;i--){
sug[i]=sug[i-1];
}
sug[i]=node;
}
else{ //replace the first suggestion node and move it to right position
size_t index=0;
sug[index].freq=query_freq;
sug[index].query=content;
while(index+1<sug.size()&&sug[index+1].freq<=query_freq){
std::swap(sug[index],sug[index+1]);
index++;
}
}
}
else{ //make a new SuggestionList for this prefix
SuggestionList sug;
sug.push_back({content,query_freq});
_suggest_map.emplace(gram,std::move(sug));
}
}
}
void AutoSuggestor::de_update(const std::string &content)
{
}
std::vector<std::string_view> AutoSuggestor::auto_suggest(const std::string &query_prefix)
{
std::vector<std::string_view> suggestions;
auto it=_suggest_map.find(query_prefix);
if(it!=_suggest_map.end()){
SuggestionList &sug=it->second;
size_t len=sug.size();
suggestions.resize(len);
for(size_t i=0;i<sug.size();i++){
suggestions[i]=sug[len-i-1].query;
}
}
return suggestions;
}
std::vector<std::string_view> AutoSuggestor::edge_ngram(const std::string_view query)
{
std::vector<std::string_view> ngrams;
size_t index=0;
size_t i=0;
for(;i<_min_gram&&index<query.length();i++){
index+=Util::get_utf8_char_len(query[index]);
}
while(index<=query.length()&&i<_max_gram){
ngrams.push_back(query.substr(0,index));
index+=Util::get_utf8_char_len(query[index]);
i++;
}
return ngrams;
}
} //namespace Search
} //namespace Skilo
| 31.932203 | 129 | 0.586253 | [
"vector"
] |
71c2f9e1c5a5ac3816770de51ae1891c55a1e667 | 24,372 | cpp | C++ | tests/index/index_test.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 1 | 2021-02-28T19:37:04.000Z | 2021-02-28T19:37:04.000Z | tests/index/index_test.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 57 | 2016-03-19T22:27:55.000Z | 2017-07-08T00:41:51.000Z | tests/index/index_test.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 4 | 2016-07-17T20:44:56.000Z | 2018-06-27T01:01:36.000Z | //===----------------------------------------------------------------------===//
//
// Peloton
//
// index_test.cpp
//
// Identification: tests/index/index_test.cpp
//
// Copyright (c) 2015-16, CMU Database Group
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "harness.h"
#include "backend/common/logger.h"
#include "backend/common/platform.h"
#include "backend/index/index_factory.h"
#include "backend/storage/tuple.h"
//#define ALLOW_UNIQUE_KEY
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Index Tests
//===--------------------------------------------------------------------===//
class IndexTests : public PelotonTest {};
catalog::Schema *key_schema = nullptr;
catalog::Schema *tuple_schema = nullptr;
ItemPointer item0(120, 5);
ItemPointer item1(120, 7);
ItemPointer item2(123, 19);
index::Index *BuildIndex(const bool unique_keys) {
// Build tuple and key schema
std::vector<std::vector<std::string>> column_names;
std::vector<catalog::Column> columns;
std::vector<catalog::Schema *> schemas;
IndexType index_type = INDEX_TYPE_BTREE;
// FIXME: Try to use BWTREE
// index_type = INDEX_TYPE_BWTREE;
catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"A", true);
catalog::Column column2(VALUE_TYPE_VARCHAR, 1024, "B", true);
catalog::Column column3(VALUE_TYPE_DOUBLE, GetTypeSize(VALUE_TYPE_DOUBLE),
"C", true);
catalog::Column column4(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"D", true);
columns.push_back(column1);
columns.push_back(column2);
// INDEX KEY SCHEMA -- {column1, column2}
key_schema = new catalog::Schema(columns);
key_schema->SetIndexedColumns({0, 1});
columns.push_back(column3);
columns.push_back(column4);
// TABLE SCHEMA -- {column1, column2, column3, column4}
tuple_schema = new catalog::Schema(columns);
// Build index metadata
index::IndexMetadata *index_metadata = new index::IndexMetadata(
"test_index", 125, index_type, INDEX_CONSTRAINT_TYPE_DEFAULT,
tuple_schema, key_schema, unique_keys);
// Build index
index::Index *index = index::IndexFactory::GetInstance(index_metadata);
EXPECT_TRUE(index != NULL);
return index;
}
TEST_F(IndexTests, BasicTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
// INSERT
index->InsertEntry(key0.get(), item0);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 1);
EXPECT_EQ(locations[0].block, item0.block);
locations.clear();
// DELETE
index->DeleteEntry(key0.get(), item0);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
delete tuple_schema;
}
// INSERT HELPER FUNCTION
void InsertTest(index::Index *index, VarlenPool *pool, size_t scale_factor) {
// Loop based on scale factor
for (size_t scale_itr = 1; scale_itr <= scale_factor; scale_itr++) {
// Insert a bunch of keys based on scale itr
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key3(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key4(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> keynonce(
new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
key3->SetValue(0, ValueFactory::GetIntegerValue(400 * scale_itr), pool);
key3->SetValue(1, ValueFactory::GetStringValue("d"), pool);
key4->SetValue(0, ValueFactory::GetIntegerValue(500 * scale_itr), pool);
key4->SetValue(1, ValueFactory::GetStringValue(
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"),
pool);
keynonce->SetValue(0, ValueFactory::GetIntegerValue(1000 * scale_itr),
pool);
keynonce->SetValue(1, ValueFactory::GetStringValue("f"), pool);
// INSERT
index->InsertEntry(key0.get(), item0);
index->InsertEntry(key1.get(), item1);
index->InsertEntry(key1.get(), item2);
index->InsertEntry(key1.get(), item1);
index->InsertEntry(key1.get(), item1);
index->InsertEntry(key1.get(), item0);
index->InsertEntry(key2.get(), item1);
index->InsertEntry(key3.get(), item1);
index->InsertEntry(key4.get(), item1);
}
}
// DELETE HELPER FUNCTION
void DeleteTest(index::Index *index, VarlenPool *pool, size_t scale_factor) {
// Loop based on scale factor
for (size_t scale_itr = 1; scale_itr <= scale_factor; scale_itr++) {
// Delete a bunch of keys based on scale itr
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key3(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key4(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100 * scale_itr), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
key3->SetValue(0, ValueFactory::GetIntegerValue(400 * scale_itr), pool);
key3->SetValue(1, ValueFactory::GetStringValue("d"), pool);
key4->SetValue(0, ValueFactory::GetIntegerValue(500 * scale_itr), pool);
key4->SetValue(1, ValueFactory::GetStringValue(
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"),
pool);
// DELETE
index->DeleteEntry(key0.get(), item0);
index->DeleteEntry(key1.get(), item1);
index->DeleteEntry(key2.get(), item2);
index->DeleteEntry(key3.get(), item1);
index->DeleteEntry(key4.get(), item1);
}
}
TEST_F(IndexTests, MultiMapInsertTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Single threaded test
size_t scale_factor = 1;
LaunchParallelTest(1, InsertTest, index.get(), pool, scale_factor);
// Checks
index->ScanAllKeys(locations);
EXPECT_EQ(locations.size(), 9);
locations.clear();
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> keynonce(
new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
keynonce->SetValue(0, ValueFactory::GetIntegerValue(1000), pool);
keynonce->SetValue(1, ValueFactory::GetStringValue("f"), pool);
index->ScanKey(keynonce.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 1);
EXPECT_EQ(locations[0].block, item0.block);
locations.clear();
delete tuple_schema;
}
#ifdef ALLOW_UNIQUE_KEY
TEST_F(IndexTests, UniqueKeyDeleteTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(true));
// Single threaded test
size_t scale_factor = 1;
LaunchParallelTest(1, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(1, DeleteTest, index.get(), pool, scale_factor);
// Checks
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key1.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key2.get(), locations);
EXPECT_EQ(locations.size(), 1);
EXPECT_EQ(locations[0].block, item1.block);
locations.clear();
delete tuple_schema;
}
#endif
TEST_F(IndexTests, NonUniqueKeyDeleteTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Single threaded test
size_t scale_factor = 1;
LaunchParallelTest(1, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(1, DeleteTest, index.get(), pool, scale_factor);
// Checks
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key1.get(), locations);
EXPECT_EQ(locations.size(), 2);
locations.clear();
index->ScanKey(key2.get(), locations);
EXPECT_EQ(locations.size(), 1);
EXPECT_EQ(locations[0].block, item1.block);
locations.clear();
delete tuple_schema;
}
TEST_F(IndexTests, MultiThreadedInsertTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Parallel Test
size_t num_threads = 4;
size_t scale_factor = 1;
LaunchParallelTest(num_threads, InsertTest, index.get(), pool, scale_factor);
index->ScanAllKeys(locations);
EXPECT_EQ(locations.size(), 9 * num_threads);
locations.clear();
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> keynonce(
new storage::Tuple(key_schema, true));
keynonce->SetValue(0, ValueFactory::GetIntegerValue(1000), pool);
keynonce->SetValue(1, ValueFactory::GetStringValue("f"), pool);
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
index->ScanKey(keynonce.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), num_threads);
EXPECT_EQ(locations[0].block, item0.block);
locations.clear();
delete tuple_schema;
}
#ifdef ALLOW_UNIQUE_KEY
TEST_F(IndexTests, UniqueKeyMultiThreadedTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(true));
// Parallel Test
size_t num_threads = 4;
size_t scale_factor = 1;
LaunchParallelTest(num_threads, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(num_threads, DeleteTest, index.get(), pool, scale_factor);
// Checks
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key1.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key2.get(), locations);
EXPECT_EQ(locations.size(), 1);
EXPECT_EQ(locations[0].block, item1.block);
locations.clear();
index->ScanAllKeys(locations);
EXPECT_EQ(locations.size(), 1);
locations.clear();
// FORWARD SCAN
index->Scan({key1->GetValue(0)}, {0}, {EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_GREATERTHAN},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_GREATERTHAN, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
delete tuple_schema;
}
#endif
TEST_F(IndexTests, NonUniqueKeyMultiThreadedTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Parallel Test
size_t num_threads = 4;
size_t scale_factor = 1;
LaunchParallelTest(num_threads, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(num_threads, DeleteTest, index.get(), pool, scale_factor);
// Checks
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key1.get(), locations);
EXPECT_EQ(locations.size(), 2 * num_threads);
locations.clear();
index->ScanKey(key2.get(), locations);
EXPECT_EQ(locations.size(), 1 * num_threads);
EXPECT_EQ(locations[0].block, item1.block);
locations.clear();
index->ScanAllKeys(locations);
EXPECT_EQ(locations.size(), 3 * num_threads);
locations.clear();
// FORWARD SCAN
index->Scan({key1->GetValue(0)}, {0}, {EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 3 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 2 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_GREATERTHAN},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 1 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_GREATERTHAN, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_FORWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
// REVERSE SCAN
index->Scan({key1->GetValue(0)}, {0}, {EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_BACKWARD, locations);
EXPECT_EQ(locations.size(), 3 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_BACKWARD, locations);
EXPECT_EQ(locations.size(), 2 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_EQUAL, EXPRESSION_TYPE_COMPARE_GREATERTHAN},
SCAN_DIRECTION_TYPE_BACKWARD, locations);
EXPECT_EQ(locations.size(), 1 * num_threads);
locations.clear();
index->Scan(
{key1->GetValue(0), key1->GetValue(1)}, {0, 1},
{EXPRESSION_TYPE_COMPARE_GREATERTHAN, EXPRESSION_TYPE_COMPARE_EQUAL},
SCAN_DIRECTION_TYPE_BACKWARD, locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
delete tuple_schema;
}
TEST_F(IndexTests, NonUniqueKeyMultiThreadedStressTest) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Parallel Test
size_t num_threads = 4;
size_t scale_factor = 100;
LaunchParallelTest(num_threads, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(num_threads, DeleteTest, index.get(), pool, scale_factor);
// Checks
std::unique_ptr<storage::Tuple> key0(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key0->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key0->SetValue(1, ValueFactory::GetStringValue("a"), pool);
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key0.get(), locations);
EXPECT_EQ(locations.size(), 0);
locations.clear();
index->ScanKey(key1.get(), locations);
EXPECT_EQ(locations.size(), 2 * num_threads);
locations.clear();
index->ScanKey(key2.get(), locations);
EXPECT_EQ(locations.size(), 1 * num_threads);
EXPECT_EQ(locations[0].block, item1.block);
locations.clear();
index->ScanAllKeys(locations);
EXPECT_EQ(locations.size(), 3 * num_threads * scale_factor);
locations.clear();
delete tuple_schema;
}
TEST_F(IndexTests, NonUniqueKeyMultiThreadedStressTest2) {
auto pool = TestingHarness::GetInstance().GetTestingPool();
std::vector<ItemPointer> locations;
// INDEX
std::unique_ptr<index::Index> index(BuildIndex(false));
// Parallel Test
size_t num_threads = 15;
size_t scale_factor = 30;
LaunchParallelTest(num_threads, InsertTest, index.get(), pool, scale_factor);
LaunchParallelTest(num_threads, DeleteTest, index.get(), pool, scale_factor);
index->ScanAllKeys(locations);
if (index->HasUniqueKeys())
EXPECT_EQ(locations.size(), scale_factor);
else
EXPECT_EQ(locations.size(), 3 * num_threads * scale_factor);
locations.clear();
std::unique_ptr<storage::Tuple> key1(new storage::Tuple(key_schema, true));
std::unique_ptr<storage::Tuple> key2(new storage::Tuple(key_schema, true));
key1->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key1->SetValue(1, ValueFactory::GetStringValue("b"), pool);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), pool);
key2->SetValue(1, ValueFactory::GetStringValue("c"), pool);
index->ScanKey(key1.get(), locations);
if (index->HasUniqueKeys()) {
EXPECT_EQ(locations.size(), 0);
} else {
EXPECT_EQ(locations.size(), 2 * num_threads);
}
locations.clear();
index->ScanKey(key2.get(), locations);
if (index->HasUniqueKeys()) {
EXPECT_EQ(locations.size(), num_threads);
} else {
EXPECT_EQ(locations.size(), num_threads);
}
locations.clear();
delete tuple_schema;
}
} // End test namespace
} // End peloton namespace | 37.611111 | 80 | 0.688905 | [
"vector"
] |
71cf0b06f0388fc4aafb50968cf6849533410793 | 9,363 | hpp | C++ | 3rdparty/GPSTk/core/lib/GNSSCore/GCATTropModel.hpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/core/lib/GNSSCore/GCATTropModel.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/core/lib/GNSSCore/GCATTropModel.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#ifndef GCAT_TROP_MODEL_HPP
#define GCAT_TROP_MODEL_HPP
#include "TropModel.hpp"
namespace gpstk
{
/** Tropospheric model implemented in "GPS Code Analysis Tool" (GCAT)
* software.
*
* This model is described in the book "GPS Data processing: code and
* phase Algorithms, Techniques and Recipes" by Hernandez-Pajares, M.,
* J.M. Juan-Zornoza and Sanz-Subirana, J. See Chapter 5.
*
* This book and associated software are freely available at:
*
* http://gage152.upc.es/~manuel/tdgps/tdgps.html
*
* This is a simple but efective model composed of the wet and dry
* vertical tropospheric delays as defined in Gipsy/Oasis-II GPS
* analysis software, and the mapping function as defined by Black and
* Eisner (H. D. Black, A. Eisner. Correcting Satellite Doppler
* Data for Tropospheric Effects. Journal of Geophysical Research.
* Vol 89. 1984.) and used in MOPS (RTCA/DO-229C) standards.
*
* Usually, the caller will set the receiver height using
* setReceiverHeight() method, and then call the correction() method
* with the satellite elevation as parameter.
*
* @code
* GCATTropModel gcatTM();
* ...
* gcatTM.setReceiverHeight(150.0);
* trop = gcatTM.correction(elevation);
* @endcode
*
* Another posibility is to set the receiver height when calling
* the constructor.
*
* @code
* GCATTropModel gcatTM(150.0); // Receiver height is 150.0 meters
* ...
* trop = gcatTM.correction(elevation);
* @endcode
*/
class GCATTropModel : public TropModel
{
public:
/// Empty constructor
GCATTropModel(void)
{ valid = false; };
/// Constructor to create a GCAT trop model providing the height
/// of the receiver above mean sea level (as defined by ellipsoid
/// model).
///
/// @param ht Height of the receiver above mean sea level, in meters.
GCATTropModel(const double& ht);
/// Return the name of the model
virtual std::string name(void)
{ return std::string("GCAT"); }
/** Compute and return the full tropospheric delay. The receiver
* height must has been provided before, whether using the
* appropriate constructor or with the setReceiverHeight() method
*
* @param elevation Elevation of satellite as seen at receiver, in
* degrees
*/
virtual double correction(double elevation) const
throw(InvalidTropModel);
/** Compute and return the full tropospheric delay, given the
* positions of receiver and satellite. This version is most useful
* within positioning algorithms, where the receiver position may
* vary; it computes the elevation (and other receiver location
* information as height) and passes them to setReceiverHeight()
* method and correction(elevation) method.
*
* @param RX Receiver position
* @param SV Satellite position
*/
virtual double correction( const Position& RX,
const Position& SV )
throw(InvalidTropModel);
/** Compute and return the full tropospheric delay, given the
* positions of receiver and satellite and the time tag. This version
* is most useful within positioning algorithms, where the receiver
* position and timetag may vary; it computes the elevation (and
* other receiver location information as height) and passes them to
* setReceiverHeight() method and correction(elevation) method.
*
* @param RX Receiver position
* @param SV Satellite position
* @param tt Time. In this model, tt is a dummy parameter kept just
* for consistency
*/
virtual double correction( const Position& RX,
const Position& SV,
const CommonTime& tt )
throw(InvalidTropModel)
{ return correction(RX, SV); };
/** \deprecated
* Compute and return the full tropospheric delay, given the positions
* of receiver and satellite and the time tag. This version is most
* useful within positioning algorithms, where the receiver position
* and timetag may vary; it computes the elevation (and other receiver
* location information as height) and passes them to
* setReceiverHeight() method and correction(elevation) method.
*
* @param RX Receiver position in ECEF cartesian coordinates (meters)
* @param SV Satellite position in ECEF cartesian coordinates
* (meters)
* @param tt Time. In this model, tt is a dummy parameter kept just
* for consistency
*/
virtual double correction( const Xvt& RX,
const Xvt& SV,
const CommonTime& tt )
throw(InvalidTropModel);
/** Compute and return the zenith delay for dry component of the
* troposphere.
*/
virtual double dry_zenith_delay(void) const
throw(InvalidTropModel);
/** Compute and return the zenith delay for wet component of the
* troposphere.
*/
virtual double wet_zenith_delay(void) const
throw(InvalidTropModel)
{ return 0.1; };
/** Compute and return the mapping function for both components of
* the troposphere.
*
* @param elevation Elevation of satellite as seen at receiver, in
* degrees
*/
virtual double mapping_function(double elevation) const
throw(InvalidTropModel);
/** Compute and return the mapping function for dry component
* of the troposphere.
* @param elevation Elevation of satellite as seen at receiver, in
* degrees
*/
virtual double dry_mapping_function(double elevation) const
throw(InvalidTropModel)
{ return mapping_function(elevation); };
/** Compute and return the mapping function for wet component
* of the troposphere.
*
* @param elevation Elevation of satellite as seen at receiver, in
* degrees
*/
virtual double wet_mapping_function(double elevation) const
throw(InvalidTropModel)
{ return mapping_function(elevation); };
/** In GCAT tropospheric model, this is a dummy method kept here just
* for consistency.
*/
virtual void setWeather( const double& T,
const double& P,
const double& H )
throw(InvalidParameter) {};
/** In GCAT tropospheric model, this is a dummy method kept here just
* for consistency.
*/
virtual void setWeather(const WxObservation& wx)
throw(InvalidParameter) {};
/** Define the receiver height; this is required before calling
* correction() or any of the zenith_delay routines.
*
* @param ht Height of the receiver above mean sea level, in meters.
*/
virtual void setReceiverHeight(const double& ht);
private:
/// Receiver height
double gcatHeight;
};
}
#endif
| 37.906883 | 79 | 0.59105 | [
"model"
] |
71d33a00d60b12959b008fd1e8b6b08c0313d1ec | 20,049 | cpp | C++ | reformat/HiRes.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 84 | 2015-01-01T00:27:18.000Z | 2022-03-28T22:55:56.000Z | reformat/HiRes.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 49 | 2015-01-11T19:58:57.000Z | 2022-01-08T00:27:12.000Z | reformat/HiRes.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 19 | 2015-06-06T15:23:18.000Z | 2022-01-12T23:26:43.000Z | /*
* CiderPress
* Copyright (C) 2007 by faddenSoft, LLC. All Rights Reserved.
* See the file LICENSE for distribution terms.
*/
/*
* Reformat hi-res graphics into a bitmap.
*/
#include "StdAfx.h"
#include "HiRes.h"
/*
* Hi-Res image format:
*
* <16-bit load address> [DOS 3.3 only]
* <16-bit file length> [DOS 3.3 only]
* lines, in wonky format
*
* Each line is 40 bytes long. Each byte holds 7 bits that define a color
* value from 0 to 3, and the high byte determines which set of colors to
* use.
*
* The colors are:
* 0 black0 4 black1 00 00 / 80 80
* 1 green 5 orange 2a 55 / aa d5
* 2 purple 6 blue 55 2a / d5 aa
* 3 white0 7 white1 7f 7f / ff ff
*
* There is also a "half-shift" phenomenon for the second set, which appear
* to be shifted half a pixel to the right. The stair-step looks like this:
*
* white0
* purple
* white1
* blue
* green
* orange
*
* white1/blue/orange have a half-pixel shift, while green/orange have a
* full-pixel shift because the colors don't start until the appropriate
* bit (and stop on the appropriate bit). The area between two identical
* colors is filled. If you have a "1 0 0 1" bit situation, a black gap
* is formed, and a "0 1 1 0" situation creates a white area, but "0 1 0 1"
* forms a solid color starting and stopping on the 1/280th pixels where
* the 1s are.
*
* Some transition examples:
* purpleBBBorange
* purpleBBgreen
* blueBgreen
*
* orangeWWblue
* greenWWpurple
*
* The IIgs monochrome mode is not enabled on the RGB output unless you
* turn off AN3 by hitting $c05e (it can be re-enabled by hitting $c05f).
* This register turns off the half-pixel shift, so it doesn't appear to
* be possible to view hi-res output on an RGB monitor with the half-pixel
* shift intact. On the composite output, the removal of the half-pixel
* shift is quite visible.
*/
/*
* Regarding color...
* [ Found on http://www.geocities.com/jonrelay/software/a2info/munafo.htm ]
From: munafo@gcctech.com
Newsgroups: comp.emulators.apple2,comp.sys.apple2.programmer
Subject: RGB values for the standard Apple ][ colors
Date: Thu, 12 Oct 2000 03:13:33 GMT
Lines: 137
I am giving a table of all the lores and hires colors with their values in
RGB. First, though there is a bit to explain...
[...]
Here is the table. It was used by taking the chroma/luma values and
transforming to R-Y and B-Y, then transforming to YUV and finally to RGB.
The last step requires a gamma correction for display on an RGB monitor,
I used Y to the power of -0.4. For reference, the NTSC "color bars" test
pattern colors and the YIQ axis colors are also given.
--chroma--
Color name phase ampl luma -R- -G- -B-
black COLOR=0 0 0 0 0 0 0
gray COLOR=5 0 0 50 156 156 156
grey COLOR=10 0 0 50 156 156 156
white COLOR=15 0 0 100 255 255 255
dk blue COLOR=2 0 60 25 96 78 189
lt blue COLOR=7 0 60 75 208 195 255
purple COLOR=3 45 100 50 255 68 253
purple HCOLOR=2 45 100 50 255 68 253
red COLOR=1 90 60 25 227 30 96
pink COLOR=11 90 60 75 255 160 208
orange COLOR=9 135 100 50 255 106 60
orange HCOLOR=5 135 100 50 255 106 60
brown COLOR=8 180 60 25 96 114 3
yellow COLOR=13 180 60 75 208 221 141
lt green COLOR=12 225 100 50 20 245 60
green HCOLOR=1 225 100 50 20 245 60
dk green COLOR=4 270 60 25 0 163 96
aqua COLOR=14 270 60 75 114 255 208
med blue COLOR=6 315 100 50 20 207 253
blue HCOLOR=6 315 100 50 20 207 253
NTSC Hsync 0 0 -40 0 0 0
NTSC black 0 0 7.5 41 41 41
NTSC Gray75 0 0 77 212 212 212
YIQ +Q 33 100 50 255 81 255
NTSC magenta 61 82 36 255 40 181
NTSC red 104 88 28 255 28 76
YIQ +I 123 100 50 255 89 82
NTSC yellow 167 62 69 221 198 121
Color burst 180 40 0 0 4 0
YIQ -Q 213 100 50 51 232 41
NTSC green 241 82 48 12 234 97
NTSC cyan 284 88 56 10 245 198
YIQ -I 303 100 50 0 224 231
NTSC blue 347 62 15 38 65 155
---
I don't think these are 100% correct, e.g. he only found one value for both
grey colors, even though one is noticeably darker than the other on-screen.
The IIgs tech note #63 uses the following for border colors:
Color Color Register Master Color
Name Value Value
---------------------------------------
Black $0 $0000
Deep Red $1 $0D03
Dark Blue $2 $0009
Purple $3 $0D2D
Dark Green $4 $0072
Dark Gray $5 $0555
Medium Blue $6 $022F
Light Blue $7 $06AF
Brown $8 $0850
Orange $9 $0F60
Light Gray $A $0AAA
Pink $B $0F98
Light Green $C $01D0
Yellow $D $0FF0
Aquamarine $E $04F9
White $F $0FFF
---------------------------------------
KEGS uses this (rearranged slightly to match the order above):
const int g_dbhires_colors[] = {
\* rgb *\
0x000, \* 0x0 black *\
0xd03, \* 0x1 deep red *\
0x009, \* 0x8 dark blue *\
0xd0d, \* 0x9 purple *\
0x070, \* 0x4 dark green *\
0x555, \* 0x5 dark gray *\
0x22f, \* 0xc medium blue *\
0x6af, \* 0xd light blue *\
0x852, \* 0x2 brown *\
0xf60, \* 0x3 orange *\
0xaaa, \* 0xa light gray *\
0xf98, \* 0xb pink *\
0x0d0, \* 0x6 green *\
0xff0, \* 0x7 yellow *\
0x0f9, \* 0xe aquamarine *\
0xfff \* 0xf white *\
};
The Apple values seem to be good.
*/
/*
* Decide whether or not we want to handle this file.
*
* FOT with auxtype $4000 is a compressed hi-res image. FOT with auxtype
* $4001 is a compressed DHR image. In practice, nobody uses these, so
* any FOT file with a correct-looking length is treated as hi-res.
*/
void ReformatHiRes::Examine(ReformatHolder* pHolder)
{
ReformatHolder::ReformatApplies applies = ReformatHolder::kApplicNot;
long fileLen = pHolder->GetSourceLen(ReformatHolder::kPartData);
long fileType = pHolder->GetFileType();
long auxType = pHolder->GetAuxType();
bool dosStructure =
(pHolder->GetSourceFormat() == ReformatHolder::kSourceFormatDOS);
bool relaxed;
relaxed = pHolder->GetOption(ReformatHolder::kOptRelaxGfxTypeCheck) != 0;
if (dosStructure) {
if (fileType == kTypeBIN &&
(fileLen >= kExpectedSize-8 && fileLen <= kExpectedSize+1) /*&&
(auxType == 0x2000 || auxType == 0x4000)*/)
{
applies = ReformatHolder::kApplicProbably;
}
} else {
if (fileType == kTypeFOT) {
if (auxType == 0x8066) {
// fhpack LZ4FH-compressed file
applies = ReformatHolder::kApplicYes;
} else if (fileLen >= kExpectedSize-8 &&
fileLen <= kExpectedSize + 1) {
// uncompressed FOT file... probably
applies = ReformatHolder::kApplicProbably;
}
} else if (relaxed && fileType == kTypeBIN &&
(fileLen >= kExpectedSize-8 && fileLen <= kExpectedSize+1))
{
applies = ReformatHolder::kApplicProbably;
}
}
pHolder->SetApplic(ReformatHolder::kReformatHiRes, applies,
ReformatHolder::kApplicNot, ReformatHolder::kApplicNot);
pHolder->SetApplic(ReformatHolder::kReformatHiRes_BW, applies,
ReformatHolder::kApplicNot, ReformatHolder::kApplicNot);
/*
* Set the "preferred" flag on one option.
*/
if (pHolder->GetOption(ReformatHolder::kOptHiResBW) == 0)
pHolder->SetApplicPreferred(ReformatHolder::kReformatHiRes);
else
pHolder->SetApplicPreferred(ReformatHolder::kReformatHiRes_BW);
}
/*
* Convert a Hi-Res image to a bitmap.
*/
int ReformatHiRes::Process(const ReformatHolder* pHolder,
ReformatHolder::ReformatID id, ReformatHolder::ReformatPart part,
ReformatOutput* pOutput)
{
MyDIBitmap* pDib;
const uint8_t* srcBuf = pHolder->GetSourceBuf(part);
long srcLen = pHolder->GetSourceLen(part);
int retval = -1;
if (id == ReformatHolder::kReformatHiRes_BW) {
fBlackWhite = true;
}
uint8_t expandBuf[kExpectedSize];
if (pHolder->GetFileType() == kTypeFOT &&
pHolder->GetAuxType() == 0x8066)
{
srcLen = ExpandLZ4FH(expandBuf, srcBuf, srcLen);
if (srcLen == 0) {
goto bail; // fail
}
srcBuf = expandBuf;
}
if (srcLen > kExpectedSize+1 || srcLen < kExpectedSize-8) {
LOGI(" HiRes file is not ~%d bytes long (got %d)",
kExpectedSize, srcLen);
goto bail;
}
InitLineOffset(fLineOffset);
pDib = HiResScreenToBitmap(srcBuf);
if (pDib == NULL)
goto bail;
SetResultBuffer(pOutput, pDib);
retval = 0;
bail:
return retval;
}
/*
* Set up the line offset table.
*
* Table must be able to hold kNumLines values.
*/
/*static*/ void ReformatHiRes::InitLineOffset(int* pOffsetBuf)
{
long offset;
int line;
ASSERT(pOffsetBuf != NULL);
for (line = 0; line < kNumLines; line++) {
offset = (line & 0x07) << 10 | (line & 0x38) << 4 |
(line & 0xc0) >> 1 | (line & 0xc0) >> 3;
ASSERT(offset >= 0 && offset < (8192 - 40));
pOffsetBuf[line] = offset;
}
}
/*
* (Lifted directly from fhpack.)
*
* Uncompress LZ4FH data from "srcBuf" to "dstBuf". "dstBuf" must hold
* kExpectedSize bytes.
*
* Returns the uncompressed length on success, 0 on failure.
*/
/*static*/ long ReformatHiRes::ExpandLZ4FH(uint8_t* outBuf,
const uint8_t* inBuf, long inLen)
{
// constants
static const uint8_t LZ4FH_MAGIC = 0x66;
static const int MIN_MATCH_LEN = 4;
static const int INITIAL_LEN = 15;
static const int EMPTY_MATCH_TOKEN = 253;
static const int EOD_MATCH_TOKEN = 254;
static const int MAX_SIZE = kExpectedSize;
uint8_t* outPtr = outBuf;
const uint8_t* inPtr = inBuf;
LOGD("Expanding LZ4FH");
if (*inPtr++ != LZ4FH_MAGIC) {
LOGE("Missing LZ4FH magic");
return 0;
}
while (true) {
uint8_t mixedLen = *inPtr++;
int literalLen = mixedLen >> 4;
if (literalLen != 0) {
if (literalLen == INITIAL_LEN) {
literalLen += *inPtr++;
}
if ((outPtr - outBuf) + literalLen > MAX_SIZE ||
(inPtr - inBuf) + literalLen > inLen) {
LOGE("Buffer overrun");
return 0;
}
memcpy(outPtr, inPtr, literalLen);
outPtr += literalLen;
inPtr += literalLen;
}
int matchLen = mixedLen & 0x0f;
if (matchLen == INITIAL_LEN) {
uint8_t addon = *inPtr++;
if (addon == EMPTY_MATCH_TOKEN) {
matchLen = - MIN_MATCH_LEN;
} else if (addon == EOD_MATCH_TOKEN) {
break; // out of while
} else {
matchLen += addon;
}
}
matchLen += MIN_MATCH_LEN;
if (matchLen != 0) {
int matchOffset = *inPtr++;
matchOffset |= (*inPtr++) << 8;
// Can't use memcpy() here, because we need to guarantee
// that the match is overlapping.
uint8_t* srcPtr = outBuf + matchOffset;
if ((outPtr - outBuf) + matchLen > MAX_SIZE ||
(srcPtr - outBuf) + matchLen > MAX_SIZE) {
LOGE("Buffer overrun");
return 0;
}
while (matchLen-- != 0) {
*outPtr++ = *srcPtr++;
}
}
}
if (inPtr - inBuf != (long) inLen) {
LOGW("Warning: LZ4FH uncompress used only %ld of %zd bytes",
inPtr - inBuf, inLen);
}
return outPtr - outBuf;
}
/*
* Convert an 8KB buffer of hi-res data to a 16-color 560x384 DIB.
*/
MyDIBitmap* ReformatHiRes::HiResScreenToBitmap(const uint8_t* buf)
{
MyDIBitmap* pDib = new MyDIBitmap;
uint8_t* outBuf;
const int kLeadIn = 4;
unsigned int colorBuf[kLeadIn+kOutputWidth +1]; // 560 half-pixels
int pixelBits[kPixelsPerLine];
int shiftBits[kPixelsPerLine];
int line;
/* color map */
enum {
kColorBlack0 = 0,
kColorGreen,
kColorPurple,
kColorWhite0,
kColorBlack1,
kColorOrange,
kColorBlue,
kColorWhite1,
kColorNone, // really only useful for debugging
kNumColors
};
RGBQUAD colorConv[kNumColors];
colorConv[0] = fPalette[kPaletteBlack];
colorConv[1] = fPalette[kPaletteGreen];
colorConv[2] = fPalette[kPalettePurple];
colorConv[3] = fPalette[kPaletteWhite];
colorConv[4] = fPalette[kPaletteBlack];
colorConv[5] = fPalette[kPaletteOrange];
colorConv[6] = fPalette[kPaletteMediumBlue];
colorConv[7] = fPalette[kPaletteWhite];
colorConv[8] = fPalette[kPaletteBlack]; // for "blank spaces"
ASSERT(kOutputWidth == 2*kPixelsPerLine);
if (pDib == NULL)
goto bail;
outBuf = (uint8_t*) pDib->Create(kOutputWidth, kOutputHeight,
4, kNumColors);
if (outBuf == NULL) {
delete pDib;
pDib = NULL;
goto bail;
}
pDib->SetColorTable(colorConv);
/*
* Run through the lines.
*/
for (line = 0; line < kNumLines; line++) {
const uint8_t* lineData = buf + fLineOffset[line];
int* bitPtr = pixelBits;
int* shiftPtr = shiftBits;
/* unravel the bits */
for (int byt = 0; byt < kPixelsPerLine / 7; byt++) {
uint8_t val = *lineData;
int shifted = (val & 0x80) != 0;
for (int bit = 0; bit < 7; bit++) {
*bitPtr++ = val & 0x01;
*shiftPtr++ = shifted;
val >>= 1;
}
lineData++;
}
ASSERT(lineData <= buf + kExpectedSize);
ASSERT((char*)bitPtr == (char*)pixelBits + sizeof(pixelBits));
ASSERT((char*)shiftPtr == (char*)shiftBits + sizeof(shiftBits));
/*
* Convert the bits to colors, taking half-pixel shifts into account.
*/
int idx;
for (idx = 0; idx < NELEM(colorBuf); idx++)
colorBuf[idx] = kColorNone;
if (fBlackWhite) {
for (idx = 0; idx < kPixelsPerLine; idx ++) {
int bufShift = (int) shiftBits[idx];
// simulate GS RGB by setting bufShift=0
ASSERT(bufShift == 0 || bufShift == 1);
int bufTarget = kLeadIn + idx * 2 + bufShift;
if (!pixelBits[idx]) {
colorBuf[bufTarget] = kColorBlack0;
colorBuf[bufTarget+1] = kColorBlack0;
} else {
colorBuf[bufTarget] = kColorWhite0;
colorBuf[bufTarget+1] = kColorWhite0;
}
}
} else {
for (idx = 0; idx < kPixelsPerLine; idx ++) {
int bufShift = (int) shiftBits[idx];
ASSERT(bufShift == 0 || bufShift == 1);
int colorShift = 4 * bufShift;
int bufTarget = kLeadIn + idx * 2 + bufShift;
if (!pixelBits[idx]) {
colorBuf[bufTarget] = kColorBlack0 + colorShift;
colorBuf[bufTarget+1] = kColorBlack0 + colorShift;
} else {
if (colorBuf[bufTarget-2] != kColorBlack0 &&
colorBuf[bufTarget-2] != kColorBlack1 &&
colorBuf[bufTarget-2] != kColorNone)
{
/* previous bit was set, this is white */
colorBuf[bufTarget] = kColorWhite0 + colorShift;
colorBuf[bufTarget+1] = kColorWhite0 + colorShift;
/* make sure the previous bit is in with us */
colorBuf[bufTarget-2] = kColorWhite0 + colorShift;
colorBuf[bufTarget-1] = kColorWhite0 + colorShift;
} else {
/* previous bit was zero, this is color */
if (idx & 0x01) {
colorBuf[bufTarget] = kColorGreen + colorShift;
colorBuf[bufTarget+1] = kColorGreen + colorShift;
} else {
colorBuf[bufTarget] = kColorPurple + colorShift;
colorBuf[bufTarget+1] = kColorPurple + colorShift;
}
/*
* Do we have a run of the same color? If so, smooth
* the color out. Note that white blends smoothly
* with everything.
*/
if (colorBuf[bufTarget-4] == colorBuf[bufTarget] ||
colorBuf[bufTarget-4] == kColorWhite0 ||
colorBuf[bufTarget-4] == kColorWhite1)
{
/* back-fill previous gap with color */
ASSERT(colorBuf[bufTarget-2] == kColorBlack0 ||
colorBuf[bufTarget-2] == kColorBlack1);
colorBuf[bufTarget-2] = colorBuf[bufTarget];
colorBuf[bufTarget-1] = colorBuf[bufTarget];
}
}
}
} /*for boolean pixels*/
} /*!black&white*/
/* convert colors to 4-bit bitmap pixels */
/* (NOTE: should advance by GetPitch(), not assume it's equal to width) */
#define SetPix(x, y, twoval) \
outBuf[((kOutputHeight-1) - (y)) * (kOutputWidth/2) + (x)] = twoval
uint8_t pix4;
for (int pix = 0; pix < kPixelsPerLine; pix++) {
int bufPosn = kLeadIn + pix * 2;
ASSERT(colorBuf[bufPosn] < kNumColors);
ASSERT(colorBuf[bufPosn+1] < kNumColors);
pix4 = colorBuf[bufPosn] << 4 | colorBuf[bufPosn+1];
SetPix(pix, line*2, pix4);
SetPix(pix, line*2+1, pix4);
//SetPix(pix*2, line*2, colorBuf[bufPosn]);
//SetPix(pix*2, line*2+1, colorBuf[bufPosn]);
//SetPix(pix*2+1, line*2, colorBuf[bufPosn+1]);
//SetPix(pix*2+1, line*2+1, colorBuf[bufPosn+1]);
}
} /*for each line*/
#undef SetPix
bail:
return pDib;
}
| 36.189531 | 83 | 0.518779 | [
"solid"
] |
71da9512b6b445292363e26b96200a0c80a1047d | 334 | cpp | C++ | 781.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 781.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 781.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
int numRabbits(vector<int>& answers) {
unordered_map<int,int> count;
for(int i = 0; i < answers.size(); i++) count[answers[i]]++;
int ans = 0;
for(auto e:count){
ans += (e.second + e.first) / (e.first + 1) * (e.first + 1);
}
return ans;
}
}; | 27.833333 | 72 | 0.494012 | [
"vector"
] |
71e117d8c9b9fe2df726d3149886a4929afd3589 | 5,002 | cpp | C++ | released_plugins/v3d_plugins/sync_swc_terafly/sync_swc_terafly_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/sync_swc_terafly/sync_swc_terafly_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | released_plugins/v3d_plugins/sync_swc_terafly/sync_swc_terafly_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /* sync_swc_terafly_plugin.cpp
* This is a test plugin, you can use it as a demo.
* 2017-8-29 : by Zhi Zhou
*/
#include "v3d_message.h"
#include <vector>
#include "sync_swc_terafly_plugin.h"
using namespace std;
Q_EXPORT_PLUGIN2(sync_swc_terafly, sync_swc_terafly);
static lookPanel *panel = 0;
QStringList sync_swc_terafly::menulist() const
{
return QStringList()
<<tr("sync")
<<tr("about");
}
QStringList sync_swc_terafly::funclist() const
{
return QStringList()
<<tr("help");
}
void sync_swc_terafly::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
if (menu_name == tr("sync"))
{
if (panel)
{
panel->show();
return;
}
else
{
panel = new lookPanel(callback, parent);
if (panel)
{
panel->show();
panel->raise();
panel->move(100,100);
panel->activateWindow();
}
}
}
else
{
v3d_msg(tr("This is a test plugin, you can use it as a demo.. "
"Developed by Zhi Zhou, 2017-8-29"));
}
}
lookPanel::lookPanel(V3DPluginCallback2 &_v3d, QWidget *parent) :
QDialog(parent), m_v3d(_v3d)
{
gridLayout = new QGridLayout();
QPushButton* sync = new QPushButton("Sync (one shot)");
QPushButton* set_markers = new QPushButton("Set Annotations");
gridLayout->addWidget(sync, 0,0);
gridLayout->addWidget(set_markers, 1,0);
setLayout(gridLayout);
setWindowTitle(QString("Synchronize annotation "));
connect(sync, SIGNAL(clicked()), this, SLOT(_slot_sync_onetime()));
connect(set_markers, SIGNAL(clicked()), this, SLOT(_slot_set_markers()));
}
lookPanel::~lookPanel()
{
}
void lookPanel::_slot_sync_onetime()
{
NeuronTree nt = m_v3d.getSWCTeraFly();
NeuronTree resultTree;
QList <NeuronSWC> listNeuron;
QHash <int, int> hashNeuron;
listNeuron.clear();
hashNeuron.clear();
for(int j = 0; j < nt.listNeuron.size(); j++)
{
listNeuron.append(nt.listNeuron.at(j));
hashNeuron.insert(nt.listNeuron.at(j).n, listNeuron.size()-1);
}
resultTree.listNeuron = listNeuron;
resultTree.hashNeuron = hashNeuron;
resultTree.color.r = 0;
resultTree.color.g = 0;
resultTree.color.b = 0;
resultTree.color.a = 0;
QList <V3dR_MainWindow *> list_3dviewer = m_v3d.getListAll3DViewers();
int current_index = -1;
for(int i=0; i<list_3dviewer.size();i++)
{
if(m_v3d.getImageName(list_3dviewer[i]) == "3D View [Annotations in TeraFly]")
{
current_index = i;
}
}
LandmarkList terafly_landmarks = m_v3d.getLandmarkTeraFly();
if(current_index == -1)
{
V3dR_MainWindow * new3DWindow = NULL;
new3DWindow = m_v3d.createEmpty3DViewer();
QList<NeuronTree> * treeList = m_v3d.getHandleNeuronTrees_Any3DViewer (new3DWindow);
treeList->push_back(resultTree);
m_v3d.setWindowDataTitle(new3DWindow, "Annotations in TeraFly");
m_v3d.setHandleLandmarkList_Any3DViewer(new3DWindow,terafly_landmarks);
m_v3d.update_NeuronBoundingBox(new3DWindow);
}else
{
V3dR_MainWindow *surface_win = m_v3d.getListAll3DViewers()[current_index];
QList<NeuronTree> * treeList = m_v3d.getHandleNeuronTrees_Any3DViewer (surface_win);
treeList->clear();
treeList->push_back(resultTree);
m_v3d.setHandleLandmarkList_Any3DViewer(surface_win,terafly_landmarks);
m_v3d.update_NeuronBoundingBox(surface_win);
}
}
void lookPanel::_slot_set_markers()
{
QList <V3dR_MainWindow *> list_3dviewer = m_v3d.getListAll3DViewers();
int current_index = -1;
for(int i=0; i<list_3dviewer.size();i++)
{
if(m_v3d.getImageName(list_3dviewer[i]) == "3D View [Annotations in TeraFly]")
{
current_index = i;
}
}
if(current_index != -1)
{
V3dR_MainWindow *surface_win = m_v3d.getListAll3DViewers()[current_index];
LandmarkList* updated_landmarks = m_v3d.getHandleLandmarkList_Any3DViewer(surface_win);
QList<NeuronTree> * updated_treeList = m_v3d.getHandleNeuronTrees_Any3DViewer(surface_win);
m_v3d.setLandmarkTeraFly(*updated_landmarks);
if(updated_treeList->size()>0){
NeuronTree updated_nt = updated_treeList->at(0);
m_v3d.setSWCTeraFly(updated_nt);
}
}
}
bool sync_swc_terafly::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent)
{
vector<char*> infiles, inparas, outfiles;
if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p);
if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p);
if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p);
if (func_name == tr("help"))
{
v3d_msg("To be implemented.");
}
else return false;
return true;
}
| 28.747126 | 165 | 0.647141 | [
"vector",
"3d"
] |
71e5aee1b15d1e3c100df77c2c33fda33b4bde14 | 2,541 | cxx | C++ | src/sdp_solve/SDP_Solver/run/compute_bilinear_pairings/compute_A_X_inv.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 45 | 2015-02-10T15:45:22.000Z | 2022-02-24T07:45:01.000Z | src/sdp_solve/SDP_Solver/run/compute_bilinear_pairings/compute_A_X_inv.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 58 | 2015-02-27T10:03:18.000Z | 2021-08-10T04:21:42.000Z | src/sdp_solve/SDP_Solver/run/compute_bilinear_pairings/compute_A_X_inv.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 38 | 2015-02-10T11:11:27.000Z | 2022-02-11T20:59:42.000Z | #include "../../../Block_Diagonal_Matrix.hxx"
#include "../../../Block_Info.hxx"
// A_X_inv = bilinear_base^T X^{-1} bilinear_base for each block
void compute_A_X_inv(
const Block_Info &block_info, const Block_Diagonal_Matrix &X_cholesky,
const std::vector<El::DistMatrix<El::BigFloat>> &bases_blocks,
std::array<std::vector<std::vector<std::vector<El::DistMatrix<El::BigFloat>>>>,
2> &A_X_inv)
{
A_X_inv[0].resize(bases_blocks.size());
A_X_inv[1].resize(bases_blocks.size());
for(size_t index(0); index < bases_blocks.size(); ++index)
{
auto &block(bases_blocks[index]);
auto &X_cholesky_block(X_cholesky.blocks[index]);
El::DistMatrix<El::BigFloat> temp_space(block),
A_X_inv_matrix(block.Width(), block.Width(), block.Grid());
El::Trsm(El::LeftOrRight::LEFT, El::UpperOrLowerNS::LOWER,
El::Orientation::NORMAL, El::UnitOrNonUnit::NON_UNIT,
El::BigFloat(1), X_cholesky_block, temp_space);
// We have to set this to zero because the values can be NaN.
// Multiplying 0*NaN = NaN.
El::Zero(A_X_inv_matrix);
El::Syrk(El::UpperOrLowerNS::LOWER, El::Orientation::TRANSPOSE,
El::BigFloat(1), temp_space, El::BigFloat(0), A_X_inv_matrix);
El::MakeSymmetric(El::UpperOrLower::LOWER, A_X_inv_matrix);
const size_t block_size(
block_info.num_points.at(block_info.block_indices.at(index / 2))),
dim(block_info.dimensions.at(block_info.block_indices.at(index / 2)));
const size_t parity(index % 2), Q_index(index / 2);
auto &A_X_inv_block(A_X_inv[parity][Q_index]);
A_X_inv_block.resize(dim);
for(size_t column_block = 0; column_block < dim; ++column_block)
{
A_X_inv_block[column_block].clear();
A_X_inv_block[column_block].reserve(dim);
const size_t column_offset(column_block * block_size);
for(size_t row_block = 0; row_block < dim; ++row_block)
{
const size_t row_offset(row_block * block_size);
El::DistMatrix<El::BigFloat> submatrix(
El::View(A_X_inv_matrix, column_offset, row_offset, block_size,
block_size));
A_X_inv_block[column_block].emplace_back(block_size, block_size,
block.Grid());
A_X_inv_block[column_block].back().Align(0, 0);
El::Copy(submatrix, A_X_inv_block[column_block].back());
}
}
}
}
| 43.067797 | 81 | 0.627312 | [
"vector"
] |
71e929d4f3044ae6be59ebf4a2a0c487ac74b47b | 4,898 | cc | C++ | tests/test.cc | CS126SP20/final-project-lpan8 | 850c5e983d719b0d58c740c8c25a29a46e597da2 | [
"MIT"
] | 1 | 2020-08-26T03:16:56.000Z | 2020-08-26T03:16:56.000Z | tests/test.cc | CS126SP20/final-project-lpan8 | 850c5e983d719b0d58c740c8c25a29a46e597da2 | [
"MIT"
] | null | null | null | tests/test.cc | CS126SP20/final-project-lpan8 | 850c5e983d719b0d58c740c8c25a29a46e597da2 | [
"MIT"
] | 1 | 2020-05-06T17:54:50.000Z | 2020-05-06T17:54:50.000Z | // Copyright (c) 2020 CS126SP20. All rights reserved.
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <cinder/Rand.h>
#include <Box2D/Box2D.h>
#include "mylibrary/cue.h"
#include "mylibrary/box2d_utility.h"
#include "mylibrary/ball.h"
#include "mylibrary/table.h"
#include <mylibrary/game.h>
using namespace myapp;
TEST_CASE("Random sanity test", "[random]") {
const float random = cinder::randFloat();
REQUIRE(0. <= random);
REQUIRE(random <= 1.);
}
TEST_CASE("Cue calculate angle test", "[angle]") {
vec2 center = vec2(0, 0);
b2BodyDef b2body1;
b2body1.type = b2_kinematicBody;
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Cue> cue = std::shared_ptr<myapp::Cue>(new myapp::Cue(nullptr, nullptr, pos));
vec2 pos1(0, 0);
vec2 pos2(1, 1);
float angle = cue->CalculateAngle(pos1, pos2);
REQUIRE(angle <= 2.3561945);
}
TEST_CASE("Cue set power", "[power]") {
vec2 center = vec2(0, 0);
b2BodyDef b2body1;
b2body1.type = b2_kinematicBody;
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Cue> cue = std::shared_ptr<myapp::Cue>(new myapp::Cue(nullptr, nullptr, pos));
cue->DecreasePower();
REQUIRE(cue->GetPower() == 25);
cue->IncreasePower();
REQUIRE(cue->GetPower() == 30);
}
TEST_CASE("Ball set id", "[ball id]") {
vec2 center = vec2(0, 0);
b2BodyDef b2body1;
b2body1.type = b2_kinematicBody;
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos, 10.5));
ball->setId(5);
REQUIRE(ball->id_ == 5);
}
TEST_CASE("Ball is visible", "[ball visibility]") {
vec2 center = vec2(0, 0);
b2BodyDef b2body1;
b2body1.type = b2_kinematicBody;
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos, 10.5));
REQUIRE(ball->is_visible);
}
TEST_CASE("Table pockets", "[pockets]") {
vec2 center = vec2(0, 0);
b2BodyDef b2body1;
b2body1.type = b2_kinematicBody;
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Table> table = std::shared_ptr<myapp::Table>(new myapp::Table(nullptr, nullptr, pos));
std::vector<vec2> pockets;
pockets.push_back(vec2(1, 1));
table->TestPockets(pockets);
REQUIRE(table->GetPockets().size() == 1);
}
TEST_CASE("Table ball pocketed", "[ball pocketed]") {
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Table> table = std::shared_ptr<myapp::Table>(new myapp::Table(nullptr, nullptr, pos));
std::vector<vec2> pockets;
pockets.push_back(vec2(1, 1));
table->TestPockets(pockets);
vec2 pos_pt1(1, 1);
auto pos1 = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos1, 10.5));
// ball that is within pocket should be pocketed
REQUIRE(table->is_pocketed(ball));
}
TEST_CASE("Table ball not pocketed", "[ball not pocketed]") {
vec2 pos_pt(200, 150);
auto pos = Box2DUtility::pointsToMeters(pos_pt);
std::shared_ptr<myapp::Table> table = std::shared_ptr<myapp::Table>(new myapp::Table(nullptr, nullptr, pos));
std::vector<vec2> pockets;
pockets.push_back(vec2(1, 1));
table->TestPockets(pockets);
vec2 pos_pt1(200, 200);
auto pos1 = Box2DUtility::pointsToMeters(pos_pt1);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos1, 1));
// ball that is not within distance should not be pocketed
REQUIRE(!table->is_pocketed(ball));
}
TEST_CASE("Not game over", "[not game over]") {
myapp::Game game;
vec2 pos_pt1(200, 200);
auto pos1 = Box2DUtility::pointsToMeters(pos_pt1);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos1, 1));
ball->SetVisibility(true);
std::vector<std::shared_ptr<myapp::Ball>> balls;
balls.push_back(ball);
game.SetBalls(balls);
// game not over when ball is visible
bool over = game.GameOver();
REQUIRE(!over);
}
TEST_CASE("game over", "[game over]") {
myapp::Game game;
vec2 pos_pt1(200, 200);
auto pos1 = Box2DUtility::pointsToMeters(pos_pt1);
std::shared_ptr<myapp::Ball> ball = std::shared_ptr<myapp::Ball>(new myapp::Ball(nullptr, nullptr, pos1, 1));
ball->SetVisibility(false);
std::vector<std::shared_ptr<myapp::Ball>> balls;
balls.push_back(ball);
game.SetBalls(balls);
// game over when balls all not visible
bool over = game.GameOver();
REQUIRE(over);
} | 34.251748 | 116 | 0.67109 | [
"vector"
] |
71f3fe4d8cd4d2ef136dd27942568421fcc5e888 | 1,456 | cpp | C++ | Homework6/corrected_code_hw6.cpp | TanvirSayed/MNXB01-learn | 806022f6f143952c9430172d63cff7285b47f50e | [
"Apache-2.0"
] | null | null | null | Homework6/corrected_code_hw6.cpp | TanvirSayed/MNXB01-learn | 806022f6f143952c9430172d63cff7285b47f50e | [
"Apache-2.0"
] | 1 | 2021-10-19T11:49:18.000Z | 2021-10-19T11:49:18.000Z | Homework6/corrected_code_hw6.cpp | TanvirSayed/MNXB01-learn | 806022f6f143952c9430172d63cff7285b47f50e | [
"Apache-2.0"
] | null | null | null | // Printing all prime numbers between two integers entered by the user.
//Checking prime numbers via a user-defined function.
#include <iostream>
#include <vector>
using namespace std; //So no need std inside
int checkPrime(int);
int main()
{
int n1, n2;
bool flag;
cout << "Please type in two positive integers: "<< endl;
cin >> n1 >> n2;
cout << "The prime numbers between °C " << n1 << " and " << n2 << " are: " << endl;
for ( int i = n1+1; i < n2; i++) // initiliaztion, condition, increment
{
// Call the funtion checking the prime status of an integer
// If "i" is a prime the flag will be set to true (i.e. 1)
flag = checkPrime(i);
if (flag == 1)
cout << i << "\n";
}
cout << endl;
std::vector<double> v{1,2,3,4,7};
double K = 3;
int j=0;
int index;
for (double i:v) {
if (i==K){
index=j;
std::cout<<index;
break;}
j++;}
// std::vector<double> max_temps{1.0,2.3,23,4};
// std::vector<double> diff{};
// auto pointer = max_temps.begin();
// while (pointer < (max_temps.end()-1)) {
// diff.push_back(*(pointer+1)-*(pointer))
// pointer++;
// }
// return 0;
}
// user-defined function to check prime number
int checkPrime(int n)
{
bool flag = true;
for(int j = 2; j <= n/2; j++)
{
if (n%j == 0)
{
flag = false;
break;
}
}
return flag;
}
| 20.222222 | 87 | 0.536401 | [
"vector"
] |
9f97fea7bddcd5c9ec2258e5b024482bf186243c | 930 | cc | C++ | exkaldirtcbin/exkaldi-srfft.cc | mzaksana/exkaldi-rt | 828137d9c85bb99758ddd8235913dc75ef58ce6d | [
"Apache-2.0"
] | 1 | 2021-04-16T21:03:34.000Z | 2021-04-16T21:03:34.000Z | exkaldirtcbin/exkaldi-srfft.cc | mzaksana/exkaldi-rt | 828137d9c85bb99758ddd8235913dc75ef58ce6d | [
"Apache-2.0"
] | null | null | null | exkaldirtcbin/exkaldi-srfft.cc | mzaksana/exkaldi-rt | 828137d9c85bb99758ddd8235913dc75ef58ce6d | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<vector>
#include "matrix/srfft.h"
#include "matrix/kaldi-vector.h"
int main(int argc, char *argv[])
{
using namespace kaldi;
int padded_window_size = atoi(argv[2]);
int num_frames, points;
std::cin >> num_frames;
std::cin >> points;
std::cin.ignore();
Vector<BaseFloat> mywave;
mywave.Resize(padded_window_size);
mywave.SetZero();
SplitRadixRealFft<BaseFloat> *srfft2 = new SplitRadixRealFft<BaseFloat>(padded_window_size);
for (int i=0; i<num_frames; i++)
{
mywave.SetZero();
for (int j=0; j<points; j++)
{
std::cin >> mywave(j);
}
srfft2->Compute(mywave.Data(), true);
mywave(0) = ( mywave(0) + mywave(1) ) / 2.0;
mywave(1) = mywave(0) - mywave(1);
for(int k=0; k<padded_window_size; k++)
{
std::cout << mywave(k) << " ";
}
}
delete srfft2;
std::cout << std::endl;
std::cout.flush();
return 0;
} | 18.6 | 94 | 0.607527 | [
"vector"
] |
9fa78dac607258f7d890b235379c2bee9ce1fbb6 | 48,615 | cpp | C++ | src/pumex/RenderGraph.cpp | pumexx/pumex | 86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe | [
"MIT"
] | 299 | 2017-07-17T17:07:39.000Z | 2022-03-27T20:33:20.000Z | src/pumex/RenderGraph.cpp | pumexx/pumex | 86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe | [
"MIT"
] | 9 | 2018-08-09T11:49:37.000Z | 2020-12-10T03:55:12.000Z | src/pumex/RenderGraph.cpp | pumexx/pumex | 86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe | [
"MIT"
] | 21 | 2017-12-03T16:08:21.000Z | 2022-01-17T06:34:39.000Z | //
// Copyright(c) 2017-2018 Paweł Księżopolski ( pumexx )
//
// 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 <pumex/RenderGraph.h>
#include <algorithm>
#include <pumex/utils/Log.h>
using namespace pumex;
AttachmentDefinition::AttachmentDefinition()
: format{ VK_FORMAT_UNDEFINED }, attachmentType{ atUndefined }, attachmentSize{}, swizzles(gli::swizzle::SWIZZLE_RED, gli::swizzle::SWIZZLE_GREEN, gli::swizzle::SWIZZLE_BLUE, gli::swizzle::SWIZZLE_ALPHA)
{
}
AttachmentDefinition::AttachmentDefinition(VkFormat f, const ImageSize& as, AttachmentType at, const gli::swizzles& sw)
: format{ f }, attachmentSize{ as }, attachmentType{ at }, swizzles{ sw }
{
}
ResourceDefinition::ResourceDefinition()
: metaType{ rmtUndefined }, attachment{}
{
}
ResourceDefinition::ResourceDefinition(VkFormat f, const ImageSize& as, AttachmentType at, const std::string& n, const gli::swizzles& sw)
: metaType{ rmtImage }, attachment{ f, as, at, sw }, name{ n }
{
}
ResourceDefinition::ResourceDefinition(const std::string& n)
: metaType{ rmtBuffer }, name{ n }
{
CHECK_LOG_THROW(name.empty(), "ResourceDefinition : all buffers must have a name defined");
}
RenderOperationEntry::RenderOperationEntry(OperationEntryType et, const ResourceDefinition& rd, const LoadOp& lop, const ImageSubresourceRange& ir, VkImageLayout il, VkImageUsageFlags iu, VkImageCreateFlags ic, VkImageViewType ivt , const std::string& rse)
: entryType{ et }, resourceDefinition{ rd }, loadOp{ lop }, imageRange{ ir }, layout{ il }, imageUsage{ iu }, imageCreate{ ic }, imageViewType{ ivt }, resolveSourceEntryName{ rse }
{
}
RenderOperationEntry::RenderOperationEntry(OperationEntryType et, const ResourceDefinition& rd, const BufferSubresourceRange& br, VkPipelineStageFlags ps, VkAccessFlags af, VkFormat bf)
: entryType{ et }, resourceDefinition{ rd }, bufferRange{ br }, pipelineStage{ ps }, accessFlags{ af }, bufferFormat{ bf }
{
}
RenderOperation::RenderOperation()
{
}
RenderOperation::RenderOperation(const std::string& n, OperationType t, const ImageSize& as, uint32_t mvm )
: name{ n }, operationType{ t }, attachmentSize{ as }, multiViewMask{ mvm }
{
}
void RenderOperation::addAttachmentInput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate)
{
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Input entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Cannot add input entry when output entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as attachment input is not an image : " << name << "->" << entryName);
CHECK_LOG_THROW(!compareRenderOperationSizeWithImageSize(attachmentSize, resourceDefinition.attachment.attachmentSize, imageRange ), "RenderOperation : Attachment must have the same size as its operation : " << name << "->" << entryName);
CHECK_LOG_THROW(loadOp.loadType == LoadOp::DontCare, "RenderOperation : Attachment input cannot have LoadOp equal to LoadOp::DontCare : " << name << "->" << entryName);
inputEntries.insert({ entryName, RenderOperationEntry{ opeAttachmentInput, resourceDefinition, loadOp, imageRange, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, imageUsage, imageCreate, VK_IMAGE_VIEW_TYPE_MAX_ENUM, std::string() } });
//valid = false;
}
void RenderOperation::addAttachmentOutput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate)
{
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Output entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Cannot add output entry when input entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as attachment output is not an image : " << name << "->" << entryName);
CHECK_LOG_THROW(!compareRenderOperationSizeWithImageSize(attachmentSize, resourceDefinition.attachment.attachmentSize, imageRange), "RenderOperation : Attachment must have the same size as its operation : " << name << "->" << entryName);
RenderOperationEntry newEntry{ opeAttachmentOutput, resourceDefinition, loadOp, imageRange, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, imageUsage, imageCreate, VK_IMAGE_VIEW_TYPE_MAX_ENUM, std::string() };
outputEntries.insert({ entryName, newEntry });
// if output is loaded - it means that it also serves as an input ( someone has to generate the data to load )
if (loadOp.loadType == LoadOp::Load)
{
newEntry.entryType = opeAttachmentInput;
inputEntries.insert({ entryName, newEntry });
}
//valid = false;
}
void RenderOperation::addAttachmentResolveOutput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate, const std::string& sourceEntryName)
{
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Output entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Cannot add output entry when input entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as attachment output is not an image : " << name << "->" << entryName);
// compare operation size and attachment size skipping samples
CHECK_LOG_THROW(!compareRenderOperationSizeWithImageSize(attachmentSize, resourceDefinition.attachment.attachmentSize, imageRange), "RenderOperation : Attachment must have the same size as its operation : " << name << "->" << entryName);
CHECK_LOG_THROW(sourceEntryName.empty(), "RenderOperation : Resolve source entry not defined : " << name << " : " << entryName);
auto sourceEntry = outputEntries.find(sourceEntryName);
CHECK_LOG_THROW(sourceEntry == end(outputEntries), "RenderOperation : Resolve source entry does not exist : " << name << "->" << entryName << "(" <<sourceEntryName << ")" );
CHECK_LOG_THROW(sourceEntry->second.resourceDefinition.metaType != rmtImage, "RenderOperation : Resolve source entry is not an image : " << name << "->" << entryName << "(" << sourceEntryName << ")");
outputEntries.insert({ entryName, RenderOperationEntry{ opeAttachmentResolveOutput, resourceDefinition, loadOp, imageRange, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, imageUsage, imageCreate, VK_IMAGE_VIEW_TYPE_MAX_ENUM, sourceEntryName } });
//valid = false;
}
void RenderOperation::setAttachmentDepthInput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate)
{
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Input entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Cannot add input entry when output entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as attachment depth input is not an image : " << name << "->" << entryName);
CHECK_LOG_THROW(!compareRenderOperationSizeWithImageSize(attachmentSize, resourceDefinition.attachment.attachmentSize, imageRange), "RenderOperation : Attachment must have the same size as its operation : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.attachment.attachmentType != atDepth &&
resourceDefinition.attachment.attachmentType != atDepthStencil &&
resourceDefinition.attachment.attachmentType != atStencil, "RenderOperation : Attachment type must be atDepth, atDepthStencil or atStencil : " << name << "->" << entryName);
auto redundantInput = std::find_if(begin(inputEntries), end(inputEntries), [](std::pair<const std::string, RenderOperationEntry>& entry) { return ( entry.second.entryType == opeAttachmentDepthInput || entry.second.entryType == opeAttachmentDepthOutput ); });
auto redundantOutput = std::find_if(begin(outputEntries), end(outputEntries), [](std::pair<const std::string, RenderOperationEntry>& entry) { return ( entry.second.entryType == opeAttachmentDepthInput || entry.second.entryType == opeAttachmentDepthOutput ); });
CHECK_LOG_THROW(redundantInput != end(inputEntries) || redundantOutput != end(outputEntries), "RenderOperation : There must be only one depth input or output : " << name << "->" << entryName);
CHECK_LOG_THROW(loadOp.loadType == LoadOp::DontCare, "RenderOperation : Attachment input cannot have LoadOp equal to LoadOp::DontCare : " << name << "->" << entryName);
inputEntries.insert({ entryName, RenderOperationEntry{ opeAttachmentDepthInput, resourceDefinition, loadOp, imageRange, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, imageUsage, imageCreate, VK_IMAGE_VIEW_TYPE_MAX_ENUM, std::string() } });
//valid = false;
}
void RenderOperation::setAttachmentDepthOutput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate)
{
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Output entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Cannot add output entry when input entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as attachment depth output is not an image : " << name << "->" << entryName);
CHECK_LOG_THROW(!compareRenderOperationSizeWithImageSize(attachmentSize, resourceDefinition.attachment.attachmentSize, imageRange), "RenderOperation : Attachment must have the same size as its operation : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.attachment.attachmentType != atDepth &&
resourceDefinition.attachment.attachmentType != atDepthStencil &&
resourceDefinition.attachment.attachmentType != atStencil, "RenderOperation : Attachmenmt type must be atDepth, atDepthStencil or atStencil : " << name << "->" << entryName);
auto redundantInput = std::find_if(begin(inputEntries), end(inputEntries), [](std::pair<const std::string, RenderOperationEntry>& entry) { return ( entry.second.entryType == opeAttachmentDepthInput || entry.second.entryType == opeAttachmentDepthOutput ); });
auto redundantOutput = std::find_if(begin(outputEntries), end(outputEntries), [](std::pair<const std::string, RenderOperationEntry>& entry) { return ( entry.second.entryType == opeAttachmentDepthInput || entry.second.entryType == opeAttachmentDepthOutput ); });
CHECK_LOG_THROW(redundantInput != end(inputEntries) || redundantOutput != end(outputEntries), "RenderOperation : There must be only one depth input or output : " << name << "->" << entryName);
RenderOperationEntry newEntry{ opeAttachmentDepthOutput, resourceDefinition, loadOp, imageRange, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, imageUsage, imageCreate, VK_IMAGE_VIEW_TYPE_MAX_ENUM, std::string() };
outputEntries.insert({ entryName, newEntry });
if (loadOp.loadType == LoadOp::Load)
{
newEntry.entryType = opeAttachmentDepthInput;
inputEntries.insert({ entryName, newEntry });
}
//valid = false;
}
void RenderOperation::addImageInput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageLayout layout, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate, VkImageViewType imageViewType)
{
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Input entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Cannot add input entry when output entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as image input is not an image : " << name << "->" << entryName);
inputEntries.insert({ entryName, RenderOperationEntry{ opeImageInput, resourceDefinition, loadOp, imageRange, layout, imageUsage, imageCreate, imageViewType, std::string() } });
//valid = false;
}
void RenderOperation::addImageOutput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const LoadOp& loadOp, const ImageSubresourceRange& imageRange, VkImageLayout layout, VkImageUsageFlags imageUsage, VkImageCreateFlags imageCreate, VkImageViewType imageViewType)
{
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Cannot add output entry when input entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtImage, "RenderOperation : Resource used as image output is not an image : " << name << "->" << entryName);
outputEntries.insert({ entryName, RenderOperationEntry{ opeImageOutput, resourceDefinition, loadOp, imageRange, layout, imageUsage, imageCreate, imageViewType, std::string() } });
//valid = false;
}
void RenderOperation::addBufferInput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const BufferSubresourceRange& bufferRange, VkPipelineStageFlags pipelineStage, VkAccessFlags accessFlags)
{
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Cannot add input entry when output entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtBuffer, "RenderOperation : Resource used as buffer input is not a buffer : " << name << "->" << entryName);
inputEntries.insert({ entryName, RenderOperationEntry{ opeBufferInput, resourceDefinition, bufferRange, pipelineStage, accessFlags } });
//valid = false;
}
void RenderOperation::addBufferOutput(const std::string& entryName, const ResourceDefinition& resourceDefinition, const BufferSubresourceRange& bufferRange, VkPipelineStageFlags pipelineStage, VkAccessFlags accessFlags)
{
CHECK_LOG_THROW(outputEntries.find(entryName) != end(outputEntries), "RenderOperation : Entry with that name already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(inputEntries.find(entryName) != end(inputEntries), "RenderOperation : Cannot add output entry when input entry with the same name is already defined : " << name << "->" << entryName);
CHECK_LOG_THROW(resourceDefinition.metaType != rmtBuffer, "RenderOperation : Resource used as buffer output is not a buffer : " << name << "->" << entryName);
outputEntries.insert({ entryName, RenderOperationEntry{ opeBufferOutput, resourceDefinition, bufferRange, pipelineStage, accessFlags } });
//valid = false;
}
void RenderOperation::setRenderOperationNode(std::shared_ptr<Node> n)
{
node = n;
}
std::shared_ptr<Node> RenderOperation::getRenderOperationNode()
{
return node;
}
std::vector<std::reference_wrapper<const RenderOperationEntry>> RenderOperation::getEntries(OperationEntryTypeFlags entryTypes) const
{
std::vector<std::reference_wrapper<const RenderOperationEntry>> results;
for (auto& entry : inputEntries)
if (entry.second.entryType & entryTypes)
results.push_back(entry.second);
for (auto& entry : outputEntries)
if (entry.second.entryType & entryTypes)
results.push_back(entry.second);
return results;
}
ResourceTransition::ResourceTransition(uint32_t rteid, uint32_t tid, uint32_t oid, const std::list<RenderOperation>::const_iterator& op, const std::map<std::string, RenderOperationEntry>::const_iterator& e, const std::string& emon, VkImageLayout ela)
: rteid_{ rteid }, tid_{ tid }, oid_{ oid }, operation_ { op }, entry_{ e }, externalMemoryObjectName_{ emon }, externalLayout_{ela}
{
}
RenderGraph::RenderGraph(const std::string& n)
: name{ n }
{
}
RenderGraph::~RenderGraph()
{
}
void RenderGraph::addRenderOperation(const RenderOperation& op)
{
auto it = std::find_if(begin(operations), end(operations), [&op](const RenderOperation& opx) { return opx.name == op.name; });
CHECK_LOG_THROW(it != end(operations), "RenderGraph : operation already exists : " + op.name);
operations.push_back(op);
valid = false;
}
uint32_t RenderGraph::addResourceTransition(const std::string& generatingOperation, const std::string& generatingEntry, const std::string& consumingOperation, const std::string& consumingEntry, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName)
{
return addResourceTransition({ generatingOperation, generatingEntry }, { { consumingOperation, consumingEntry } }, suggestedObjectID, externalMemoryObjectName);
}
uint32_t RenderGraph::addResourceTransition(const ResourceTransitionEntry& gen, const ResourceTransitionEntry& con, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName)
{
std::vector<ResourceTransitionEntry> cons;
cons.push_back(con);
return addResourceTransition( gen, cons, suggestedObjectID, externalMemoryObjectName );
}
uint32_t RenderGraph::addResourceTransition(const ResourceTransitionEntry& gen, const std::vector<ResourceTransitionEntry>& cons, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName)
{
CHECK_LOG_THROW(cons.empty(), "RenderGraph : vector of consumers is empty : " << gen.first);
const auto genOp = std::find_if(begin(operations), end(operations), [&gen](const RenderOperation& opx) { return opx.name == gen.first; });
CHECK_LOG_THROW(genOp == end(operations), "RenderGraph : generating operation not defined : " << gen.first);
const auto genEntry = genOp->outputEntries.find(gen.second);
CHECK_LOG_THROW(genEntry == end(genOp->outputEntries), "RenderGraph : operation " << gen.first << " does not have entry named : " << gen.second);
CHECK_LOG_THROW((genEntry->second.entryType & opeAllOutputs) == 0, "RenderGraph : entry " << gen.first << "->" << gen.second << " is not an output");
// generating entry may have zero or more outputs
auto existingGenTransition = std::find_if(begin(transitions), end(transitions), [genOp, genEntry](const ResourceTransition& rt) { return (rt.operationIter() == genOp && ( rt.entry().entryType & opeAllOutputs) && rt.entryIter() == genEntry); });
uint32_t transitionID, objectID;
if (existingGenTransition != end(transitions))
{
// all transitions using the same output must have the same external resource defined
CHECK_LOG_THROW(existingGenTransition->externalMemoryObjectName() != externalMemoryObjectName, "RenderGraph : All transitions using " << gen.first << "->" << gen.second << " must have the same external resource : " << existingGenTransition->externalMemoryObjectName() << " != " << externalMemoryObjectName);
transitionID = existingGenTransition->tid();
objectID = existingGenTransition->oid();
// if suggestedObjectID is provided, then it must be the same as the one that exists already - two different objects cannot use the same generating entry
CHECK_LOG_THROW( suggestedObjectID!=0 && objectID != suggestedObjectID, "RenderGraph : All transitions using entry " << gen.first << "->" << gen.second << " must have the same objectID");
}
else
{
// if the entry is LoadOp::Load, then we have to use objectID from genOp input
transitionID = generateTransitionID();
auto prevConTransition = std::find_if(begin(transitions), end(transitions), [genOp, genEntry](const ResourceTransition& rt) { return (rt.operationIter() == genOp && (rt.entry().entryType & opeAllInputs) && rt.entryIter()->first == genEntry->first); });
if (prevConTransition != end(transitions))
{
objectID = prevConTransition->oid();
CHECK_LOG_THROW(suggestedObjectID != 0 && objectID != suggestedObjectID, "RenderGraph : All transitions using generating entry " << gen.first << "->" << gen.second << " must have the same objectID. Suggested objectID is wrong");
}
else
objectID = (suggestedObjectID != 0) ? suggestedObjectID : generateObjectID();
}
std::vector<ImageSubresourceRange> imageRanges;
std::set<VkImageLayout> conImageLayouts;
std::vector<BufferSubresourceRange> bufferRanges;
for (const auto& con : cons)
{
CHECK_LOG_THROW(gen.first == con.first, "RenderGraph : generating and consuming operation can't be the same : " << gen.first);
auto conOp = std::find_if(begin(operations), end(operations), [&con](const RenderOperation& opx) { return opx.name == con.first; });
CHECK_LOG_THROW(conOp == end(operations), "RenderGraph : consuming operation not defined : " << con.first);
auto conEntry = conOp->inputEntries.find(con.second);
CHECK_LOG_THROW(conEntry == end(conOp->inputEntries), "RenderGraph : operation " << con.first << " does not have entry named : " << con.second);
CHECK_LOG_THROW((conEntry->second.entryType & opeAllInputs) == 0, "RenderGraph : entry " << con.first << "->" << con.second << " is not an input");
conImageLayouts.insert(conEntry->second.layout);
// both entries must have the same resource definition
CHECK_LOG_THROW(!(genEntry->second.resourceDefinition == conEntry->second.resourceDefinition), "RenderGraph : entries " << gen.first << "->" << gen.second << " and " << con.first << "->" << con.second << " must have the same resource definition");
// only one consuming transition may exist
auto existingConTransition = std::find_if(begin(transitions), end(transitions), [conOp, conEntry](const ResourceTransition& rt) { return (rt.operationIter() == conOp && (rt.entry().entryType & opeAllInputs) && rt.entryIter() == conEntry); });
CHECK_LOG_THROW(existingConTransition != end(transitions), "RenderGraph : consuming operation may only have one entry : " << con.first << "->" << con.second);
if ((conEntry->second.entryType & ( opeAllImages | opeAllAttachments )) != 0)
imageRanges.push_back(conEntry->second.imageRange);
else
bufferRanges.push_back(conEntry->second.bufferRange);
}
CHECK_LOG_THROW(imageRanges.empty() == bufferRanges.empty(), "RenderGraph : all consuming operations must be either image based or buffer based");
if (!imageRanges.empty())
{
auto consumentRange = mergeRanges(imageRanges);
CHECK_LOG_THROW(consumentRange.valid() && !genEntry->second.imageRange.contains(consumentRange), "RenderGraph : generating transition image range must contain consuming image ranges" << gen.first << "->" << gen.second);
CHECK_LOG_THROW(conImageLayouts.size() > 1, "RenderGraph : all consuming image layouts must be the same for generating transition : " << gen.first << "->" << gen.second);
}
else if (!bufferRanges.empty())
{
auto consumentRange = mergeRanges(bufferRanges);
CHECK_LOG_THROW(consumentRange.valid() && !genEntry->second.bufferRange.contains(consumentRange), "RenderGraph : generating transition buffer range must contain consuming buffer ranges" << gen.first << "->" << gen.second);
}
if (existingGenTransition == end(transitions))
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, genOp, genEntry, externalMemoryObjectName, VK_IMAGE_LAYOUT_UNDEFINED));
for (const auto& con : cons)
{
auto conOp = std::find_if(begin(operations), end(operations), [&con](const RenderOperation& opx) { return opx.name == con.first; });
auto conEntry = conOp->inputEntries.find(con.second);
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, conOp, conEntry, externalMemoryObjectName, VK_IMAGE_LAYOUT_UNDEFINED));
}
valid = false;
return objectID;
}
uint32_t RenderGraph::addResourceTransition(const std::vector<ResourceTransitionEntry>& gens, const ResourceTransitionEntry& con, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName)
{
CHECK_LOG_THROW(gens.empty(), "RenderGraph : vector of generators is empty : " << con.first);
auto conOp = std::find_if(begin(operations), end(operations), [&con](const RenderOperation& opx) { return opx.name == con.first; });
CHECK_LOG_THROW(conOp == end(operations), "RenderGraph : consuming operation not defined : " << con.first);
auto conEntry = conOp->inputEntries.find(con.second);
CHECK_LOG_THROW(conEntry == end(conOp->inputEntries), "RenderGraph : operation " << con.first << " does not have entry named : " << con.second);
CHECK_LOG_THROW((conEntry->second.entryType & opeAllInputs) == 0, "RenderGraph : entry " << con.first << "->" << con.second << " is not an input");
// consuming entry may have inly one input
auto existingConTransition = std::find_if(begin(transitions), end(transitions), [conOp, conEntry](const ResourceTransition& rt) { return (rt.operationIter() == conOp && (rt.entry().entryType & opeAllInputs) && rt.entryIter() == conEntry); });
CHECK_LOG_THROW(existingConTransition != end(transitions), "RenderGraph : consuming operation may only have one entry : " << con.first << "->" << con.second);
// Before we add any transition - we must choose tid and oid for new set of transitions. Problem is that some generating transitions may be defined already.
// OK, so idea is that all existing generating transitions must have at most one tid and oid defined.
std::set<uint32_t> existingTransitionID;
std::set<uint32_t> existingObjectID;
std::vector<ImageSubresourceRange> imageRanges;
std::set<VkImageLayout> genImageLayouts;
std::vector<BufferSubresourceRange> bufferRanges;
for (const auto& gen : gens)
{
auto genOp = std::find_if(begin(operations), end(operations), [&gen](const RenderOperation& opx) { return opx.name == gen.first; });
CHECK_LOG_THROW(genOp == end(operations), "RenderGraph : generating operation not defined : " << gen.first);
auto genEntry = genOp->outputEntries.find(gen.second);
CHECK_LOG_THROW(genEntry == end(genOp->outputEntries), "RenderGraph : operation " << gen.first << " does not have entry named : " << gen.second);
CHECK_LOG_THROW((genEntry->second.entryType & opeAllOutputs) == 0, "RenderGraph : entry " << gen.first << "->" << gen.second << " is not an output");
// both entries must have the same resource definition
CHECK_LOG_THROW(!(genEntry->second.resourceDefinition == conEntry->second.resourceDefinition), "RenderGraph : entries " << gen.first << "->" << gen.second << " and " << con.first << "->" << con.second << " must have the same resource definition");
genImageLayouts.insert(genEntry->second.layout);
auto existingGenTransition = std::find_if(begin(transitions), end(transitions), [genOp, genEntry](const ResourceTransition& rt) { return (rt.operationIter() == genOp && (rt.entry().entryType & opeAllOutputs) && rt.entryIter() == genEntry); });
if (existingGenTransition != end(transitions))
{
// all transitions using the same output must have the same external resource defined
CHECK_LOG_THROW(existingGenTransition->externalMemoryObjectName() != externalMemoryObjectName, "RenderGraph : All transitions using " << gen.first << "->" << gen.second << " must have the same external resource : " << existingGenTransition->externalMemoryObjectName() << " != " << externalMemoryObjectName);
existingTransitionID.insert(existingGenTransition->tid());
existingObjectID.insert(existingGenTransition->oid());
}
else
{
// transition does not exist, but if the entry is LoadOp::Load then we have to use objectID from previous input transition
auto prevConTransition = std::find_if(begin(transitions), end(transitions), [genOp, genEntry](const ResourceTransition& rt) { return (rt.operationIter() == genOp && (rt.entry().entryType & opeAllInputs) && rt.entryIter()->first == genEntry->first); });
if (prevConTransition != end(transitions))
existingObjectID.insert(prevConTransition->oid());
}
if ((genEntry->second.entryType & ( opeAllImages | opeAllAttachments )) != 0)
imageRanges.push_back(genEntry->second.imageRange);
else
bufferRanges.push_back(genEntry->second.bufferRange);
}
CHECK_LOG_THROW(imageRanges.empty() == bufferRanges.empty(), "RenderGraph : all generating operations must be either image based or buffer based");
if (!imageRanges.empty())
{
auto generatorRange = mergeRanges(imageRanges);
CHECK_LOG_THROW(generatorRange.valid() && !generatorRange.contains(conEntry->second.imageRange), "RenderGraph : generating transition image range must contain consuming image ranges" << con.first << "->" << con.second);
CHECK_LOG_THROW(genImageLayouts.size() > 1, "RenderGraph : all generating image layouts must be the same for consuming tranistion : " << con.first << "->" << con.second);
CHECK_LOG_THROW(anyRangeOverlaps(imageRanges), "RenderGraph : all generating image transitions must have disjunctive image ranges : " << con.first << "->" << con.second);
}
else if( !bufferRanges.empty() )
{
auto generatorRange = mergeRanges(bufferRanges);
CHECK_LOG_THROW(generatorRange.valid() && !generatorRange.contains( conEntry->second.bufferRange), "RenderGraph : generating transition buffer range must contain consuming buffer ranges" << con.first << "->" << con.second);
CHECK_LOG_THROW(anyRangeOverlaps(bufferRanges), "RenderGraph : all generating buffer transitions must have disjunctive buffer ranges : " << con.first << "->" << con.second);
}
// check if consumed entry is not treated also as output ( which means that output is used as LoadOp::Load )
auto nextGenTransition = std::find_if(begin(transitions), end(transitions), [conOp, conEntry](const ResourceTransition& rt) { return (rt.operationIter() == conOp && (rt.entry().entryType & opeAllOutputs) && rt.entryIter()->first == conEntry->first); });
if (nextGenTransition != end(transitions))
existingObjectID.insert(nextGenTransition->oid());
CHECK_LOG_THROW(existingTransitionID.size() > 1, "RenderGraph : cannot add generating transitions, because some transitions already exist and have different IDs. Consumer : " << con.first << "->" << con.second);
CHECK_LOG_THROW(existingObjectID.size() > 1, "RenderGraph : cannot add generating transitions, because the number of objectID candidates exceeds 1. Consumer : " << con.first << "->" << con.second);
uint32_t transitionID, objectID;
if (!existingTransitionID.empty())
transitionID = *begin(existingTransitionID);
else
transitionID = generateTransitionID();
if (!existingObjectID.empty())
{
objectID = *begin(existingObjectID);
// if suggestedObjectID is provided, then it must be the same as the one that exists already - two different objects cannot use the same generating entry
CHECK_LOG_THROW(suggestedObjectID != 0 && objectID != suggestedObjectID, "RenderGraph : All transitions using consuming entry " << con.first << "->" << con.second << " must have the same objectID. Suggested objectID is wrong");
}
else
objectID = (suggestedObjectID != 0) ? suggestedObjectID : generateObjectID();
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, conOp, conEntry, externalMemoryObjectName, VK_IMAGE_LAYOUT_UNDEFINED));
for (const auto& gen : gens)
{
auto genOp = std::find_if(begin(operations), end(operations), [&gen](const RenderOperation& opx) { return opx.name == gen.first; });
auto genEntry = genOp->outputEntries.find(gen.second);
auto existingGenTransition = std::find_if(begin(transitions), end(transitions), [genOp, genEntry](const ResourceTransition& rt) { return (rt.operationIter() == genOp && (rt.entry().entryType & opeAllOutputs) && rt.entryIter() == genEntry); });
if (existingGenTransition == end(transitions))
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, genOp, genEntry, externalMemoryObjectName, VK_IMAGE_LAYOUT_UNDEFINED));
}
valid = false;
return objectID;
}
uint32_t RenderGraph::addResourceTransitionInput(const std::string& opName, const std::string& entryName, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName, VkImageLayout externalLayout)
{
return addResourceTransitionInput({ opName, entryName }, suggestedObjectID, externalMemoryObjectName, externalLayout);
}
uint32_t RenderGraph::addResourceTransitionInput(const ResourceTransitionEntry& tren, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName, VkImageLayout externalLayout)
{
auto op = std::find_if(begin(operations), end(operations), [&tren](const RenderOperation& opx) { return opx.name == tren.first; });
CHECK_LOG_THROW(op == end(operations), "RenderGraph : generating operation not defined : " << tren.first);
auto entry = op->inputEntries.find(tren.second);
CHECK_LOG_THROW(entry == end(op->inputEntries), "RenderGraph : operation " << tren.first << " does not have input entry named : " << tren.second);
auto existingTransition = std::find_if(begin(transitions), end(transitions), [op, entry](const ResourceTransition& rt) { return (rt.operationIter() == op && (rt.entry().entryType & opeAllInputs) && rt.entryIter() == entry); });
CHECK_LOG_THROW(existingTransition != end(transitions), "RenderGraph : consuming operation may only have one entry : " << tren.first << "->" << tren.second);
uint32_t transitionID, objectID;
transitionID = generateTransitionID();
// check if there is output transition with the same entry name ( LoadOp::Load )
auto nextGenTransition = std::find_if(begin(transitions), end(transitions), [op, entry](const ResourceTransition& rt) { return (rt.operationIter() == op && (rt.entry().entryType & opeAllOutputs) && rt.entryIter()->first == entry->first); });
if (nextGenTransition != end(transitions))
{
objectID = nextGenTransition->oid();
CHECK_LOG_THROW(suggestedObjectID != 0 && objectID != suggestedObjectID, "RenderGraph : All transitions using consuming entry " << tren.first << "->" << tren.second << " must have the same objectID. Suggested objectID is wrong");
}
else
objectID = (suggestedObjectID != 0) ? suggestedObjectID : generateObjectID();
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, op, entry, externalMemoryObjectName, externalLayout));
valid = false;
return objectID;
}
uint32_t RenderGraph::addResourceTransitionOutput(const std::string& opName, const std::string& entryName, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName, VkImageLayout externalLayout)
{
return addResourceTransitionOutput({ opName, entryName }, suggestedObjectID, externalMemoryObjectName, externalLayout);
}
uint32_t RenderGraph::addResourceTransitionOutput(const ResourceTransitionEntry& tren, uint32_t suggestedObjectID, const std::string& externalMemoryObjectName, VkImageLayout externalLayout)
{
auto op = std::find_if(begin(operations), end(operations), [&tren](const RenderOperation& opx) { return opx.name == tren.first; });
CHECK_LOG_THROW(op == end(operations), "RenderGraph : generating operation not defined : " << tren.first);
auto entry = op->outputEntries.find(tren.second);
CHECK_LOG_THROW(entry == end(op->outputEntries), "RenderGraph : operation " << tren.first << " does not have output entry named : " << tren.second);
auto existingTransition = std::find_if(begin(transitions), end(transitions), [op, entry](const ResourceTransition& rt) { return (rt.operationIter() == op && (rt.entry().entryType & opeAllOutputs) && rt.entryIter() == entry); });
uint32_t transitionID, objectID;
if (existingTransition != end(transitions))
{
// all transitions using the same output must have the same external resource defined
CHECK_LOG_THROW(existingTransition->externalMemoryObjectName() != externalMemoryObjectName, "RenderGraph : All transitions using " << tren.first << "->" << tren.second << " must have the same external resource : " << existingTransition->externalMemoryObjectName() << " != " << externalMemoryObjectName);
transitionID = existingTransition->tid();
objectID = existingTransition->oid();
// if suggestedObjectID is provided, then it must be the same as the one that exists already - two different objects () cannot use the same generating entry
CHECK_LOG_THROW(suggestedObjectID != 0 && objectID != suggestedObjectID, "RenderGraph : All transitions using entry " << tren.first << "->" << tren.second << " must have the same objectID");
}
else
{
transitionID = generateTransitionID();
auto prevConTransition = std::find_if(begin(transitions), end(transitions), [op, entry](const ResourceTransition& rt) { return (rt.operationIter() == op && (rt.entry().entryType & opeAllInputs) && rt.entryIter()->first == entry->first); });
if (prevConTransition != end(transitions))
{
objectID = prevConTransition->oid();
CHECK_LOG_THROW(suggestedObjectID != 0 && objectID != suggestedObjectID, "RenderGraph : All transitions using generating entry " << tren.first << "->" << tren.second << " must have the same objectID. Suggested objectID is wrong");
}
else
objectID = (suggestedObjectID != 0) ? suggestedObjectID : generateObjectID();
}
transitions.push_back(ResourceTransition(generateTransitionEntryID(), transitionID, objectID, op, entry, externalMemoryObjectName, externalLayout));
valid = false;
return objectID;
}
void RenderGraph::addMissingResourceTransitions()
{
std::vector<ResourceTransition> emptyTransitions;
for (auto opit = begin(operations); opit != end(operations); ++opit)
{
auto inTransitions = getOperationIO(opit->name, opeAllInputs);
for (auto opeit = begin(opit->inputEntries); opeit != end(opit->inputEntries); ++opeit)
if (std::none_of(begin(inTransitions), end(inTransitions), [&opeit](const ResourceTransition& tr) { return opeit->first == tr.entryName(); }))
// if (opeit->first != SWAPCHAIN_NAME)
// emptyTransitions.push_back(ResourceTransition(generateTransitionEntryID(), generateTransitionID(), 0, opit, opeit, std::string(), VK_IMAGE_LAYOUT_UNDEFINED));
// else
emptyTransitions.push_back(ResourceTransition(generateTransitionEntryID(), generateTransitionID(), generateObjectID(), opit, opeit, std::string(), VK_IMAGE_LAYOUT_UNDEFINED));
auto outTransitions = getOperationIO(opit->name, opeAllOutputs);
for (auto opeit = begin(opit->outputEntries); opeit != end(opit->outputEntries); ++opeit)
if (std::none_of(begin(outTransitions), end(outTransitions), [&opeit](const ResourceTransition& tr) { return opeit->first == tr.entryName(); }))
// if(opeit->first != SWAPCHAIN_NAME)
// emptyTransitions.push_back(ResourceTransition(generateTransitionEntryID(), generateTransitionID(), 0, opit, opeit, std::string(), VK_IMAGE_LAYOUT_UNDEFINED));
// else
emptyTransitions.push_back(ResourceTransition(generateTransitionEntryID(), generateTransitionID(), generateObjectID(), opit, opeit, std::string(), VK_IMAGE_LAYOUT_UNDEFINED));
}
std::copy(begin(emptyTransitions), end(emptyTransitions), std::back_inserter(transitions));
}
std::vector<std::string> RenderGraph::getRenderOperationNames() const
{
std::vector<std::string> results;
for (auto& op : operations)
results.push_back(op.name);
return results;
}
const RenderOperation& RenderGraph::getRenderOperation(const std::string& opName) const
{
auto it = std::find_if(begin(operations), end(operations), [&opName](const RenderOperation& opx) { return opx.name == opName; });
CHECK_LOG_THROW(it == end(operations), "RenderGraph : there is no operation with name " + opName);
return *it;
}
RenderOperation& RenderGraph::getRenderOperation(const std::string& opName)
{
auto it = std::find_if(begin(operations), end(operations), [&opName](const RenderOperation& opx) { return opx.name == opName; });
CHECK_LOG_THROW(it == end(operations), "RenderGraph : there is no operation with name " + opName);
return *it;
}
void RenderGraph::setRenderOperationNode(const std::string& opName, std::shared_ptr<Node> n)
{
getRenderOperation(opName).setRenderOperationNode( n );
valid = false;
}
std::shared_ptr<Node> RenderGraph::getRenderOperationNode(const std::string& opName)
{
return getRenderOperation(opName).node;
}
std::vector<std::reference_wrapper<const ResourceTransition>> RenderGraph::getOperationIO(const std::string& opName, OperationEntryTypeFlags entryTypes) const
{
std::vector<std::reference_wrapper<const ResourceTransition>> results;
std::copy_if(begin(transitions), end(transitions), std::back_inserter(results),
[opName, entryTypes](const ResourceTransition& c)->bool { return c.operationName() == opName && (c.entry().entryType & entryTypes); });
return results;
}
std::vector<std::reference_wrapper<const ResourceTransition>> RenderGraph::getTransitionIO(uint32_t transitionID, OperationEntryTypeFlags entryTypes) const
{
std::vector<std::reference_wrapper<const ResourceTransition>> results;
std::copy_if(begin(transitions), end(transitions), std::back_inserter(results),
[transitionID, entryTypes](const ResourceTransition& c)->bool { return c.tid() == transitionID && (c.entry().entryType & entryTypes); });
return results;
}
std::reference_wrapper<const ResourceTransition> RenderGraph::getTransition(uint32_t rteid) const
{
auto it = std::find_if(begin(transitions), end(transitions), [rteid](const ResourceTransition& c)->bool { return c.rteid() == rteid; });
CHECK_LOG_THROW(it == end(transitions), "Canot find transition rteid = " << rteid);
return *it;
}
std::vector<std::reference_wrapper<const ResourceTransition>> RenderGraph::getObjectIO(uint32_t objectID, OperationEntryTypeFlags entryTypes) const
{
std::vector<std::reference_wrapper<const ResourceTransition>> results;
std::copy_if(begin(transitions), end(transitions), std::back_inserter(results),
[objectID, entryTypes](const ResourceTransition& c)->bool { return c.oid() == objectID && (c.entry().entryType & entryTypes); });
return results;
}
uint32_t RenderGraph::generateTransitionEntryID()
{
auto result = nextTransitionEntryID++;
return result;
}
uint32_t RenderGraph::generateTransitionID()
{
auto result = nextTransitionID++;
return result;
}
uint32_t RenderGraph::generateObjectID()
{
auto result = nextObjectID++;
return result;
}
namespace pumex
{
ResourceDefinition SWAPCHAIN_DEFINITION(VkFormat format, uint32_t arrayLayers)
{
return ResourceDefinition(format, ImageSize{ isSurfaceDependent, glm::vec2(1.0f,1.0f), arrayLayers, 1, 1 }, atColor);
}
RenderOperationSet getInitialOperations(const RenderGraph& renderGraph)
{
// operation is initial when there are no input resources, or input resources do not have outputs that created them
RenderOperationSet initialOperations;
for (const auto& it : renderGraph.getOperations())
{
auto inTransitions = renderGraph.getOperationIO(it.name, opeAllInputs);
if(inTransitions.empty())
initialOperations.insert(it);
bool existingOutputs = false;
for (auto& inTransition : inTransitions)
{
auto outTransitions = renderGraph.getTransitionIO(inTransition.get().tid(), opeAllOutputs);
existingOutputs = !outTransitions.empty();
if(existingOutputs)
break;
}
if(!existingOutputs)
initialOperations.insert(it);
}
return initialOperations;
}
RenderOperationSet getFinalOperations(const RenderGraph& renderGraph)
{
// operation is final when there are no output resources, or output resources do not have inputs that consume them
RenderOperationSet finalOperations;
for (const auto& it : renderGraph.getOperations())
{
auto outTransitions = renderGraph.getOperationIO(it.name, opeAllOutputs);
if (outTransitions.empty())
finalOperations.insert(it);
bool existingInputs = false;
for (auto& outTransition : outTransitions)
{
auto inTransitions = renderGraph.getTransitionIO(outTransition.get().tid(), opeAllInputs);
existingInputs = !inTransitions.empty();
if (existingInputs)
break;
}
if (!existingInputs)
finalOperations.insert(it);
}
return finalOperations;
}
RenderOperationSet getPreviousOperations(const RenderGraph& renderGraph, const std::string& opName)
{
auto inTransitions = renderGraph.getOperationIO(opName, opeAllInputs);
RenderOperationSet previousOperations;
for (auto& inTransition : inTransitions)
{
auto transitions = renderGraph.getTransitionIO(inTransition.get().tid(), opeAllOutputs);
for (auto transition : transitions)
previousOperations.insert(transition.get().operation());
}
return previousOperations;
}
RenderOperationSet getNextOperations(const RenderGraph& renderGraph, const std::string& opName)
{
auto outTransitions = renderGraph.getOperationIO(opName, opeAllOutputs);
RenderOperationSet nextOperations;
for (auto& outTransition : outTransitions)
{
auto transitions = renderGraph.getTransitionIO(outTransition.get().tid(), opeAllInputs);
for (auto transition : transitions)
nextOperations.insert(transition.get().operation());
}
return nextOperations;
}
RenderOperationSet getAllPreviousOperations(const RenderGraph& renderGraph, const std::string& opName)
{
RenderOperationSet results;
auto prevOperations = getPreviousOperations(renderGraph, opName);
while (!prevOperations.empty())
{
decltype(prevOperations) prevOperations2;
for (auto operation : prevOperations)
{
results.insert(operation);
auto x = getPreviousOperations(renderGraph, operation.get().name);
std::copy(begin(x), end(x), std::inserter(prevOperations2, end(prevOperations2)));
}
prevOperations = prevOperations2;
}
return results;
}
RenderOperationSet getAllNextOperations(const RenderGraph& renderGraph, const std::string& opName)
{
RenderOperationSet results;
auto nextOperations = getNextOperations(renderGraph, opName);
while (!nextOperations.empty())
{
decltype(nextOperations) nextOperations2;
for (auto operation : nextOperations)
{
results.insert(operation);
auto x = getNextOperations(renderGraph, operation.get().name);
std::copy(begin(x), end(x), std::inserter(nextOperations2, end(nextOperations2)));
}
nextOperations = nextOperations2;
}
return results;
}
}
| 64.476127 | 313 | 0.743988 | [
"vector"
] |
9faa0f954a45ff574c172b08f2b23375bac633b4 | 9,033 | cpp | C++ | vtkFreeWrapper/vtkFreeWrapper/Curvatures/main.cpp | Sanaxen/vtkFreeWrapper | fe0b87aa54e3717c8f5b1d3d5ea68d50009e536a | [
"MIT"
] | 3 | 2018-11-27T02:00:12.000Z | 2019-05-28T07:54:49.000Z | vtkFreeWrapper/vtkFreeWrapper/Curvatures/main.cpp | Sanaxen/vtkFreeWrapper | fe0b87aa54e3717c8f5b1d3d5ea68d50009e536a | [
"MIT"
] | null | null | null | vtkFreeWrapper/vtkFreeWrapper/Curvatures/main.cpp | Sanaxen/vtkFreeWrapper | fe0b87aa54e3717c8f5b1d3d5ea68d50009e536a | [
"MIT"
] | 1 | 2019-05-28T07:55:02.000Z | 2019-05-28T07:55:02.000Z | #include "gmrVTKRender.hpp"
#include "gmrVTKImport.hpp"
#include "gmrVTKExport.hpp"
#include "gmrVTKCapture.hpp"
#include "gmrVTKText.hpp"
#include "gmrVTKMeshFilter.hpp"
#include "gmrVTK.hpp"
#define NO_LINK_LIBS
#include "gmrVTKLIBs.hpp"
#pragma comment( lib, "../../../vtkFreeWrapper/util/lib/Release/64bit/vtkWrapperLib.lib" )
#pragma comment( lib, "opengl32.lib" )
#pragma comment( lib, "vfw32.lib")
int exportVertexColorOBJ(char* filename, gmrVTKMeshFilter* meshFilter, vtkPolyDataAlgorithm* poly)
{
FILE* fp = fopen(filename, "w");
if (fp == NULL)
{
char szFullPath[_MAX_PATH] = { '\0' };
char *szFilePart;
DWORD dwRet = GetFullPathNameA(filename, _MAX_PATH, szFullPath, &szFilePart);
if (fp == NULL)
{
printf("file open error,[%s]\n", szFullPath);
if (strlen(szFullPath) >= _MAX_PATH || dwRet == 0)
{
printf("FullPathName failed.!\n");
}
}
}
if (fp == NULL) return -1;
double opacity = meshFilter->GetPolyActor()->GetProperty()->GetOpacity();
vtkUnsignedCharArray* color_array = meshFilter->GetPolyMapper()->MapScalars(opacity);
//vtkUnsignedCharArray* color_array = Mapper->GetColorMapColors();
int comp = color_array->GetNumberOfComponents();
printf("GetNumberOfComponents:%d Name:[%s]\n", comp, color_array->GetName());
printf("GetNumberOfValues:%lld %I64d\n", color_array->GetNumberOfValues(), color_array->GetNumberOfValues() / comp);
//for (int i = 0; i < color_array->GetNumberOfValues(); i++)
//{
// printf("%d ", color_array->GetValue(i));
//}
vtkSmartPointer<vtkPoints> vertices = poly->GetOutput()->GetPoints();
vtkSmartPointer<vtkDataArray> verticesArray = vertices->GetData();
long long numberOfVertices = vertices->GetNumberOfPoints();
printf("numberOfVertices:%I64d\n", numberOfVertices);
if (comp >= 3 && numberOfVertices == color_array->GetNumberOfValues() / comp)
{
for (int i = 0; i < numberOfVertices; i++)
{
double x = verticesArray->GetComponent(i, 0);
double y = verticesArray->GetComponent(i, 1);
double z = verticesArray->GetComponent(i, 2);
fprintf(fp, "v %f %f %f", x, y, z);
fprintf(fp, " %.3f %.3f %.3f\n",
color_array->GetComponent(i, 0),
color_array->GetComponent(i, 1),
color_array->GetComponent(i, 2));
}
}
else
{
for (int i = 0; i < numberOfVertices; i++)
{
double x = verticesArray->GetComponent(i, 0);
double y = verticesArray->GetComponent(i, 1);
double z = verticesArray->GetComponent(i, 2);
fprintf(fp, "v %f %f %f\n", x, y, z);
}
}
int numberOfFaces = poly->GetOutput()->GetNumberOfCells();
for (int i = 0; i < numberOfFaces; i++)
{
vtkSmartPointer<vtkIdList> face = vtkSmartPointer<vtkIdList>::New();
poly->GetOutput()->GetCellPoints(i, face);
if (face->GetId(0) == face->GetId(1) || face->GetId(0) == face->GetId(2) || face->GetId(2) == face->GetId(1))
{
continue;
}
int f = face->GetNumberOfIds();
if (f < 3)
{
printf("skipp Faces with fewer than 3 vertices.\n");
continue;
}
fprintf(fp, "f");
for (int j = 0; j < f; j++)
{
fprintf(fp, " %I64d", face->GetId(j) + 1);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("Curvatures obj_file [-t mean|gauss|max|min -range min max -cs color_scheme -no_render] -o output\n");
return -99;
}
vtkObject::SetGlobalWarningDisplay(0);
std::string type = "";
int scalarRange_set = 0;
int scheme = 15;
int no_render = 0;
int render_only = 0;
double scalarRange[2];
char* file1 = NULL;
char* output = NULL;
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-t") == 0)
{
if (strcmp("mean", argv[i + 1]) == 0) type = argv[i + 1];
if (strcmp("gauss", argv[i + 1]) == 0) type = argv[i + 1];
if (strcmp("max", argv[i + 1]) == 0) type = argv[i + 1];
if (strcmp("min", argv[i + 1]) == 0) type = argv[i + 1];
i++;
continue;
}
if (strcmp(argv[i], "-o") == 0)
{
output = argv[i + 1];
i++;
continue;
}
else if (strcmp(argv[i], "-no_render") == 0)
{
no_render = 1;
render_only = 0;
}
else if (strcmp(argv[i], "-render_only") == 0)
{
no_render = 0;
render_only = 1;
}
else if (strcmp(argv[i], "-cs") == 0)
{
scheme = atoi(argv[i + 1]);
if (scheme < 0 || scheme > 60)
{
scheme = 15;
}
i++;
continue;
}
else if (strcmp(argv[i], "-range") == 0)
{
scalarRange_set++;
scalarRange[0] = atof(argv[i + 1]);
i++;
scalarRange[1] = atof(argv[i + 1]);
i++;
if (scalarRange[0] == scalarRange[1])
{
scalarRange_set = 0;
printf("scalarRange auto!!\n");
}
continue;
}
else if (file1 == NULL) file1 = argv[i];
}
if (file1 == NULL)
{
return -1;
}
if (output == NULL)
{
return -3;
}
gmrVTKImportOBJ* polygon1 = new gmrVTKImportOBJ(file1);
polygon1->Get()->Update();
gmrVTKMeshFilter* meshFilter = new gmrVTKMeshFilter;
int stat = 0;
meshFilter->SetPoly(polygon1->Get());
vtkSmartPointer<vtkCurvatures> curvaturesFilter = meshFilter->curvaturesFilter(type, scalarRange, scheme, stat);
if (stat != 0)
{
return stat;
}
gmrVTKRender* render = new gmrVTKRender();
render->AddActor(meshFilter->GetPolyActor());
render->GetRenderer()->AddViewProp(meshFilter->Get_curvatures_scalarBar());
gmrVTKText* text2d = new gmrVTKText;
char testbuf[128];
sprintf(testbuf, "max:%.3f min:%.3f ave:%.3f", meshFilter->max_curvature, meshFilter->min_curvature, meshFilter->av_curvature / curvaturesFilter->GetOutput()->GetPointData()->GetScalars()->GetNumberOfTuples());
text2d->SetText(testbuf);
text2d->SetColor(0.0, 0.0, 0.0);
text2d->SetSize(15);
text2d->SetPosition(20, 20);
render->AddActor(text2d->GetActor());
printf("render_only:%d\n", render_only);
if (!render_only)
{
int stat = exportVertexColorOBJ(output, meshFilter, curvaturesFilter);
if (stat != 0)
{
gmrVTKExportOBJ* expoter = new gmrVTKExportOBJ();
char* p = strstr(output, ".obj");
if (p) *p = '\0';
p = strstr(output, ".OBJ");
if (p) *p = '\0';
expoter->SaveFile(render, output);
delete expoter;
}
//PLY export
if (1)
{
gmrVTKExportPLY* plyexpoter = new gmrVTKExportPLY();
char* p = strstr(output, ".obj");
if (p) *p = '\0';
p = strstr(output, ".OBJ");
if (p) *p = '\0';
std::string debug_file = output;
debug_file += "_debug";
char array_name[32];
strcpy(array_name, curvaturesFilter->GetOutput()->GetPointData()->GetScalars()->GetName());
int comp = curvaturesFilter->GetOutput()->GetPointData()->GetScalars()->GetNumberOfComponents();
printf("GetNumberOfComponents:%d Name:[%s]\n", comp, array_name);
plyexpoter->Get()->SetArrayName(array_name);
plyexpoter->Get()->SetLookupTable(meshFilter->GetPolyMapper()->GetLookupTable());
//plyexpoter->SaveFile(Mapper->GetOutputPort(), array_name, output);
plyexpoter->SaveFile(curvaturesFilter->GetOutputPort(), array_name, (char*)debug_file.c_str());
//plyexpoter->SaveFile(polygon1->Get()->GetOutputPort(), color_array->GetName(), output);
delete plyexpoter;
}
}
if (!no_render || render_only)
{
#if 0
char testbuf[128];
vtkSmartPointer<vtkColorSeries> colorSeries = vtkSmartPointer<vtkColorSeries>::New();
colorSeries->SetColorScheme(scheme);
gmrVTKText* text2d = new gmrVTKText;
sprintf(testbuf, "Using color scheme[%d][%s]", colorSeries->GetColorScheme(), colorSeries->GetColorSchemeName().c_str());
render->Run(); //get Window size!!
int* win_size = render->GetRenderWindow()->GetScreenSize();
printf("%dx%d\n", win_size[0], win_size[1]);
text2d->SetText(testbuf);
text2d->SetColor(0.0, 0.0, 0.0);
text2d->SetSize(15);
text2d->SetPosition(10, win_size[1]-20);
render->AddActor(text2d->GetActor());
#if 0
sprintf(testbuf, "%d", colorSeries->GetColorScheme());
gmrVTKText* text2d0 = new gmrVTKText;
text2d0->SetText(testbuf);
text2d0->SetColor(0.0, 0.0, 0.0);
text2d0->SetSize(15*10);
text2d0->SetPosition(30, win_size[1]);
render->AddActor(text2d0->GetActor());
#endif
render->Run();
render->GetRenderWindow()->SetWindowName("curvature");
// Screenshot
vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
vtkSmartPointer<vtkWindowToImageFilter>::New();
windowToImageFilter->SetInput(render->GetRenderWindow());
windowToImageFilter->SetMagnification(3); //set the resolution of the output image (3 times the current resolution of vtk render window)
windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
windowToImageFilter->Update();
vtkSmartPointer<vtkPNGWriter> writer =
vtkSmartPointer<vtkPNGWriter>::New();
char screenshotName[128];
sprintf(screenshotName, "screenshot_colorScheme%02d.png", colorSeries->GetColorScheme());
writer->SetFileName(screenshotName);
writer->SetInputConnection(windowToImageFilter->GetOutputPort());
writer->Write();
//exit(0);
#endif
render->DefaultRun("curvature");
}
delete meshFilter;
delete polygon1;
} | 28.140187 | 211 | 0.661242 | [
"render"
] |
9faa6cb42d3d662e26cd3400aa4e3bc8c24f862d | 6,180 | cpp | C++ | openFrameworks/apps/Ray Tracing Renderer/src/rtGraphics/rtRenderThreadPool.cpp | AlexWolski/Ray-Tracing-Renderer | c52a82fabaef937686da89df0c46501cbbce0a17 | [
"MIT"
] | null | null | null | openFrameworks/apps/Ray Tracing Renderer/src/rtGraphics/rtRenderThreadPool.cpp | AlexWolski/Ray-Tracing-Renderer | c52a82fabaef937686da89df0c46501cbbce0a17 | [
"MIT"
] | null | null | null | openFrameworks/apps/Ray Tracing Renderer/src/rtGraphics/rtRenderThreadPool.cpp | AlexWolski/Ray-Tracing-Renderer | c52a82fabaef937686da89df0c46501cbbce0a17 | [
"MIT"
] | null | null | null | #include "rtRenderThreadPool.h"
namespace rtGraphics
{
///Static data member initialization
//Set the number of threads to the number of cores on the machine
int rtRenderThreadPool::numThreads = thread::hardware_concurrency();
RenderThreadData::RenderThreadData(renderMode RenderMode, shared_ptr<rtScene>scene, rtVec3f& camPos, float nearClip, float farClip,
int maxBounces, ofPixels* bufferPixels, rtVec3f& firstPoint, rtVec3f& hStep, rtVec3f& vStep)
{
this->RenderMode = RenderMode;
//Scene data
this->objects = scene->getObjects();
this->lights = scene->getLights();
//Camera Data
this->camPos = camPos;
this->nearClip = nearClip;
this->farClip = farClip;
this->maxBounces = maxBounces;
//Buffer data
this->bufferPixels = bufferPixels;
this->bufferWidth = bufferPixels->getWidth();
this->bufferHeight = bufferPixels->getHeight();
//Ray iteration data
this->firstPoint = firstPoint;
this->hStep = hStep;
this->vStep = vStep;
}
//Renders a section of the frame buffer
void RenderThread::threadedFunction()
{
//The current index in the buffer pixels array
int bufferIndex = sharedData->bufferWidth * startRow * 3;
//The first grid point of the current row. This vector stays on the left edge of the near clip plane and moves downwards
rtVec3f currRow = sharedData->firstPoint + (sharedData->vStep * startRow);
//The current grid point. This vector is in the same row as currRowStart and moves to the right
rtVec3f R = currRow;
//The direction vector from the camera to the current point
rtVec3f D;
//Iterate over all the grid points
for (int row = startRow; row < endRow; row++)
{
for (int col = 0; col < sharedData->bufferPixels->getWidth(); col++)
{
//Find new direction vector
D = (R - sharedData->camPos).normalize();
rtColorf pixelColor;
//There is no origin point for a camera ray
rtRayHit originPoint;
originPoint.hit = false;
//Calculate the pixel color based on the current render mode
switch (sharedData->RenderMode)
{
case renderMode::rayTrace:
pixelColor = rtRenderer::rayTrace(sharedData->objects, sharedData->lights, sharedData->camPos, D, sharedData->nearClip, sharedData->farClip, 0, sharedData->maxBounces, originPoint);
break;
case renderMode::rayMarch:
//To-Do: Implement ray marching
pixelColor = rtRenderer::rayMarch(sharedData->objects, sharedData->lights, sharedData->camPos, D, sharedData->nearClip, sharedData->farClip, 0, sharedData->maxBounces, originPoint);
break;
default:
//If no render mode is selected, set it to black
pixelColor = rtColorf::black;
}
//Write the color to the pixel buffer
(*sharedData->bufferPixels)[bufferIndex++] = (int)(pixelColor.getR() * 255.0f);
(*sharedData->bufferPixels)[bufferIndex++] = (int)(pixelColor.getG() * 255.0f);
(*sharedData->bufferPixels)[bufferIndex++] = (int)(pixelColor.getB() * 255.0f);
//Iterate to the next column
R += sharedData->hStep;
}
//After a row is completed, move to the next row
currRow += sharedData->vStep;
R = currRow;
}
}
rtRenderThreadPool::rtRenderThreadPool()
{
//Instantiate the thread pool
threadPool = make_unique<RenderThread[]>(numThreads);
}
void rtRenderThreadPool::setData(renderMode RenderMode, shared_ptr<rtScene> scene, rtVec3f& camPos, rtVec3f& u, rtVec3f& v, rtVec3f& n,
float hFov, float nearClip, float farClip, int maxBounces, ofPixels* bufferPixels)
{
//Cache the pixel buffer dimensions as floats
float bufferWidth = bufferPixels->getWidth();
float bufferHeight = bufferPixels->getHeight();
//The width and height of the near clip plane based on the FOV and distance to the clip plane
float halfClipWidth = sin(degToRad(hFov / 2)) * nearClip;
float halfClipHeight = halfClipWidth * (bufferHeight / bufferWidth);
//Calculate the point in the center of the near clip plane using the camera position and look vector
rtVec3f clipCenter = camPos + (-n * nearClip);
//Get the vectors pointing from the center of the screen to the left edge and top edge of the near clip plane
rtVec3f widthVector = u * halfClipWidth;
rtVec3f heightVector = v * halfClipHeight;
//The distance between each grid point of the near clip plane in world space
rtVec3f hStep = (widthVector * -2) / bufferWidth;
rtVec3f vStep = (heightVector * -2) / bufferHeight;
//The first grid point, at the top-left corner
rtVec3f firstPoint = clipCenter + widthVector + heightVector;
//Save the scene data and render settings in a struct
sharedData = make_shared<RenderThreadData>(RenderMode, scene, camPos, nearClip, farClip, maxBounces, bufferPixels, firstPoint, hStep, vStep);
//The minimum number of rows each thread will render
int baseRows = bufferHeight / numThreads;
//The number of threads that will render an additional row
int extraRows = bufferHeight - (numThreads * baseRows);
//The starting row of the next section
int sectionStart = 0;
//Spawn threads to render all of the image
for (int threadIndex = 0; threadIndex < numThreads; threadIndex++)
{
//Calculate the end of the section
int sectionEnd = sectionStart + baseRows;
//Add an extra row until all the extra rows are allocated
if (threadIndex < extraRows)
sectionEnd++;
//Set the shared data and section to render
threadPool[threadIndex].setData(sharedData);
threadPool[threadIndex].setSection(sectionStart, sectionEnd);
//Move onto the next section
sectionStart = sectionEnd;
}
}
void rtRenderThreadPool::startThreads()
{
for (int threadIndex = 0; threadIndex < numThreads; threadIndex++)
if (!threadPool[threadIndex].isThreadRunning())
threadPool[threadIndex].startThread();
}
void rtRenderThreadPool::joinThreads()
{
for (int threadIndex = 0; threadIndex < numThreads; threadIndex++)
if (threadPool[threadIndex].isThreadRunning())
threadPool[threadIndex].waitForThread();
}
bool rtRenderThreadPool::threadsRunning()
{
for (int threadIndex = 0; threadIndex < numThreads; threadIndex++)
if (~threadPool[threadIndex].isThreadRunning())
return false;
return true;
}
} | 35.930233 | 186 | 0.721521 | [
"render",
"vector"
] |
9fb2b2926a6beb2be44f1404f4c880af2e0164fe | 1,550 | cpp | C++ | Source/MarmotteUnrealGD/FireBallCapacityComponent.cpp | FelixPog/Guard-of-City | a05adc94def66cd4423c740a53e6dd460ce84590 | [
"Apache-2.0"
] | null | null | null | Source/MarmotteUnrealGD/FireBallCapacityComponent.cpp | FelixPog/Guard-of-City | a05adc94def66cd4423c740a53e6dd460ce84590 | [
"Apache-2.0"
] | null | null | null | Source/MarmotteUnrealGD/FireBallCapacityComponent.cpp | FelixPog/Guard-of-City | a05adc94def66cd4423c740a53e6dd460ce84590 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "FireBallCapacityComponent.h"
#include "FireBallProjectile.h"
#include "PlayerCharacter.h"
#include "Kismet/GameplayStatics.h"
bool UFireBallCapacityComponent::UseCapacity()
{
if (!IsCapacityReady)
{
return false;
}
//try and fire a projectile
if (ProjectileClass != nullptr)
{
UWorld* const World = GetWorld();
APlayerCharacter* PlayerCharacter = static_cast<APlayerCharacter *>(UGameplayStatics::GetPlayerPawn(World, 0));
if (World != nullptr)
{
const FRotator SpawnRotation = PlayerCharacter->GetControlRotation();
// MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle position
const FVector SpawnLocation = ((PlayerCharacter != nullptr) ? PlayerCharacter->GetFPMuzzleLocation()->GetComponentLocation() : PlayerCharacter->GetActorLocation()) + SpawnRotation.RotateVector(PlayerCharacter->GunOffset);
//Set Spawn Collision Handling Override
FActorSpawnParameters ActorSpawnParams;
ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
// spawn the projectile at the muzzle
World->SpawnActor<AFireBallProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);
if (CapacitySound != nullptr)
{
UGameplayStatics::PlaySoundAtLocation(this, CapacitySound, GetOwner()->GetActorLocation());
}
StartCooldown();
return true;
}
}
return false;
}
| 32.978723 | 224 | 0.769032 | [
"transform"
] |
9fb7078aa9cc0a79fa4b673e6d1ebb59a112b3e6 | 8,528 | cpp | C++ | src/adtfUser/katana_mission_control/src/mission_control/LateralController.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/katana_mission_control/src/mission_control/LateralController.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/katana_mission_control/src/mission_control/LateralController.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// This file was taken from the Open Autonomous Driving Library
// This file is part of the Open Autonomous Driving Library.
//
// This program is free software licensed under the CDDL
// (COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0).
// You can find a copy of this license in LICENSE.txt in the top
// directory of the source code.
//
// © Copyright 2015 FZI Forschungszentrum Informatik, Karlsruhe, Germany
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Raphael Frisch <frisch@fzi.de>
* \date 2014-11-15
*
* \author Christoph Rist <rist@fzi.de>
* \date 2015-01-08
*
*/
//----------------------------------------------------------------------
#include "LateralController.h"
#include <cmath>
#include <oadrive_core/Interpolator.h>
#ifdef KATANA_MC_LATERAL_CONTROLLER_DEBUG
#include <iostream>
#endif
using namespace oadrive::core;
namespace katana
{
const Position2d LateralController::STRAIGHT = Position2d(1.0, 0.0);
LateralController::LateralController()
: m_reached(true)
{
m_trajectory.isForwardTrajectory() = true;
}
float LateralController::calculateSteering(const Pose2d &vehicle_pose)
{
assert(m_trajectory.size() >= MIN_EXTENDED_POINTS_NEEDED_FOR_LATERAL_CONTROLLER);
assert(m_trajectory.curvatureAvailable());
updatePosAndCheckForReached(vehicle_pose);
Controller(PoseTraits<Pose2d>::yaw(vehicle_pose), m_projected.getYaw(), m_projected.getCurvature(), m_distance);
#ifdef KATANA_MC_LATERAL_CONTROLLER_DEBUG
static u_int32_t counter = 0;
if (counter % 10 == 0)
std::cout <<"LateralController [calculateSteering] - Calculated delta " <<m_delta <<" from " <<m_trajectory.size() <<" points." <<std::endl;
counter++;
#endif
return m_delta;
}
void LateralController::updatePosAndCheckForReached(const Pose2d& vehicle_pose)
{
calculateProjection(m_trajectory, vehicle_pose.translation(), m_projected, m_distance, m_nearest_point_index);
// check if at end of trajectory
const bool position_good_enough = m_distance < 0.5 && (m_projected.getYaw() - PoseTraits<Pose2d>::yaw(vehicle_pose)) < M_PI/3;
if (position_good_enough && (m_projected.getPosition() - m_trajectory.back().getPosition()).norm() < REACHED_ZONE_DISTANCE)
{
m_reached = true;
}
// check custom position
checkReachedPoints();
#ifdef KATANA_MC_LATERAL_CONTROLLER_DEBUG
static u_int32_t counter = 0;
if (counter % 10 == 0)
{
std::cout <<"Position: " <<vehicle_pose <<" Projected: " <<m_projected <<std::endl;
std::cout <<"Reached distance: " <<(m_projected.getPosition() - m_trajectory.back().getPosition()).norm() <<std::endl;
}
counter++;
#endif
}
bool LateralController::calculateProjection(const Trajectory2d& trajectory, const Position2d& position, ExtendedPose2d& projection,
double& distance, std::size_t& nearest_pose_index) const
{
float dist1, dist2, ratio, curr_distance_squared;
float t;
float shortest_distance_squared = std::numeric_limits<float>::infinity();
bool shortest_distance_found_before_first_point = true;
nearest_pose_index = 0;
const double& xP = position.x();
const double& yP = position.y();
for( u_int32_t i = 0; i < trajectory.size()-1 ; ++i)
{
const double& x1 = trajectory[i].getX();
const double& y1 = trajectory[i].getY();
const double& x2 = trajectory[i+1].getX();
const double& y2 = trajectory[i+1].getY();
_position_type Xnew, Ynew;
const double& APx = xP - x1;
const double& APy = yP - y1;
const double& ABx = x2 - x1;
const double& ABy = y2 - y1;
const double& magAB2 = ABx*ABx + ABy*ABy;
const double& ABdotAP = ABx*APx + ABy*APy;
t = ABdotAP / magAB2;
if ( t < 0)
{
Xnew = x1;
Ynew = y1;
}
else if (t > 1)
{
Xnew = x2;
Ynew = y2;
}
else
{
Xnew = x1 + ABx*t;
Ynew = y1 + ABy*t;
}
_position_type a = (xP - Xnew)*(xP - Xnew);
_position_type b = (yP - Ynew)*(yP - Ynew);
curr_distance_squared = (a + b);
if (curr_distance_squared < shortest_distance_squared)
{
shortest_distance_squared = curr_distance_squared;
shortest_distance_found_before_first_point = (i == 0 && t < 0);
nearest_pose_index = i;
dist1 = sqrt((Xnew - x1)*(Xnew - x1) + (Ynew - y1)*(Ynew - y1));
dist2 = sqrt((Xnew - x2)*(Xnew - x2) + (Ynew - y2)*(Ynew - y2));
ratio = dist1/(dist1+dist2);
}
}
// A-B:
const Eigen::Vector2d vector_ab = trajectory[nearest_pose_index].getPose().rotation() * STRAIGHT;
// A-Vehicle
const Eigen::Vector2d vector_a_vehicle = position - trajectory[nearest_pose_index].getPosition();
// pose of the car is before the beginning of the trajectory -> use distance to projection on AB-Vector
if (shortest_distance_found_before_first_point)
{
// copy speed and curvature from first point
projection = trajectory.front();
// Projection
const double t = vector_a_vehicle.dot(vector_ab)/vector_ab.squaredNorm();
projection.setPosition(trajectory[0].getPosition() + vector_ab * t);
// Calculate distance
distance = (projection.getPosition() - position).norm();
}
else
{
//calculate projected pose
projection = oadrive::core::Interpolator::interpolateLinear(trajectory[nearest_pose_index], trajectory[nearest_pose_index+1], ratio);
// distance calculation
distance = sqrt(shortest_distance_squared);
}
//Sign of distance
Eigen::Matrix<double, 2, 2> m;
m.col(0) <<vector_ab;
m.col(1) <<vector_a_vehicle;
// If the determinant is negative, the point lies on the right hand to the line
if (m.determinant() > 0.0)
distance = -distance;
return shortest_distance_found_before_first_point;
}
void LateralController::Controller(double psiArg, double thetaArg, double kappaArg, double distanceArg)
{
// Vorsteuerung
float vorsteuerung = (float)-(((AFTER_ATAN * atan(BEFORE_ATAN*WHEELBASE*kappaArg))*180)/M_PI);
// Winkel
float angleFinal = -KD * NormalizeAngle(thetaArg - psiArg);
if (!m_trajectory.isForwardTrajectory())
angleFinal = -angleFinal;
// Distanz
float distFinal = -/*AdaptRefPointFuction(velocityArg) * */ WEIGHTING_DISTANCE * SignedFunction(distanceArg);
#ifdef KATANA_MC_LATERAL_CONTROLLER_DEBUG
static u_int32_t counter = 0;
if (counter % 10 == 0)
std::cout <<"LateralController [Controller] - vorsteuerung: " <<vorsteuerung <<" angleFinal: " <<angleFinal
<<" distFinal: " <<distFinal <<" distanceArg: " <<distanceArg <<" kappa: " <<kappaArg <<std::endl;
counter++;
#endif
m_delta = vorsteuerung + angleFinal + distFinal;
if(m_delta > 100)
m_delta = 100;
else if(m_delta < -100)
m_delta = -100;
}
float LateralController::NormalizeAngle(float angleArg)
{
while (std::abs(angleArg) > M_PI)
{
angleArg = (angleArg >= 0) ? angleArg - 2*M_PI : angleArg + 2*M_PI;
}
angleArg = angleArg * 100 / M_PI;
return angleArg;
}
float LateralController::SignedFunction(float numArg)
{
float res = numArg/SIGN_FCT_LIMIT*MAX_FUNCTION;
if (res > MAX_FUNCTION)
res = MAX_FUNCTION;
else if (res < -MAX_FUNCTION)
res = -MAX_FUNCTION;
return res;
}
void LateralController::checkReachedPoints()
{
for (u_int8_t i = 0; i < (u_int8_t)REACHED_POINT::RP_COUNT; i++)
{
if (!m_reached_positions[i].reached)
{
if ((m_projected.getPosition() - m_reached_positions[i].position).norm() < m_reached_positions[i].reached_distance)
m_reached_positions[i].reached = true;
}
}
}
/*float LateralController::AdaptRefPointFuction(float numArg)
{
//TODO for calibration
return 1;
//return numArg;
float res = numArg;
if(abs (numArg) > REF_POINT_2){
res = 0;
}
if((abs (numArg) > REF_POINT_1) && (abs(numArg) < REF_POINT_2)){
res = (1-((abs(numArg)-REF_POINT_1)/(REF_POINT_2-REF_POINT_1))) * abs(numArg);
}
if(abs(numArg) < REF_POINT_1) res = 1;
return res;
}*/
} // ns
| 29.508651 | 145 | 0.638602 | [
"vector"
] |
9fb8e0ae548e6b511326dcc05d96aabda63b9249 | 2,060 | cpp | C++ | leetcode/weekly/236.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/weekly/236.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/weekly/236.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: April 11th, 2021
Successful submissions : 0
Time expiration : 0
Not Solved : 0
Wrong Answer/ Partial result : 0
Note: Solved it after the contest as I could not make it!!. Able to solve only 1!!
link: https://leetcode.com/contest/weekly-contest-236
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
using namespace std;
/*
Q: 1822. Sign of the Product of an Array
*/
class Solution1_t
{
public:
int arraySign(vector<int>& nums)
{
long long ans = 1;
for(int& n : nums)
{
if(n == 0)
{
return 0;
}
ans = (ans * n) > 0 ? 1 : -1;
}
return ans;
}
};
/*
Q: 1823. Find the Winner of the Circular Game - not working!! problem is always taking from the beginning!!
*/
class Solution2_t
{
public:
int findTheWinner(int n, int k)
{
if(k == 1)
{
return n;
}
vector<int> nums;
int i = 1;
while(i <= n)
{
nums.push_back(i);
i++;
}
while(nums.size() > 1)
{
if(nums.size() >= k)
{
nums.erase(nums.begin() + k - 1);
}
else
{
k = k % nums.size();
}
if(k == 1)
{
return nums.back();
}
}
return nums[0];
}
};
/*
Q: 1824. Minimum Sideway Jumps
*/
class Solution3_t
{
public:
int minSideJumps(vector<int>& obstacles)
{
}
};
/*
Q: 1825. Finding MK Average
*/
class MKAverage {
public:
MKAverage(int m, int k) {
}
void addElement(int num) {
}
int calculateMKAverage() {
}
};
/**
* Your MKAverage object will be instantiated and called as such:
* MKAverage* obj = new MKAverage(m, k);
* obj->addElement(num);
* int param_2 = obj->calculateMKAverage();
*/
| 15.846154 | 109 | 0.520874 | [
"object",
"vector"
] |
9fc75d2169df3ec47096d63da6195a44881a8bc3 | 531 | hpp | C++ | libs/core/include/fcppt/signal/object_fwd.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/signal/object_fwd.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/signal/object_fwd.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2017.
// Copyright Philipp Middendorf 2009 - 2017.
// 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 FCPPT_SIGNAL_OBJECT_FWD_HPP_INCLUDED
#define FCPPT_SIGNAL_OBJECT_FWD_HPP_INCLUDED
#include <fcppt/signal/base_fwd.hpp>
namespace fcppt::signal
{
template <typename T, template <typename> class Base = fcppt::signal::base>
class object;
}
#endif
| 26.55 | 75 | 0.73258 | [
"object"
] |
9fca6040d489a4ad299feee7107147d4dc6d8856 | 11,501 | cpp | C++ | Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-01-31T08:15:30.000Z | 2022-01-31T08:15:30.000Z | Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <GemCatalog/GemCatalogHeaderWidget.h>
#include <AzCore/std/functional.h>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QLabel>
#include <QPushButton>
#include <TagWidget.h>
namespace O3DE::ProjectManager
{
CartOverlayWidget::CartOverlayWidget(GemModel* gemModel, QWidget* parent)
: QWidget(parent)
, m_gemModel(gemModel)
{
setObjectName("GemCatalogCart");
m_layout = new QVBoxLayout();
m_layout->setSpacing(0);
m_layout->setMargin(5);
m_layout->setAlignment(Qt::AlignTop);
setLayout(m_layout);
QHBoxLayout* hLayout = new QHBoxLayout();
QPushButton* closeButton = new QPushButton();
closeButton->setFlat(true);
closeButton->setFocusPolicy(Qt::NoFocus);
closeButton->setIcon(QIcon(":/WindowClose.svg"));
connect(closeButton, &QPushButton::clicked, this, [=]
{
deleteLater();
});
hLayout->addSpacerItem(new QSpacerItem(10, 0, QSizePolicy::Expanding));
hLayout->addWidget(closeButton);
m_layout->addLayout(hLayout);
// added
CreateGemSection( tr("Gem to be activated"), tr("Gems to be activated"), [=]
{
QVector<QModelIndex> gems;
const QVector<QModelIndex> toBeAdded = m_gemModel->GatherGemsToBeAdded(/*includeDependencies=*/false);
// don't include gems that were already active because they were dependencies
for (const QModelIndex& modelIndex : toBeAdded)
{
if (!GemModel::WasPreviouslyAddedDependency(modelIndex))
{
gems.push_back(modelIndex);
}
}
return gems;
});
// removed
CreateGemSection( tr("Gem to be deactivated"), tr("Gems to be deactivated"), [=]
{
QVector<QModelIndex> gems;
const QVector<QModelIndex> toBeAdded = m_gemModel->GatherGemsToBeRemoved(/*includeDependencies=*/false);
// don't include gems that are still active because they are dependencies
for (const QModelIndex& modelIndex : toBeAdded)
{
if (!GemModel::IsAddedDependency(modelIndex))
{
gems.push_back(modelIndex);
}
}
return gems;
});
// added dependencies
CreateGemSection( tr("Dependency to be activated"), tr("Dependencies to be activated"), [=]
{
QVector<QModelIndex> dependencies;
const QVector<QModelIndex> toBeAdded = m_gemModel->GatherGemsToBeAdded(/*includeDependencies=*/true);
// only include gems that are dependencies and not explicitly added
for (const QModelIndex& modelIndex : toBeAdded)
{
if (GemModel::IsAddedDependency(modelIndex) && !GemModel::IsAdded(modelIndex))
{
dependencies.push_back(modelIndex);
}
}
return dependencies;
});
// removed dependencies
CreateGemSection( tr("Dependency to be deactivated"), tr("Dependencies to be deactivated"), [=]
{
QVector<QModelIndex> dependencies;
const QVector<QModelIndex> toBeRemoved = m_gemModel->GatherGemsToBeRemoved(/*includeDependencies=*/true);
// don't include gems that were explicitly removed - those are listed in a different section
for (const QModelIndex& modelIndex : toBeRemoved)
{
if (!GemModel::WasPreviouslyAdded(modelIndex))
{
dependencies.push_back(modelIndex);
}
}
return dependencies;
});
setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
}
void CartOverlayWidget::CreateGemSection(const QString& singularTitle, const QString& pluralTitle, GetTagIndicesCallback getTagIndices)
{
QWidget* widget = new QWidget();
widget->setFixedWidth(s_width);
m_layout->addWidget(widget);
QVBoxLayout* layout = new QVBoxLayout();
layout->setAlignment(Qt::AlignTop);
widget->setLayout(layout);
QLabel* label = new QLabel();
label->setObjectName("GemCatalogCartOverlaySectionLabel");
layout->addWidget(label);
TagContainerWidget* tagContainer = new TagContainerWidget();
layout->addWidget(tagContainer);
auto update = [=]()
{
const QVector<QModelIndex> tagIndices = getTagIndices();
if (tagIndices.isEmpty())
{
widget->hide();
}
else
{
tagContainer->Update(ConvertFromModelIndices(tagIndices));
label->setText(QString("%1 %2").arg(tagIndices.size()).arg(tagIndices.size() == 1 ? singularTitle : pluralTitle));
widget->show();
}
};
connect(m_gemModel, &GemModel::dataChanged, this, update);
update();
}
QStringList CartOverlayWidget::ConvertFromModelIndices(const QVector<QModelIndex>& gems) const
{
QStringList gemNames;
gemNames.reserve(gems.size());
for (const QModelIndex& modelIndex : gems)
{
gemNames.push_back(GemModel::GetDisplayName(modelIndex));
}
return gemNames;
}
CartButton::CartButton(GemModel* gemModel, QWidget* parent)
: QWidget(parent)
, m_gemModel(gemModel)
{
m_layout = new QHBoxLayout();
m_layout->setMargin(0);
setLayout(m_layout);
QPushButton* iconButton = new QPushButton();
iconButton->setFlat(true);
iconButton->setFocusPolicy(Qt::NoFocus);
iconButton->setIcon(QIcon(":/Summary.svg"));
iconButton->setFixedSize(s_iconSize, s_iconSize);
connect(iconButton, &QPushButton::clicked, this, &CartButton::ShowOverlay);
m_layout->addWidget(iconButton);
m_countLabel = new QLabel();
m_countLabel->setObjectName("GemCatalogCartCountLabel");
m_countLabel->setFixedHeight(s_iconSize - 1); // Compensate for the empty icon space by using a slightly smaller label height.
m_layout->addWidget(m_countLabel);
m_dropDownButton = new QPushButton();
m_dropDownButton->setFlat(true);
m_dropDownButton->setFocusPolicy(Qt::NoFocus);
m_dropDownButton->setIcon(QIcon(":/CarrotArrowDown.svg"));
m_dropDownButton->setFixedSize(s_arrowDownIconSize, s_arrowDownIconSize);
connect(m_dropDownButton, &QPushButton::clicked, this, &CartButton::ShowOverlay);
m_layout->addWidget(m_dropDownButton);
// Adjust the label text whenever the model gets updated.
connect(gemModel, &GemModel::dataChanged, [=]
{
const QVector<QModelIndex> toBeAdded = m_gemModel->GatherGemsToBeAdded(/*includeDependencies=*/true);
const QVector<QModelIndex> toBeRemoved = m_gemModel->GatherGemsToBeRemoved(/*includeDependencies=*/true);
const int count = toBeAdded.size() + toBeRemoved.size();
m_countLabel->setText(QString::number(count));
m_dropDownButton->setVisible(!toBeAdded.isEmpty() || !toBeRemoved.isEmpty());
// Automatically close the overlay window in case there are no gems to be activated or deactivated anymore.
if (m_cartOverlay && toBeAdded.isEmpty() && toBeRemoved.isEmpty())
{
m_cartOverlay->deleteLater();
m_cartOverlay = nullptr;
}
});
}
void CartButton::mousePressEvent([[maybe_unused]] QMouseEvent* event)
{
ShowOverlay();
}
void CartButton::hideEvent(QHideEvent*)
{
if (m_cartOverlay)
{
m_cartOverlay->hide();
}
}
void CartButton::ShowOverlay()
{
const QVector<QModelIndex> toBeAdded = m_gemModel->GatherGemsToBeAdded(/*includeDependencies=*/true);
const QVector<QModelIndex> toBeRemoved = m_gemModel->GatherGemsToBeRemoved(/*includeDependencies=*/true);
if (toBeAdded.isEmpty() && toBeRemoved.isEmpty())
{
return;
}
if (m_cartOverlay)
{
// Directly delete the former overlay before creating the new one.
// Don't use deleteLater() here. This might overwrite the new overlay pointer
// depending on the event queue.
delete m_cartOverlay;
}
m_cartOverlay = new CartOverlayWidget(m_gemModel, this);
connect(m_cartOverlay, &QWidget::destroyed, this, [=]
{
// Reset the overlay pointer on destruction to prevent dangling pointers.
m_cartOverlay = nullptr;
});
m_cartOverlay->show();
const QPoint parentPos = m_dropDownButton->mapToParent(m_dropDownButton->pos());
const QPoint globalPos = m_dropDownButton->mapToGlobal(m_dropDownButton->pos());
const QPoint offset(-4, 10);
m_cartOverlay->setGeometry(globalPos.x() - parentPos.x() - m_cartOverlay->width() + width() + offset.x(),
globalPos.y() + offset.y(),
m_cartOverlay->width(),
m_cartOverlay->height());
}
CartButton::~CartButton()
{
// Make sure the overlay window is automatically closed in case the gem catalog is destroyed.
if (m_cartOverlay)
{
m_cartOverlay->deleteLater();
}
}
GemCatalogHeaderWidget::GemCatalogHeaderWidget(GemModel* gemModel, GemSortFilterProxyModel* filterProxyModel, QWidget* parent)
: QFrame(parent)
{
QHBoxLayout* hLayout = new QHBoxLayout();
hLayout->setAlignment(Qt::AlignLeft);
hLayout->setContentsMargins(10, 7, 10, 7);
setLayout(hLayout);
setObjectName("GemCatalogHeaderWidget");
setFixedHeight(s_height);
QLabel* titleLabel = new QLabel(tr("Gem Catalog"));
titleLabel->setObjectName("GemCatalogTitle");
hLayout->addWidget(titleLabel);
hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding));
m_filterLineEdit = new AzQtComponents::SearchLineEdit();
m_filterLineEdit->setStyleSheet("background-color: #DDDDDD;");
connect(m_filterLineEdit, &QLineEdit::textChanged, this, [=](const QString& text)
{
filterProxyModel->SetSearchString(text);
});
hLayout->addWidget(m_filterLineEdit);
hLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding));
hLayout->addSpacerItem(new QSpacerItem(75, 0, QSizePolicy::Fixed));
CartButton* cartButton = new CartButton(gemModel);
hLayout->addWidget(cartButton);
}
void GemCatalogHeaderWidget::ReinitForProject()
{
m_filterLineEdit->setText({});
}
} // namespace O3DE::ProjectManager
| 37.708197 | 139 | 0.601426 | [
"model",
"3d"
] |
9fcb9d50c0702607f3a09fcbef71c0fe5b379f39 | 34,745 | cpp | C++ | src/rpcrawtransaction.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | src/rpcrawtransaction.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | src/rpcrawtransaction.cpp | moorecoin/MooreCoinMiningAlgorithm | fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d | [
"MIT"
] | null | null | null | // copyright (c) 2010 satoshi nakamoto
// copyright (c) 2009-2015 the moorecoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "merkleblock.h"
#include "net.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "uint256.h"
#ifdef enable_wallet
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "univalue/univalue.h"
using namespace std;
void scriptpubkeytojson(const cscript& scriptpubkey, univalue& out, bool fincludehex)
{
txnouttype type;
vector<ctxdestination> addresses;
int nrequired;
out.push_back(pair("asm", scriptpubkey.tostring()));
if (fincludehex)
out.push_back(pair("hex", hexstr(scriptpubkey.begin(), scriptpubkey.end())));
if (!extractdestinations(scriptpubkey, type, addresses, nrequired)) {
out.push_back(pair("type", gettxnoutputtype(type)));
return;
}
out.push_back(pair("reqsigs", nrequired));
out.push_back(pair("type", gettxnoutputtype(type)));
univalue a(univalue::varr);
boost_foreach(const ctxdestination& addr, addresses)
a.push_back(cmoorecoinaddress(addr).tostring());
out.push_back(pair("addresses", a));
}
void txtojson(const ctransaction& tx, const uint256 hashblock, univalue& entry)
{
entry.push_back(pair("txid", tx.gethash().gethex()));
entry.push_back(pair("version", tx.nversion));
entry.push_back(pair("locktime", (int64_t)tx.nlocktime));
univalue vin(univalue::varr);
boost_foreach(const ctxin& txin, tx.vin) {
univalue in(univalue::vobj);
if (tx.iscoinbase())
in.push_back(pair("coinbase", hexstr(txin.scriptsig.begin(), txin.scriptsig.end())));
else {
in.push_back(pair("txid", txin.prevout.hash.gethex()));
in.push_back(pair("vout", (int64_t)txin.prevout.n));
univalue o(univalue::vobj);
o.push_back(pair("asm", txin.scriptsig.tostring()));
o.push_back(pair("hex", hexstr(txin.scriptsig.begin(), txin.scriptsig.end())));
in.push_back(pair("scriptsig", o));
}
in.push_back(pair("sequence", (int64_t)txin.nsequence));
vin.push_back(in);
}
entry.push_back(pair("vin", vin));
univalue vout(univalue::varr);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const ctxout& txout = tx.vout[i];
univalue out(univalue::vobj);
out.push_back(pair("value", valuefromamount(txout.nvalue)));
out.push_back(pair("n", (int64_t)i));
univalue o(univalue::vobj);
scriptpubkeytojson(txout.scriptpubkey, o, true);
out.push_back(pair("scriptpubkey", o));
vout.push_back(out);
}
entry.push_back(pair("vout", vout));
if (!hashblock.isnull()) {
entry.push_back(pair("blockhash", hashblock.gethex()));
blockmap::iterator mi = mapblockindex.find(hashblock);
if (mi != mapblockindex.end() && (*mi).second) {
cblockindex* pindex = (*mi).second;
if (chainactive.contains(pindex)) {
entry.push_back(pair("confirmations", 1 + chainactive.height() - pindex->nheight));
entry.push_back(pair("time", pindex->getblocktime()));
entry.push_back(pair("blocktime", pindex->getblocktime()));
}
else
entry.push_back(pair("confirmations", 0));
}
}
}
univalue getrawtransaction(const univalue& params, bool fhelp)
{
if (fhelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nnote: by default this function only works sometimes. this is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. to make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nreturn the raw transaction data.\n"
"\nif verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"if verbose is non-zero, returns an object with information about 'txid'.\n"
"\narguments:\n"
"1. \"txid\" (string, required) the transaction id\n"
"2. verbose (numeric, optional, default=0) if 0, return a string, other return a json object\n"
"\nresult (if verbose is not set or set to 0):\n"
"\"data\" (string) the serialized, hex-encoded data for 'txid'\n"
"\nresult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) the serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) the transaction id (same as provided)\n"
" \"version\" : n, (numeric) the version\n"
" \"locktime\" : ttt, (numeric) the lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) the transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptsig\": { (json object) the script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) the script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) the value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptpubkey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqsigs\" : n, (numeric) the required sigs\n"
" \"type\" : \"pubkeyhash\", (string) the type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"moorecoinaddress\" (string) moorecoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) the confirmations\n"
" \"time\" : ttt, (numeric) the transaction time in seconds since epoch (jan 1 1970 gmt)\n"
" \"blocktime\" : ttt (numeric) the block time in seconds since epoch (jan 1 1970 gmt)\n"
"}\n"
"\nexamples:\n"
+ helpexamplecli("getrawtransaction", "\"mytxid\"")
+ helpexamplecli("getrawtransaction", "\"mytxid\" 1")
+ helpexamplerpc("getrawtransaction", "\"mytxid\", 1")
);
lock(cs_main);
uint256 hash = parsehashv(params[0], "parameter 1");
bool fverbose = false;
if (params.size() > 1)
fverbose = (params[1].get_int() != 0);
ctransaction tx;
uint256 hashblock;
if (!gettransaction(hash, tx, hashblock, true))
throw jsonrpcerror(rpc_invalid_address_or_key, "no information available about transaction");
string strhex = encodehextx(tx);
if (!fverbose)
return strhex;
univalue result(univalue::vobj);
result.push_back(pair("hex", strhex));
txtojson(tx, hashblock, result);
return result;
}
univalue gettxoutproof(const univalue& params, bool fhelp)
{
if (fhelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nreturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nnote: by default this function only works sometimes. this is when there is an\n"
"unspent output in the utxo for this transaction. to make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included in manually (by blockhash).\n"
"\nreturn the raw transaction data.\n"
"\narguments:\n"
"1. \"txids\" (string) a json array of txids to filter\n"
" [\n"
" \"txid\" (string) a transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) if specified, looks for txid in the block with this hash\n"
"\nresult:\n"
"\"data\" (string) a string that is a serialized, hex-encoded data for the proof.\n"
);
set<uint256> settxids;
uint256 onetxid;
univalue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const univalue& txid = txids[idx];
if (txid.get_str().length() != 64 || !ishex(txid.get_str()))
throw jsonrpcerror(rpc_invalid_parameter, string("invalid txid ")+txid.get_str());
uint256 hash(uint256s(txid.get_str()));
if (settxids.count(hash))
throw jsonrpcerror(rpc_invalid_parameter, string("invalid parameter, duplicated txid: ")+txid.get_str());
settxids.insert(hash);
onetxid = hash;
}
lock(cs_main);
cblockindex* pblockindex = null;
uint256 hashblock;
if (params.size() > 1)
{
hashblock = uint256s(params[1].get_str());
if (!mapblockindex.count(hashblock))
throw jsonrpcerror(rpc_invalid_address_or_key, "block not found");
pblockindex = mapblockindex[hashblock];
} else {
ccoins coins;
if (pcoinstip->getcoins(onetxid, coins) && coins.nheight > 0 && coins.nheight <= chainactive.height())
pblockindex = chainactive[coins.nheight];
}
if (pblockindex == null)
{
ctransaction tx;
if (!gettransaction(onetxid, tx, hashblock, false) || hashblock.isnull())
throw jsonrpcerror(rpc_invalid_address_or_key, "transaction not yet in block");
if (!mapblockindex.count(hashblock))
throw jsonrpcerror(rpc_internal_error, "transaction index corrupt");
pblockindex = mapblockindex[hashblock];
}
cblock block;
if(!readblockfromdisk(block, pblockindex))
throw jsonrpcerror(rpc_internal_error, "can't read block from disk");
unsigned int ntxfound = 0;
boost_foreach(const ctransaction&tx, block.vtx)
if (settxids.count(tx.gethash()))
ntxfound++;
if (ntxfound != settxids.size())
throw jsonrpcerror(rpc_invalid_address_or_key, "(not all) transactions not found in specified block");
cdatastream ssmb(ser_network, protocol_version);
cmerkleblock mb(block, settxids);
ssmb << mb;
std::string strhex = hexstr(ssmb.begin(), ssmb.end());
return strhex;
}
univalue verifytxoutproof(const univalue& params, bool fhelp)
{
if (fhelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nverifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an rpc error if the block is not in our best chain\n"
"\narguments:\n"
"1. \"proof\" (string, required) the hex-encoded proof generated by gettxoutproof\n"
"\nresult:\n"
"[\"txid\"] (array, strings) the txid(s) which the proof commits to, or empty array if the proof is invalid\n"
);
cdatastream ssmb(parsehexv(params[0], "proof"), ser_network, protocol_version);
cmerkleblock merkleblock;
ssmb >> merkleblock;
univalue res(univalue::varr);
vector<uint256> vmatch;
if (merkleblock.txn.extractmatches(vmatch) != merkleblock.header.hashmerkleroot)
return res;
lock(cs_main);
if (!mapblockindex.count(merkleblock.header.gethash()) || !chainactive.contains(mapblockindex[merkleblock.header.gethash()]))
throw jsonrpcerror(rpc_invalid_address_or_key, "block not found in chain");
boost_foreach(const uint256& hash, vmatch)
res.push_back(hash.gethex());
return res;
}
univalue createrawtransaction(const univalue& params, bool fhelp)
{
if (fhelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
"\ncreate a transaction spending the given inputs and sending to the given addresses.\n"
"returns hex-encoded raw transaction.\n"
"note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\narguments:\n"
"1. \"transactions\" (string, required) a json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) the transaction id\n"
" \"vout\":n (numeric, required) the output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) the key is the moorecoin address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nresult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nexamples\n"
+ helpexamplecli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ helpexamplerpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
);
lock(cs_main);
rpctypecheck(params, boost::assign::list_of(univalue::varr)(univalue::vobj));
univalue inputs = params[0].get_array();
univalue sendto = params[1].get_obj();
cmutabletransaction rawtx;
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const univalue& input = inputs[idx];
const univalue& o = input.get_obj();
uint256 txid = parsehasho(o, "txid");
const univalue& vout_v = find_value(o, "vout");
if (!vout_v.isnum())
throw jsonrpcerror(rpc_invalid_parameter, "invalid parameter, missing vout key");
int noutput = vout_v.get_int();
if (noutput < 0)
throw jsonrpcerror(rpc_invalid_parameter, "invalid parameter, vout must be positive");
ctxin in(coutpoint(txid, noutput));
rawtx.vin.push_back(in);
}
set<cmoorecoinaddress> setaddress;
vector<string> addrlist = sendto.getkeys();
boost_foreach(const string& name_, addrlist) {
cmoorecoinaddress address(name_);
if (!address.isvalid())
throw jsonrpcerror(rpc_invalid_address_or_key, string("invalid moorecoin address: ")+name_);
if (setaddress.count(address))
throw jsonrpcerror(rpc_invalid_parameter, string("invalid parameter, duplicated address: ")+name_);
setaddress.insert(address);
cscript scriptpubkey = getscriptfordestination(address.get());
camount namount = amountfromvalue(sendto[name_]);
ctxout out(namount, scriptpubkey);
rawtx.vout.push_back(out);
}
return encodehextx(rawtx);
}
univalue decoderawtransaction(const univalue& params, bool fhelp)
{
if (fhelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nreturn a json object representing the serialized, hex-encoded transaction.\n"
"\narguments:\n"
"1. \"hex\" (string, required) the transaction hex string\n"
"\nresult:\n"
"{\n"
" \"txid\" : \"id\", (string) the transaction id\n"
" \"version\" : n, (numeric) the version\n"
" \"locktime\" : ttt, (numeric) the lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) the transaction id\n"
" \"vout\": n, (numeric) the output number\n"
" \"scriptsig\": { (json object) the script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) the script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) the value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptpubkey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqsigs\" : n, (numeric) the required sigs\n"
" \"type\" : \"pubkeyhash\", (string) the type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvkaxcxzjsmdnbao16dkxc8trwfcf5oc\" (string) moorecoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nexamples:\n"
+ helpexamplecli("decoderawtransaction", "\"hexstring\"")
+ helpexamplerpc("decoderawtransaction", "\"hexstring\"")
);
lock(cs_main);
rpctypecheck(params, boost::assign::list_of(univalue::vstr));
ctransaction tx;
if (!decodehextx(tx, params[0].get_str()))
throw jsonrpcerror(rpc_deserialization_error, "tx decode failed");
univalue result(univalue::vobj);
txtojson(tx, uint256(), result);
return result;
}
univalue decodescript(const univalue& params, bool fhelp)
{
if (fhelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\ndecode a hex-encoded script.\n"
"\narguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nresult:\n"
"{\n"
" \"asm\":\"asm\", (string) script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) the output type\n"
" \"reqsigs\": n, (numeric) the required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) moorecoin address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nexamples:\n"
+ helpexamplecli("decodescript", "\"hexstring\"")
+ helpexamplerpc("decodescript", "\"hexstring\"")
);
lock(cs_main);
rpctypecheck(params, boost::assign::list_of(univalue::vstr));
univalue r(univalue::vobj);
cscript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptdata(parsehexv(params[0], "argument"));
script = cscript(scriptdata.begin(), scriptdata.end());
} else {
// empty scripts are valid
}
scriptpubkeytojson(script, r, false);
r.push_back(pair("p2sh", cmoorecoinaddress(cscriptid(script)).tostring()));
return r;
}
/** pushes a json object for script verification or signing errors to verrorsret. */
static void txinerrortojson(const ctxin& txin, univalue& verrorsret, const std::string& strmessage)
{
univalue entry(univalue::vobj);
entry.push_back(pair("txid", txin.prevout.hash.tostring()));
entry.push_back(pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(pair("scriptsig", hexstr(txin.scriptsig.begin(), txin.scriptsig.end())));
entry.push_back(pair("sequence", (uint64_t)txin.nsequence));
entry.push_back(pair("error", strmessage));
verrorsret.push_back(entry);
}
univalue signrawtransaction(const univalue& params, bool fhelp)
{
if (fhelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptpubkey\":\"hex\",\"redeemscript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nsign inputs for raw transaction (serialized, hex-encoded).\n"
"the second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"the third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef enable_wallet
+ helprequiringpassphrase() + "\n"
#endif
"\narguments:\n"
"1. \"hexstring\" (string, required) the transaction hex string\n"
"2. \"prevtxs\" (string, optional) an json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) the transaction id\n"
" \"vout\":n, (numeric, required) the output number\n"
" \"scriptpubkey\": \"hex\", (string, required) script key\n"
" \"redeemscript\": \"hex\" (string, required for p2sh) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) a json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=all) the signature hash type. must be one of\n"
" \"all\"\n"
" \"none\"\n"
" \"single\"\n"
" \"all|anyonecanpay\"\n"
" \"none|anyonecanpay\"\n"
" \"single|anyonecanpay\"\n"
"\nresult:\n"
"{\n"
" \"hex\" : \"value\", (string) the hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) if the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) the hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) the index of the output to spent and used as input\n"
" \"scriptsig\" : \"hex\", (string) the hex-encoded signature script\n"
" \"sequence\" : n, (numeric) script sequence number\n"
" \"error\" : \"text\" (string) verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nexamples:\n"
+ helpexamplecli("signrawtransaction", "\"myhex\"")
+ helpexamplerpc("signrawtransaction", "\"myhex\"")
);
#ifdef enable_wallet
lock2(cs_main, pwalletmain ? &pwalletmain->cs_wallet : null);
#else
lock(cs_main);
#endif
rpctypecheck(params, boost::assign::list_of(univalue::vstr)(univalue::varr)(univalue::varr)(univalue::vstr), true);
vector<unsigned char> txdata(parsehexv(params[0], "argument 1"));
cdatastream ssdata(txdata, ser_network, protocol_version);
vector<cmutabletransaction> txvariants;
while (!ssdata.empty()) {
try {
cmutabletransaction tx;
ssdata >> tx;
txvariants.push_back(tx);
}
catch (const std::exception&) {
throw jsonrpcerror(rpc_deserialization_error, "tx decode failed");
}
}
if (txvariants.empty())
throw jsonrpcerror(rpc_deserialization_error, "missing transaction");
// mergedtx will end up with all the signatures; it
// starts as a clone of the rawtx:
cmutabletransaction mergedtx(txvariants[0]);
// fetch previous transactions (inputs):
ccoinsview viewdummy;
ccoinsviewcache view(&viewdummy);
{
lock(mempool.cs);
ccoinsviewcache &viewchain = *pcoinstip;
ccoinsviewmempool viewmempool(&viewchain, mempool);
view.setbackend(viewmempool); // temporarily switch cache backend to db+mempool view
boost_foreach(const ctxin& txin, mergedtx.vin) {
const uint256& prevhash = txin.prevout.hash;
ccoins coins;
view.accesscoins(prevhash); // this is certainly allowed to fail
}
view.setbackend(viewdummy); // switch back to avoid locking mempool for too long
}
bool fgivenkeys = false;
cbasickeystore tempkeystore;
if (params.size() > 2 && !params[2].isnull()) {
fgivenkeys = true;
univalue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
univalue k = keys[idx];
cmoorecoinsecret vchsecret;
bool fgood = vchsecret.setstring(k.get_str());
if (!fgood)
throw jsonrpcerror(rpc_invalid_address_or_key, "invalid private key");
ckey key = vchsecret.getkey();
if (!key.isvalid())
throw jsonrpcerror(rpc_invalid_address_or_key, "private key outside allowed range");
tempkeystore.addkey(key);
}
}
#ifdef enable_wallet
else if (pwalletmain)
ensurewalletisunlocked();
#endif
// add previous txouts given in the rpc call:
if (params.size() > 1 && !params[1].isnull()) {
univalue prevtxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevtxs.size(); idx++) {
const univalue& p = prevtxs[idx];
if (!p.isobject())
throw jsonrpcerror(rpc_deserialization_error, "expected object with {\"txid'\",\"vout\",\"scriptpubkey\"}");
univalue prevout = p.get_obj();
rpctypecheckobj(prevout, boost::assign::map_list_of("txid", univalue::vstr)("vout", univalue::vnum)("scriptpubkey", univalue::vstr));
uint256 txid = parsehasho(prevout, "txid");
int nout = find_value(prevout, "vout").get_int();
if (nout < 0)
throw jsonrpcerror(rpc_deserialization_error, "vout must be positive");
vector<unsigned char> pkdata(parsehexo(prevout, "scriptpubkey"));
cscript scriptpubkey(pkdata.begin(), pkdata.end());
{
ccoinsmodifier coins = view.modifycoins(txid);
if (coins->isavailable(nout) && coins->vout[nout].scriptpubkey != scriptpubkey) {
string err("previous output scriptpubkey mismatch:\n");
err = err + coins->vout[nout].scriptpubkey.tostring() + "\nvs:\n"+
scriptpubkey.tostring();
throw jsonrpcerror(rpc_deserialization_error, err);
}
if ((unsigned int)nout >= coins->vout.size())
coins->vout.resize(nout+1);
coins->vout[nout].scriptpubkey = scriptpubkey;
coins->vout[nout].nvalue = 0; // we don't know the actual output value
}
// if redeemscript given and not using the local wallet (private keys
// given), add redeemscript to the tempkeystore so it can be signed:
if (fgivenkeys && scriptpubkey.ispaytoscripthash()) {
rpctypecheckobj(prevout, boost::assign::map_list_of("txid", univalue::vstr)("vout", univalue::vnum)("scriptpubkey", univalue::vstr)("redeemscript",univalue::vstr));
univalue v = find_value(prevout, "redeemscript");
if (!v.isnull()) {
vector<unsigned char> rsdata(parsehexv(v, "redeemscript"));
cscript redeemscript(rsdata.begin(), rsdata.end());
tempkeystore.addcscript(redeemscript);
}
}
}
}
#ifdef enable_wallet
const ckeystore& keystore = ((fgivenkeys || !pwalletmain) ? tempkeystore : *pwalletmain);
#else
const ckeystore& keystore = tempkeystore;
#endif
int nhashtype = sighash_all;
if (params.size() > 3 && !params[3].isnull()) {
static map<string, int> mapsighashvalues =
boost::assign::map_list_of
(string("all"), int(sighash_all))
(string("all|anyonecanpay"), int(sighash_all|sighash_anyonecanpay))
(string("none"), int(sighash_none))
(string("none|anyonecanpay"), int(sighash_none|sighash_anyonecanpay))
(string("single"), int(sighash_single))
(string("single|anyonecanpay"), int(sighash_single|sighash_anyonecanpay))
;
string strhashtype = params[3].get_str();
if (mapsighashvalues.count(strhashtype))
nhashtype = mapsighashvalues[strhashtype];
else
throw jsonrpcerror(rpc_invalid_parameter, "invalid sighash param");
}
bool fhashsingle = ((nhashtype & ~sighash_anyonecanpay) == sighash_single);
// script verification errors
univalue verrors(univalue::varr);
// sign what we can:
for (unsigned int i = 0; i < mergedtx.vin.size(); i++) {
ctxin& txin = mergedtx.vin[i];
const ccoins* coins = view.accesscoins(txin.prevout.hash);
if (coins == null || !coins->isavailable(txin.prevout.n)) {
txinerrortojson(txin, verrors, "input not found or already spent");
continue;
}
const cscript& prevpubkey = coins->vout[txin.prevout.n].scriptpubkey;
txin.scriptsig.clear();
// only sign sighash_single if there's a corresponding output:
if (!fhashsingle || (i < mergedtx.vout.size()))
signsignature(keystore, prevpubkey, mergedtx, i, nhashtype);
// ... and merge in other signatures:
boost_foreach(const cmutabletransaction& txv, txvariants) {
txin.scriptsig = combinesignatures(prevpubkey, mergedtx, i, txin.scriptsig, txv.vin[i].scriptsig);
}
scripterror serror = script_err_ok;
if (!verifyscript(txin.scriptsig, prevpubkey, standard_script_verify_flags, mutabletransactionsignaturechecker(&mergedtx, i), &serror)) {
txinerrortojson(txin, verrors, scripterrorstring(serror));
}
}
bool fcomplete = verrors.empty();
univalue result(univalue::vobj);
result.push_back(pair("hex", encodehextx(mergedtx)));
result.push_back(pair("complete", fcomplete));
if (!verrors.empty()) {
result.push_back(pair("errors", verrors));
}
return result;
}
univalue sendrawtransaction(const univalue& params, bool fhelp)
{
if (fhelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nsubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nalso see createrawtransaction and signrawtransaction calls.\n"
"\narguments:\n"
"1. \"hexstring\" (string, required) the hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) allow high fees\n"
"\nresult:\n"
"\"hex\" (string) the transaction hash in hex\n"
"\nexamples:\n"
"\ncreate a transaction\n"
+ helpexamplecli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"sign the transaction, and get back the hex\n"
+ helpexamplecli("signrawtransaction", "\"myhex\"") +
"\nsend the transaction (signed hex)\n"
+ helpexamplecli("sendrawtransaction", "\"signedhex\"") +
"\nas a json rpc call\n"
+ helpexamplerpc("sendrawtransaction", "\"signedhex\"")
);
lock(cs_main);
rpctypecheck(params, boost::assign::list_of(univalue::vstr)(univalue::vbool));
// parse hex string from parameter
ctransaction tx;
if (!decodehextx(tx, params[0].get_str()))
throw jsonrpcerror(rpc_deserialization_error, "tx decode failed");
uint256 hashtx = tx.gethash();
bool foverridefees = false;
if (params.size() > 1)
foverridefees = params[1].get_bool();
ccoinsviewcache &view = *pcoinstip;
const ccoins* existingcoins = view.accesscoins(hashtx);
bool fhavemempool = mempool.exists(hashtx);
bool fhavechain = existingcoins && existingcoins->nheight < 1000000000;
if (!fhavemempool && !fhavechain) {
// push to local node and sync with wallets
cvalidationstate state;
bool fmissinginputs;
if (!accepttomemorypool(mempool, state, tx, false, &fmissinginputs, !foverridefees)) {
if (state.isinvalid()) {
throw jsonrpcerror(rpc_transaction_rejected, strprintf("%i: %s", state.getrejectcode(), state.getrejectreason()));
} else {
if (fmissinginputs) {
throw jsonrpcerror(rpc_transaction_error, "missing inputs");
}
throw jsonrpcerror(rpc_transaction_error, state.getrejectreason());
}
}
} else if (fhavechain) {
throw jsonrpcerror(rpc_transaction_already_in_chain, "transaction already in block chain");
}
relaytransaction(tx);
return hashtx.gethex();
}
| 42.736777 | 180 | 0.565376 | [
"object",
"vector"
] |
9fcca55b7f9fa6d04765207ff8e08b7c405399c5 | 710 | cpp | C++ | depspawn-blitz-0.10/testsuite/preexisting.cpp | fraguela/depspawn | b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45 | [
"MIT"
] | 8 | 2017-04-12T11:05:40.000Z | 2022-03-29T11:10:27.000Z | ibtk/third_party/blitz-0.10/testsuite/preexisting.cpp | MSV-Project/IBAMR | 3cf614c31bb3c94e2620f165ba967cba719c45ea | [
"BSD-3-Clause"
] | null | null | null | ibtk/third_party/blitz-0.10/testsuite/preexisting.cpp | MSV-Project/IBAMR | 3cf614c31bb3c94e2620f165ba967cba719c45ea | [
"BSD-3-Clause"
] | null | null | null | #include "testsuite.h"
#include <blitz/array.h>
BZ_USING_NAMESPACE(blitz)
// tests that preexisting memory constructors work with padding
int main()
{
Array<int,2> b(3,3);
b = 1,2,3,4,5,6,7,8,9;
{
int p[] = {1,2,3,4,5,6,7,8,9};
Array<int,2> a(p, shape(3,3), neverDeleteData);
BZTEST(all(a==b));
}
{
int* pp;
pp = new int[3*3];
Array<int,2> a(pp, shape(3,3), deleteDataWhenDone);
a = 1,2,3,4,5,6,7,8,9;
BZTEST(all(a==b));
}
const int w =simdTypes<int>::vecWidth;
if(w>1) {
int p[] = {1,2,3,4,5,6,7,8,9};
beginCheckAssert();
Array<int,2> a(p, shape(3,3), neverDeleteData, FortranArray<2>(paddedData));
endCheckAssert();
}
return 0;
}
| 18.684211 | 80 | 0.576056 | [
"shape"
] |
9fcd77f77c8c6253dc2570a5e150bb663d5c515e | 4,981 | cpp | C++ | third_party/poco_1.5.3/PageCompiler/src/OSPCodeWriter.cpp | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | 3rdparty/poco/PageCompiler/src/OSPCodeWriter.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | 3rdparty/poco/PageCompiler/src/OSPCodeWriter.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | //
// OSPCodeWriter.cpp
//
// $Id: //poco/1.4/PageCompiler/src/OSPCodeWriter.cpp#3 $
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "OSPCodeWriter.h"
#include "Page.h"
#include "Poco/NumberParser.h"
OSPCodeWriter::OSPCodeWriter(const Page& page, const std::string& clazz):
CodeWriter(page, clazz)
{
}
OSPCodeWriter::~OSPCodeWriter()
{
}
void OSPCodeWriter::writeHeaderIncludes(std::ostream& ostr)
{
CodeWriter::writeHeaderIncludes(ostr);
ostr << "#include \"Poco/OSP/Web/WebRequestHandlerFactory.h\"\n";
ostr << "#include \"Poco/OSP/BundleContext.h\"\n";
}
void OSPCodeWriter::writeHandlerClass(std::ostream& ostr)
{
std::string base(page().get("page.baseClass", "Poco::Net::HTTPRequestHandler"));
handlerClass(ostr, base, "Poco::OSP::BundleContext::Ptr");
}
void OSPCodeWriter::writeHandlerMembers(std::ostream& ostr)
{
std::string base(page().get("page.baseClass", ""));
if (base.empty())
{
ostr << "\n";
ostr << "protected:\n";
ostr << "\tPoco::OSP::BundleContext::Ptr context() const\n";
ostr << "\t{\n";
ostr << "\t\treturn _pContext;\n";
ostr << "\t}\n";
ostr << "\n";
ostr << "private:\n";
ostr << "\tPoco::OSP::BundleContext::Ptr _pContext;\n";
}
}
void OSPCodeWriter::writeFactoryClass(std::ostream& ostr)
{
ostr << "\n\n";
factoryClass(ostr, "Poco::OSP::Web::WebRequestHandlerFactory");
}
void OSPCodeWriter::writeImplIncludes(std::ostream& ostr)
{
CodeWriter::writeImplIncludes(ostr);
if (page().has("page.session"))
{
ostr << "#include \"Poco/OSP/Web/WebSession.h\"\n";
ostr << "#include \"Poco/OSP/Web/WebSessionManager.h\"\n";
ostr << "#include \"Poco/OSP/ServiceRegistry.h\"\n";
}
}
void OSPCodeWriter::writeConstructor(std::ostream& ostr)
{
std::string base(page().get("page.baseClass", ""));
ostr << clazz() << "::" << clazz() << "(Poco::OSP::BundleContext::Ptr pContext):\n";
if (base.empty())
{
ostr << "\t_pContext(pContext)\n";
}
else
{
ostr << "\t" << base << "(pContext)\n";
}
ostr << "{\n}\n";
ostr << "\n\n";
}
void OSPCodeWriter::writeSession(std::ostream& ostr)
{
if (page().has("page.session"))
{
std::string session = page().get("page.session");
std::string sessionCode;
if (session.empty()) return;
if (session[0] == '@')
sessionCode = "context()->thisBundle()->properties().getString(\"" + session.substr(1) + "\")";
else
sessionCode = "\"" + session + "\"";
std::string sessionTimeoutCode = page().get("page.sessionTimeout", "30");
int sessionTimeout;
if (!Poco::NumberParser::tryParse(sessionTimeoutCode, sessionTimeout))
{
sessionTimeoutCode = "context()->thisBundle()->properties().getInt(\"" + sessionTimeoutCode + "\")";
}
ostr << "\tPoco::OSP::Web::WebSession::Ptr session;\n";
ostr << "\t{\n";
ostr << "\t\tPoco::OSP::ServiceRef::Ptr pWebSessionManagerRef = context()->registry().findByName(Poco::OSP::Web::WebSessionManager::SERVICE_NAME);\n";
ostr << "\t\tif (pWebSessionManagerRef)\n";
ostr << "\t\t{\n";
ostr << "\t\t\tPoco::OSP::Web::WebSessionManager::Ptr pWebSessionManager = pWebSessionManagerRef->castedInstance<Poco::OSP::Web::WebSessionManager>();\n";
if (page().get("page.createSession", "true") != "false")
{
ostr << "\t\t\tsession = pWebSessionManager->get(" << sessionCode << ", request, " << sessionTimeoutCode << ", context());\n";
}
else
{
ostr << "\t\t\tsession = pWebSessionManager->find(" << sessionCode << ", request);\n";
}
ostr << "\t\t}\n";
ostr << "\t}\n";
}
}
void OSPCodeWriter::writeFactory(std::ostream& ostr)
{
ostr << "\n\n";
factoryImpl(ostr, "context()");
}
| 30.937888 | 156 | 0.678177 | [
"object"
] |
9fce624c195dfb1c4ccc8b50823f1d56cf08ff26 | 1,672 | cpp | C++ | src/Component.cpp | inoricat/Markdown-CLI | 46c11629a4d7aefc86eac01fa2dc0c0303f686c1 | [
"MIT"
] | null | null | null | src/Component.cpp | inoricat/Markdown-CLI | 46c11629a4d7aefc86eac01fa2dc0c0303f686c1 | [
"MIT"
] | null | null | null | src/Component.cpp | inoricat/Markdown-CLI | 46c11629a4d7aefc86eac01fa2dc0c0303f686c1 | [
"MIT"
] | null | null | null | #include <string>
#include "Component.hpp"
// Default constructor, type of the Component needed (div, tag, code...)
Component::Component(std::string type){
this->type=type;
}
// Overloaded constructor to include text before any of the components
Component::Component(std::string type, std::string text){
this->type=type;
this->content = {text};
}
// Add subcomponents
void Component::addChild(Component newChild){
this->children.push_back(newChild); // Add the new component to the end
}
// Sets the text contained in this component. It is placed after the last added component
void Component::setText(std::string text){
if(this->children.size() == 0) // If no components were added before,
this->content = {text}; // just set the text (keep the reference NULL, the default)
else // Otherwise,
this->content = {text, &this->children.back()}; // set the reference to the last component added
}
std::string Component::render(){
std::string tmp = "<" + this->type + ">\n"; // Open the tag
if(this->content.after == NULL && !this->content.text.empty()) // If the text's "after" is NULL, it means that the text should be rendered first
tmp += this->content.text + "\n";
for(Component c: this->children){ // For each subcomponent,
tmp += c.render() + "\n"; // render it
if(this->content.after == &c){ // and then check if the text goes after it
tmp += this->content.text + "\n"; // (if it does, render the text)
}
}
tmp += "</" + this->type + ">\n"; // And close the tag
return tmp;
} | 37.155556 | 152 | 0.611842 | [
"render"
] |
9fd66cebfed573f886540e131c712d270ffd9d68 | 7,581 | hpp | C++ | include/dukpp/detail/detail_types.hpp | Koncord/dukpp | 66584a7be4f63868dc4f702ab5a9d423956a9273 | [
"MIT"
] | 2 | 2021-06-06T17:18:33.000Z | 2021-06-11T14:10:33.000Z | include/dukpp/detail/detail_types.hpp | Koncord/dukpp | 66584a7be4f63868dc4f702ab5a9d423956a9273 | [
"MIT"
] | 1 | 2021-07-15T23:03:25.000Z | 2021-07-18T09:34:31.000Z | include/dukpp/detail/detail_types.hpp | Koncord/dukpp | 66584a7be4f63868dc4f702ab5a9d423956a9273 | [
"MIT"
] | 2 | 2021-08-05T05:59:05.000Z | 2022-02-01T22:28:53.000Z | #pragma once
#include <type_traits>
#include <duktape.h>
#include "detail_refs.hpp"
#include "detail_typeinfo.hpp"
#include "detail_class_proto.hpp"
namespace dukpp::types {
// Bare<T>::type is T stripped of reference, pointer, and const off a type, like so:
// Bare<Dog>::type = Dog
// Bare<const Dog>::type = Dog
// Bare<Dog*>::type = Dog
// Bare<const Dog*>::type = Dog
// Bare<Dog&>::type = Dog
// Bare<const Dog&>::type = Dog
template<typename T>
struct Bare {
typedef typename std::remove_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::type type;
};
// DukType<T> provides functions for reading and writing T from the Duktape stack.
// T is always a "bare type," i.e. "Dog" rather than "Dog*".
// There are two kinds of DukTypes:
// 1. "Native" DukTypes. This is the default.
// These types use an underlying native object allocated on the heap.
// A pointer to the object (of type T*) is expected at script_object.\xFFobj_ptr.
// "Native" DukTypes can return a value (returns a copy-constructed T from the native object),
// a pointer (just returns script_object.\xFFobj_ptr), or a reference (dereferences script_object.\xFFobj_ptr if it is not null).
// 2. "Value" DukTypes. These are implemented through template specialization.
// This is how primitive types are implemented (int, float, char const *).
// These types can only be returned by value (T) or by const reference (const T&).
// Attempting to read a pointer (T*) or non-const reference (T&) will give a compile-time error.
// You can also use this to implement your own lightweight types, such as a 3D vector.
// (Strictly speaking, non-const references (T&) *could* be returned, but any changes to the reference would
// be discarded. So, I wrote a static assert to disable the option. If you understand the implications,
// you should be able to safely comment out the static_assert in ArgStorage.)
template<typename T>
struct DukType {
static_assert(std::is_same<T, typename Bare<T>::type>::value, "Invalid base type, expected bare type");
typedef std::false_type IsValueType;
// read pointer
template<typename FullT, typename = typename std::enable_if<std::is_pointer<FullT>::value>::type>
static T *read(duk_context *ctx, duk_idx_t arg_idx) {
if (duk_is_null(ctx, arg_idx)) {
return nullptr;
}
if (!duk_is_object(ctx, arg_idx)) {
duk_int_t type_idx = duk_get_type(ctx, arg_idx);
duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected native object, got %s", arg_idx,
detail::get_type_name(type_idx));
}
duk_get_prop_string(ctx, arg_idx, DUK_HIDDEN_SYMBOL("type_info"));
if (!duk_is_pointer(ctx, -1)) { // missing type_info, must not be a native object
duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: expected native object (missing type_info)", arg_idx);
}
// make sure this object can be safely returned as a T*
auto info = static_cast<detail::TypeInfo *>(duk_get_pointer(ctx, -1));
if (!info->can_cast<T>()) {
duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: wrong type of native object", arg_idx);
}
duk_pop(ctx); // pop type_info
duk_get_prop_string(ctx, arg_idx, DUK_HIDDEN_SYMBOL("obj_ptr"));
if (!duk_is_pointer(ctx, -1)) {
duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: invalid native object.", arg_idx);
}
auto obj = static_cast<T *>(duk_get_pointer(ctx, -1));
duk_pop(ctx); // pop obj_ptr
return obj;
}
// read reference
template<typename FullT, typename = typename std::enable_if<std::is_reference<FullT>::value>::type>
static T &read(duk_context *ctx, duk_idx_t arg_idx) {
auto obj = read<T *>(ctx, arg_idx);
if (obj == nullptr) {
duk_error(ctx, DUK_RET_TYPE_ERROR, "Argument %d: cannot be null (native function expects reference)",
arg_idx);
}
return *obj;
}
// read value
// commented out because it breaks for abstract classes
/*template<typename FullT, typename = typename std::enable_if< std::is_same<T, typename std::remove_const<FullT>::type >::value>::type >
static T read(duk_context* ctx, duk_idx_t arg_idx) {
static_assert(std::is_copy_constructible<T>::value, "Reading a value requires a copy-constructable type");
const T& obj = read<T&>(ctx, arg_idx);
return T(obj);
}*/
// -----------------------------------------------------
// Writing
// Reference
template<typename FullT, typename = typename std::enable_if<std::is_reference<FullT>::value>::type>
static void push(duk_context *ctx, T &value) {
if (!detail::RefManager::find_and_push_native_object(ctx, &value)) {
// need to create new script object
detail::ProtoManager::make_script_object<T>(ctx, &value);
detail::RefManager::register_native_object(ctx, &value);
}
}
// Pointer
template<typename FullT, typename = typename std::enable_if<std::is_pointer<FullT>::value>::type>
static void push(duk_context *ctx, T *value) {
if (value == nullptr) {
duk_push_null(ctx);
} else {
push<T &>(ctx, *value);
}
}
// Value (create new instance on the heap)
// commented out because this is an easy way to accidentally cause a memory leak
/*template<typename FullT, typename = typename std::enable_if< std::is_same<T, typename std::remove_const<FullT>::type >::value>::type >
static void push(duk_context* ctx, T value) {
static_assert(std::is_copy_constructible<T>::value, "Cannot push value for non-copy-constructable type.");
return push<T*>(ctx, new T(value));
}*/
};
// Figure out what the type for an argument should be inside the tuple.
// If a function expects a reference to a value type, we need temporary storage for the value.
// For example, a reference to a value type (const int&) will need to be temporarily
// stored in the tuple, so ArgStorage<const int&>::type == int.
// Native objects are already allocated on the heap, so there's no problem storing, say, const Dog& in the tuple.
template<typename T>
struct ArgStorage {
private:
typedef typename Bare<T>::type BareType;
//typedef DukType<BareType> ThisDukType;
typedef typename DukType<BareType>::IsValueType IsValueType;
static_assert(!IsValueType::value || !std::is_pointer<T>::value, "Cannot return pointer to value type.");
static_assert(!IsValueType::value ||
(!std::is_reference<T>::value ||
std::is_const<typename std::remove_reference<T>::type>::value),
"Value types can only be returned as const references.");
public:
typedef typename std::conditional<IsValueType::value, BareType, T>::type type;
};
}
#include "detail_primitive_types.h"
| 45.945455 | 144 | 0.612056 | [
"object",
"vector",
"3d"
] |
9fd711c75f32c7cdcd0a35a9a259172a84ded1dc | 4,441 | cpp | C++ | templates/compiletime_ds.cpp | ishansheth/cplusplus_concepts | f5e53a8bef87674e66eafc05d103a0feec165330 | [
"MIT"
] | null | null | null | templates/compiletime_ds.cpp | ishansheth/cplusplus_concepts | f5e53a8bef87674e66eafc05d103a0feec165330 | [
"MIT"
] | null | null | null | templates/compiletime_ds.cpp | ishansheth/cplusplus_concepts | f5e53a8bef87674e66eafc05d103a0feec165330 | [
"MIT"
] | null | null | null | /*
Structure to store compiletime objects
https://www.fluentcpp.com/2018/11/02/variable-number-compile-time/
*/
#include <iostream>
#include <tuple>
#include <vector>
template<int k> struct Simplex { void print(){ std::cout << k << '\n';} };
template<std::size_t n>
class SimplexStorage
{
template<std::size_t ... ks>
using StorageImpl = std::tuple<Simplex<ks>...>;
template<std::size_t ... ks>
static StorageImpl<(1+ks)...> make_storage(std::index_sequence<ks...>)
{
return StorageImpl<(1+ks)...>{};
}
using Storage = decltype(make_storage(std::make_index_sequence<n>{}));
Storage storage_;
public:
template<int k>
Simplex<k>& getSimplexes()
{
// since its k-1, the indexing starts from 1,2,3,.....
return std::get<k-1>(storage_);
}
};
/*
https://www.fluentcpp.com/2017/06/02/write-template-metaprogramming-expressively/
https://stackoverflow.com/questions/27687389/how-does-void-t-work
Example of a meta function
*/
/* this is essentially a void_t from C++17*/
template<typename...>
using try_to_instantiate = void;
template<typename T, typename = void>
struct is_incrementable : std::false_type
{};
template<typename T>
struct is_incrementable<T, try_to_instantiate< decltype(++std::declval<T&>()) >>: std::true_type
{};
constexpr std::size_t sample_func()
{
return 10;
}
/*
Another example of compile time collection using tuples and varaidc templates
https://stackoverflow.com/questions/27941661/generating-one-class-member-per-variadic-template-argument
*/
template<typename T1, typename T2>
struct SameType
{
static const bool value = false;
};
template<typename T>
struct SameType<T,T>
{
static const bool value = true;
};
template<typename...Types>
class FantasticCollection
{
using vtype = std::tuple<std::vector<Types>...>;
vtype m_collection;
public:
template<int N, typename T>
struct VectorOfType : SameType<T, typename std::tuple_element<N,vtype>::type::value_type>
{};
template <int N, class T, class Tuple,bool Match>
struct MatchingField
{
static std::vector<T>& get(Tuple& tp)
{
// The "non-matching" version, recursively call the get function of
return MatchingField<N+1, T, Tuple,VectorOfType<N+1, T>::value>::get(tp);
}
};
template <int N, class T, class Tuple>
struct MatchingField<N, T, Tuple, true>
{
static std::vector<T>& get(Tuple& tp)
{
return std::get<N>(tp);
}
};
template <typename T>
std::vector<T>& get()
{
return MatchingField<0, T, vtype,VectorOfType<0, T>::value>::get(m_collection);
}
};
template<std::size_t idx,typename...Rest>
struct GetHelper{};
template<typename...T>
struct DataStructure
{};
template<typename T,typename...Rest>
struct DataStructure<T,Rest...>
{
T first;
DataStructure<Rest...> rest;
DataStructure(const T& f, const Rest&...r):first(f),rest(r...)
{}
template<std::size_t idx>
auto get()
{
return GetHelper<idx,DataStructure<T,Rest...>>::get(*this);
}
};
template<typename T, typename...Rest>
struct GetHelper<0,DataStructure<T,Rest...>>
{
static T get(DataStructure<T,Rest...>& data)
{
return data.first;
}
};
template<std::size_t idx,typename T, typename...Rest>
struct GetHelper<idx,DataStructure<T,Rest...>>
{
static auto get(DataStructure<T,Rest...>& data)
{
return GetHelper<idx-1,DataStructure<Rest...>>::get(data.rest);
}
};
int main()
{
SimplexStorage<sample_func()> storage_collection;
storage_collection.getSimplexes<1>().print();
storage_collection.getSimplexes<2>().print();
storage_collection.getSimplexes<3>().print();
storage_collection.getSimplexes<4>().print();
storage_collection.getSimplexes<5>().print();
std::cout<<"If int incrementable:"<<is_incrementable<int>::value<<std::endl;
std::cout<<"If string incrementable:"<<is_incrementable<std::string>::value<<std::endl;
FantasticCollection<int,float,std::string> a;
auto vec = a.get<float>();
vec.push_back(2.5f);
DataStructure<int, float, std::string> data(1, 2.1, "Hello");
std::cout << data.get<0>() << std::endl;
std::cout << data.get<1>() << std::endl;
std::cout << data.get<2>() << std::endl;
} | 24.26776 | 107 | 0.639045 | [
"vector"
] |
9fdcc181396d4ace8d213fa6fb155c1b6f89db9f | 6,731 | cpp | C++ | code/editors/xrECore/Editor/EDetailModel.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | 6 | 2020-07-06T13:34:28.000Z | 2021-07-12T10:36:23.000Z | code/editors/xrECore/Editor/EDetailModel.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | null | null | null | code/editors/xrECore/Editor/EDetailModel.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | #include "stdafx.h"
#include "EDetailModel.h"
#include <xrECoreLite\EditObject.h>
#include <xrECoreLite\EditMesh.h>
#include "Library.h"
#include "ImageManager.h"
//------------------------------------------------------------------------------
#define DETOBJ_CHUNK_VERSION 0x1000
#define DETOBJ_CHUNK_REFERENCE 0x0101
#define DETOBJ_CHUNK_SCALE_LIMITS 0x0102
#define DETOBJ_CHUNK_DENSITY_FACTOR 0x0103
#define DETOBJ_CHUNK_FLAGS 0x0104
#define DETOBJ_VERSION 0x0001
//------------------------------------------------------------------------------
void EDetail::EVertexIn::remapUV(const fvfVertexIn& src, const Fvector2& offs, const Fvector2& scale, bool bRotate)
{
P.set(src.P);
ImageLib.MergedTextureRemapUV(u, v, src.u, src.v, offs, scale, bRotate);
}
EDetail::EDetail()
{
shader = 0;
m_Flags.zero();
m_pRefs = 0;
m_fMinScale = 0.5f;
m_fMaxScale = 2.f;
m_fDensityFactor = 1.f;
m_sRefs = "";
vertices = 0;
number_vertices = 0;
indices = 0;
number_indices = 0;
}
EDetail::~EDetail()
{
Unload();
}
void EDetail::Unload()
{
CDetail::Unload();
Lib.RemoveEditObject(m_pRefs);
OnDeviceDestroy();
}
LPCSTR EDetail::GetName()
{
return m_pRefs ? m_pRefs->GetName() : m_sRefs.c_str();
}
LPCSTR EDetail::GetTextureName()
{
VERIFY(m_pRefs);
CSurface* surf = *m_pRefs->FirstSurface(); VERIFY(surf);
return surf->_Texture();
}
void EDetail::DefferedLoad()
{
}
void EDetail::OnDeviceCreate()
{
if (!m_pRefs)
return;
CSurface *surf = *m_pRefs->FirstSurface();
VERIFY(surf);
AnsiString s_name = surf->_ShaderName();
AnsiString t_name = surf->_Texture();
//shader.create (s_name.c_str(),t_name.c_str());
}
void EDetail::OnDeviceDestroy()
{
//shader.destroy();
}
u16 EDetail::_AddVert(const Fvector& p, float u, float v)
{
EVertexIn V(p, u, v);
for (u16 k = 0; k < (u16)number_vertices; ++k)
if (V.similar((EVertexIn&)vertices[k]))
return k;
++number_vertices;
vertices = (fvfVertexIn*)xr_realloc(vertices, number_vertices * sizeof(fvfVertexIn));
vertices[number_vertices - 1] = V;
return u16(number_vertices - 1);
}
IC BOOL isDegenerated(u16 v[3])
{
return (v[0] == v[1] || v[0] == v[2] || v[1] == v[2]);
};
IC BOOL isEqual(U16Vec& ind, u16 v[3])
{
for (U16Vec::iterator it = ind.begin(); it != ind.end(); it += 3)
{
// Test for 6 variations
if ((*(it + 0) == v[0]) && (*(it + 1) == v[1]) && (*(it + 2) == v[2]))
return true;
if ((*(it + 0) == v[0]) && (*(it + 2) == v[1]) && (*(it + 1) == v[2]))
return true;
if ((*(it + 2) == v[0]) && (*(it + 0) == v[1]) && (*(it + 1) == v[2]))
return true;
if ((*(it + 2) == v[0]) && (*(it + 1) == v[1]) && (*(it + 0) == v[2]))
return true;
if ((*(it + 1) == v[0]) && (*(it + 0) == v[1]) && (*(it + 2) == v[2]))
return true;
if ((*(it + 1) == v[0]) && (*(it + 2) == v[1]) && (*(it + 0) == v[2]))
return true;
}
return false;
}
bool EDetail::Update(LPCSTR name)
{
m_sRefs = name;
// update link
CEditableObject* R = Lib.CreateEditObject(name);
if (!R) {
ELog.Msg(mtError, "Can't load detail object '%s'.", name);
return false;
}
if (R->SurfaceCount() != 1) {
ELog.Msg(mtError, "Object must contain 1 material.");
Lib.RemoveEditObject(R);
return false;
}
if (R->MeshCount() == 0) {
ELog.Msg(mtError, "Object must contain 1 mesh.");
Lib.RemoveEditObject(R);
return false;
}
Lib.RemoveEditObject(m_pRefs);
m_pRefs = R;
// fill geometry
CEditableMesh* M = *m_pRefs->FirstMesh();
U16Vec inds;
// fill vertices
bv_bb.invalidate();
u32 idx = 0;
for (u32 f_id = 0; f_id < M->GetFCount(); ++f_id)
{
st_Face& F = const_cast<st_Face&> (M->GetFaces()[f_id]);
u16 ind[3];
for (int k = 0; k < 3; ++k, ++idx)
{
Fvector& P = const_cast <Fvector&>(M->GetVertices()[F.pv[k].pindex]);
st_VMapPt&vm = M->GetVMRefs()[F.pv[k].vmref].pts[0];
Fvector2& uv = M->GetVMaps()[vm.vmap_index]->getUV(vm.index);
ind[k] = _AddVert(P, uv.x, uv.y);
bv_bb.modify(vertices[ind[k]].P);
}
if (isDegenerated(ind))
continue;
if (isEqual(inds, ind))
continue;
inds.push_back(ind[0]);
inds.push_back(ind[1]);
inds.push_back(ind[2]);
}
number_indices = inds.size();
indices = (u16*)xr_malloc(number_indices * sizeof(u16));
memcpy(indices, inds.begin()._Ptr, number_indices * sizeof(u16));
bv_bb.getsphere(bv_sphere.P, bv_sphere.R);
OnDeviceCreate();
return true;
}
bool EDetail::Load(IReader& F)
{
// check version
R_ASSERT(F.find_chunk(DETOBJ_CHUNK_VERSION));
u32 version = F.r_u32();
if (version != DETOBJ_VERSION)
{
ELog.Msg(mtError, "EDetail: unsupported version.");
return false;
}
// references
string256 buf;
R_ASSERT(F.find_chunk(DETOBJ_CHUNK_REFERENCE));
F.r_stringZ(buf, sizeof(buf));
// scale
R_ASSERT(F.find_chunk(DETOBJ_CHUNK_SCALE_LIMITS));
m_fMinScale = F.r_float();
if (fis_zero(m_fMinScale))
m_fMinScale = 0.1f;
m_fMaxScale = F.r_float();
if (m_fMaxScale < m_fMinScale)
m_fMaxScale = m_fMinScale;
// density factor
if (F.find_chunk(DETOBJ_CHUNK_DENSITY_FACTOR))
m_fDensityFactor = F.r_float();
if (F.find_chunk(DETOBJ_CHUNK_FLAGS))
m_Flags.assign(F.r_u32());
// update object
return Update(buf);
}
void EDetail::Save(IWriter& F)
{
// version
F.open_chunk(DETOBJ_CHUNK_VERSION);
F.w_u32(DETOBJ_VERSION);
F.close_chunk();
// reference
F.open_chunk(DETOBJ_CHUNK_REFERENCE);
F.w_stringZ(m_sRefs.c_str());
F.close_chunk();
// scale
F.open_chunk(DETOBJ_CHUNK_SCALE_LIMITS);
F.w_float(m_fMinScale);
F.w_float(m_fMaxScale);
F.close_chunk();
// density factor
F.open_chunk(DETOBJ_CHUNK_DENSITY_FACTOR);
F.w_float(m_fDensityFactor);
F.close_chunk();
// flags
F.open_chunk(DETOBJ_CHUNK_FLAGS);
F.w_u32(m_Flags.get());
F.close_chunk();
}
void EDetail::Export(IWriter& F, LPCSTR tex_name, const Fvector2& offs, const Fvector2& scale, bool rot)
{
R_ASSERT(m_pRefs);
CSurface* surf = *m_pRefs->FirstSurface();
R_ASSERT(surf);
// write data
F.w_stringZ(surf->_ShaderName());
F.w_stringZ(tex_name);//surf->_Texture());
F.w_u32(m_Flags.get());
F.w_float(m_fMinScale);
F.w_float(m_fMaxScale);
F.w_u32(number_vertices);
F.w_u32(number_indices);
// remap UV
EVertexIn* rm_vertices = xr_alloc<EVertexIn>(number_vertices);
for (u32 k = 0; k < number_vertices; ++k)
rm_vertices[k].remapUV(vertices[k], offs, scale, rot);
F.w(rm_vertices, number_vertices * sizeof(fvfVertexIn));
F.w(indices, number_indices * sizeof(WORD));
xr_free(rm_vertices);
}
void EDetail::Export(LPCSTR name)
{
CSurface* surf = *m_pRefs->FirstSurface();
R_ASSERT(surf);
IWriter* F = FS.w_open(name);
if (F)
{
Fvector2 offs = { 0,0 };
Fvector2 scale = { 1,1 };
Export(*F, surf->_Texture(), offs, scale, false);
FS.w_close(F);
}
else
Log("!Can't export detail:", name);
} | 22.068852 | 115 | 0.638241 | [
"mesh",
"geometry",
"object"
] |
9fde9e064279b10ba720d29693c534fd32970b82 | 2,674 | hpp | C++ | build/stx/libdb/libopenDBX/support/opendbx-1.4.6/lib/odbx_iface.hpp | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | 1 | 2020-01-23T20:46:08.000Z | 2020-01-23T20:46:08.000Z | build/stx/libdb/libopenDBX/support/opendbx-1.4.6/lib/odbx_iface.hpp | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | null | null | null | build/stx/libdb/libopenDBX/support/opendbx-1.4.6/lib/odbx_iface.hpp | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | null | null | null | /*
* OpenDBX - A simple but extensible database abstraction layer
* Copyright (C) 2004-2008 Norbert Sendetzky and others
*
* Distributed under the terms of the GNU Library General Public Licence
* version 2 or (at your option) any later version.
*/
#include "lib/opendbx/api"
#include <string>
#include <vector>
#ifndef ODBX_IFACE_HPP
#define ODBX_IFACE_HPP
namespace OpenDBX
{
class Lob_Iface
{
public:
virtual ~Lob_Iface() throw() {}
virtual void close() throw( std::exception ) = 0;
virtual ssize_t read( void* buffer, size_t buflen ) throw( std::exception ) = 0;
virtual ssize_t write( void* buffer, size_t buflen ) throw( std::exception ) = 0;
};
class Result_Iface
{
public:
virtual ~Result_Iface() throw() {}
virtual void finish() throw( std::exception ) = 0;
virtual odbxres getResult( struct timeval* timeout, unsigned long chunk ) throw( std::exception ) = 0;
virtual odbxrow getRow() throw( std::exception ) = 0;
virtual uint64_t rowsAffected() throw( std::exception ) = 0;
virtual unsigned long columnCount() throw( std::exception ) = 0;
virtual unsigned long columnPos( const string& name ) throw( std::exception ) = 0;
virtual const string columnName( unsigned long pos ) throw( std::exception ) = 0;
virtual odbxtype columnType( unsigned long pos ) throw( std::exception ) = 0;
virtual unsigned long fieldLength( unsigned long pos ) throw( std::exception ) = 0;
virtual const char* fieldValue( unsigned long pos ) throw( std::exception ) = 0;
virtual Lob_Iface* getLob( const char* value ) throw( std::exception ) = 0;
};
class Stmt_Iface
{
public:
virtual ~Stmt_Iface() throw() {};
virtual Result_Iface* execute() throw( std::exception ) = 0;
// virtual void bind( const void* data, unsigned long size, size_t pos, int flags ) = 0;
// virtual size_t count() = 0;
};
class Conn_Iface
{
public:
virtual ~Conn_Iface() throw() {};
virtual void finish() throw( std::exception ) = 0;
virtual void bind( const char* database, const char* who, const char* cred, odbxbind method = ODBX_BIND_SIMPLE ) throw( std::exception ) = 0;
virtual void unbind() throw( std::exception ) = 0;
virtual bool getCapability( odbxcap cap ) throw( std::exception ) = 0;
virtual void getOption( odbxopt option, void* value ) throw( std::exception ) = 0;
virtual void setOption( odbxopt option, void* value ) throw( std::exception ) = 0;
virtual string& escape( const char* from, unsigned long fromlen, string& to ) throw( std::exception ) = 0;
virtual Stmt_Iface* create( const string& sql, Stmt::Type type ) throw( std::exception ) = 0;
};
} // namespace
#endif
| 26.475248 | 143 | 0.690726 | [
"vector"
] |
9fe99e128bbdd139c57a3166e4abb6063eb6703d | 3,890 | cpp | C++ | client/OAIEzsignbulksendsignermapping_createObject_v1_Request.cpp | ezmaxinc/eZmax-SDK-cpp-qt5-client | 70cc5ea2bccba1a7c192f88b15bee8225dbb3d01 | [
"MIT"
] | null | null | null | client/OAIEzsignbulksendsignermapping_createObject_v1_Request.cpp | ezmaxinc/eZmax-SDK-cpp-qt5-client | 70cc5ea2bccba1a7c192f88b15bee8225dbb3d01 | [
"MIT"
] | null | null | null | client/OAIEzsignbulksendsignermapping_createObject_v1_Request.cpp | ezmaxinc/eZmax-SDK-cpp-qt5-client | 70cc5ea2bccba1a7c192f88b15bee8225dbb3d01 | [
"MIT"
] | null | null | null | /**
* eZmax API Definition (Full)
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIEzsignbulksendsignermapping_createObject_v1_Request.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QObject>
#include "OAIHelpers.h"
namespace OpenAPI {
OAIEzsignbulksendsignermapping_createObject_v1_Request::OAIEzsignbulksendsignermapping_createObject_v1_Request(QString json) {
this->initializeModel();
this->fromJson(json);
}
OAIEzsignbulksendsignermapping_createObject_v1_Request::OAIEzsignbulksendsignermapping_createObject_v1_Request() {
this->initializeModel();
}
OAIEzsignbulksendsignermapping_createObject_v1_Request::~OAIEzsignbulksendsignermapping_createObject_v1_Request() {}
void OAIEzsignbulksendsignermapping_createObject_v1_Request::initializeModel() {
m_a_obj_ezsignbulksendsignermapping_isSet = false;
m_a_obj_ezsignbulksendsignermapping_isValid = false;
}
void OAIEzsignbulksendsignermapping_createObject_v1_Request::fromJson(QString jsonString) {
QByteArray array(jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void OAIEzsignbulksendsignermapping_createObject_v1_Request::fromJsonObject(QJsonObject json) {
m_a_obj_ezsignbulksendsignermapping_isValid = ::OpenAPI::fromJsonValue(a_obj_ezsignbulksendsignermapping, json[QString("a_objEzsignbulksendsignermapping")]);
m_a_obj_ezsignbulksendsignermapping_isSet = !json[QString("a_objEzsignbulksendsignermapping")].isNull() && m_a_obj_ezsignbulksendsignermapping_isValid;
}
QString OAIEzsignbulksendsignermapping_createObject_v1_Request::asJson() const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject OAIEzsignbulksendsignermapping_createObject_v1_Request::asJsonObject() const {
QJsonObject obj;
if (a_obj_ezsignbulksendsignermapping.size() > 0) {
obj.insert(QString("a_objEzsignbulksendsignermapping"), ::OpenAPI::toJsonValue(a_obj_ezsignbulksendsignermapping));
}
return obj;
}
QList<OAIEzsignbulksendsignermapping_RequestCompound> OAIEzsignbulksendsignermapping_createObject_v1_Request::getAObjEzsignbulksendsignermapping() const {
return a_obj_ezsignbulksendsignermapping;
}
void OAIEzsignbulksendsignermapping_createObject_v1_Request::setAObjEzsignbulksendsignermapping(const QList<OAIEzsignbulksendsignermapping_RequestCompound> &a_obj_ezsignbulksendsignermapping) {
this->a_obj_ezsignbulksendsignermapping = a_obj_ezsignbulksendsignermapping;
this->m_a_obj_ezsignbulksendsignermapping_isSet = true;
}
bool OAIEzsignbulksendsignermapping_createObject_v1_Request::is_a_obj_ezsignbulksendsignermapping_Set() const{
return m_a_obj_ezsignbulksendsignermapping_isSet;
}
bool OAIEzsignbulksendsignermapping_createObject_v1_Request::is_a_obj_ezsignbulksendsignermapping_Valid() const{
return m_a_obj_ezsignbulksendsignermapping_isValid;
}
bool OAIEzsignbulksendsignermapping_createObject_v1_Request::isSet() const {
bool isObjectUpdated = false;
do {
if (a_obj_ezsignbulksendsignermapping.size() > 0) {
isObjectUpdated = true;
break;
}
} while (false);
return isObjectUpdated;
}
bool OAIEzsignbulksendsignermapping_createObject_v1_Request::isValid() const {
// only required properties are required for the object to be considered valid
return m_a_obj_ezsignbulksendsignermapping_isValid && true;
}
} // namespace OpenAPI
| 38.137255 | 193 | 0.810283 | [
"object"
] |
9ff0287daae723d85a7a8c075bfc0a65798e46e5 | 10,681 | cpp | C++ | SVIEngine/jni/SVI/Physics/SVIConeCurveSimulator.cpp | Samsung/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 27 | 2015-04-24T07:14:55.000Z | 2020-01-24T16:16:37.000Z | SVIEngine/jni/SVI/Physics/SVIConeCurveSimulator.cpp | Lousnote5/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | null | null | null | SVIEngine/jni/SVI/Physics/SVIConeCurveSimulator.cpp | Lousnote5/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 15 | 2015-12-08T14:46:19.000Z | 2020-01-21T19:26:41.000Z | #include "SVIPhysics.h"
#include "../Render/SVIDebugRenderer.h"
// The below implementation is based on cone curl algorithm
// Mesh will be created with width of 1.0 and height of 0.8 units.
// The deformation of mesh will depend on 3 factors Axis, Angle and Offset.
// The above 3 parameters are set passed using deformation ratio
// and needs to updated to this class in update method.
//
// For every loop the 2d mesh coords will be wrapped as the axis, angle and offset
// and copied to the 3D coords output array
//
//
// For some reasons the image was inverted and hence Y and Z are getting multiplied
// by -1 in build()
//
# define DEFAULT_Z 0.0f
//2012-12-11 masterkeaton27@gmail.com
namespace SVI{
#define GRID_DETAIL 20
#define GRID_VERTICAL_COUNT 20
#define MESH_WIDTH 1.0f
#define MESH_HEIGHT 1.0f
SVIConeCurveSimulator::SVIConeCurveSimulator() :
mGridSize(GRID_DETAIL),
mPivotCount(mGridSize*GRID_VERTICAL_COUNT),
mControlTarget(0.0f,0.5f,0.0f),
mControlBase(0.0f,0.5f,0.0f)
{
mPivots = new SVIPivot[mPivotCount];
mLines = new SVISectorLine[mGridSize];
mWidth = MESH_WIDTH;
mHeight = MESH_HEIGHT;
mRows = GRID_DETAIL - 1; //Y_PARTICLES;
mColumns = GRID_VERTICAL_COUNT - 1; //X_PARTICLES;
mRho = 0; //rotation
mTheta = 0; //Angle of
mA.x = 0; //Distance
mA.y = 0; //Distance
xOffset = 0.0f;
mNumOfVertices = (GRID_DETAIL) * (GRID_VERTICAL_COUNT);
//Array to create a 2D mesh and store the position of 2D mesh
mpInputVertex2D = new SVIVector2[sizeof(SVIVector2) * mNumOfVertices]; //2d description of page mesh
if(mpInputVertex2D == NULL)
return;
SVIInt vertexCountY = GRID_VERTICAL_COUNT;
SVIInt vertexCountX = GRID_DETAIL;
SVIInt currentVertex= 0;
for(SVIInt iY =0 ; iY < vertexCountY ; iY++)
{
for(SVIInt iX= 0 ; iX < vertexCountX ; iX++)
{
SVIFloat px = (SVIFloat)iX * mWidth/mRows;
SVIFloat py = (SVIFloat)((vertexCountY - 1)- iY) * mHeight/mColumns;
mpInputVertex2D[currentVertex].x = px;
mpInputVertex2D[currentVertex].y = py;
currentVertex++;
}
}
reset();
}
SVIConeCurveSimulator::~SVIConeCurveSimulator(){
SVI_SVIFE_DELETE_ARRAY(mPivots);
SVI_SVIFE_DELETE_ARRAY(mLines);
SVI_SVIFE_DELETE_ARRAY(mpInputVertex2D);
}
void SVIConeCurveSimulator::reset(){
SVIFloat inverseRatio = 1.0f / (SVIFloat)(mGridSize-1);
SVIFloat inverseVerticalRatio = 1.0f / (SVIFloat)(GRID_VERTICAL_COUNT-1);
for (SVIInt y = 0; y < GRID_VERTICAL_COUNT; ++y){
for (SVIUInt x = 0; x < mGridSize; ++x){
SVIPivot * pPivot = &mPivots[y * mGridSize + x];
pPivot->setPosition(SVIVector3((SVIFloat)x*inverseRatio,(SVIFloat)y*inverseVerticalRatio,0));
}
}
for (SVIUInt x = 0; x < mGridSize; ++x){
SVISectorLine * pLine = &mLines[x];
for (SVIInt y = 0; y < GRID_VERTICAL_COUNT; ++y){
SVIPivot * pPivot = &mPivots[y * mGridSize + x];
if (y == 0) pLine->mStart = pPivot; else
if (y == GRID_VERTICAL_COUNT-1) pLine->mEnd = pPivot;
pLine->mNaturalLength = 1.0f;
pLine->mActiveLength = 1.0f;
pLine->mPivots.push_back(pPivot);
}
}
}
void SVIConeCurveSimulator::setControlTarget(const SVIVector3& target){
mControlTarget = target;
}
void SVIConeCurveSimulator::updateTarget(){
mControlBase.x = mControlTarget.x * SVI_2_PI;
mControlBase.y = mControlTarget.y;
}
void SVIConeCurveSimulator::deformMesh()
{
SVIVector2 p;
SVIVector3 temp;
SVIFloat R;
SVIFloat r;
SVIFloat beta;
SVIFloat tempX;
for(int count = 0 ; count < mNumOfVertices ; count++)
{
if(mpInputVertex2D[count].x >= xOffset)
{
p = mpInputVertex2D[count];
tempX = p.x - xOffset;
R = sqrt(pow(tempX -mA.x, 2) + pow(p.y - mA.y, 2));
r = R * sin(mTheta);
beta = asin(tempX / R) / sin(mTheta);
//wrap p around the imaginary cone
temp.x = r * sin(beta);
temp.y = R + mA.y - r *(1.0f - cos(beta)) * sin(mTheta);
temp.z = r* (1.0f - cos(beta)) * cos(mTheta);
// to x we add offset
// Z is calculated as follows
// default position is added to the above calculation of z with cone curl
// formula
temp.x = temp.x + xOffset;
temp.z += DEFAULT_Z;
}
else
{
temp.x = mpInputVertex2D[count].x;
temp.y = mpInputVertex2D[count].y;
temp.z = DEFAULT_Z;
}
mPivots[count].setPosition(temp);
}
}
void SVIConeCurveSimulator::setAxis(SVIFloat Axis){
mA.y = Axis;
}
void SVIConeCurveSimulator::setAngle(SVIFloat Angle){
mTheta = Angle * RAD;
}
void SVIConeCurveSimulator::setxOffset(SVIFloat Offset){
if(Offset < 0.0f)
xOffset = 0.0f;
else if(Offset > 1.0f)
xOffset = 1.0f;
else
xOffset = Offset;
}
void SVIConeCurveSimulator::update(){
deformMesh();
updateTarget();
}
SVIUInt SVIConeCurveSimulator::getIndicesCount(){
return (mGridSize-1) * (GRID_VERTICAL_COUNT-1) * 6;
}
SVIUInt SVIConeCurveSimulator::getVerticesCount(){
return (mGridSize-1) * (GRID_VERTICAL_COUNT-1) * 4;
}
void SVIConeCurveSimulator::build(const SVIVector3& offset, const SVIVector3& scale,SVIVector3 * pPositions,
SVIUShort * pIndices,SVIVector3 * pNormals,SVIVector2 * pTexcoords,SVIBool isVertical, SVIBool isReverse, SVIBool bFliped){
SVIUInt indexVertex = 0;
SVIUInt index = 0;
for (SVIInt n = 0; n < mPivotCount; ++n){
mPivots[n].setNormal(SVIVector3(0.0f,0.0f,0.0f));
}
for (SVIInt y = 0; y < GRID_VERTICAL_COUNT-1; ++y){
for (SVIUInt x = 0; x < mGridSize-1; ++x){
SVIVector3& p0 = mPivots[y * mGridSize + x].getPosition();
SVIVector3& p1 = mPivots[y * mGridSize + x + 1].getPosition();
SVIVector3& p2 = mPivots[(y + 1) * mGridSize + x].getPosition();
SVIVector3& p3 = mPivots[(y + 1) * mGridSize + (x + 1)].getPosition();
SVIVector3& n0 = mPivots[y * mGridSize + x].getNormal();
SVIVector3& n1 = mPivots[y * mGridSize + x + 1].getNormal();
SVIVector3& n2 = mPivots[(y + 1) * mGridSize + x].getNormal();
SVIVector3& n3 = mPivots[(y + 1) * mGridSize + (x + 1)].getNormal();
SVIVector3 normal = (p1 - p0).Cross(p2 - p0);
if (!bFliped) normal = normal * -1.0f;
n0 += normal;
n1 += normal;
n2 += normal;
normal = (p1 - p2).Cross(p3 - p2);
if (!bFliped) normal = normal * -1.0f;
n1 += normal;
n2 += normal;
n3 += normal;
}
}
for (SVIInt n = 0; n < mPivotCount; ++n){
mPivots[n].getNormal().normalize();
}
//2012-02-09 masterkeaton27@gmail.com
//let reverse action to page
SVIVector3 filteredScale = scale;
if (isReverse){
if (isVertical) {
filteredScale.y *= -1.0f;
}else filteredScale.x *= -1.0f;
}
//2012-12-19 venkat.vr
//Y and Z coordinates are inverted so as we were getting an inverted image
//we are seeing the back face of the image and hence inverting the Y and Z coords
if(1){
filteredScale.y *=-1.0f;
filteredScale.z *=-1.0f;
}
float tuR = 1.0f / (float)(mGridSize-1);
float tvR = 1.0f / (float)(GRID_VERTICAL_COUNT-1);
for (SVIInt y = 0; y < GRID_VERTICAL_COUNT-1; ++y){
for (SVIUInt x = 0; x < mGridSize-1; ++x){
SVIVector3& p0 = mPivots[y * mGridSize + x].getPosition();
SVIVector3& p1 = mPivots[y * mGridSize + x + 1].getPosition();
SVIVector3& p2 = mPivots[(y + 1) * mGridSize + x].getPosition();
SVIVector3& p3 = mPivots[(y + 1) * mGridSize + (x + 1)].getPosition();
if (isVertical){
SVIVector3 pT0 = SVIVector3(p0.y,p0.x,p0.z);
SVIVector3 pT1 = SVIVector3(p1.y,p1.x,p1.z);
SVIVector3 pT2 = SVIVector3(p2.y,p2.x,p2.z);
SVIVector3 pT3 = SVIVector3(p3.y,p3.x,p3.z);
pPositions[indexVertex+0] = offset + pT0 * filteredScale;
pPositions[indexVertex+1] = offset + pT1 * filteredScale;
pPositions[indexVertex+2] = offset + pT2 * filteredScale;
pPositions[indexVertex+3] = offset + pT3 * filteredScale;
}else{
pPositions[indexVertex+0] = offset + p0 * filteredScale;
pPositions[indexVertex+1] = offset + p1 * filteredScale;
pPositions[indexVertex+2] = offset + p2 * filteredScale;
pPositions[indexVertex+3] = offset + p3 * filteredScale;
}
pNormals[indexVertex+0] = mPivots[y * mGridSize + x].getNormal();
pNormals[indexVertex+1] = mPivots[y * mGridSize + (x + 1)].getNormal();
pNormals[indexVertex+2] = mPivots[(y + 1) * mGridSize + x].getNormal();
pNormals[indexVertex+3] = mPivots[(y + 1) * mGridSize + (x + 1)].getNormal();
if (isVertical){
if (!bFliped){
pTexcoords[indexVertex+0] = SVIVector2((SVIFloat)(y) * tvR,(SVIFloat)(x) * tuR);
pTexcoords[indexVertex+1] = SVIVector2((SVIFloat)(y) * tvR,(SVIFloat)(x+1) * tuR);
pTexcoords[indexVertex+2] = SVIVector2((SVIFloat)(y+1)* tvR,(SVIFloat)(x) * tuR);
pTexcoords[indexVertex+3] = SVIVector2((SVIFloat)(y+1)* tvR,(SVIFloat)(x+1) * tuR);
}else{
pTexcoords[indexVertex+0] = SVIVector2(1.0f - (SVIFloat)(y) * tvR,(SVIFloat)(x) * tuR);
pTexcoords[indexVertex+1] = SVIVector2(1.0f - (SVIFloat)(y) * tvR,(SVIFloat)(x+1) * tuR);
pTexcoords[indexVertex+2] = SVIVector2(1.0f - (SVIFloat)(y+1)* tvR,(SVIFloat)(x) * tuR);
pTexcoords[indexVertex+3] = SVIVector2(1.0f - (SVIFloat)(y+1)* tvR,(SVIFloat)(x+1) * tuR);
}
}else{
if (!bFliped){
pTexcoords[indexVertex+0] = SVIVector2((SVIFloat)(x) * tuR,(SVIFloat)(y) * tvR);
pTexcoords[indexVertex+1] = SVIVector2((SVIFloat)(x+1) * tuR,(SVIFloat)(y) * tvR);
pTexcoords[indexVertex+2] = SVIVector2((SVIFloat)(x) * tuR,(SVIFloat)(y+1)* tvR);
pTexcoords[indexVertex+3] = SVIVector2((SVIFloat)(x+1) * tuR,(SVIFloat)(y+1)* tvR);
}else{
pTexcoords[indexVertex+0] = SVIVector2((SVIFloat)(x) * tuR,1.0f - (SVIFloat)(y) * tvR);
pTexcoords[indexVertex+1] = SVIVector2((SVIFloat)(x+1) * tuR,1.0f - (SVIFloat)(y) * tvR);
pTexcoords[indexVertex+2] = SVIVector2((SVIFloat)(x) * tuR,1.0f - (SVIFloat)(y+1)* tvR);
pTexcoords[indexVertex+3] = SVIVector2((SVIFloat)(x+1) * tuR,1.0f - (SVIFloat)(y+1)* tvR);
}
}
if (bFliped){
pIndices[index + 0] = indexVertex+0;
pIndices[index + 1] = indexVertex+1;
pIndices[index + 2] = indexVertex+2;
pIndices[index + 3] = indexVertex+2;
pIndices[index + 4] = indexVertex+1;
pIndices[index + 5] = indexVertex+3;
}else{
pIndices[index + 0] = indexVertex+2;
pIndices[index + 1] = indexVertex+1;
pIndices[index + 2] = indexVertex+0;
pIndices[index + 3] = indexVertex+3;
pIndices[index + 4] = indexVertex+1;
pIndices[index + 5] = indexVertex+2;
}
indexVertex += 4;
index += 6;
}
}
}
};
| 31.694362 | 125 | 0.639921 | [
"mesh",
"render",
"3d"
] |
9ff3a2c28dfb0c2116e7ecfd4b7a8d38e40aecaf | 4,895 | hpp | C++ | wykobi_demo_torri.hpp | jocarsa/WyKobi | f8eb7783b26bc8cb7d83411ca8a43b6dd6f77e20 | [
"MIT"
] | null | null | null | wykobi_demo_torri.hpp | jocarsa/WyKobi | f8eb7783b26bc8cb7d83411ca8a43b6dd6f77e20 | [
"MIT"
] | null | null | null | wykobi_demo_torri.hpp | jocarsa/WyKobi | f8eb7783b26bc8cb7d83411ca8a43b6dd6f77e20 | [
"MIT"
] | null | null | null | /*
(***********************************************************************)
(* *)
(* Wykobi Computational Geometry Library *)
(* Release Version 0.0.5 *)
(* http://www.wykobi.com *)
(* Copyright (c) 2005-2017 Arash Partow, All Rights Reserved. *)
(* *)
(* The Wykobi computational geometry library and its components are *)
(* supplied under the terms of the open source MIT License. *)
(* The contents of the Wykobi computational geometry library and its *)
(* components may not be copied or disclosed except in accordance with *)
(* the terms of the MIT License. *)
(* *)
(* URL: https://opensource.org/licenses/MIT *)
(* *)
(***********************************************************************)
*/
#ifndef INCLUDE_WYKOBI_DEMO_TORRI_HPP
#define INCLUDE_WYKOBI_DEMO_TORRI_HPP
#include <vector>
#include <string>
#include "wykobi.hpp"
#include "wykobi_algorithm.hpp"
#include "wykobi_demo_types.hpp"
#include "wykobi_demo_utils.hpp"
template<typename T, typename Graphic>
class torricelli_point : public task_interface<T,Graphic>
{
public:
void operator()(const Graphic& graphic)
{
graphic.clear(clWhite);
wykobi::triangle<T,2> triangle;
wykobi::generate_random_object<T>
(
T(10), T(10), graphic.width() - T(10), graphic.height() - T(10),
triangle
);
wykobi::point2d<T> torricelli_point = wykobi::torricelli_point(triangle);
graphic.set_color(clBlack);
graphic.set_pen_width(2);
graphic.draw(triangle);
graphic.set_color(clBlue);
graphic.set_pen_width(1);
graphic.draw(wykobi::make_segment(triangle[0],torricelli_point));
graphic.draw(wykobi::make_segment(triangle[1],torricelli_point));
graphic.draw(wykobi::make_segment(triangle[2],torricelli_point));
graphic.set_color(clRed);
graphic.set_pen_width(1);
graphic.draw(wykobi::make_circle<T>(torricelli_point,5));
graphic.draw(wykobi::make_circle<T>(torricelli_point,2));
graphic.set_color(clBlue);
graphic.set_pen_width(1);
graphic.draw(wykobi::make_circle<T>(triangle[0],5));
graphic.draw(wykobi::make_circle<T>(triangle[1],5));
graphic.draw(wykobi::make_circle<T>(triangle[2],5));
}
std::string name() { return "Torricelli Point"; }
};
template<typename T, typename Graphic>
class trilateration : public task_interface<T,Graphic>
{
public:
void operator()(const Graphic& graphic)
{
graphic.clear(clWhite);
if ((graphic.width()) < 200 || (graphic.height() < 200))
return;
wykobi::triangle<T,2> triangle;
wykobi::circle<T> c0;
wykobi::circle<T> c1;
wykobi::circle<T> c2;
wykobi::rectangle<T> window_rect = wykobi::make_rectangle<T>(T(100), T(100), graphic.width() - T(100), graphic.height() - T(100));
do
{
do
{
wykobi::generate_random_object<T>
(T(100), T(100), graphic.width() - T(100), graphic.height() - T(100),triangle);
}
while (wykobi::is_skinny_triangle(triangle));
wykobi::point2d<T> p = wykobi::generate_random_point(triangle);
c0 = wykobi::make_circle(triangle[0],wykobi::distance(triangle[0],p));
c1 = wykobi::make_circle(triangle[1],wykobi::distance(triangle[1],p));
c2 = wykobi::make_circle(triangle[2],wykobi::distance(triangle[2],p));
}
while (
!wykobi::circle_within_rectangle(c0,window_rect) ||
!wykobi::circle_within_rectangle(c1,window_rect) ||
!wykobi::circle_within_rectangle(c2,window_rect)
);
wykobi::point2d<T> trilaterated_point = wykobi::trilateration(c0,c1,c2);
graphic.set_color(clBlue);
graphic.set_pen_width(2);
graphic.set_dash_mode();
graphic.draw(c0);
graphic.draw(c1);
graphic.draw(c2);
graphic.set_pen_width(3);
graphic.set_nodash_mode();
graphic.draw(wykobi::make_circle(triangle[0],3.0));
graphic.draw(wykobi::make_circle(triangle[1],3.0));
graphic.draw(wykobi::make_circle(triangle[2],3.0));
graphic.set_color(clRed);
graphic.set_pen_width(2);
graphic.draw_crosshair(trilaterated_point,5);
graphic.set_pen_width(3);
graphic.draw(wykobi::make_circle(trilaterated_point,4.0));
}
std::string name() { return "Trilateration"; }
};
#endif
| 34.471831 | 136 | 0.563841 | [
"geometry",
"vector"
] |
9ff714780a5b42e0b6b785b901f6bbf715eb7eaa | 2,195 | hpp | C++ | SDK/IEffects.hpp | Bartis1313/csgo | 2af92e14406182bd0b3c15c0143a67e7d1908d02 | [
"MIT"
] | 54 | 2021-11-15T13:39:51.000Z | 2022-03-21T17:13:28.000Z | SDK/IEffects.hpp | Bartis1313/csgo | 2af92e14406182bd0b3c15c0143a67e7d1908d02 | [
"MIT"
] | 24 | 2021-11-08T06:59:34.000Z | 2022-03-17T05:17:03.000Z | SDK/IEffects.hpp | Bartis1313/csgo | 2af92e14406182bd0b3c15c0143a67e7d1908d02 | [
"MIT"
] | 10 | 2021-11-10T06:52:14.000Z | 2022-02-02T17:09:20.000Z | #pragma once
#include "math/Vector.hpp"
#include "../utilities/vfunc.hpp"
class IEffects
{
public:
VFUNC(void, beam, 1,
(const Vector& start, const Vector& end, int modelIndex,
int haloIndex, unsigned char frameStart, unsigned char frameRate,
float life, unsigned char width, unsigned char endWidth, unsigned char fadeLength,
unsigned char noise, unsigned char red, unsigned char green,
unsigned char blue, unsigned char brightness, unsigned char speed),
(this, std::cref(start), std::cref(end), modelIndex, haloIndex, frameStart, frameRate, life, width, endWidth, fadeLength, noise, red, green, blue, brightness, speed)
);
//-----------------------------------------------------------------------------
// Purpose: Emits smoke sprites.
// Input : origin - Where to emit the sprites.
// scale - Sprite scale * 10.
// framerate - Framerate at which to animate the smoke sprites.
//-----------------------------------------------------------------------------
VFUNC(void, smoke, 2, (const Vector& origin, int modelIndex, float scale, float framerate), (this, std::cref(origin), modelIndex, scale, framerate));
VFUNC(void, sparks, 3, (const Vector& position, int magnitude = 1, int trialLength = 1, const Vector* pvecDir = NULL), (this, std::cref(position), magnitude, trialLength, pvecDir));
VFUNC(void, dust, 4, (const Vector& pos, const Vector& dir, float size, float speed), (this, std::cref(pos), std::cref(dir), size, size, speed));
VFUNC(void, muzzleFlash, 5, (const Vector& vecOrigin, const Vector& vecAngles, float scale, int type), (this, std::cref(vecOrigin), std::cref(vecAngles), scale, type));
// like ricochet, but no sound
VFUNC(void, metalSparks, 6, (const Vector& position, const Vector& direction), (this, std::cref(position), std::cref(direction)));
VFUNC(void, energySplash, 7, (const Vector& position, const Vector& direction, bool explosive = false), (this, std::cref(position), std::cref(direction), explosive));
VFUNC(void, ricochet, 8, (const Vector& position, const Vector& direction), (this, std::cref(position), std::cref(direction)));
// if you want to mess with effects abit then add dispatch, I will probably never need it
}; | 66.515152 | 182 | 0.667882 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.