blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d091a3e06147a79bd4b20a6bb2e20e12dfd36212 | C++ | jpbirdy/poj | /模拟题/poj1107/main.cpp | UTF-8 | 2,017 | 3.0625 | 3 | [] | no_license | /*
给定一串字符和k1,k2,k3
将这串字符分组a~i为1,j~r为2,s~z包括_为3
将原串分解为S1,S2,S3
将s1中的字符都改为其坐标向右移动k1个距离的字符,s2s3类似
得到的为加密的串
已知加密的串,求原串
如
the_quick_brown_fox
分组后
S1: i c b f h e
S2: o n o q k r
S3: _ u _ w _ x t
k1=2
右移2位得到的串为
S1: heicbf
S2: qkrono
S3: t_u_w_x
得到的加密串为
_icuo_bfnwhoq_kxert
反着做一遍即可
注意下标会越界
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
int main()
{
int k1,k2,k3;
int i;
while(scanf("%d%d%d",&k1,&k2,&k3)==3)
{
if(k1==0 && k2==0 && k3==0)
break;
string str,s1,s2,s3;
cin >> str;
s1 = s2 = s3 = "";
for(i=0; i<str.size() ; i++)
{
if(str[i]>='a' && str[i]<='i')
{
s1+=str[i];
}
else if(str[i]>='j' && str[i]<='r')
{
s2+=str[i];
}
else
s3+=str[i];
}
int i1,i2,i3;
i1=i2=i3=0;
string ret = "";
int temp;
for(i=0 ; i<str.size(); i++)
{
if(str[i]>='a' && str[i]<='i')
{
temp = i1 - k1;
while(temp<0) temp+=s1.size();
ret+=s1[temp];
i1++;
}
else if(str[i]>='j' && str[i]<='r')
{
temp = i2 - k2;
while(temp<0) temp+=s2.size();
ret+=s2[temp];
i2++;
}
else
{
temp = i3 - k3;
while(temp<0) temp+=s3.size();
ret+=s3[temp];
i3++;
}
}
cout << ret << endl;
}
return 0;
}
| true |
a636953b84654f0709c10b63bec3ac41766f9296 | C++ | orklann/switch-emu-pub | /switch-emu/src/hle/kernel/handleManager.cpp | UTF-8 | 1,663 | 2.609375 | 3 | [] | no_license | #include <vector>
#include <optional>
#include <map>
#include "handleManager.h"
#include "log.h"
namespace kernel::handleman {
// TODO should use table in KProcess
std::vector<KHandleEntry> gHandleTable;
std::map<uint32_t, ObjectPtr<KAutoObject>> gCompressedPointerMap;
// TODO not this
handle_t gHandleCounter = 1; // TODO how are handles generator? Debug sdk asserts that the handle for the main thread < 0x40
uint32_t gCompressedpointerCounter = 0;
handle_t createHandle(ObjectPtr<KAutoObject> object) {
handle_t handle = gHandleCounter++;
uint32_t compressedPointer = gCompressedpointerCounter++;
KHandleEntry newEntry;
newEntry.handleId = static_cast<uint16_t>(handle);
newEntry.objectCompressedPointer = compressedPointer;
newEntry.objectType = object->getType();
gHandleTable.push_back(newEntry);
gCompressedPointerMap[compressedPointer] = object;
return handle;
}
ObjectPtr<KAutoObject> lookupObject(handle_t handle) {
for (const auto& entry : gHandleTable) {
if (entry.handleId == static_cast<uint16_t>(handle)) {
return gCompressedPointerMap[entry.objectCompressedPointer];
}
}
return ObjectPtr<KAutoObject>();
}
bool closeHandle(handle_t handle) {
for (auto i = 0u; i < gHandleTable.size(); i++) {
if (gHandleTable[i].handleId == static_cast<uint16_t>(handle)) {
logger::info("Closing handle %d", handle);
gCompressedPointerMap.erase(gHandleTable[i].objectCompressedPointer);
gHandleTable.erase(gHandleTable.begin() + i);
return true;
}
}
return false;
}
} // namespace kernel::handleman
| true |
a55f43dec3d194fc324772fc29a2125a2cc1274d | C++ | landiinii/C-Based | /BinarySearchTree/NodeInterface.h | UTF-8 | 753 | 2.921875 | 3 | [
"MIT"
] | permissive | //YOU MAY NOT MODIFY THIS DOCUMENT
#ifndef NODE_INTERFACE_H
#define NODE_INTERFACE_H
#include <iostream>
class NodeInterface {
public:
NodeInterface() {}
virtual ~NodeInterface() {}
/*
* Returns the data that is stored in this node
*
* @return the data that is stored in this node.
*/
virtual int getData() const = 0;
/*
* Returns the left child of this node or null if it doesn't have one.
*
* @return the left child of this node or null if it doesn't have one.
*/
virtual NodeInterface * getLeftChild() const = 0;
/*
* Returns the right child of this node or null if it doesn't have one.
*
* @return the right child of this node or null if it doesn't have one.
*/
virtual NodeInterface * getRightChild() const = 0;
};
#endif | true |
dc2aae750c566a748f4a80ccf6f3075171c057e4 | C++ | rainliu/leetcode | /src/734SentenceSimilarity/734SentenceSimilarity.cpp | UTF-8 | 737 | 2.84375 | 3 | [] | no_license | class Solution {
public:
bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<vector<string>>& pairs) {
if (words1.size() != words2.size()) return false;
unordered_map<string, unordered_set<string>> m;
for(const auto& pair: pairs) {
m[pair[0]].insert(pair[1]);
m[pair[1]].insert(pair[0]);
}
for(int i=0; i<words1.size(); ++i){
if ( words1[i]==words2[i] ||
(m.find(words1[i])!=m.end() &&
m[words1[i]].find(words2[i])!=m[words1[i]].end())
){
continue;
}else{
return false;
}
}
return true;
}
};
| true |
0d673c10f2c909103d1229e85fb5c4f4f798d28b | C++ | RedTarantula-Unisinos/GrauA-Physics | /_GrauA/exFisica19/Spaceship.h | UTF-8 | 1,999 | 3 | 3 | [] | no_license | #include <Box2D/Box2D.h>
#include <iostream>
#include <cmath>
#include <string>
#pragma once
class Spaceship
{
public:
Spaceship();
~Spaceship();
void SpawnShip(b2World* world, double _x, double _y); // Creates the spaceship
void DrainFuel(int amount); // Drains fuel
int GetShipFuel() { return fuel; }; // Returns the current ammount of fuel available
float GetAngle(); // Returns the ship's rotation
void DestroyShip(); // Not used yet
b2Body * GetBody() { return body; } // Returns the ship's body
void ShipDecelerate(); // SPACE
void ShipMoveUp(); // W
void ShipMoveDown(); // S
void ShipRotateClockwise(); // A
void ShipRotateAntiClockwise(); // D
b2Vec2 GetGlobalPoint(b2Vec2 pos) { body->GetWorldPoint(pos) ;};
void SetForceMagnitude(float magnitude) { forceMagnitude = magnitude; }; // Changes the impulse's magnitude
void SetForceRotationCompensation(float compensation) { forceRotationCompensation = compensation; }; // Changes the impulse's magnitude for rotation
b2Vec2 VectorComponent(float magnitude, float angulo); // Imported from MatVet.h
float ToRad(float angulo) {return angulo*b2_pi / 180;}; // Imported from MatVet.h
float ToDegrees(float angle) {return angle * 180 / b2_pi;}; // Imported from MatVet.h
void CheckShipWithPlatform(int multiplier); // Checks the ship's conditions when in contact with a platform
float GetSpeed(); // Returns the ship's speed
double FixAngle(double ang); // Keeps the angle in values between 0 and 360 for convenience
void Die() { if (!dead) { PrintWarning("You died"); } dead = true; }; // Kills the ship
bool GetDead() { return dead; }; // Returns if the ship's dead or not
void PrintShipStats(); // Prints the ship's speed, angle and fuel on the console
void PrintWarning(std::string warning); // Prints warnings on the console
private:
float forceMagnitude, forceRotationCompensation;
int fuel, maxfuel;
bool dead;
bool fuelWarning75, fuelWarning50, fuelWarning25, fuelWarning0;
b2Body* body;
};
| true |
779319b320ef3527e1815ee3925e4cbd731d3607 | C++ | shvnick/OpenGL | /OpenGL/ExampleWindow.cc | WINDOWS-1251 | 4,616 | 2.59375 | 3 | [] | no_license | /*
* ExampleWindow.cc
*
* Created on: 22 . 2021 .
* Author:
*/
#include "ExampleWindow.h"
#include <cmath>
static constexpr double Pi = acos(-1.);
//Snowman coordinates
double x1=4.5, x2=4, x3=3.5, x4=3, x5=-0.2;
double y1=1, y2=0, y3=-1, y4=-2, y5=2.7;
double z1=0, z2=0, z3=0, z4=0, z5=4.8;
#include "Primitives.h"
ExampleWindow::ExampleWindow(int width, int height)
:Window(width, height),
_crate_texture("crate_tex_house.png"),
_carrot("carrot.png"),
_leaf("leaf.png"),
tex_roof("roof.png"),
tex_roof2("roof2.png"),
_snow("snow.png"),
_snowfloor("snowfloor.png"),
_wood("wood.png")
{
}
void ExampleWindow::setup() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float ambient[4] = {1, 1, 1, 1};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
glEnable(GL_TEXTURE);
glClearColor(0.2f, 0.35f, 0.45f, 1.0f);
glMatrixMode(GL_PROJECTION);
gluPerspective(45.,
double(width())/double(height()),
0.1, 60.0);
glMatrixMode(GL_MODELVIEW);
}
void ExampleWindow::render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(
15., 15., _camera_z,
0.0, 0.0, 0.0,
0., 0., 1.);
glRotated(_angle, 0., 0., 1.);
_snowfloor.bind();
glEnable(GL_TEXTURE_2D);
_ground.draw();
glDisable(GL_TEXTURE_2D);
_crate_texture.bind();
glEnable(GL_TEXTURE_2D);
_house.draw();
glDisable(GL_TEXTURE_2D);
tex_roof.bind();
glEnable(GL_TEXTURE_2D);
_roof.draw();
glDisable(GL_TEXTURE_2D);
tex_roof2.bind();
glEnable(GL_TEXTURE_2D);
_roof2.draw();
glDisable(GL_TEXTURE_2D);
_wood.bind();
glEnable(GL_TEXTURE_2D);
draw_cone(16, 3., 3., 4.4, 0, 0.5);
draw_cone(16, -3., -3., 4.4, 0, 0.5);
glDisable(GL_TEXTURE_2D);
_leaf.bind();
glEnable(GL_TEXTURE_2D);
draw_cone(16, 3., 3., 1.4, 1.0, 1.3);
draw_cone(16, 3., 3., 1.8, 1.4, 1.2);
draw_cone(16, 3., 3., 2.3, 1.8, 1.1);
draw_cone(16, 3., 3., 2.7, 2.3, 1.0);
draw_cone(16, 3., 3., 3.0, 2.7, 0.9);
draw_cone(16, 3., 3., 3.5, 3.0, 0.8);
draw_cone(16, 3., 3., 4.0, 3.5, 0.7);
draw_cone(16, 3., 3., 4.5, 4.0, 0.6);
draw_cone(16, -3., -3., 1.4, 1.0, 1.3);
draw_cone(16, -3., -3., 1.8, 1.4, 1.2);
draw_cone(16, -3., -3., 2.3, 1.8, 1.1);
draw_cone(16, -3., -3., 2.7, 2.3, 1.0);
draw_cone(16, -3., -3., 3.0, 2.7, 0.9);
draw_cone(16, -3., -3., 3.5, 3.0, 0.8);
draw_cone(16, -3., -3., 4.0, 3.5, 0.7);
draw_cone(16, -3., -3., 4.5, 4.0, 0.6);
glDisable(GL_TEXTURE_2D);
//First snowman
_snow.bind();
glEnable(GL_TEXTURE_2D);
draw_sphere(16, 16, x1, y1, z1, 0.5);
draw_sphere(16, 16, x1, y1, 0.7+z1, 0.4);
draw_sphere(16, 16, x1, y1, 1.25+z1, 0.25);
glDisable(GL_TEXTURE_2D);
_carrot.bind();
glEnable(GL_TEXTURE_2D);
draw_cylinder(5, 1.25+z1, y1, x1+0.5, x1+0.1, 0.1);
glDisable(GL_TEXTURE_2D);
//Second snowman
_snow.bind();
glEnable(GL_TEXTURE_2D);
draw_sphere(16, 16, x2, y2, z2, 0.5);
draw_sphere(16, 16, x2, y2, 0.7+z2, 0.4);
draw_sphere(16, 16, x2, y2, 1.25+z2, 0.25);
glDisable(GL_TEXTURE_2D);
_carrot.bind();
glEnable(GL_TEXTURE_2D);
draw_cylinder(5, 1.25+z2, y2, x2+0.5, x2+0.1, 0.1);
glDisable(GL_TEXTURE_2D);
//Third snowman
_snow.bind();
glEnable(GL_TEXTURE_2D);
draw_sphere(16, 16, x3, y3, z3, 0.5);
draw_sphere(16, 16, x3, y3, 0.7+z3, 0.4);
draw_sphere(16, 16, x3, y3, 1.25+z3, 0.25);
glDisable(GL_TEXTURE_2D);
_carrot.bind();
glEnable(GL_TEXTURE_2D);
draw_cylinder(5, 1.25+z3, y3, x3+0.5, x3+0.1, 0.1);
glDisable(GL_TEXTURE_2D);
//Fourth snowman
_snow.bind();
glEnable(GL_TEXTURE_2D);
draw_sphere(16, 16, x4, y4, z4, 0.5);
draw_sphere(16, 16, x4, y4, 0.7+z4, 0.4);
draw_sphere(16, 16, x4, y4, 1.25+z4, 0.25);
glDisable(GL_TEXTURE_2D);
_carrot.bind();
glEnable(GL_TEXTURE_2D);
draw_cylinder(5, 1.25+z4, y4, x4+0.5, x4+0.1, 0.1);
glDisable(GL_TEXTURE_2D);
//Fifth snowman
_snow.bind();
glEnable(GL_TEXTURE_2D);
draw_sphere(16, 16, x5, y5, z5, 0.3);
draw_sphere(16, 16, x5, y5, 0.4+z5, 0.2);
draw_sphere(16, 16, x5, y5, 0.7+z5, 0.15);
glDisable(GL_TEXTURE_2D);
_carrot.bind();
glEnable(GL_TEXTURE_2D);
draw_cylinder(5, 0.65+z5, y5, x5+0.2, x5+0.05, 0.05);
glDisable(GL_TEXTURE_2D);
}
void ExampleWindow::do_logic() {
_angle += 1.;
if (_angle >= 360.)
_angle -= 360.;
x1 += sin(_angle / 180. * Pi) * 0.05;
x2 += sin(_angle / 180. * Pi) * 0.06;
x3 += sin(_angle / 180. * Pi) * 0.07;
x4 += sin(_angle / 180. * Pi) * 0.08;
_camera_z = 13. + sin(_angle / 180. * Pi) * 5.;
}
| true |
06082a7a03a69284fb22bddc3ceadf89f456d61d | C++ | noeltrivedi/parse_tree | /opNode.h | UTF-8 | 306 | 2.859375 | 3 | [] | no_license | #ifndef OPNODE_H
#define OPNODE_H
#include "node.h"
#include "visitor.h"
class opNode : public Node
{
public:
opNode(char op)
{
this->op = op;
}
opNode()
{
op = 'R';
}
virtual void accept(visitor* v)
{
v->visit(this);
}
char returnOp()
{
return op;
}
private:
char op;
};
#endif | true |
0f96b29f11bcc35118989484a45caf5b15e3a964 | C++ | tanishq1306/Leetcode-Monthy-Challenges | /June/4_Open The Lock.cpp | UTF-8 | 1,426 | 2.90625 | 3 | [] | no_license | class Solution {
public:
int openLock(vector<string>& deadends, string target) {
set<string> dead;
for (const auto &it: deadends) {
dead.insert(it);
}
int level = 0;
queue<string> q;
if (dead.find("0000") == dead.end()) {
q.push("0000");
dead.insert("0000");
}
while (!q.empty()) {
int level_size = q.size();
while (level_size--) {
string top = q.front();
q.pop();
if (top == target) {
return level;
}
for (int i = 0; i < 4; i++) {
// clockwise
string nxt = top;
nxt[i] = (nxt[i] == '9'? '0': (char)(nxt[i] + 1));
if (dead.find(nxt) == dead.end()) {
q.push(nxt);
dead.insert(nxt);
}
// anti-clockwise
nxt = top;
nxt[i] = (nxt[i] == '0'? '9': (char)(nxt[i] - 1));
if (dead.find(nxt) == dead.end()) {
q.push(nxt);
dead.insert(nxt);
}
}
}
level++;
}
return -1;
}
};
| true |
32de1cb1c4779270e98a36b7fdb164cb057ef29e | C++ | LeftySolara/todo | /src/Command.h | UTF-8 | 765 | 2.65625 | 3 | [] | no_license | #ifndef COMMAND_H
#define COMMAND_H
#include "Database.h"
#include <string>
#include <vector>
#include <utility>
class Command
{
public:
enum Action {SHOW, ADD, DONE, MODIFY, DEL, REPORT, CLEAR};
enum Property {ID, STATUS, DESC, DUE, PRIORITY, TAG};
typedef std::pair<Property, std::string> Arg;
Command();
Command(std::string cmd_str);
void parse(std::string cmd_str);
int execute();
private:
Action action = REPORT;
std::vector<Arg> args;
std::string cmd;
void filter_args(const std::vector<std::string> &tokens);
int get_id();
int cmd_show_task();
int cmd_add_task();
int cmd_done_task();
int cmd_modify_task();
int cmd_delete_task();
int cmd_clear();
int cmd_report();
};
#endif
| true |
ebf491c405c9476aec066bba24de688ef15de20c | C++ | CallMeMajorTom/csci499-test | /merge_sort/src/main.cpp | UTF-8 | 643 | 3 | 3 | [] | no_license | #include "merge_sort.h"
#include <gflags/gflags.h>
#include <glog/logging.h>
int main(int argc, char** argv) {
FLAGS_logtostderr = 1;
// Initialize Google's logging library.
google::InitGoogleLogging(argv[0]);
int arr[] = {5,3,4,1,2};
int size = sizeof(arr) / sizeof(arr[0]);
std::string str_array = "";
for (int i = 0; i < size; i++)
str_array += std::to_string(arr[i]) + " ";
LOG(INFO) << "Before: " << str_array;
MergeSort(arr, 0, size-1);
str_array = "";
for (int i = 0; i < size; i++){
str_array += std::to_string(arr[i]) + " ";
}
LOG(INFO) << "After: " << str_array;
return 0;
}
| true |
b717cc4b3fa297cf34cecced79bc5188e6f2c431 | C++ | uwstudent123/LeetCode-Solutions | /XOR Queries of a Subarray.cpp | UTF-8 | 551 | 2.65625 | 3 | [] | no_license | class Solution {
public:
vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
vector<int> ans;
if (arr.empty() || queries.empty()) return ans;
vector<int> pref;
pref.reserve(arr.size() + 1);
pref[0] = arr[0];
for (int i=1; i<arr.size(); i++) {
pref[i] = pref[i - 1] ^ arr[i];
}
for (auto i : queries) {
if (i[0]) ans.push_back(pref[i[1]] ^ pref[i[0] - 1]);
else ans.push_back(pref[i[1]]);
}
return ans;
}
}; | true |
6b916d9185aabe8150b2cc4d4c09cccf7a7640b2 | C++ | lwhay/hashcomp | /stream/src/utils/QuantileStatistics.h | UTF-8 | 1,522 | 2.890625 | 3 | [] | no_license | //
// Created by Michael on 10/26/2019.
//
#ifndef HASHCOMP_QUANTILESTATISTICS_H
#define HASHCOMP_QUANTILESTATISTICS_H
#include <vector>
template<typename freqtype, typename counttype>
class FCQuantile {
private:
std::vector<std::pair<freqtype, counttype>> freqCounts;
uint64_t accCount = 0;
uint64_t keyCount = 0;
public:
void add(std::pair<freqtype, counttype> p) {
freqCounts.push_back(p);
keyCount += p.second;
accCount += (p.first * p.second);
}
uint64_t getAccCount() { return accCount; }
uint64_t getKeyCount() { return keyCount; }
uint64_t getAccCount(double perc) {
uint64_t expect = (uint64_t) (keyCount * perc);
uint64_t acount = 0;
uint64_t kcount = 0;
for (int i = 0; i < freqCounts.size(); i++) {
if (kcount > expect) {
break;
}
kcount += freqCounts.at(i).second;
acount += (freqCounts.at(i).first * freqCounts.at(i).second);
}
return acount;
}
uint64_t getKeyCount(double perc) {
uint64_t expect = (uint64_t) (accCount * perc);
uint64_t acount = 0;
uint64_t kcount = 0;
for (int i = 0; i < freqCounts.size(); i++) {
if (acount > expect) {
break;
}
kcount += freqCounts.at(i).second;
acount += (freqCounts.at(i).first * freqCounts.at(i).second);
}
return kcount;
}
};
#endif //HASHCOMP_QUANTILESTATISTICS_H
| true |
da6a5c52ba84408505f1450c129ef2e384521d09 | C++ | jetaehyun/SW_Doge | /include/data_packet.h | UTF-8 | 1,096 | 2.625 | 3 | [] | no_license | #ifndef DATA_PACKET_H
#define DATA_PACKET_H
#include <iostream>
#include <cstdint>
#include <string>
#include "../include/data_manipulation.h"
#define NO_USER_SPECIFIED 0
#define PAYLOAD_SIZE 28
#define DATA_PACKET_SIZE 37
#define PAYLOAD_OFFSET 8
using std::cout;
using std::endl;
using namespace Data_Manipulation;
/*
// 0
// type
// 4
// user id
// 8
// payload
// 36
// checksum
// 37
*/
class Data_Packet {
public:
Data_Packet(uint32_t user_id) { this->user_id = user_id; }
Data_Packet() { this->user_id = NO_USER_SPECIFIED; }
virtual ~Data_Packet() {}
virtual void create_packet() = 0;
virtual void unpack_payload() = 0;
virtual uint8_t *get_packet() = 0;
virtual void packet_details() = 0;
bool unpack_packet(uint8_t *packet);
protected:
enum packet_type_e { light, testing };
uint32_t user_id;
uint8_t packet[DATA_PACKET_SIZE] = {0};
uint8_t calculate_checksum();
bool verify_checksum(uint8_t *packet);
};
#endif | true |
9b166d275832ec997bb4fe855c6421b3160b85b7 | C++ | alexseppar/RISC-V-fsim | /sim/options.h | UTF-8 | 2,633 | 3.046875 | 3 | [
"MIT"
] | permissive | #ifndef OPTIONS_H
#define OPTIONS_H
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <string>
#include <type_traits>
namespace options
{
template<typename T>
T ParseArg(int &cur_arg, int num_arg, char *argv[])
{
if constexpr (std::is_same_v<T, bool>)
return true;
if (cur_arg >= num_arg)
throw std::invalid_argument("the required option is not specified");
if constexpr (std::is_unsigned_v<T>)
{
try
{
return std::stoull(std::string(argv[cur_arg++]));
}
catch (std::invalid_argument &e)
{
throw std::invalid_argument(argv[cur_arg]);
}
}
else if constexpr (std::is_same_v<T, char *>)
return argv[cur_arg++];
else
static_assert("Unsupported type");
}
template<typename T>
class Option
{
private:
T data_;
const char *opt_name_;
const char *arg_name_;
const char *opt_desc_;
public:
Option(T default_value, const char *opt_name, const char *arg_name, const char *opt_desc)
: data_(default_value)
, opt_name_(opt_name)
, arg_name_(arg_name)
, opt_desc_(opt_desc)
{
}
operator T() const
{
return data_;
}
bool ParseOption(int &cur_arg, int num_arg, char *argv[])
{
if (!strcmp(opt_name_, argv[cur_arg]))
{
++cur_arg;
try
{
data_ = ParseArg<T>(cur_arg, num_arg, argv);
}
catch (std::exception &e)
{
throw std::invalid_argument(std::string("Unrecognized ") + opt_name_ +
" option: " + e.what());
}
return true;
}
else
return false;
}
void PrintHelp()
{
printf("%s ", opt_name_);
if (arg_name_)
printf("[%s] ", arg_name_);
printf("(value = ");
if constexpr (std::is_same_v<T, bool>)
printf("%s", data_ ? "true" : "false");
else if constexpr (std::is_unsigned_v<T>)
printf("%llu", static_cast<unsigned long long>(data_));
else if constexpr (std::is_same_v<T, char *>)
printf("%s", data_ ? data_ : "<empty>");
else
static_assert("Unsupported type");
printf(") - %s\n", opt_desc_);
}
};
#define OPTION_DEF(var, type, def, opt_name, arg_name, desc) extern Option<type> var;
#include "options_list.h"
#undef OPTION_DEF
extern FILE *log;
void ParseOptions(int argc, char *argv[]);
void OpenLog();
void CloseLog();
} // namespace options
#endif
| true |
10ca9e8feb88bbca80cac33eb34ee6ca0b85e8ac | C++ | matthewrdev/Neural-Network | /Neural Network Source Code/Game/include/Clarity/Math/LineSegment3.h | UTF-8 | 6,433 | 2.671875 | 3 | [] | no_license | #ifndef CLARITY_LINESEGMENT3_H
#define CLARITY_LINESEGMENT3_H
/** @file LineSegment3.h
*
* This file contains the LineSegment3 class definition.
*
* This source file is part of Clarity.
* Clarity is a game engine designed for teaching.
* For the latest info, see http://members.optusnet.com.au/dfreya
*
* Copyright (c) 2007 Dale Freya
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* or go to http://www.gnu.org/copyleft/lesser.txt.
*
*/
#include <Clarity/Math/Vector3.h>
#include <Clarity/Math/Line3.h>
#include <iosfwd>
namespace Clarity
{
class LineSegment2;
/**
* This class represents a line segment in 3D space.
*/
class LineSegment3
{
public:
/**
* Construct a line segment.
*
* @param tail
* The tail end point of the line segment.
* @param head
* The head end point of the line segment.
*/
LineSegment3(const Vector3 &tail, const Vector3 &head);
/**
* Construct a line segment from a 2D line segment.
*
* @param lineSegment
* The 2D line segment from which to construct the 3D line segment.
* @param tailZ
* The z coordinate of the tail of the new 3D line segment.
* @param headZ
* The z coordinate of the head of the new 3D line segment.
*/
LineSegment3(const LineSegment2 &lineSegment2, float tailZ, float headZ);
/**
* Destructor.
*/
~LineSegment3();
/**
* Get the tail end point of the line segment.
*
* @returns
* The tail end point of the line segment.
*/
const Vector3 &GetTail() const;
/**
* Get the head end point of the line segment.
*
* @returns
* The head end point of the line segment.
*/
const Vector3 &GetHead() const;
/**
* Get a vector from the tail to the head.
*
* @returns
* A vector from the tail to the head of the line segment.
*/
const Vector3 &GetVector() const;
/**
* Get a unit vector in the direction from the tail to the head.
*
* @returns
* A unit vector in the direction from the tail to the head.
*/
const Vector3 &GetDirection() const;
/**
* Get a vector normal to this line segment.
*
* @returns
* A vector normal to this line segment.
*/
const Vector3 &GetNormal() const;
/**
* Get the length of the line segement.
*
* @returns
* The length of the line segment.
*/
float GetLength() const;
/**
* Get the squared length of the line segement. Faster than get length
* and can be used to compare relative lengths.
*
* @returns
* The squared length of the line segment.
*/
float GetLengthSquared() const;
/**
* Find the mid point of the line segment.
*
* @returns
* A vector representing the point that is the mid point of the line
* segment.
*/
Vector3 Midpoint() const;
/**
* Transform this line segment by the given matrix to generate a new
* line segment.
*
* @param transform
* The matrix used to transform the line segment.
*
* @returns
* A transformed copy of the line segment.
*/
LineSegment3 Transform(const Matrix4 &transform) const;
/**
* Set the tail and head end points of the line segment.
*
* @param tail
* The tail of the line segment.
* @param head
* The head of the line segment.
*/
void Set(const Vector3 &tail, const Vector3 &head);
/**
* Get the line that this segment lies on.
*
* @returns
* The line that this line segment lies on.
*/
const Line3 &GetLine() const;
/**
* Finds a point on the line segment closer than any other point on the
* line segment to startingPoint.
*
* @param startingPoint
* Find the point on the line segment nearest to this point.
*
* @returns
* The point on the line segment nearest the starting point.
*/
Vector3 FindNearestPoint(const Vector3 &startingPoint) const;
/**
* Returns the closest point on the line segment to a given displacement
* where the tail of the line is displacement zero and the head is the
* length of the line. Note that the displacement will always be on the
* line but not necessarily within the bounds of the line segment.
*
* @param displacement
* The displacement along the line.
*
* @returns
* A vector representing the point on the line that is displacment
* units away from the tail.
*/
Vector3 GetClosestPointFromDisplacement(float displacement) const;
private:
void MarkAsDirty() const;
Vector3 m_tail;
Vector3 m_head;
mutable Line3 m_line;
mutable bool m_lineDirty;
mutable float m_length;
mutable bool m_lengthDirty;
mutable float m_lengthSquared;
mutable bool m_lengthSquaredDirty;
mutable Vector3 m_vector;
mutable bool m_vectorDirty;
};
/**
* Output a 3D line segment to a stream.
*
* @param os
* Write the line segment to this output stream.
* @param rhs
* Write this line segment to the output stream.
*
* @returns
* The supplied output stream.
*/
std::ostream &operator<<(std::ostream &os, const LineSegment3 &rhs);
}
#endif
| true |
7bb059835ac0f91df22e778e021f612f36836f71 | C++ | mycicle/cpp_datastructures | /solar_system/solar_system.cc | UTF-8 | 6,649 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <random>
using namespace std;
default_random_engine gen(0);
uniform_int_distribution<int> distribution(0, 99);
class Vec3d {
public:
long double x, y, z;
Vec3d(): x(0), y(0), z(0) {}
Vec3d(const long double x, const long double y, const long double z): x(x), y(y), z(z){}
Vec3d(const Vec3d& orig): x(orig.x), y(orig.y), z(orig.z) {}
Vec3d(Vec3d&& orig): x(orig.x), y(orig.y), z(orig.z) {}
Vec3d& operator =(const Vec3d& orig) {
x = orig.x;
y = orig.y;
z = orig.z;
return *this;
}
Vec3d operator /(const long double scalar) const {
Vec3d a(x/scalar, y/scalar, z/scalar);
return a;
}
Vec3d operator +(const Vec3d& vec) const {
Vec3d a(vec.x+x, vec.y+y, vec.z+z);
return a;
}
Vec3d operator -(const Vec3d& vec) const {
return (*this + (-vec));
}
Vec3d operator -() const {
return Vec3d(-x, -y, -z);
}
Vec3d operator *(const Vec3d& vec) const {
Vec3d a(x*vec.x, y*vec.y, z*vec.z);
return a;
}
Vec3d operator *(const long double scalar) const {
Vec3d a(x*scalar, y*scalar, z*scalar);
return a;
}
Vec3d perpendicular2D() const {
return Vec3d(-y, x, 0);
}
Vec3d handleNan() {
if (isnan(x))
x = 0;
if (isnan(y))
y = 0;
if (isnan(z))
z = 0;
return (*this);
}
long double mag() const {
return sqrt(x*x + y*y + z*z);
}
Vec3d unitVector() const {
Vec3d unit = (*this) * (1/(*this).mag());
return unit;
}
friend long double dot(const Vec3d& left, const Vec3d& right) {
return left.x*right.x + left.y*right.y + left.z*right.z;
}
friend Vec3d cross(const Vec3d& left, const Vec3d& right) {
return Vec3d(left.y*right.z - left.z*right.y, left.z*right.x - left.x*right.z, left.x*right.y - left.y*right.x);
}
friend ostream& operator <<(ostream& s, const Vec3d& v) {
return s << "(" << v.x << "," << v.y << "," << v.z <<")";
}
};
class Body {
private:
const long double G = 6.67430e-11;
Vec3d pos, vel, acc;
long double mass, radius, orb; //orb = orbital distance
string name;
int random = distribution(gen);
public:
Body(): pos(), vel(), acc(), mass(), radius(), orb(), name() {}
Body(const Vec3d& pos, const Vec3d& vel, const Vec3d& acc, const long double mass, const long double radius, const string& name):
pos(pos), vel(vel), acc(acc), mass(mass), radius(radius), orb(orb), name(name) {}
Body(const Body& o): pos(o.pos), vel(o.vel), acc(o.acc), mass(o.mass), radius(o.radius), orb(o.orb), name(o.name) {}
Body(Body&& o): pos(o.pos), vel(o.vel), acc(o.acc), mass(o.mass), radius(o.radius), orb(o.orb), name(o.name) {}
Body operator =(const Body& o) {
pos = o.pos; vel = o.vel; acc = o.acc; mass = o.mass;
radius = o.radius; name = o.name;
return *this;
}
Vec3d calcGravForce(Body* body) {
// gravitational force equation
long double force = (G * mass * body->mass) / ((body->pos - pos).mag() * (body->pos - pos).mag());
// cout << "force vector "<< force << endl;
Vec3d forceVector = (body->pos-pos).unitVector() * force;
return forceVector;
}
void update(vector<Body*>& bodies, const long double dt) {
Vec3d netForce(0,0,0);
for (auto body : bodies) {
if(body != this) {
// cout << "net force " << netForce << endl;
netForce = netForce + calcGravForce(body);
} else {
// cout << "This is in the array!" << endl;
}
}
pos = pos + vel*dt + acc*0.5*pow(dt, 2);
vel = vel + acc*dt;
acc = acc + (netForce/mass);
}
Vec3d getPos() const {
return pos;
}
string getName() const {
return name;
}
friend ostream& operator <<(ostream& s, const Body& b) {
return s << "Name: " << b.name << " Mass: " << b.mass << " Radius: " << b.radius << " Position: " << b.pos
<< endl << "Velocity: " << b.vel << " Acceleration: " << b.acc;
}
friend void operator >>(istream &out, Body& b) {
string i;
vector<string> attribs;
while (out >> i) {
attribs.push_back(i);
}
if (attribs.size() != 10) {
throw length_error("Invalid input length. Expected 10 columns");
}
b.name = attribs.at(0);
b.mass = stod(attribs.at(2));
b.radius = stod(attribs.at(3))/2;
long double rad = (stod(attribs.at(4)) + stod(attribs.at(5))) / 2;
long double diam = rad*2;
b.pos = Vec3d(rad*cos(b.random), rad*sin(b.random), 0).handleNan();
Vec3d velocity_direction = Vec3d(-rad*sin(b.random), rad*cos(b.random), 0).handleNan();
Vec3d velocity_unit = velocity_direction.unitVector().handleNan();
long double velocity_mag = (diam * M_PI) / (stod(attribs.at(6)) * 24 * 60 * 60);
if (isnan(velocity_mag))
velocity_mag = 0;
b.vel = velocity_unit * velocity_mag;
Vec3d acceleration = (b.vel.perpendicular2D() * b.vel.perpendicular2D()).handleNan() / rad;
b.acc = acceleration.handleNan();
}
};
class SolarSystem {
private:
vector<Body*> bodies;
public:
SolarSystem(string filepath) {
stringstream ss;
string line;
string name, orbits, mass, diam, rest;
ifstream f(filepath);
int counter = 0;
while(getline(f, line)) {
if (line.substr(0, 4) == "Name")
continue;
Body* b = new Body();;
ss << line;
ss >> (*b);
bodies.push_back(b);
counter ++;
ss.clear();
}
}
SolarSystem(vector<Body*>& bodies): bodies(bodies) {}
void timeStep(long double dt) {
for (auto body : bodies) {
body->update(bodies, dt);
}
}
friend ostream& operator <<(ostream& s, const SolarSystem& ss) {
for (auto body : ss.bodies) {
s << body->getPos() << endl;
}
// s << endl;
return s;
}
};
int main() {
SolarSystem s("solarsystem.dat"); // this must not change
// each body should have a random position in a circular or elliptical orbit around the sun
// each body should start with an appropriate velocity
//each body should have velocity = https://en.wikipedia.org/wiki/Circular_orbit v= sqrt(GM/r)
long double earthYear = 365.2425 * 24 * 60 * 60;
const int numTimeSteps = 1000;
long double dt = earthYear / numTimeSteps;
for (int i = 0; i < numTimeSteps; i++)
s.timeStep(dt);
cout << s; // print out the state of the solar system (where each object is, location only)
return 0;
// if you do it right, earth should be in roughly the same place...
} | true |
5994fa9a1140695adfae863e21ee3894ff58d066 | C++ | Stagno/cuda-pt | /cuda_alloc.h | UTF-8 | 1,488 | 2.53125 | 3 | [] | no_license | /*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2009 Thierry Berger-Perrin <tbptbp@gmail.com>, http://ompf.org
*/
#ifndef RT_ALLOC_H
#define RT_ALLOC_H
#include <cuda_runtime_api.h>
void fatal() {
exit(1);
}
//
// make those calls a bit safer to use (and traceable).
//
template<bool device_side, typename T>
void cuda_allocate(T *&p, size_t n) {
if (device_side)
cudaMalloc((void**)&p, sizeof(T)*n);
else
cudaMallocHost((void**)&p, sizeof(T)*n);
if (p == 0) {
fprintf(stderr, "*** cuda_allocate: failed to allocate %.3fM on %s\n", sizeof(T)*n / (1024. * 1024), device_side ? "device" : "host");
fatal();
}
#ifndef NDEBUG
printf("allocated %.3fM on %s\n", (sizeof(T)*n) / (1024. * 1024), device_side ? "device" : "host");
#endif
}
template<typename T>
void cuda_deallocate(T *&p) {
cudaFree(p);
p = 0;
}
template<typename T>
void cuda_memset(T *p, size_t n) {
cudaMemset(p, 0, sizeof(T)*n);
}
#endif
| true |
bc9b3b3754946f1ab8a49a8cf7ba48c7b6021307 | C++ | voithos/quarkGL | /quarkgl/cubemap.h | UTF-8 | 1,990 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef QUARKGL_CUBEMAP_H_
#define QUARKGL_CUBEMAP_H_
#include <qrk/framebuffer.h>
#include <qrk/mesh_primitives.h>
#include <qrk/shader.h>
#include <qrk/shader_primitives.h>
#include <qrk/texture_registry.h>
namespace qrk {
class CubemapException : public QuarkException {
using QuarkException::QuarkException;
};
// A helper for rendering to a cubemap texture in a framebuffer. The passed-in
// framebuffer must outlive the life of this helper.
class CubemapRenderHelper {
public:
CubemapRenderHelper(Framebuffer* buffer) : buffer_(buffer) {}
void setTargetMip(int mip) { targetMip_ = mip; }
// Draws with the given shader to each face of the cubemap. This results in 6
// different draw calls. Shader should be prepared (i.e. necessary textures
// should either be bound or be in the registry, uniforms should be set, etc).
void multipassDraw(Shader& shader,
TextureRegistry* textureRegistry = nullptr);
private:
Framebuffer* buffer_;
RoomMesh room_;
int targetMip_ = 0;
};
class EquirectCubemapShader : public Shader {
public:
EquirectCubemapShader();
};
// Converts an equirect texture to a cubemap.
class EquirectCubemapConverter : public TextureSource {
public:
EquirectCubemapConverter(int width, int height, bool generateMips = false);
explicit EquirectCubemapConverter(ImageSize size, bool generateMips = false)
: EquirectCubemapConverter(size.width, size.height, generateMips) {}
virtual ~EquirectCubemapConverter() = default;
// Draw onto the allocated cubemap from the given texture as the source.
void multipassDraw(Texture source);
Texture getCubemap() { return cubemap_.asTexture(); }
unsigned int bindTexture(unsigned int nextTextureUnit,
Shader& shader) override;
private:
Framebuffer buffer_;
Attachment cubemap_;
EquirectCubemapShader equirectCubemapShader_;
CubemapRenderHelper cubemapRenderHelper_;
bool generateMips_;
};
} // namespace qrk
#endif | true |
7ee7a2c9e878599429ccae667acb18a1d78ba651 | C++ | kolyvoshko/Isometric-game | /src/object/animal_genetic_code.cpp | UTF-8 | 1,227 | 2.734375 | 3 | [
"MIT"
] | permissive | /**
* @file animal_genetic_code.cpp
*/
#include "animal_genetic_code.h"
AnimalGeneticCode::AnimalGeneticCode():
GeneticCode()
{
}
AnimalGeneticCode AnimalGeneticCode::create_carnivorous_code(){
AnimalGeneticCode carnivorous_code;
carnivorous_code.carnivorous = 1.0;
carnivorous_code.herbivorous = 0.0;
carnivorous_code.max_turn = 0.2;
carnivorous_code.max_velosity = 0.1;
carnivorous_code.max_acceleration = 0.0;
carnivorous_code.max_eyesight = 5.0;
carnivorous_code.max_mass = 1.0;
carnivorous_code.max_length = 0.1;
carnivorous_code.max_width = 0.05;
carnivorous_code.max_time_life = 2;
return carnivorous_code;
}
AnimalGeneticCode AnimalGeneticCode::create_herbivorous_code(){
AnimalGeneticCode herbivorous_code;
herbivorous_code.carnivorous = 0.0;
herbivorous_code.herbivorous = 1.0;
herbivorous_code.max_turn = 0.2;
herbivorous_code.max_velosity = 0.1;
herbivorous_code.max_acceleration = 0.0;
herbivorous_code.max_eyesight = 5.0;
herbivorous_code.max_mass = 1.0;
herbivorous_code.max_length = 0.1;
herbivorous_code.max_width = 0.05;
herbivorous_code.max_time_life = 100;
return herbivorous_code;
}
| true |
93fa56738cc689631717cf8c8605060af127e5c4 | C++ | ManishDV/Engineering-Assignments | /SE-SEM2-Assigns/DFSL Assignments/Assign5/Queue.cpp | UTF-8 | 1,040 | 3.359375 | 3 | [] | no_license | /*
* queue.cpp
*
* Created on: 05-Feb-2019
* Author: neo
*/
#include "Queue.h"
#include <iostream>
using namespace std;
template<class T>
Queue<T>::Queue() {
// TODO Auto-generated constructor stub
front = new struct queue;
rear = new struct queue;
front = NULL;
rear = NULL;
}
template<class T>
Queue<T>::~Queue() {
// TODO Auto-generated destructor stub
}
template<class T>
bool Queue<T>::isEmpty() {
if (front == NULL && rear == NULL)
return true;
return false;
}
template<class T>
void Queue<T>::enque(T data) {
if (isEmpty()) {
struct queue *temp = new struct queue;
temp->obj = data;
temp->next = NULL;
front = temp;
rear = temp;
} else {
rear->next = new struct queue;
rear = rear->next;
rear->obj = data;
rear->next = NULL;
}
}
template<class T>
T Queue<T>::dequeue() {
struct queue *temp = front;
T ob;
if (front != rear) {
front = front->next;
ob = temp->obj;
delete temp;
} else {
front = front->next;
ob = temp->obj;
delete temp;
rear = NULL;
}
return ob;
}
| true |
4863fd791b88ca2516c418202a61c3e607118cca | C++ | tstibro/chip8 | /Chip8lib/core/cpu/registers/pcreg.cpp | UTF-8 | 691 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
* gpr.cpp
*
* Created on: September 29, 2016
* Author: Tomas Stibrany
*/
#include "pcreg.hpp"
using namespace chip8::core::cpu::registers;
ProgramCounterRegister::ProgramCounterRegister(u16 resetAddress)
{
registerContents = resetAddress;
Unlock();
}
ProgramCounterRegister::~ProgramCounterRegister()
{
}
void ProgramCounterRegister::Lock()
{
locked = true;
}
void ProgramCounterRegister::Unlock()
{
locked = false;
}
void ProgramCounterRegister::JumpToAddress(u16 address)
{
if (!locked)
registerContents = address;
}
void ProgramCounterRegister::SetNextInstruction()
{
if (!locked)
registerContents += 2;
}
u16 ProgramCounterRegister::Read()
{
return registerContents;
} | true |
46c8e15f1787819d91f0f2238e899c3c68f35121 | C++ | SirMouthAlot/Blight-3D | /OpenGL Framework Test1/OpenGL Framework Test1/Model.h | UTF-8 | 911 | 2.5625 | 3 | [] | no_license | #ifndef __MODEL_H__
#define __MODEL_H__
#include "Mesh.h"
class Model {
public:
Model();
Model(const Model& copy);
~Model();
bool LoadFromFile(const std::string &_path, const std::string &_name);
void Draw(Shader* shader);
//Meshes
std::vector<Mesh*> meshes;
unsigned int meshIndex = 0;
//Materials
std::vector<Material*> materials;
std::vector<std::string> matNames;
unsigned int matIndex = 0;
//helper functions
inline Transform* GetTransform() { return &transform; }
//File stuffs
std::string path;
std::string name;
//unique data
std::vector<glm::vec3> vertexData;
std::vector<glm::vec2> textureData;
std::vector<glm::vec3> normalData;
std::vector<MeshFace> faceData;
glm::vec3 colorTint = glm::vec3(1.f, 1.f, 1.f);
bool firstObj = false;
bool hasUVs = false;
private:
bool ProcessMaterials(const std::string &file);
Transform transform;
};
#endif // !__MODEL_H__
| true |
8a4ff0ea712985fc8a8f9365ab4640f948d5f35a | C++ | godori/Algorithm_basic | /01.C++/Pointer/call_by.cpp | UTF-8 | 575 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void call_by_val(int val){
val = 20;
}
void call_by_ref(int *ref){
*ref = 20;
}
int main(int argc, char const *argv[]) {
int value = 10;
int refer = 10;
cout << "before : " << value << "," << refer << endl;
call_by_val(value);
// cout << "&refer : " << &refer << endl;
// cout << "*(&refer) : " << *(&refer) << endl;
call_by_ref(&refer);
// cout << "&refer : " << &refer << endl;
// cout << "*(&refer) : " << *(&refer) << endl;
cout << "after : " << value << "," << refer << endl;
return 0;
}
| true |
6614d9d821c8d46dc896cef29554175531834528 | C++ | crisdeodates/Robotics-control-toolbox | /ct_core/include/ct/core/integration/EventHandlers/KillIntegrationEventHandler.h | UTF-8 | 2,150 | 2.5625 | 3 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**********************************************************************************************************************
This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.
Licensed under the BSD-2 license (see LICENSE file in main directory)
**********************************************************************************************************************/
#pragma once
#include <ct/core/integration/EventHandler.h>
namespace ct {
namespace core {
//! Event handler to kill integration
/*!
* This event handler kills the integration if the kill flag is set. This is useful
* for multi-threaded applications where an external kill signal needs to interrupt
* an ongoing integration
*
* @tparam STATE_DIM size of the state vector
*/
template <size_t STATE_DIM>
class KillIntegrationEventHandler : public EventHandler<STATE_DIM>
{
public:
typedef Eigen::Matrix<double, STATE_DIM, 1> State_T;
//! default constructor
/*!
* sets kill event to false
*/
KillIntegrationEventHandler() : killIntegration_(false) {}
//! default destructor
virtual ~KillIntegrationEventHandler() {}
virtual bool callOnSubsteps() override { return false; }
//! checks the kill flag
bool checkEvent(const State_T& state, const double& t) override { return killIntegration_; }
//! interrupts integration
/*!
* interrupts the integration by throwing a std::runtime_error
* @param state current state (ignored)
* @param t current time (ignored)
*/
void handleEvent(const State_T& state, const double& t) override
{
/* throw an exception which stops the integration */
throw std::runtime_error("Integration terminated due to external event specified by user.");
}
//! enables killing at next call
void setEvent() { killIntegration_ = true; }
//! disable killing at next call
void resetEvent() { killIntegration_ = false; }
//! resets kill flag to false
virtual void reset() override { resetEvent(); };
private:
bool killIntegration_; //! kill flag
};
} // namespace core
} // namespace ct
| true |
27b6b21e77ec496a0a65876ab9ca40554616d994 | C++ | jhseoeo/C_Algoritm_DataStructure | /C_Data_Structure/src/Sorting_Algorithm/Complicated_Sorting/HeapSort.cpp | UTF-8 | 549 | 3.8125 | 4 | [] | no_license | #include "HeapSort.h"
void HeapSort(int* arr, int s, int e) {
for(int i = (s + e) / 2; i >= s; i--) // Make the array heap.
ReHeapDown(arr, i, e);
for(int i = e; i > s; i--) { // Sorting array.
if(arr[s] > arr[i])
swap(arr[s], arr[i]);
ReHeapDown(arr, s, i-1);
}
}
void ReHeapDown(int* arr, int s, int e) {
int i = s;
while(true) {
if (i*2 + 2 > e) break;
int bigger = (arr[i*2 + 1] >= arr[i*2 + 2] ? i*2 + 1 : i*2 + 2);
if (arr[i] < arr[bigger]) {
swap(arr[i], arr[bigger]);
i = bigger;
}
else
break;
}
} | true |
e25bb159cfdad76a61c16bf1e52de7174db5183d | C++ | jorgealemangonzalez/3DGames | /src/controller.h | UTF-8 | 860 | 2.5625 | 3 | [] | no_license |
#ifndef TJE_FRAMEWORK_2017_CONTROLLER_H
#define TJE_FRAMEWORK_2017_CONTROLLER_H
#include "constants.h"
#include "includes.h"
#include "entity.h"
class CameraController{
/*TODO Meter todos los comportamientos de la camara aqui:
- Que tenga un punto al que siempre ve a una distancia en concreto,
ir cambiando la posición de este punto conforme lo que seleccionamos con el raton
Hay que guardar dos vectores para reconstruir la camara con la misma inclinación
http://tamats.com/games/ld27/
*/
public:
int mode;
Vector3 entityPreviusPos;
//Methods
CameraController();
~CameraController();
void setMode(int m);
void notifyEntity(UID e_uid);
void update( double seconds_elapsed);
void onMouseWheel(SDL_MouseWheelEvent event);
};
#endif //TJE_FRAMEWORK_2017_CONTROLLER_H
| true |
d845ba7e488df404fd1d5690aaf21c81e4d49114 | C++ | GameDevMike/Elementary-Fighter | /portrait_functions.cpp | UTF-8 | 3,056 | 2.734375 | 3 | [] | no_license | #include "headers.hpp"
Hero_Portrait::Hero_Portrait( HEROES name, SIDE looking )
{
this->name = name;
this->looking = looking;
width = 140;
height = 144;
color_red = al_map_rgb( 255, 0, 0 );
color_blue = al_map_rgb( 0, 0, 255 );
border_red = false;
border_blue = false;
calibri = al_load_font( "fonts/calibri.ttf", 50, 0 );
name_title = false;
}
int Hero_Portrait::choose_bitmap_and_load()
{
if( looking == Right )
{
switch( name )
{
case Panda: { portrait_map = al_load_bitmap( "img_faces/panda_right.png" ); break; }
case HolderH: { portrait_map = al_load_bitmap( "img_faces/holder.png" ); break; }
case NoneH: break;
}
}
else if( looking == Left )
{
switch( name )
{
case Panda: { portrait_map = al_load_bitmap( "img_faces/panda_left.png" ); break; }
case HolderH: { portrait_map = al_load_bitmap( "img_faces/holder.png" ); break; }
case NoneH: break;
}
}
if( !portrait_map ) return -1;
else return 1;
}
void Hero_Portrait::draw( float x, float y )
{
position_x = x;
position_y = y;
al_draw_scaled_bitmap( portrait_map, 0, 0, 140, 144, position_x, position_y, Display_Monitor_Issues::get_scaling_factor_x()*width, Display_Monitor_Issues::get_scaling_factor_y()*height, 0 );
}
void Hero_Portrait::allow_red_border( bool a )
{
border_red = a;
}
void Hero_Portrait::allow_blue_border( bool a )
{
border_blue = a;
}
void Hero_Portrait::draw_red_border()
{
if( border_red )
al_draw_rectangle( position_x, position_y, position_x+Display_Monitor_Issues::get_scaling_factor_x()*width, position_y+Display_Monitor_Issues::get_scaling_factor_y()*height, color_red, 3 );
}
void Hero_Portrait::draw_blue_border()
{
if( border_blue )
al_draw_rectangle( position_x, position_y, position_x+Display_Monitor_Issues::get_scaling_factor_x()*width, position_y+Display_Monitor_Issues::get_scaling_factor_y()*height, color_blue, 3 );
}
void Hero_Portrait::allow_write_name( bool a )
{
name_title = a;
}
void Hero_Portrait::write_name()
{
if( name_title )
{
const char *c;
float x;
if( looking == Right ) x = 350.0;
else if( looking == Left ) x = 1150.0;
switch( name )
{
case Panda: c = "PANDA"; break;
case HolderH: c = "/holder/"; break;
case NoneH: break;
}
al_draw_text( calibri, al_map_rgb( 0, 0, 0 ), Display_Monitor_Issues::get_scaling_factor_x()*x, Display_Monitor_Issues::get_scaling_factor_y()*200.0, 0, c );
}
}
/*float Hero_Portrait::get_x() { return position_x; }
float Hero_Portrait::get_y() { return position_y; }
float Hero_Portrait::get_w() { return width; }
float Hero_Portrait::get_h() { return height; }*/
Hero_Portrait::~Hero_Portrait()
{
al_destroy_bitmap( portrait_map );
al_destroy_font( calibri );
}
| true |
bf1bc802609ea080306adce8cf411ec5e7ad66d5 | C++ | tanwi1234/Interview-Bit-coding-problems | /Two pointer/remove duplicates from aray.cpp | UTF-8 | 536 | 2.734375 | 3 | [] | no_license | int Solution::removeDuplicates(vector<int> &A) {
int i;
vector<int>s;
for(i=0;i<A.size();i++)
{
bool found=true;
int j=A.size()-1;
while(j>i)
{
if(A[j]==A[i])
{
found=false;
break;
}
j--;
}
if(found==true)
{
s.push_back(A[i]);
}
}
A.clear();
for(i=0;i<s.size();i++)
{
A.push_back(s[i]);
}
return A.size();
} | true |
4211cc096069b53a7fe4e9076c5c893ed7ea7529 | C++ | heojoung2/Baekjoon | /숫자 카드.cpp | UTF-8 | 577 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<map>
#include<cstdio>
using namespace std;
int main()
{
int card1_num, card2_num;
map<int, int> map;
scanf("%d", &card1_num);
int *card1 = new int[card1_num];
for (int i = 0; i < card1_num; i++)
{
scanf("%d", &card1[i]);
map.insert(pair<int, int>(card1[i], 1));
}
int num;
scanf("%d", &card2_num);
for (int i = 0; i < card2_num; i++)
{
scanf("%d",&num);
try {
printf("%d ", map[num]);
}
catch (exception e)
{
printf("0 ");
}
}
delete[] card1;
return 0;
} | true |
7f0759314be8f12736174567e14a20894d06fc02 | C++ | embosfer/record-store | /Record.h | UTF-8 | 167 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <string>
using std::string;
class Record {
public:
Record(string& name): _name(name) {}
string name();
private:
string _name;
}; | true |
31515045175dbf0acbb88ee931055b323164a994 | C++ | jffifa/algo-solution | /ural/1792.cpp | UTF-8 | 550 | 2.921875 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstring>
int hmr[7];
bool ok()
{
if ((hmr[1]+hmr[2]+hmr[3])%2!=hmr[4]) return 0;
if ((hmr[0]+hmr[2]+hmr[3])%2!=hmr[5]) return 0;
if ((hmr[0]+hmr[1]+hmr[3])%2!=hmr[6]) return 0;
return 1;
}
int main()
{
for (int i = 0; i < 7; ++i)
scanf("%d", hmr+i);
if (ok())
{
for (int i = 0; i < 7; ++i)
printf("%d ", hmr[i]);
puts("");
return 0;
}
for (int i = 0; i < 7; ++i)
{
hmr[i]^=1;
if (ok())
{
for (int j = 0; j < 7; ++j)
printf("%d ", hmr[j]);
return 0;
}
hmr[i]^=1;
}
return 0;
}
| true |
1996e8d9f29a61a6cea1ddd425b0f5afd65e593f | C++ | tzik/wasm | /src/irt/memory.cc | UTF-8 | 826 | 2.578125 | 3 | [] | no_license |
#include <stdarg.h>
#include <stdio.h>
#include "memory.h"
#include "env.h"
namespace irt {
constexpr unsigned long page_size = 0x10000;
unsigned long current_memory() {
volatile unsigned long ret = 0;
__asm__ volatile("current_memory %0=" : "=r"(ret));
return ret;
}
unsigned long grow_memory(unsigned long x) {
volatile unsigned long ret = 0;
__asm__ volatile("grow_memory %0=, %1" : "=r"(ret) : "r"(x));
return ret;
}
long sys_brk(va_list argp) {
const unsigned long page_size = 64 * 1024;
unsigned long addr = va_arg(argp, unsigned long);
if (addr == 0)
return current_memory() * page_size;
unsigned long grow_to = (addr + page_size - 1) / page_size;
unsigned long delta = grow_to - current_memory();
grow_memory(delta);
return current_memory() * page_size;
}
} // namespace irt
| true |
356dff4007633ca9c96378d169c72d8dca947f49 | C++ | strikeraryu/Competitive_Coding | /may_challenge_leetcode/Counting Bits.cpp | UTF-8 | 1,045 | 3.203125 | 3 | [] | no_license | // Problem
// Given a non negative integer number num.
// For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
// Example
// Input: 2
// Output: [0,1,1]
// Input: 5
// Output: [0,1,1,2,1,2]
// Constraints:
// It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
// Space complexity should be O(n).
// Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
//-----------------------------------------------------------------------------------------------------
// Solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans{0};
for(int i=1;i<=num;){
for(int ind=0,n=ans.size();i<=num && ind<n;i++,ind++)
ans.push_back(1+ans[ind]);
}
return ans;
}
}; | true |
6ae6628891303d9a45fdac5cf5c2dc4fc0da76c0 | C++ | weihangxiao/Operating-System | /Labs/lab1/lab1.cpp | UTF-8 | 5,474 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
//unordered_map<string, int> symtable;
struct Tokens {
int linecount;
int offset;
string str;
};
queue<Tokens> tokenlist; //store parsed tokenss
//vector<pair<string, int>> symbolTable;
void tokenizer(string filename) {
ifstream infile;
infile.open(filename);
int linenum;
string line;
// vector <string> tokens;
if (infile.is_open()) {
while (getline(infile, line)) {
linenum++;
char *cstr = new char[line.length() + 1];
strcpy(cstr, line.c_str());
int loc = -1; //make sure start from the index 0 position
char *token = strtok(& line[0], " "); //there could be '\t'
while (token != NULL) {
loc = line.find(string(token), loc + 1) + 1;
Tokens tok;
tok.linecount = linenum;
tok.offset = loc;
tok.str = string(token);
tokenlist.push(tok);
token = strtok(NULL, " ");
}
delete[] cstr;
}
//Record the end position
infile.close();
}
// for (int i = 0; i < tokenlist.size(); i++) {
// cout << tokenlist[i].offset << " " << endl;
// }
}
int readInt(string str) {
if (str.size() == 0) return -1;
for (int i = 0; i < str.size(); i++) {
if((str[i]>='0' && str[i]<='9')==false) {
return -1;
}
}
return stoi(str);
}
bool readSym(string str) {
if (!isalpha(str[0])) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!isalnum(str[i])) {
return false;
}
}
return true;
}
void parseerror(int linenum, int lineoffset, int errcode) {
static string errstr[] = {
"NUM_EXPECTED",
"SYM_EXPECTED",
"ADDR_EXPECTED",
"SYM_TOLONG",
"TO_MANY_DEF_IN_MODULE",
"TO_MANY_USE_IN_MODULE",
"TO_MANY_INSTR"
};
printf("Parse Error line %d offset %d: %s\n", linenum, lineoffset, errstr[errcode].c_str());
}
bool parser() {
int index = 0;
while (!tokenlist.empty()) {
Tokens token = tokenlist.front();
tokenlist.pop();
if (tokenlist.empty()) {
parseerror(token.linecount, token.offset, 1); //expected sym
return false;
}
//tokenqueue.pop();
int defcount = readInt(token.str);
if (defcount == -1) {
parseerror(token.linecount, token.offset, 0); // too many def in module
return false;
}
if (defcount > 16) {
parseerror(token.linecount, token.offset, 4); // too many def in module
return false;
}
for (int i = 0; i < defcount; i++) {
token = tokenlist.front();
tokenlist.pop();
string symbol = token.str;
if (tokenlist.empty()) {
parseerror(token.linecount, token.offset, 1); //expected sym ?????????????
return false;
}
if (!readSym(symbol)) {
parseerror(token.linecount, token.offset, 1); //expected symbol
return false;
}
if (symbol.length() > 16) {
parseerror(token.linecount, token.offset, 3); // too many def in module
return false;
}
token = tokenlist.front();
tokenlist.pop();
if (tokenlist.empty()) {
parseerror(token.linecount, token.offset, 0); //expected num
return false;
}
int val = readInt(token.str);
if (val == -1) {
parseerror(token.linecount, token.offset, 0); // too many def in module
return false;
}
}
/***********Use List*************/
token = tokenlist.front();
tokenlist.pop();
if (tokenlist.empty()) {
parseerror(token.linecount, token.offset, 1); // expected symbol
return false;
}
int usecount = readInt(token.str);
if (usecount == -1) {
parseerror(token.linecount, token.offset, 0); // expected num
return false;
}
if (usecount > 16) {
parseerror(token.linecount, token.offset, 4); // too many def in module
return false;
}
for (int i = 0; i < usecount; i++) {
token = tokenlist.front();
tokenlist.pop();
string symbol = token.str;
if (symbol.length() > 16) {
parseerror(token.linecount, token.offset, 3); // too many def in module
return false;
}
if (!readSym(symbol)) {
parseerror(token.linecount, token.offset, 1); //expected symbol
return false;
}
}
/*********** Program Text *************/
token = tokenlist.front();
tokenlist.pop();
}
return true;
}
int main(int argc, char* argv[]) {
//for(int i=0; i < argc; i++) {// i=1, assuming files arguments are right after the executable
string fn = argv[1]; //filename
tokenizer(fn);
//}
if (!parser()) {
return 0;
}
return 0;
} | true |
0008ff979da734b6e415b32f1f014e4ed3417182 | C++ | MangeI89/Test | /TSBK03Project/TSBK03Project/Entity.cpp | UTF-8 | 3,482 | 2.671875 | 3 | [] | no_license | #include "Entity.h"
Entity::Entity() {}
Entity::Entity(const Mesh& mesh) {
//m_mesh = mesh;
}
Entity::Entity(const shared_ptr<Mesh>& mesh, const vec3& position, const vec3& velocity, const vec3& rotation, const vec3& scale) {
this->mesh = mesh;
this->currentPosition = position;
this->initialPosition = position;
this->currentVelocity = velocity;
this->initialVelocity = velocity;
this->rotation = rotation;
this->scale = scale;
lifeTime = 0;
resetWhenZero = false;
}
Entity::~Entity() {}
void Entity::AttachShader(const shared_ptr<Shader>& shader) {
this->shader = shader;
}
void Entity::AddTexture(const shared_ptr<Texture>& texture) {
textures.push_back(texture);
}
void Entity::AddFBO(const shared_ptr<FrameBufferObject>& fbo) {
fbos.push_back(fbo);
}
void Entity::AddSkybox(const shared_ptr<Skybox>& skybox) {
skyboxes.push_back(skybox);
currentSkybox = skybox;
}
shared_ptr<Shader> Entity::GetShader() {
return shader;
}
vector<shared_ptr<Texture>> Entity::GetTextures() {
return textures;
}
vector<shared_ptr<FrameBufferObject>> Entity::GetFBOs() {
return fbos;
}
vector<shared_ptr<Skybox>> Entity::GetSkyboxes() {
return skyboxes;
}
shared_ptr<Skybox> Entity::GetCurrentSkybox() {
return currentSkybox;
}
void Entity::ChooseSkybox(const GLuint& unit) {
currentSkybox = skyboxes[unit];
}
vec3 Entity::GetPosition() const { return currentPosition; }
vec3 Entity::GetRotation() { return rotation; }
vec3 Entity::GetScale() { return scale; }
mat4 Entity::GetModelMatrix() {
mat4 translationMatrix = translate(currentPosition);
mat4 rotX = rotate(radians(rotation.x), vec3(1, 0, 0));
mat4 rotY = rotate(radians(rotation.y), vec3(0, 1, 0));
mat4 rotZ = rotate(radians(rotation.z), vec3(0, 0, 1));
mat4 rotationMatrix = rotZ * rotY * rotX;
mat4 scaleMatrix = glm::scale(scale);
return translationMatrix * rotationMatrix * scaleMatrix;
}
mat4 Entity::GetBillboardModelMatrix(const vec3& cameraForward) {
vec3 u = cross(-cameraForward, vec3(0, 1, 0));
u = normalize(u);
vec3 n = cross(u, -cameraForward);
mat4 modelMatrix = mat4(1.0);
modelMatrix[0] = vec4(n, 0.0);
modelMatrix[1] = vec4(u, 0.0);
modelMatrix[2] = vec4(-cameraForward, 0.0);
return translate(currentPosition) * modelMatrix;
}
shared_ptr<Mesh> Entity::GetMesh() {
return mesh;
}
void Entity::UpdatePosition(const float& deltaT) {
currentPosition = currentPosition + currentVelocity * deltaT;
if (currentPosition.y < initialPosition.y) {
currentPosition = initialPosition;
currentVelocity = initialVelocity;
lifeTime = 0;
}
lifeTime += deltaT;
}
void Entity::UpdateVelocity(const float& deltaT) {
currentVelocity.y = currentVelocity.y - 9.82 * deltaT;
}
float Entity::GetBlendFactor() {
double fraction, intFactor;
double mod = lifeTime / 0.125;
fraction = modf(mod, &intFactor);
return fraction;
}
vec2 Entity::GetOffset() {
double xFraction1, yFraction1, xFraction2, yFraction2, xInt1, yInt1, xInt2, yInt2;
double xMod = lifeTime / 0.125;
double yMod = lifeTime / 0.5;
if (yMod > 4.0) { resetWhenZero = true; }
xFraction1 = modf(xMod, &xInt1);
yFraction1 = modf(yMod, &yInt1);
xFraction2 = modf(xInt1 / 4.0, &xInt2);
yFraction2 = modf(yInt1 / 4.0, &yInt2);
return vec2(xInt1, yInt1);
}
void Entity::SetPosition(const vec3& position) { this->currentPosition = position; }
void Entity::SetRotation(const vec3& rotation) { this->rotation = rotation; }
void Entity::SetScale(const vec3& scale) { this->scale = scale; }
| true |
1a6a0039f5a0ca6e1c5b8cb2185abfbf627e9a8e | C++ | alenthankz/Master_DSA | /CODE/Tree/11mirrorTreeCheck.cpp | UTF-8 | 505 | 3.3125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node * left,*right;
Node(int val){
data=val;
left=right=NULL;
}
};
bool isMirror(Node * root1, Node*root2 ){
if(!root1 && !root2)return true;
if(!root1 || !root2)return false;
return (root1->data==root2->data) &&
(isMirror(root1->left,root2->right))&&
(isMirror(root1->right,root2->left));
}
// to check a tree is symetric , pass root1& root2 as root | true |
0ffa86333969ee0c29f0aaf8e37186faa7bff455 | C++ | SandorSu/DataStructure-Algorith | /Algo2017_0722_6.cpp | UTF-8 | 485 | 3.890625 | 4 | [] | no_license | /*Horner Rule for Taylor Series*/
#include<iostream>
using namespace std;
double exp1(int x,int n)
{
static double s = 1;
if ( n == 0)
{
double s1 = s;
s = 1;
return s1;
}
s = 1+s*x/n;
return exp1(x,n-1);
}
double exp2(int x, int n)
{
double s = 1;
for (; n> 0 ;n --)
s = 1+s*x/n;
return s;
}
int main()
{
cout<<exp1(4,10)<<endl;
cout<<exp2(4,10)<<endl;
}
| true |
45605bcea0f80e4a9bc1eb6d943633568a22bf78 | C++ | zhaoyujie199196/doubanspider | /DBS/DBS/core/DBSQueue.h | UTF-8 | 1,416 | 3.078125 | 3 | [] | no_license | #pragma once
#pragma once
#include <list>
#include <memory>
#include <mutex>
#include <condition_variable>
#include "assert.h"
template <class T>
class DBSQueue
{
public:
DBSQueue(int nMaxCount)
{
assert(nMaxCount > 0);
m_nMaxCount = nMaxCount;
}
~DBSQueue() {}
T takeOne()
{
std::unique_lock<std::mutex> locker(m_mutex);
m_NotEmptyCondition.wait(locker, [this] {
return notEmpty() || m_bQuit;
});
if (m_bQuit)
return nullptr;
T pData = *m_DataList.begin();
m_DataList.erase(m_DataList.begin());
return pData;
}
void appendOne(T pTask)
{
std::unique_lock<std::mutex> locker(m_mutex);
m_NotFullCondition.wait(locker, [this] {
return notFull() || m_bQuit;
});
if (m_bQuit)
return;
m_DataList.emplace_back(pTask);
m_NotEmptyCondition.notify_one();
return;
}
void close()
{
{
std::unique_lock<std::mutex> locker(m_mutex);
m_DataList.clear();
m_bQuit = true;
}
m_NotEmptyCondition.notify_all();
m_NotFullCondition.notify_all();
}
protected:
bool notEmpty()
{
return !m_DataList.empty();
}
bool notFull()
{
return m_DataList.size() != m_nMaxCount;
}
protected:
int m_nMaxCount = 0;
volatile bool m_bQuit = false;
std::list<T> m_DataList;
std::mutex m_mutex;
std::condition_variable m_NotFullCondition;
std::condition_variable m_NotEmptyCondition;
}; | true |
98e2f3f2d9dd4ab5909eee0a1a5ffd9a16a18020 | C++ | Jiinwoo/Algorithm | /10430 나머지.cpp | UTF-8 | 241 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int a,b,c;
scanf("%d %d %d", &a,&b,&c);
int year =1;
while(1){
if((year%15)+1==a && ((year%28)+1)==b && ((year%19)+1)==c){
printf("%d\n", year);
break;
}
}
return 0;
}
| true |
cc96e5e53d822506906260a08425729cd06388f0 | C++ | tianjigezhu/Algorithm | /C++/test.cpp | UTF-8 | 546 | 2.953125 | 3 | [] | no_license | #include "CSingleLinkList.hpp"
#include <iostream>
using Paradise::Algorithm::CSingleLinkList;
using Paradise::Type::EBool;
using std::cout;
using std::endl;
namespace a
{
template<class T>
struct B
{
T c;
};
}
int main(int argc, char *argv[])
{
Paradise::Algorithm::CSingleLinkList<int> singleLinkList;
for (int index = 0; index < 10; ++index) {
singleLinkList.insertFirst(index);
}
int count = singleLinkList.length();
for (int index = 0; index < count; ++index) {
cout << singleLinkList.valueAt(index) << endl;
}
return 0;
} | true |
5226eb101d1e8292a86f862b4f7d4baae5ff60d7 | C++ | burgerj123/stack-queue | /JQueue.cpp | UTF-8 | 2,439 | 3.84375 | 4 | [] | no_license | /*
* File: JQueue.cpp
* Author: Jackson Burger
* Purpose: JQueue implementation
* Created on June 27, 2021, 11:05 AM
*/
#include "JQueue.h"
template <typename J> JQueue<J>::JQueue() //Default constructor
{
count = 0;
front = 0;
back = -1;
}
template <typename J> JQueue<J>::JQueue(const JQueue& copyMe) //Copy constructor
{
count = copyMe.count;
front = copyMe.front;
back = copyMe.back;
for (int i=0; i <= count; i++)
{
array[i] = copyMe.array[i];
}
}
template <typename J> JQueue<J>::~JQueue() //Destructor
{
//No data allocating
}
template <typename J> void JQueue<J>::insert(const J letter) //Insert into queue
{
if (!isFull()) //If queue is not full
{
back = (back + 1) % size; //Updates the back of the arrays index and wraps around if needed due to this being a circular array
array[back] = letter; //The new item is placed at the back end of the array
count++;
}
}
template <typename J> J JQueue<J>::remove() //Removes item from queue
{
if (!isEmpty())
{
J temp = array[front]; //Stores value of the item about to be removed
front = (front + 1) % size; //Updates the front of the arrays index and wraps around if needed due to this being a circular array
count--; //Removes item
return temp;
}
}
template <typename J> bool JQueue<J>::isFull() const
{
return (count >= size); //If count is greater or equal to size then its full
}
template <typename J> bool JQueue<J>::isEmpty() const
{
return (count <= 0); //If count is less than or equal to 0 then the queue is empty
}
template <typename J> J JQueue<J>::getFront()const
{
return array[front]; //Returns the character at the front end of the array
}
template <typename J> int JQueue<J>::getSize()const
{
return count; //Returns the count to signify the amount of items in the queue
}
template <typename J> void JQueue<J>::print() const
{
if (!isEmpty())
{
for (int i = 0; i < count; i++)
{
int index = (front + i) % size; //Index is incremented to where it can wrap around the circular array
cout << array[index]; //Print at the index of the array
}
}
cout << endl;
}
template class JQueue<char>;
template class JQueue<float>;
template class JQueue<int>;
template class JQueue<string>;
| true |
e28364efec8980d2a55b3585be365457cb78ee9e | C++ | i-tsvetkov/opencv | /detect.cpp | UTF-8 | 2,193 | 2.546875 | 3 | [] | no_license | #include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
double factor = 1.0625;
if (argc < 2)
{
printf("usage: <image> [<factor>]\n");
return 1;
}
else if (argc >= 3)
{
factor = stod(argv[2]);
}
const char FaceCascade[] = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt_tree.xml";
const char EyeCascade[] = "/usr/share/opencv/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cas(FaceCascade);
CascadeClassifier eye_cas(EyeCascade);
Mat image = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
equalizeHist(image, image);
vector<Rect> faces;
face_cas.detectMultiScale(image, faces, factor,
2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
for (auto face : faces)
{
Mat f = image(face);
imshow("Preview", f);
waitKey(0);
destroyAllWindows();
string person("");
printf("Please enter the person name: ");
getline(cin, person);
if (person.empty())
person = "unknown";
vector<Rect> eyes;
eye_cas.detectMultiScale(f, eyes, factor,
2, 0 | CASCADE_SCALE_IMAGE, Size(10, 10));
if (eyes.size() == 2)
{
Rect left_eye = (eyes[0].x < eyes[1].x) ? eyes[0] : eyes[1];
Rect right_eye = (eyes[0].x > eyes[1].x) ? eyes[0] : eyes[1];
Point le_center(face.x + left_eye.x + left_eye.width / 2,
face.y + left_eye.y + left_eye.height / 2);
Point re_center(face.x + right_eye.x + right_eye.width / 2,
face.y + right_eye.y + right_eye.height / 2);
printf("(\"%s\" \"%s\" (%d %d %d %d) (%d %d) (%d %d))\n",
argv[1], person.c_str(), face.x, face.y, face.width, face.height,
le_center.x, le_center.y, re_center.x, re_center.y);
}
else
{
printf("(\"%s\" \"%s\" (%d %d %d %d))\n",
argv[1], person.c_str(), face.x, face.y, face.width, face.height);
}
}
return 0;
}
| true |
b43202eb24f87cac6cc7f74aad679df1f5812fdc | C++ | zhujun98/A-Star-search | /test/test_map_search.cpp | UTF-8 | 3,367 | 3.421875 | 3 | [
"Apache-2.0"
] | permissive | //
// Test Map class and A* search.
//
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <vector>
#include "../map.h"
/**
* Summarize the shorted path
*
* @param path: output from function shortestPath()
* @param height: height of the map
*/
void display(std::pair<double, std::vector<bool>> path, size_t width)
{
std::cout << "Shortest path length: " << path.first << std::endl;
std::cout << "The shortest path is: " << std::endl;
for (size_t i = 0; i < path.second.size(); ++i)
{
std::cout << path.second[i];
if ( (i + 1) % width == 0 ) { std::cout << std::endl; }
}
std::cout << std::endl;
}
/**
* Run test on a uniform path
*
* 1 1 1 1
* 1 1 1 1
* 1 1 1 1
*/
void testUniformMap()
{
size_t width = 4;
size_t height = 3;
std::vector<uint8_t> elevation(width*height, 0x01);
std::vector<bool> obstacles(width*height, false);
mmap::Map map(width, height, elevation, obstacles);
std::pair<double, std::vector<bool>>
path = map.shortestPath(std::make_pair(0, 0), std::make_pair(3, 1), 1, 1, 0);
// display(path, width);
assert(std::abs(path.first - 3.41421) < 1.0e-5 );
assert(std::accumulate(path.second.begin(), path.second.end(), 0) == 4);
std::cout << "Passed!" << std::endl;
}
/**
* Run test on a map with river marsh and water basin
*
* 1 O 1 1
* 1 O O 1
* 1 1 1 1
*/
void testWaterMap()
{
size_t width = 4;
size_t height = 3;
std::vector<uint8_t> elevation(width*height, 0x01);
std::vector<bool> obstacles(width*height, false);
obstacles[1] = true;
obstacles[5] = true;
obstacles[6] = true;
mmap::Map map(width, height, elevation, obstacles);
std::pair<double, std::vector<bool>>
path = map.shortestPath(std::make_pair(0, 0), std::make_pair(3, 1), 1, 1, 0);
assert(std::abs(path.first - 4.82843) < 1.0e-5 );
assert(std::accumulate(path.second.begin(), path.second.end(), 0) == 5);
std::cout << "Passed!" << std::endl;
}
/**
* Run test on a map with river marsh and water basin as well as
* variable elevations.
*
* 0x01 0x02 0x02 0x04 0x08 0x04
* 0x02 R 0x08 W W 0x02
* 0x04 0x02 0x01 W W 0x01
* 0x02 0x04 0x04 0x02 0x01 0x01
*/
void testFullMap()
{
size_t width = 6;
size_t height = 4;
std::vector<uint8_t> elevation {0x01, 0x02, 0x02, 0x04, 0x08, 0x04,
0x02, 0xFF, 0x08, 0xFF, 0xFF, 0x02,
0x04, 0x02, 0x01, 0xFF, 0xFF, 0x01,
0x02, 0x04, 0x04, 0x02, 0x01, 0x01};
std::vector<bool> obstacles {0, 0, 0, 0, 0, 0,
0, 1, 0, 1, 1, 0,
0, 0, 0, 1, 1, 0,
0, 0, 0, 0, 0, 0};
mmap::Map map(width, height, elevation, obstacles);
std::pair<double, std::vector<bool>>
path = map.shortestPath(std::make_pair(0, 0), std::make_pair(5, 3), 1, 1, 0);
// display(path, width);
assert(std::abs(path.first - 7.16509) < 1.0e-5 );
assert(std::accumulate(path.second.begin(), path.second.end(), 0) == 7);
std::cout << "Passed!" << std::endl;
}
/**
* Test path search in different maps
*/
int main()
{
testUniformMap();
testWaterMap();
testFullMap();
}
| true |
cae7c0b23e415f68110e25fd6ac66bd06dcc9a16 | C++ | ponxosio/bioblocksTranslationTest | /bioblocksTranslationTest/tests/auto/sequentialprotocol/stringactuatorsinterface.h | UTF-8 | 3,985 | 2.84375 | 3 | [] | no_license | #ifndef STRINGACTUATORSINTERFACE_H
#define STRINGACTUATORSINTERFACE_H
#include <sstream>
#include <vector>
#include <utils/AutoEnumerate.h>
#include <protocolGraph/execution_interface/actuatorsexecutioninterface.h>
class StringActuatorsInterface : public ActuatorsExecutionInterface
{
public:
StringActuatorsInterface(const std::vector<double> & measureValues);
virtual ~StringActuatorsInterface();
virtual void applyLigth(const std::string & sourceId, units::Length wavelength, units::LuminousIntensity intensity);
virtual void stopApplyLigth(const std::string & sourceId);
virtual void applyTemperature(const std::string & sourceId, units::Temperature temperature);
virtual void stopApplyTemperature(const std::string & sourceId);
virtual void stir(const std::string & idSource, units::Frequency intensity);
virtual void stopStir(const std::string & idSource);
virtual void centrifugate(const std::string & idSource, units::Frequency intensity);
virtual void stopCentrifugate(const std::string & idSource);
virtual void shake(const std::string & idSource, units::Frequency intensity);
virtual void stopShake(const std::string & idSource);
virtual void startElectrophoresis(const std::string & idSource, units::ElectricField fieldStrenght);
virtual std::shared_ptr<ElectrophoresisResult> stopElectrophoresis(const std::string & idSource);
virtual units::Volume getVirtualVolume(const std::string & sourceId);
virtual void loadContainer(const std::string & sourceId, units::Volume initialVolume);
virtual void startMeasureOD(const std::string & sourceId, units::Frequency measurementFrequency, units::Length wavelength);
virtual double getMeasureOD(const std::string & sourceId);
virtual void startMeasureTemperature(const std::string & sourceId, units::Frequency measurementFrequency);
virtual units::Temperature getMeasureTemperature(const std::string & sourceId);
virtual void startMeasureLuminiscense(const std::string & sourceId, units::Frequency measurementFrequency);
virtual units::LuminousIntensity getMeasureLuminiscense(const std::string & sourceId);
virtual void startMeasureVolume(const std::string & sourceId, units::Frequency measurementFrequency);
virtual units::Volume getMeasureVolume(const std::string & sourceId);
virtual void startMeasureFluorescence(const std::string & sourceId,
units::Frequency measurementFrequency,
units::Length excitation,
units::Length emission);
virtual units::LuminousIntensity getMeasureFluorescence(const std::string & sourceId);
virtual void setContinuosFlow(const std::string & idSource, const std::string & idTarget, units::Volumetric_Flow rate);
virtual void stopContinuosFlow(const std::string & idSource, const std::string & idTarget);
virtual units::Time transfer(const std::string & idSource, const std::string & idTarget, units::Volume volume);
virtual void stopTransfer(const std::string & idSource, const std::string & idTarget);
virtual units::Time mix(const std::string & idSource1,
const std::string & idSource2,
const std::string & idTarget,
units::Volume volume1,
units::Volume volume2);
virtual void stopMix(const std::string & idSource1,
const std::string & idSource2,
const std::string & idTarget);
virtual void setTimeStep(units::Time time);
virtual units::Time timeStep();
const std::stringstream & getStream() const {
return stream;
}
protected:
units::Time timeSlice;
std::stringstream stream;
AutoEnumerate actualValueSerie;
std::vector<double> measureValues;
double getNextReadValue();
};
#endif // STRINGACTUATORSINTERFACE_H
| true |
1416fff07b81de413807907903cdf58d1f8768b4 | C++ | Girl-Code-It/Leetcode-Challenge | /Vaishali Thakur/July/1. Arrange Coins.cpp | UTF-8 | 458 | 2.78125 | 3 | [] | no_license | class Solution {
public:
int arrangeCoins(int n) {
long start = 0, end = n;
while(start <= end){
long mid = start + (end - start) / 2;
long curr = (mid * (mid + 1)) / 2;
if(curr == n)
return mid;
else if(curr > n){
end = mid - 1;
} else {
start = mid + 1;
}
}
return end;
}
}; | true |
9479fbe5d2208d44029a697b8ee49628eb9e2eb1 | C++ | mfixman/PAP-BGLF | /TP4/src/ej1/ej1.cpp | UTF-8 | 1,992 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <cassert>
typedef long long tint;
typedef long double ldouble;
#define forn(i,n) for(tint i=0;i<(tint)(n); i++)
#define debug(x) cout << #x << " = " << x << endl
using namespace std;
struct Punto
{
tint x,y;
Punto (tint xx, tint yy)
{
x = xx;
y = yy;
}
Punto()
{
x = 0;
y = 0;
}
};
bool operator < (Punto p1, Punto p2)
{
return make_pair(p1.x,p1.y) < make_pair(p2.x,p2.y);
}
bool operator != (Punto p1, Punto p2)
{
return (p1.x != p2.x) or (p1.y != p2.y);
}
struct Segmento
{
Punto p,q;
Segmento(Punto pp, Punto qq)
{
p = min(pp,qq);// importante tomar un representante
q = max(pp,qq);// para los segmentos
}
};
bool operator < (Segmento s1, Segmento s2)
{
return make_pair(s1.p,s1.q) < make_pair(s2.p,s2.q);
}
const tint minCoord = -999999999999999999;
int main()
{
#ifdef ACMTUYO
assert(freopen("ej1.in", "r", stdin));
#endif
ios_base::sync_with_stdio(0);
cin.tie(NULL);
tint n;
while (cin >> n)
{
map<Segmento,tint> contador;
forn(i,n-2)
{
tint x1,y1,x2,y2,x3,y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
contador[Segmento(Punto(x1,y1),Punto(x2,y2))]++;
contador[Segmento(Punto(x1,y1),Punto(x3,y3))]++;
contador[Segmento(Punto(x2,y2),Punto(x3,y3))]++;
}
map<Punto,set<Punto> > poligono;
for (auto x : contador)
if (x.second == 1)
{
poligono[x.first.p].insert(x.first.q);
poligono[x.first.q].insert(x.first.p);
}
Punto comienzo = (*poligono.begin()).first;
cout << comienzo.x << " " << comienzo.y;
Punto actual = Punto(minCoord,minCoord);
Punto anterior = comienzo;
for (auto p : poligono[comienzo])
if (p.y > actual.y)
actual = p;
forn(i,n-1)
{
cout << " " << actual.x << " " << actual.y;
for (auto p : poligono[actual]) // notar que es un for de largo 2
if (p != anterior)
{
anterior = actual;
actual = p;
break;
}
}
cout << "\n";
}
return 0;
}
| true |
7b8caf19bb471cbe595556a8c2e58ad9dce03b1e | C++ | alantany/cpprep | /lambda4.cpp | UTF-8 | 444 | 2.953125 | 3 | [] | no_license | #include<string>
#include<iostream>
#include<algorithm>
#include<cctype>
using namespace std;
int change(char &);
int main() {
//cout << char('A'+32) << endl;
string s = "alAntAnY";
for_each(s.begin(), s.end(), [](char &c) {if (isupper(c)) c = c + 32; else c = c - 32; return c; });
for_each(s.begin(), s.end(), change);
cout << s << endl;
system("pause");
}
int change(char &c) {
c=(isupper(c) == 1) ? (c + 32) :(c - 32);
return c;
}; | true |
f16eba60dc26c9e9c8c02d62405f265c536bb2e8 | C++ | bacahillsmu/benbot | /src/BehaviorTree/Node.cpp | UTF-8 | 1,169 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "Node.hpp"
// ----------------------------------------------------------------------------
Node::~Node()
{
}
// ----------------------------------------------------------------------------
Node::Status Node::Update()
{
if(m_status != Status::RUNNING)
{
Start();
}
m_status = Run();
if(m_status != Status::RUNNING)
{
Finish(m_status);
}
return m_status;
}
// ----------------------------------------------------------------------------
bool Node::IsSuccess() const
{
return m_status == Status::SUCCESS;
}
// ----------------------------------------------------------------------------
bool Node::IsFailure() const
{
return m_status == Status::FAILURE;
}
// ----------------------------------------------------------------------------
bool Node::IsRunning() const
{
return m_status == Status::RUNNING;
}
// ----------------------------------------------------------------------------
bool Node::IsFinished() const
{
return IsSuccess() || IsFailure();
}
// ----------------------------------------------------------------------------
void Node::Reset()
{
m_status = Status::INVALID;
}
| true |
93ccffc5404e993e7c9d1c27e4a384e7cc7254eb | C++ | Vanilla-In-Jxust/cpp_2048 | /Fuction/Check/Check.h | UTF-8 | 689 | 3.09375 | 3 | [] | no_license | #include <vector>
using namespace std;
/**
* check every moved whether is the last time.
* @param vec is to be tested.
* @param movedFlags used to remember special case.
* @return true if done or false if need next move.
*/
bool checkUp(const vector<int> &vec, const vector<bool> &movedFlags);
/**
* check vector<int> 0's location.
* @param check is vector<int> to be checked.
* @return empty(0) location in vector<int>.
*/
vector<int> checkEmpty(vector<int> check);
/**
* check all blocks whether can be continue moved.
* if not, means game over.
* @param check is all blocks ready to check.
* @return true if is, and false if no.
*/
bool isDead(const vector<int> &check);
| true |
96b6cca1072f45eb6a100de9f25cd86e2a057305 | C++ | moevm/oop | /8304/Butko_Artem/lab7/SOURCE/GameLib/main.cpp | UTF-8 | 1,271 | 3 | 3 | [] | no_license |
#include "UserInteraction/Rules/RuleOne/RuleOne.h"
#include "UserInteraction/Rules/RuleTwo/RuleTwo.h"
#include "UserInteraction/GameClass/GameClass.h"
void exec()
{
int choice, players;
std::cout << "------- GAME SETTINGS -------" << std::endl;
std::cout << "Input type of rule (1 or 2) : ";
std::cin >> choice;
std::cout << "Input number of players (2 or 3) : ";
if (choice == 1)
{
std::cin >> players;
if (players == 2)
{
GameClass<RuleOne, 2> game;
game.createGame();
game.playGame();
}
else if (players == 3)
{
GameClass<RuleOne, 3> game;
game.createGame();
game.playGame();
}
else return;
}
else
{
std::cin >> players;
if (players == 2)
{
GameClass<RuleTwo, 2> game;
game.createGame();
game.playGame();
}
else if (players == 3)
{
GameClass<RuleTwo, 3> game;
game.createGame();
game.playGame();
}
else return;
}
std::cout << "-----------------------------" << std::endl;
}
int main(int argc, char * argv[])
{
exec();
return 0;
}
| true |
f47e61fa8a73ad566daaa23756aa3e7404a52e22 | C++ | wanderinghobo/SDL-basic-physics | /SDL Game Project/Hero.cpp | UTF-8 | 896 | 3.109375 | 3 | [] | no_license | #include "Hero.h"
Hero::Hero()
{
animation = NULL;
faceRight = true;
}
Hero::~Hero()
{
}
void Hero::update(float dt)
{
//use basic game object vector movement
updateMovement(dt);
//update facing directio based on velocity
if (velocity.x > 0)
faceRight = true;
if (velocity.x < 0)
faceRight = false;
//update our animation
if(velocity.x != 0 || velocity.y != 0)
animation->update(dt);
}
void Hero::draw()
{
if (animation != NULL) {
if (faceRight)
animation->draw(pos.x, pos.y);
else
animation->draw(pos.x, pos.y, true);
}
}
void Hero::shoot()
{
Bullet* bullet = new Bullet();
bullet->renderer = renderer;
bullet->setPosition(pos);
bullet->angle = rand() % 360;//rand gives random int between min and max int value, modulus it into 360 degree value
bullet->movementSpeed = 200;
//add to gameObjects list
GameObject::gameObjects->push_back(bullet);
}
| true |
31f85509ba27bfa439b6cbc5544d56c2da4f7b4b | C++ | CodingTestStudy/everyday_ps | /1043_거짓말.cpp | UTF-8 | 1,036 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int n, m;
bool check[51];
vector < vector<int>>v;
int parent[51];
int find(int x) {
if (parent[x] == x)return x;
return parent[x] = find(parent[x]);
}
void Union(int a, int b) {
int x = find(a);
int y = find(b);
if (x == y)return;
if (x > y)swap(x, y);
parent[y] = x;
return;
}
int main() {
cin >> n >> m;
int a; cin >> a;
for (int i = 1; i <= 50; i++)parent[i] = i;
for (int k = 0; k <a ; k++) {
int t; cin >> t;
Union(t, 0);
}
v.resize(m);
for (int i = 0; i < m; i++) {
int num; cin >> num;
for (int j = 0; j < num; j++) {
int a; cin >> a;
v[i].push_back(a);
}
int temp = v[i][0];
for (auto T : v[i])Union(temp, T);
}
int cnt = 0;
for (int i = 0; i < v.size(); i++) {
bool ok = false;
for (auto T : v[i]) {
for (int i = 1; i <= n; i++) {
if (parent[i])continue;
if (find(T) == find(i)) {
ok = true;
break;
}
}
}
if (!ok)cnt++;
}
cout << cnt;
} | true |
3e36271579a79bb8123c89147047e7c8759ab01e | C++ | plocher/IRDetector | /Circuit.h | UTF-8 | 2,386 | 2.890625 | 3 | [
"MIT"
] | permissive | #ifndef _CIRCUIT_
#define _CIRCUIT_
#include <elapsedMillis.h>
// #define DEBUG
#define HEADROOM 180
#define HYSTERESIS 2000 // in mS units, 2000 = 2.0 seconds
#define OCCUPIED LOW
#define EMPTY ~OCCUPIED
#include <Arduino.h>
class Circuit {
public:
Circuit(void) {};
void init(int number, int ir, int out, int sensor) {
num = number;
irPin = ir;
outPin = out;
sensorPin = sensor;
detected = false;
delaytime = 0;
pinMode(irPin, OUTPUT);
pinMode(outPin, OUTPUT);
pinMode(sensorPin, INPUT);
#ifdef DEBUG
digitalWrite(outPin,EMPTY); delay(100); digitalWrite(outPin,OCCUPIED); delay(100);
#endif
digitalWrite(outPin,EMPTY); // Leave the detection pin
};
int check(void) {
digitalWrite(irPin, 0); // turn off IR transmitter
delay(5);
int r1 = analogRead(sensorPin); // read ambient light intensity
digitalWrite(irPin, 1); // turn ON IR source
delay(5);
int r2 = analogRead(sensorPin); // see if anything is reflecting
digitalWrite(irPin, 0); // make sure things are turned off when done
if ((r2 - r1) > HEADROOM) { // if a major positive difference, something has been detected...
delaytime = 0; // expiration timer is reset every time detection is seen
if (detected == false) { // newly triggered
#ifdef DEBUG
Serial.print("ON ");
Serial.print(num, DEC);
Serial.print(": ambient=");
Serial.print(r1, DEC);
Serial.print(", reflected=");
Serial.print(r2, DEC);
Serial.print(", diff=");
Serial.println(r2-r1, DEC);
#endif
}
detected = true;
}
if (detected) {
if (delaytime < HYSTERESIS) {
digitalWrite(outPin, OCCUPIED);
} else {
#ifdef DEBUG
Serial.print("OFF ");
Serial.println(num, DEC);
#endif
digitalWrite(outPin, EMPTY);
detected = false;
}
}
return detected ? 1 : 0;
};
private:
int num;
elapsedMillis delaytime;
int detected;
int irPin;
int outPin;
int sensorPin;
};
#endif
| true |
680423634b313c24f6a756c4dd653af8eecf0bef | C++ | diulianguo/leetcode | /0927leetcode/0927leetcode/iqiyi01.cpp | UTF-8 | 1,418 | 2.890625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
#define MAX 2147481647
#define MIN -214748364
//int minTimes(string s1, string s2)
//{
// for (int i = 0; i < s1.length(); i++){
//
// }
//}
//
//int main()
//{
// string s1, s2;
// cin >> s1 >> s2;
// cout << minTimes(s1, s2) << endl;
// system("pause");
// return 0;
//}
//int main()
//{
// int index, start, end, points;
// vector<int> everydayPoint;
// int maxpoints = 0, minstart = MAX, maxend = 0;
// while (cin>>index){
// if (index == 1){
// cin >> start >> end >> points;
// minstart = min(start, minstart);
// maxend = max(end, maxend);
// if (everydayPoint.empty() || end > everydayPoint.size() - 1){
// everydayPoint.resize(end + 1, MIN);
// }
// for (int i = start; i <= end; i++){
// if (points > everydayPoint[i])
// everydayPoint[i] = points;
// }
// } else if (index == 2){
// cin >> start >> points;
// maxpoints += points;
// }
// }
// if (minstart && maxend){
// for (int i = minstart; i <= maxend; i++){
// maxpoints += everydayPoint[i];
// }
// }
// cout << maxpoints << endl;
// system("pause");
// return 0;
//} | true |
3ced8c60c7f05a320e0f73a37bf70108e4ca8b64 | C++ | JoshBramlett/RDGE | /include/rdge/physics/collision.hpp | UTF-8 | 7,552 | 2.6875 | 3 | [] | no_license | //! \headerfile <rdge/physics/collision.hpp>
//! \author Josh Bramlett
//! \version 0.0.10
//! \date 03/30/2017
#pragma once
#include <rdge/core.hpp>
#include <rdge/physics/isometry.hpp>
#include <rdge/physics/shapes/ishape.hpp>
#include <rdge/math/intrinsics.hpp>
#include <rdge/math/vec2.hpp>
#include <SDL_assert.h>
// sites of import:
//
// http://www.iforce2d.net/b2dtut/collision-anatomy
// https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331
//! \namespace rdge Rainbow Drop Game Engine
namespace rdge {
namespace physics {
struct circle;
struct polygon;
//! \var Linear constraint and collision tolerance
static constexpr float LINEAR_SLOP = 0.005f;
//! \var Angular constraint and collision tolerance
static constexpr float ANGULAR_SLOP = (2.f / 180.f * math::PI);
//! \struct collision_manifold
//! \brief Container for collision resolution details
//! \details Manifold data is represented in world space. Reference/incident naming
//! convention is used to signify which shapes transform is used by the solver.
struct collision_manifold
{
float depths[2] = { 0.f, 0.f }; //!< Penetration depths
math::vec2 plane; //!< (ref) Collision plane
math::vec2 normal; //!< (ref) Vector of resolution, or collision normal
math::vec2 contacts[2]; //!< (inc) Clipping points
size_t count = 0; //!< Number of collision points
bool flip = false; //!< Flip reference/incident shapes
};
//! \struct contact_impulse
//! \brief Container for impulses generated by the solver
struct contact_impulse
{
float normals[2];
float tangents[2];
size_t count;
};
//! \struct half_plane
//! \brief 2d hyperplane (aka line)
//! \details Line that divides space into two infinite sets of points. Points on
//! the plane satisfy dot(normal, p) == d.
//! \note From Real-Time Collision Detection, Vol 1. (3.6 Planes and Halfspaces)
struct half_plane
{
math::vec2 normal; //!< Plane normal (normalized)
float d; //!< distance to origin from plane
};
//! \brief Distance from a point to the plane
//! \param [in] hp Half-plane
//! \param [in] point Point to test
constexpr float
distance (const half_plane& hp, const math::vec2& point)
{
return math::dot(hp.normal, point) - hp.d;
}
//! \brief Project a point onto the plane
//! \param [in] hp Half-plane
//! \param [in] point Point to project
constexpr math::vec2
project (const half_plane& hp, const math::vec2& point)
{
return point - (hp.normal * distance(hp, point));
}
//! \struct gjk
//! \brief Implementation of the GJK algorithm for collision detection
//! \details The algorithm operates on two convex shapes, and performs it's
//! operations using the Minkowski difference of the shapes. If
//! the shapes intersect the Minkowski difference will include the
//! origin, so the algorithm will attempt to create a surrounding
//! triangle around the origin. The intersection test hinges on
//! whether this triangle can be formed.
//! \see http://www.dyn4j.org/2010/04/gjk-gilbert-johnson-keerthi/
//! \see http://mollyrocket.com/849
struct gjk
{
const ishape* shape_a = nullptr;
const ishape* shape_b = nullptr;
math::vec2 simplex[3]; //!< Triangle surrounding the origin
size_t count = 0; //!< Number of vertices in the simplex
math::vec2 d; //!< Current search direction
//! \brief gjk ctor
//! \details Initializes the first point in the simplex and corresponding
//! direction for the intersection test to start.
//! \param [in] a First shape
//! \param [in] b Second shape
gjk (const ishape* a, const ishape* b)
: shape_a(a)
, shape_b(b)
{
math::vec2 s = shape_a->first_point() - shape_b->first_point();
simplex[count++] = s;
d = -s;
}
//! \brief Check if shapes intersect
//! \returns True iff shapes intersect
bool intersects (void)
{
// TODO This causes a segfault if called twice. Could be converted to a function
// instead of a class.
SDL_assert(count == 1);
while (true)
{
auto a = support(d);
if (a.dot(d) < 0.f)
{
// simplex does not pass the origin
return false;
}
simplex[count++] = a;
if (do_simplex())
{
return true;
}
}
}
//! \brief GJK support function
//! \details Retrieves the farthest vertex in opposite directions. The
//! resultant vertex is an edge of the Minkowski difference.
//! \param [in] d Direction to search
//! \returns Edge vertex on the Minkowski difference
math::vec2 support (const math::vec2& d)
{
return shape_a->farthest_point(d) - shape_b->farthest_point(-d);
}
//! \brief Attempt to create the simplex
//! \details If the simplex cannot be verified the search direction and
//! simplex will be updated for the next iteration.
//! \returns True iff simplex contains the origin
bool do_simplex (void)
{
const auto& a = simplex[count - 1];
auto ao = -a;
if (count == 3)
{
const auto& b = simplex[1];
const auto& c = simplex[0];
auto ab = b - a;
auto ac = c - a;
auto ac_perp = ac.perp_ccw() * math::perp_dot(ac, ab);
if (ac_perp.dot(ao) > 0)
{
// If the edge AC normal has the same direction as the origin
// we remove point B and set the direction to the normal.
simplex[1] = a;
count--;
d = ac_perp;
}
else
{
auto ab_perp = ab.perp_ccw() * math::perp_dot(ab, ac);
if (ab_perp.dot(ao) > 0)
{
// If the edge AB normal has the same direction as the origin
// we remove point C and set the direction to the normal.
simplex[0] = b;
simplex[1] = a;
count--;
d = ab_perp;
}
else
{
// The origin lies inside both the AB and AC edge
return true;
}
}
}
else
{
const auto& b = simplex[0];
auto ab = b - a;
d = ab.perp() * math::perp_dot(ab, ao);
}
return false;
}
};
//! \brief Check polygon/circle intersection and build manifold
//! \details The provided \ref collision_manifold will be populated with details
//! on how the collision could be resolved. If there was no collision
//! the manifold count will be set to zero.
//! \param [in] p Polygon shape
//! \param [in] c Circle shape
//! \param [out] mf Manifold containing resolution
//! \returns True iff intersecting
bool intersects (const polygon& p, const circle& c, collision_manifold& mf);
//! \brief collision_manifold stream output operator
std::ostream& operator<< (std::ostream& os, const collision_manifold& mf);
//! \brief contact_impulse stream output operator
std::ostream& operator<< (std::ostream& os, const contact_impulse& impulse);
} // namespace physics
} // namespace rdge
| true |
fbf36a25e2ef1ca85c2957da182d71e077fab7f6 | C++ | Aladin-Saleh/Moteur-Graphique-Physique | /CapsEngine/CAPS/Source/Rendering/ImGui/BrancheUI.cpp | UTF-8 | 803 | 2.65625 | 3 | [] | no_license | #include "BrancheUI.hpp"
#include "Debug.hpp"
namespace Ge
{
/*BrancheUI::BrancheUI(fs::path p)
{
m_path = p;
for (const auto & entry : fs::directory_iterator(m_path))
{
if (fs::is_directory(entry.path()))
{
std::cout << entry.path() << std::endl;
m_BrancheUI.push_back(new BrancheUI(entry.path()));
}
else
{
m_FeuilleUI.push_back(new FeuilleUI(entry.path()));
}
}
}
std::vector<BrancheUI*> BrancheUI::getB()
{
return m_BrancheUI;
}
std::vector<FeuilleUI*> BrancheUI::getF()
{
return m_FeuilleUI;
}
fs::path BrancheUI::getPath()
{
return m_path;
}
BrancheUI::~BrancheUI()
{
for (BrancheUI* b : m_BrancheUI)
{
delete(b);
}
for (FeuilleUI* f : m_FeuilleUI)
{
delete(f);
}
m_BrancheUI.clear();
m_FeuilleUI.clear();
}*/
} | true |
f3d918c049be295f3e4035b6ce871cd16632396c | C++ | JinGyuChoi/Data-Structure | /shopping.cpp | UTF-8 | 3,008 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
ifstream ipf("shopping.inp", ios::binary);
ofstream opf("shopping.out", ios::binary);
int N,k;
ipf>>N>>k;
int user,item;
vector<int> time;
vector<int> sorted_time;
vector<int> times(k);
vector<int> users;
queue<int> cart[k];
vector<int> out;
stack<int> sameindex;
while(ipf>>user>>item){
users.push_back(user);
time.push_back(item);
}
int j = 0;
int minIndex;
while(out.size() != N){
if(users.size() > k){
for(int x = 0; x < k; x++){
if(cart[x].empty()) {
if(j == N) break;
cart[x].push(users[j]);
times[x] += time[j];
j++;
}
}
minIndex = min_element(times.begin(),times.end()) - times.begin();
for(int i = 0; i < k; i++){
if(times[minIndex] == times[i]) sameindex.push(i);
}
if(sameindex.size() == 1){
if(!(cart[minIndex].empty())){
out.push_back(cart[minIndex].front());
cart[minIndex].pop();
sameindex.pop();
}
else{
times[minIndex] = 5000;
sameindex.pop();
}
}
else if(sameindex.size() >= 2){
if(!(cart[minIndex].empty())){
while(!(sameindex.empty())){
out.push_back(cart[sameindex.top()].front());
cart[sameindex.top()].pop();
sameindex.pop();
}
}
else{
while(!(sameindex.empty())){
times[minIndex] = 5000;
sameindex.pop();
}
}
}
}
else{
/*sorted_time = time;
sort(sorted_time.begin(), sorted_time.end());
for(int m = 0; m < sorted_time.size(); m++){
for(int n = 0; n < time.size(); n++){
if(sorted_time[m] == time[n]) out.push_back(users[n]);
}
}*/
minIndex = min_element(time.begin(),time.end()) - time.begin();
for(int i = 0; i < time.size(); i++){
if(time[minIndex] == time[i]) sameindex.push(i);
}
if(sameindex.size() == 1){
out.push_back(users[minIndex]);
time[sameindex.top()] = 5000;
sameindex.pop();
}
else if(sameindex.size() >= 2){
while(!(sameindex.empty())){
out.push_back(users[sameindex.top()]);
time[sameindex.top()] = 5000;
sameindex.pop();
}
}
}
}
for(auto it:out) opf<<it<<"\n";
return 0;
} | true |
2fb6cdd80b57fd6f1b9f677f3d8d4a7d94f6c0ba | C++ | dylandevalia/CPP_Game | /src/Entity.cpp | UTF-8 | 2,690 | 3.09375 | 3 | [] | no_license | #include "Entity.h"
#include "Utility.h"
Entity::Entity(GameEngine* pEngine, GameTileManager* pTile, bool tile, int xpos, int ypos, int width, int height, int maxHealth)
: DisplayableObject(pEngine), m_pTile(pTile)
{
m_iCurHealth = m_iMaxHealth = maxHealth;
if (tile) {
m_iCurrentScreenX = m_iPreviousScreenX = (xpos * 50) + 25 - (width / 2);
m_iCurrentScreenY = m_iPreviousScreenY = (ypos * 50) + 25 - (height / 2);
} else {
m_iCurrentScreenX = m_iPreviousScreenX = xpos - (width / 2);
m_iCurrentScreenY = m_iPreviousScreenY = ypos - (height / 2);
}
m_iStartDrawPosX = m_iStartDrawPosY = 0;
m_iDrawWidth = width;
m_iDrawHeight = height;
m_sSprite.LoadImage("spritesheet.png");
}
Entity::~Entity() {
}
/* Constrains the entity within the bounds of the screen */
void Entity::constrainInBounds(int xdir, int ydir) {
if (isInBounds()) { return; }
int x = m_iPreviousScreenX;
int y = m_iPreviousScreenY;
if (!isInBounds(x + xdir, y)) {
while (isInBounds(x + Utility::sign(xdir), y)) {
x += Utility::sign(xdir);
}
}
if (!isInBounds(x, y + ydir)) {
while (isInBounds(x, y + Utility::sign(ydir))) {
y += Utility::sign(ydir);
}
}
m_iCurrentScreenX = x;
m_iCurrentScreenY = y;
}
/* Checks if the entity is on safe tiles */
bool Entity::isInBounds() {
return isInBounds(m_iCurrentScreenX, m_iCurrentScreenY) // left up
&& isInBounds(m_iCurrentScreenX, m_iCurrentScreenY + m_iDrawHeight - 1) // left down
&& isInBounds(m_iCurrentScreenX + m_iDrawWidth - 1, m_iCurrentScreenY) // right up
&& isInBounds(m_iCurrentScreenX + m_iDrawWidth - 1, m_iCurrentScreenY + m_iDrawHeight - 1) // right down
;
}
/* Checks if the given point is not on a 'solid' tile */
// If on safe tile - return true
// If on soild tile - return false
bool Entity::isInBounds(int xpos, int ypos) {
return (m_pTile->GetValue(m_pTile->GetTileXForPositionOnScreen(xpos), m_pTile->GetTileYForPositionOnScreen(ypos)) > 2);
}
int Entity::getDistanceBetween(Entity* target) {
int xdiff = GetXCentre() - target->GetXCentre();
int ydiff = GetYCentre() - target->GetYCentre();
return xdiff*xdiff + ydiff*ydiff;
}
/* Checks if the entity is colliding with the given entity */
bool Entity::checkIntersection(Entity* target) {
// (a.x - b.x)^2 + (a.y - b.y)^2 <= (a.r + b.r)^2
double r = (GetWidth() / 2.0) + (target->GetWidth() / 2.0);
return (getDistanceBetween(target) <= r*r);
}
/* Deletes itself from the object array */
void Entity::deleteSelf() {
int index = GetEngine()->GetIndexOfObjectFromArray(this);
GetEngine()->RemoveObjectFromArray(index);
GetEngine()->Redraw(true);
}
| true |
6569203bbb16266db87a8c7ad348378455fc1024 | C++ | 0123goodvegetable/GwentGame | /GwentGame/GwentGame/CP_PlayingLogic.h | GB18030 | 930 | 2.71875 | 3 | [] | no_license | //ʵֿƲ
#pragma once
#ifndef CP_PLAYINGLOGIC_H
#define CP_PLAYINGLOGIC_H
#include"CP_Card.h"
#include"CP_AllCards.h"
#include"CardsUI.h"
class PlayingLogic
{
public:
PlayingLogic(QList<CardsUI*> &aim_stack);
~PlayingLogic() {}
//ڿƽвؼ
//cardĿ
//ֵƷ֮Ϣ
QList<CardsUI*> operateCard(Card &card,int card_number);
private:
QList<CardsUI*> cardStack;//ڴ濨Ƶ״̬GamePlayingBackgroundеĿ״̬и
AllCards allCards;
//пƵļܺ
void skill1(int number);
void skill2(int number);
void skill3(int number);
void skill4(int number);
void skill6(int number);
void skill8(int number);
void skill14(int number);
void skill19(int number);
void skill21(int number);
void skill29(int number);
};
#endif // !CP_PLAYINGLOGIC_H
| true |
341d55c633f27e04d57787b49627ff99a5acab1f | C++ | gitter-badger/coral-1 | /src/core/expr.hh | UTF-8 | 7,335 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <map>
#include <memory>
#include <vector>
#include <cstdio>
namespace coral {
namespace type {
class Type {
public:
std::string name;
Type(std::string name) : name(name) { }
};
}
using Type = type::Type;
namespace ast {
using std::vector;
using std::unique_ptr;
using std::map;
#define MAP_ALL_EXPRS(F) F(Module) F(Extern) F(Import) F(Let) F(Func) F(Block) F(Var) F(Call) F(StringLiteral) F(IntLiteral) F(FloatLiteral) F(Return) F(Comment) F(IfExpr) F(ForExpr) F(BinOp) F(Member) F(ListLiteral) F(TupleLiteral) F(Def)
// Forward-declare all Expr classes
#define F(E) class E;
MAP_ALL_EXPRS(F)
F(BaseExpr);
#undef F
// Visitor
class ExprVisitor {
public:
virtual std::string visitorName() { return "ExprVisitor"; }
#define F(E) virtual void visit(__attribute__((unused)) E * expr) { \
printf("%s: %s", visitorName().c_str(), #E "\n"); \
}
MAP_ALL_EXPRS(F)
F(BaseExpr)
#undef F
};
enum class ExprTypeKind {
#define F(E) E##Kind,
MAP_ALL_EXPRS(F)
F(BaseExpr)
#undef F
};
template<typename T>
void moveTo(vector<T *> source, vector<unique_ptr<T>> & target) {
for(auto && ptr : source) if (ptr) target.push_back(unique_ptr<coral::ast::BaseExpr>(ptr));
}
class BaseExpr {
public:
virtual void accept(ExprVisitor * v) { v->visit(this); }
virtual ~BaseExpr() { }
};
class Expr : public BaseExpr { };
class Statement : public BaseExpr { };
class ExprTypeVisitor : public ExprVisitor {
public:
ExprTypeKind out;
static ExprTypeKind of(BaseExpr * e) {
ExprTypeVisitor v;
v.out = ExprTypeKind::BaseExprKind;
if (e) e->accept(&v);
return v.out;
}
#define F(E) virtual void visit(__attribute__((unused)) E * expr) { out = ExprTypeKind::E##Kind; }
MAP_ALL_EXPRS(F)
#undef F
};
class ExprNameVisitor : public ExprVisitor {
public:
std::string out;
static std::string of(BaseExpr * e) {
ExprNameVisitor v;
v.out = "(null)";
if (e) e->accept(&v);
return v.out;
}
#define F(E) virtual void visit(__attribute__((unused)) E * expr) { out = #E; }
MAP_ALL_EXPRS(F)
#undef F
};
class Comment : public Statement {
public:
std::string value;
Comment(std::string value) : value(value) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Block : public Statement {
public:
std::vector<unique_ptr<coral::ast::BaseExpr>> lines;
Block(std::vector<coral::ast::BaseExpr *> lines) {
for(auto && ptr : lines) if (ptr) this->lines.push_back(unique_ptr<coral::ast::BaseExpr>(ptr));
}
virtual void accept(ExprVisitor * v) {
v->visit(this);
}
};
class Module : public BaseExpr {
public:
unique_ptr<Block> body;
Module();
Module(vector<BaseExpr *> lines) {
body = unique_ptr<Block>(new Block(lines));
}
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Func : public Expr {
public:
std::string name;
coral::Type type;
vector<unique_ptr<coral::ast::Def>> params;
unique_ptr<Block> body;
Func(std::string name,
Type type,
vector<coral::ast::Def *> params,
Block * body)
: name(name), type(type), body(body) {
for(auto && p : params) this->params.push_back(std::unique_ptr<Def>(p));
}
virtual void accept(ExprVisitor * v) {
v->visit(this);
}
};
class IfExpr : public Expr {
public:
unique_ptr<BaseExpr> cond, ifbody, elsebody;
IfExpr(BaseExpr* cond,
BaseExpr* ifbody,
BaseExpr* elsebody)
: cond(cond), ifbody(ifbody), elsebody(elsebody) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class ForExpr : public Expr {
public:
unique_ptr<BaseExpr> var, sequence, body;
ForExpr(BaseExpr* var, BaseExpr* sequence, BaseExpr* body)
: var(var), sequence(sequence), body(body) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Var : public Expr {
public:
std::string name;
// the declaring expression -- the node that created the name in question
// in the current scope
ast::BaseExpr * expr;
Var(std::vector<std::string> names) {
name = names.size() ? names[0] : "undefined";
}
Var(std::string name) : name(name) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class StringLiteral : public Expr {
public:
std::string value;
StringLiteral(std::string value): value(value) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
std::string getString();
};
class IntLiteral : public Expr {
public:
std::string value;
IntLiteral(std::string value) : value(value) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class FloatLiteral : public Expr {
public:
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class BinOp : public Expr {
public:
std::unique_ptr<BaseExpr> lhs, rhs;
std::string op;
BinOp(BaseExpr * lhs, std::string op, BaseExpr * rhs) : lhs(lhs), rhs(rhs), op(op) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Let : public Statement {
public:
unique_ptr<BaseExpr> var, value;
Let(BaseExpr * var, BaseExpr * value) : var(var), value(value) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Def : public Expr {
public:
std::string name;
BaseExpr * value;
Def(std::string name, BaseExpr * value) : name(name), value(value) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Member : public Expr {
public:
unique_ptr<BaseExpr> base = 0;
std::string member;
Member(BaseExpr * base, std::string member) : base(base), member(member) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class ListLiteral : public Expr {
public:
std::vector<unique_ptr<BaseExpr>> items;
ListLiteral(std::vector<BaseExpr *> items) {
for(auto && pp : items) if (pp) this->items.push_back(std::unique_ptr<BaseExpr>(pp));
}
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class TupleLiteral : public Expr {
public:
std::vector<unique_ptr<BaseExpr>> items;
TupleLiteral(std::vector<BaseExpr *> items) {
for(auto && pp : items) if (pp) this->items.push_back(std::unique_ptr<BaseExpr>(pp));
}
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Call : public Expr {
public:
unique_ptr<BaseExpr> callee;
vector<std::unique_ptr<BaseExpr>> arguments;
Call(BaseExpr * callee, TupleLiteral * arguments) : callee(callee) {
for(auto && p : arguments->items)
this->arguments.push_back(std::unique_ptr<BaseExpr>(p.release()));
}
Call(BaseExpr * callee, vector<BaseExpr *> arguments): callee(callee) {
for(auto && ptr : arguments)
if (ptr) this->arguments.push_back(std::unique_ptr<BaseExpr>(ptr));
}
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Return : public Statement {
public:
unique_ptr<BaseExpr> val;
Return(BaseExpr * val) : val(val) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Extern : public Statement {
public:
std::string name;
std::string linkage;
coral::Type type;
Extern(std::string name, coral::Type type) : name(name), type(type) { }
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
class Import : public Statement {
public:
virtual void accept(ExprVisitor * v) { v->visit(this); }
};
}
}
| true |
8bfc334fdeeb067f4dd28a9c2535fe79af5e647b | C++ | idenx/Semestr2_TSD | /Лаба 4 - Стек/TSD-4-STACK/liststack.h | WINDOWS-1251 | 4,088 | 3.328125 | 3 | [] | no_license | #ifndef LISTSTACK_H
#define LISTSTACK_H
#include "stack.h"
#include "error.h"
template<class T>
struct TList {
T data;
TList* next;
};
template<class T>
class ListStack : public Stack<T>
{
public:
inline ListStack();
T Pop();
T Top();
void Push(const T &data);
bool isEmpty();
inline QString *getLog();
void Free();
int Length();
void Clear();
QString getFreeAddresses();
QString getBusyAddresses();
bool canPush(const T &data, int MaxElements, int MaxAddress);
private:
TList<T> *Begin;
TList<T> *Head;
QString Log;
QString FreeAddresses;
};
template<class T>
inline ListStack<T>::ListStack()
{
Begin = 0;
Head = 0;
Log = " ";
FreeAddresses = "";
}
template<class T>
void ListStack<T>::Free() {
QString Addresses = "";
TList<T> *temp = Head;
while (temp != 0) {
Addresses.append(QString::number((int) temp, 16));
this->FreeAddresses.append(QString::number((int) temp, 16));
temp = temp->next;
if (temp != 0) {
Addresses.append(", ");
this->FreeAddresses.append("\n");
}
}
while (Head != 0) {
temp = Head;
Head = Head->next;
delete temp;
}
this->Log = (QString) " : " + Addresses;
}
template<class T>
bool ListStack<T>::isEmpty() {
bool Result = (Head == 0);
return Result;
}
template<class T>
void ListStack<T>::Clear()
{
this->Free();
}
template<class T>
int ListStack<T>::Length() {
TList<T> *Counter = this->Head;
int Length = 0;
while (Counter != 0) {
Length++;
Counter = Counter->next;
}
return Length;
}
template<class T>
QString ListStack<T>::getFreeAddresses()
{
return (this->FreeAddresses);
}
template<class T>
bool ListStack<T>::canPush(const T &data, int MaxElements, int MaxAddress)
{
if (this->Length() >= MaxElements)
return false;
this->Push(data);
int HeadAddress = (int)(this->Head);
if (HeadAddress > MaxAddress) {
this->Pop();
return false;
}
return true;
}
template<class T>
QString ListStack<T>::getBusyAddresses()
{
QString BusyAddresses = "";
TList<T> *temp = Head;
while (temp != 0) {
BusyAddresses.append(QString::number((int) temp, 16));
temp = temp->next;
if (temp != 0)
BusyAddresses.append("\n");
}
return BusyAddresses;
}
template<class T>
T ListStack<T>::Pop() {
if (isEmpty()) {
Error error((QString) " !");
throw error;
} else {
T toReturn = Head->data;
TList<T> *toDelete = Head;
this->FreeAddresses += QString::number((int) Head, 16) + "\n";
Log = " '" + (QString) (Head->data) +
"' " + QString::number((int) Head, 16) + " ";
Head = Head->next;
if (Head == 0)
Begin = 0;
delete toDelete;
return toReturn;
}
}
template<class T>
T ListStack<T>::Top() {
if (isEmpty()) {
Error error((QString) " !");
throw error;
} else {
Log = " '" + (QString) (Head->data) +
"' ( ) " + QString::number((int) Head, 16);
return Head->data;
}
}
template<class T>
void ListStack<T>::Push(const T &data) {
TList<T> *toAdd = new TList<T>;
toAdd->data = data;
toAdd->next = Head;
if (Head == 0)
Begin = toAdd;
Head = toAdd;
Log = " '" + (QString) (data) +
"' " + QString::number((int) Head, 16) + " ";
}
template<class T>
inline QString *ListStack<T>::getLog() {
return &(this->Log);
}
#endif // LISTSTACK_H
| true |
e4b1f6fe9b53f271b875713e541cf4c7fb93b67e | C++ | Raj-588/CP_code | /robin karp.cpp | UTF-8 | 1,309 | 3 | 3 | [] | no_license |
#include <bits/stdc++.h>
using namespace std;
#define prime 119
#define ll long long
ll Create_hash(string s, int n) {
ll result = 0;
for (int i = 0; i < n; i++) {
result += s[i] * pow(prime, i);
}
return result;
}
ll recalculate_hash(string s, int oldIndex, int NewIndex, int OldHash, int patlength) {
ll Newhash = OldHash - s[oldIndex];
Newhash /= prime;
Newhash += s[NewIndex] * pow(prime, patlength - 1);
return Newhash;
}
bool Check(string s1, string s2, int start1, int end1, int start2, int end2) {
if (end1 - start1 != end2 - start2) {
return false;
}
while (start1 <= end1 and start2 <= end2) {
if (s1[start1] != s2[start2]) {
return false;
}
start1++;
start2++;
}
return true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string str = "abdabd"; //abd
string pat = "abd";
ll pathash = Create_hash(pat, pat.length());
ll strhash = Create_hash(str, pat.length());
//cout << pathash << " " << strhash << " ";
for (int i = 0; i <= str.length() - pat.length(); i++) {
if (pathash == strhash and Check(str, pat, i, i + pat.length() - 1, 0, pat.length() - 1) == 1) {
cout << i << " ";
}
if (i <= str.length() - pat.length()) {
strhash = recalculate_hash(str, i, i + pat.length(), strhash, pat.length());
}
}
return 0;
}
| true |
61622d09b44332bd78c7a1ef0b03a9a0cd47610b | C++ | KarthikNayak/VTU | /CSE/6thSem/cglab/5.cpp | UTF-8 | 4,561 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <GL/glut.h>
#define outcode int
double xmin=50,ymin=50, xmax=100,ymax=100; // Window boundaries
double xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
//bit codes for the right, left, top, & bottom
const int RIGHT = 8;
const int LEFT = 2;
const int TOP = 4;
const int BOTTOM = 1;
//used to compute bit codes of a point
outcode ComputeOutCode (double x, double y);
//Cohen-Sutherland clipping algorithm clips a line from
//P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with
//diagonal from (xmin, ymin) to (xmax, ymax).
void CohenSutherlandLineClipAndDraw (double x0, double y0,double x1, double y1)
{
//Outcodes for P0, P1, and whatever point lies outside the clip rectangle
outcode outcode0, outcode1, outcodeOut;
bool accept = false, done = false;
//compute outcodes
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if (!(outcode0 | outcode1)) //logical or is 0 Trivially accept & exit
{
accept = true;
done = true;
}
else if (outcode0 & outcode1) //logical and is not 0. Trivially reject and exit
done = true;
else
{
//failed both tests, so calculate the line segment to clip
//from an outside point to an intersection with clip edge
double x, y;
//At least one endpoint is outside the clip rectangle; pick it.
outcodeOut = outcode0? outcode0: outcode1;
//Now find the intersection point;
//use formulas y = y0 + slope * (x - x0), x = x0 + (1/slope)* (y - y0)
if (outcodeOut & TOP) //point is above the clip rectangle
{
x = x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);
y = ymax;
}
else if (outcodeOut & BOTTOM) //point is below the clip rectangle
{
x = x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);
y = ymin;
}
else if (outcodeOut & RIGHT) //point is to the right of clip rectangle
{
y = y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);
x = xmax;
}
else //point is to the left of clip rectangle
{
y = y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);
x = xmin;
}
//Now we move outside point to intersection point to clip
//and get ready for next pass.
if (outcodeOut == outcode0)
{
x0 = x;
y0 = y;
outcode0 = ComputeOutCode (x0, y0);
}
else
{
x1 = x;
y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
}while (!done);
if (accept)
{ // Window to viewport mappings
double sx=(xvmax-xvmin)/(xmax-xmin); // Scale parameters
double sy=(yvmax-yvmin)/(ymax-ymin);
double vx0=xvmin+(x0-xmin)*sx;
double vy0=yvmin+(y0-ymin)*sy;
double vx1=xvmin+(x1-xmin)*sx;
double vy1=yvmin+(y1-ymin)*sy;
//draw a red colored viewport
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin, yvmin);
glVertex2f(xvmax, yvmin);
glVertex2f(xvmax, yvmax);
glVertex2f(xvmin, yvmax);
glEnd();
glColor3f(0.0,0.0,1.0); // draw blue colored clipped line
glBegin(GL_LINES);
glVertex2d (vx0, vy0);
glVertex2d (vx1, vy1);
glEnd();
}
}
//Compute the bit code for a point (x, y) using the clip rectangle
//bounded diagonally by (xmin, ymin), and (xmax, ymax)
outcode ComputeOutCode (double x, double y)
{
outcode code = 0;
if (y > ymax) //above the clip window
code |= TOP;
else if (y < ymin) //below the clip window
code |= BOTTOM;
if (x > xmax) //to the right of clip window
code |= RIGHT;
else if (x < xmin) //to the left of clip window
code |= LEFT;
return code;
}
void display()
{
double x0=120,y0=10,x1=40,y1=130;
glClear(GL_COLOR_BUFFER_BIT);
//draw the line with red color
glColor3f(1.0,0.0,0.0);
//bres(120,20,340,250);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
//glVertex2d (60,20);
//glVertex2d (80,120);
glEnd();
//draw a blue colored window
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);
CohenSutherlandLineClipAndDraw(60,20,80,120);
glFlush();
}
int main(int argc, char** argv)
{
//int x1, x2, y1, y2;
//printf("Enter End points:");
//scanf("%d%d%d%d", &x1,&x2,&y1,&y2);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen Suderland Line Clipping Algorithm");
glutDisplayFunc(display);
glClearColor(1.0,1.0,1.0,1.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
glutMainLoop();
return 1;
}
| true |
a9254bd41f1019ceba3a25bc444e51ead2f581c4 | C++ | wn1980/Lattice-Boltzmann | /include/core/Kernels.h | UTF-8 | 7,160 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef LATTICE_BOLTZMANN_KERNELS_H
#define LATTICE_BOLTZMANN_KERNELS_H
#include <SFML/Graphics.hpp>
namespace boltzmann {
namespace core {
/*
* Vectors' probabilities constants
*/
const double four9ths = 4.0 / 9.0;
const double one9th = 1.0 / 9.0;
const double one36th = 1.0 / 36.0;
/**
* Collision step
*/
__global__
void collide(uint32_t xdim, uint32_t ydim,
bool **barrier,
double **n0,
double **nN,
double **nS,
double **nE,
double **nW,
double **nNW,
double **nNE,
double **nSW,
double **nSE,
double **density,
double **xvel,
double **yvel,
double **speed2,
double **n0_temp,
double **nN_temp,
double **nS_temp,
double **nE_temp,
double **nW_temp,
double **nNW_temp,
double **nNE_temp,
double **nSW_temp,
double **nSE_temp,
double **density_temp,
double **xvel_temp,
double **yvel_temp,
double **speed2_temp,
double omega);
/**
* Computing flow's curl
*/
__global__
void compute_curl(uint32_t xdim, uint32_t ydim, double **curl, double **yvel, double **xvel);
/**
* Streaming step
*/
__global__
void stream(uint32_t xdim,
uint32_t ydim,
bool **barrier,
double **n0,
double **nN,
double **nS,
double **nE,
double **nW,
double **nNW,
double **nNE,
double **nSW,
double **nSE,
double **density,
double **xvel,
double **yvel,
double **speed2,
double **n0_temp,
double **nN_temp,
double **nS_temp,
double **nE_temp,
double **nW_temp,
double **nNW_temp,
double **nNE_temp,
double **nSW_temp,
double **nSE_temp,
double **density_temp,
double **xvel_temp,
double **yvel_temp,
double **speed2_temp,
double omega,
double v);
/**
* Bouncing step
*/
__global__
void bounce(uint32_t xdim,
uint32_t ydim,
bool **barrier,
double **n0,
double **nN,
double **nS,
double **nE,
double **nW,
double **nNW,
double **nNE,
double **nSW,
double **nSE,
double **density,
double **xvel,
double **yvel,
double **speed2,
double **n0_temp,
double **nN_temp,
double **nS_temp,
double **nE_temp,
double **nW_temp,
double **nNW_temp,
double **nNE_temp,
double **nSW_temp,
double **nSE_temp,
double **density_temp,
double **xvel_temp,
double **yvel_temp,
double **speed2_temp,
double omega,
double v);
/**
* Synchronize main buffer with temporary buffer on graphic card
*/
__global__
void synchronize(uint32_t xdim,
uint32_t ydim,
bool **barrier,
double **n0,
double **nN,
double **nS,
double **nE,
double **nW,
double **nNW,
double **nNE,
double **nSW,
double **nSE,
double **density,
double **xvel,
double **yvel,
double **speed2,
double **n0_temp,
double **nN_temp,
double **nS_temp,
double **nE_temp,
double **nW_temp,
double **nNW_temp,
double **nNE_temp,
double **nSW_temp,
double **nSE_temp,
double **density_temp,
double **xvel_temp,
double **yvel_temp,
double **speed2_temp,
double omega,
double v);
/**
* Generate visual graphic from current world's state depends on curl
*/
__global__
void
update_pixels_curl(uint32_t ydim, uint32_t xdim, uint8_t **pixels, bool **barrier, double n_colors, double **curl,
double contrast, sf::Color *colors);
/**
* Generate visual graphic from current world's state depends on speed
*/
__global__
void
update_pixels_speed(uint32_t ydim, uint32_t xdim, uint8_t **pixels, bool **barrier, double n_colors, double **speed,
double contrast, sf::Color *colors);
/**
* Generate visual graphic from current world's state depends on xvel
*/
__global__
void
update_pixels_xvel(uint32_t ydim, uint32_t xdim, uint8_t **pixels, bool **barrier, double n_colors, double **xvel,
double contrast, sf::Color *colors);
/**
* Generate visual graphic from current world's state depends on yvel
*/
__global__
void
update_pixels_yvel(uint32_t ydim, uint32_t xdim, uint8_t **pixels, bool **barrier, double n_colors, double **yvel,
double contrast, sf::Color *colors);
/**
* Generate visual graphic from current world's state depends on density
*/
__global__
void
update_pixels_density(uint32_t ydim, uint32_t xdim, uint8_t **pixels, bool **barrier, double n_colors, double **density,
double contrast, sf::Color *colors);
}
}
#endif //LATTICE_BOLTZMANN_KERNELS_H
| true |
fe328e0008e6467067e36a5b2039fac842334725 | C++ | ascend2001/CS-31 | /Project_5/MegaMillionsTicket.cpp | UTF-8 | 788 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cassert>
#include "MegaMillionsTicket.h"
using namespace std;
MegaMillionsTicket::MegaMillionsTicket(int ball1, int ball2, int ball3, int ball4, int ball5, int megaball) {
mBall1 = ball1; //initializing the constructor values if the arguments are written in
mBall2 = ball2;
mBall3 = ball3;
mBall4 = ball4;
mBall5 = ball5;
mMegaBall = megaball;
}
int MegaMillionsTicket::getBall1() { //defining the accessors of the class.
return (mBall1);
}
int MegaMillionsTicket::getBall2() {
return(mBall2);
}
int MegaMillionsTicket::getBall3() {
return(mBall3);
}
int MegaMillionsTicket::getBall4() {
return(mBall4);
}
int MegaMillionsTicket::getBall5() {
return(mBall5);
}
int MegaMillionsTicket::getMegaBall() {
return(mMegaBall);
} | true |
eba41dac52c83e7e5bd57a29d8bab80684dd83f8 | C++ | Zylann/godot_voxel | /meshers/transvoxel/transvoxel.cpp | UTF-8 | 61,485 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "transvoxel.h"
#include "../../constants/cube_tables.h"
#include "../../util/godot/core/sort_array.h"
#include "../../util/math/conv.h"
#include "../../util/profiling.h"
#include "transvoxel_tables.cpp"
//#define VOXEL_TRANSVOXEL_REUSE_VERTEX_ON_COINCIDENT_CASES
namespace zylann::voxel::transvoxel {
static const float TRANSITION_CELL_SCALE = 0.25;
// SDF values considered negative have a sign bit of 1 in this algorithm
inline uint8_t sign_f(float v) {
return v < 0.f;
}
Vector3f get_border_offset(const Vector3f pos_scaled, const int lod_index, const Vector3i block_size_non_scaled) {
// When transition meshes are inserted between blocks of different LOD, we need to make space for them.
// Secondary vertex positions can be calculated by linearly transforming positions inside boundary cells
// so that the full-size cell is scaled to a smaller size that allows space for between one and three
// transition cells, as necessary, depending on the location with respect to the edges and corners of the
// entire block. This can be accomplished by computing offsets (Δx, Δy, Δz) for the coordinates (x, y, z)
// in any boundary cell.
Vector3f delta;
const float p2k = 1 << lod_index; // 2 ^ lod
const float p2mk = 1.f / p2k; // 2 ^ (-lod)
const float wk = TRANSITION_CELL_SCALE * p2k; // 2 ^ (lod - 2), if scale is 0.25
for (unsigned int i = 0; i < Vector3iUtil::AXIS_COUNT; ++i) {
const float p = pos_scaled[i];
const float s = block_size_non_scaled[i];
if (p < p2k) {
// The vertex is inside the minimum cell.
delta[i] = (1.0f - p2mk * p) * wk;
} else if (p > (p2k * (s - 1))) {
// The vertex is inside the maximum cell.
delta[i] = ((p2k * s) - 1.0f - p) * wk;
}
}
return delta;
}
inline Vector3f project_border_offset(Vector3f delta, Vector3f normal) {
// Secondary position can be obtained with the following formula:
//
// | x | | 1 - nx² , -nx * ny , -nx * nz | | Δx |
// | y | + | -nx * ny , 1 - ny² , -ny * nz | * | Δy |
// | z | | -nx * nz , -ny * nz , 1 - nz² | | Δz |
//
// clang-format off
return Vector3f(
(1 - normal.x * normal.x) * delta.x - normal.y * normal.x * delta.y - normal.z * normal.x * delta.z,
-normal.x * normal.y * delta.x + (1 - normal.y * normal.y) * delta.y - normal.z * normal.y * delta.z,
-normal.x * normal.z * delta.x - normal.y * normal.z * delta.y + (1 - normal.z * normal.z) * delta.z
);
// clang-format on
}
inline Vector3f get_secondary_position(
const Vector3f primary, const Vector3f normal, const int lod_index, const Vector3i block_size_non_scaled) {
Vector3f delta = get_border_offset(primary, lod_index, block_size_non_scaled);
delta = project_border_offset(delta, normal);
// At very low LOD levels, error can be high and make secondary positions shoot very far.
// Saw this happen around LOD 8. This doesn't get rid of them, but should make it not noticeable.
const float p2k = 1 << lod_index;
delta = math::clamp(delta, Vector3f(-p2k), Vector3f(p2k));
return primary + delta;
}
inline uint8_t get_border_mask(const Vector3i &pos, const Vector3i &block_size) {
uint8_t mask = 0;
// 1: -X
// 2: +X
// 4: -Y
// 8: +Y
// 16: -Z
// 32: +Z
for (unsigned int i = 0; i < Vector3iUtil::AXIS_COUNT; i++) {
// Close to negative face.
if (pos[i] == 0) {
mask |= (1 << (i * 2));
}
// Close to positive face.
if (pos[i] == block_size[i]) {
mask |= (1 << (i * 2 + 1));
}
}
return mask;
}
inline Vector3f normalized_not_null(Vector3f n) {
const float lengthsq = math::length_squared(n);
if (lengthsq == 0) {
return Vector3f(0, 1, 0);
} else {
const float length = Math::sqrt(lengthsq);
return Vector3f(n.x / length, n.y / length, n.z / length);
}
}
inline Vector3i dir_to_prev_vec(uint8_t dir) {
// return g_corner_dirs[mask] - Vector3f(1,1,1);
return Vector3i(-(dir & 1), -((dir >> 1) & 1), -((dir >> 2) & 1));
}
inline float sdf_as_float(int8_t v) {
return -s8_to_snorm_noclamp(v);
}
inline float sdf_as_float(int16_t v) {
return -s16_to_snorm_noclamp(v);
}
inline float sdf_as_float(float v) {
return -v;
}
inline float sdf_as_float(double v) {
return -v;
}
template <typename Sdf_T>
inline Vector3f get_corner_gradient(unsigned int data_index, Span<const Sdf_T> sdf_data, const Vector3i block_size) {
const unsigned int n010 = 1; // Y+1
const unsigned int n100 = block_size.y; // X+1
const unsigned int n001 = block_size.y * block_size.x; // Z+1
const float nx = sdf_as_float(sdf_data[data_index - n100]);
const float px = sdf_as_float(sdf_data[data_index + n100]);
const float ny = sdf_as_float(sdf_data[data_index - n010]);
const float py = sdf_as_float(sdf_data[data_index + n010]);
const float nz = sdf_as_float(sdf_data[data_index - n001]);
const float pz = sdf_as_float(sdf_data[data_index + n001]);
// get_gradient_normal(nx, px, ny, py, nz, pz, cell_samples[i]);
return Vector3f(nx - px, ny - py, nz - pz);
}
inline uint32_t pack_bytes(const FixedArray<uint8_t, 4> &a) {
return (a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24));
}
void add_texture_data(
std::vector<Vector2f> &uv, unsigned int packed_indices, FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights) {
struct IntUV {
uint32_t x;
uint32_t y;
};
static_assert(sizeof(IntUV) == sizeof(Vector2f), "Expected same binary size");
uv.push_back(Vector2f());
IntUV &iuv = *(reinterpret_cast<IntUV *>(&uv.back()));
// print_line(String("{0}, {1}, {2}, {3}").format(varray(weights[0], weights[1], weights[2], weights[3])));
iuv.x = packed_indices;
iuv.y = pack_bytes(weights);
}
template <unsigned int NVoxels>
struct CellTextureDatas {
uint32_t packed_indices = 0;
FixedArray<uint8_t, MAX_TEXTURE_BLENDS> indices;
FixedArray<FixedArray<uint8_t, MAX_TEXTURE_BLENDS>, NVoxels> weights;
};
template <unsigned int NVoxels, typename WeightSampler_T>
CellTextureDatas<NVoxels> select_textures_4_per_voxel(const FixedArray<unsigned int, NVoxels> &voxel_indices,
Span<const uint16_t> indices_data, const WeightSampler_T &weights_sampler) {
// TODO Optimization: this function takes almost half of the time when polygonizing non-empty cells.
// I wonder how it can be optimized further?
struct IndexAndWeight {
unsigned int index;
unsigned int weight;
};
FixedArray<FixedArray<uint8_t, MAX_TEXTURES>, NVoxels> cell_texture_weights_temp;
FixedArray<IndexAndWeight, MAX_TEXTURES> indexed_weight_sums;
// Find 4 most-used indices in voxels
for (unsigned int i = 0; i < indexed_weight_sums.size(); ++i) {
indexed_weight_sums[i] = IndexAndWeight{ i, 0 };
}
for (unsigned int ci = 0; ci < voxel_indices.size(); ++ci) {
// ZN_PROFILE_SCOPE();
const unsigned int data_index = voxel_indices[ci];
const FixedArray<uint8_t, 4> indices = decode_indices_from_packed_u16(indices_data[data_index]);
const FixedArray<uint8_t, 4> weights = weights_sampler.get_weights(data_index);
FixedArray<uint8_t, MAX_TEXTURES> &weights_temp = cell_texture_weights_temp[ci];
fill(weights_temp, uint8_t(0));
for (unsigned int j = 0; j < indices.size(); ++j) {
const unsigned int ti = indices[j];
indexed_weight_sums[ti].weight += weights[j];
weights_temp[ti] = weights[j];
}
}
struct IndexAndWeightComparator {
inline bool operator()(const IndexAndWeight &a, const IndexAndWeight &b) const {
return a.weight > b.weight;
}
};
SortArray<IndexAndWeight, IndexAndWeightComparator> sorter;
sorter.sort(indexed_weight_sums.data(), indexed_weight_sums.size());
CellTextureDatas<NVoxels> cell_textures;
// Assign indices
for (unsigned int i = 0; i < cell_textures.indices.size(); ++i) {
cell_textures.indices[i] = indexed_weight_sums[i].index;
}
// Sort indices to avoid cases that are ambiguous for blending, like 1,2,3,4 and 2,1,3,4
// TODO maybe we could require this sorting to be done up front?
// Or maybe could be done after meshing so we do it less times?
math::sort(cell_textures.indices[0], cell_textures.indices[1], cell_textures.indices[2], cell_textures.indices[3]);
cell_textures.packed_indices = pack_bytes(cell_textures.indices);
// Remap weights to follow the indices we selected
for (unsigned int ci = 0; ci < cell_texture_weights_temp.size(); ++ci) {
// ZN_PROFILE_SCOPE();
const FixedArray<uint8_t, MAX_TEXTURES> &src_weights = cell_texture_weights_temp[ci];
FixedArray<uint8_t, 4> &dst_weights = cell_textures.weights[ci];
for (unsigned int i = 0; i < cell_textures.indices.size(); ++i) {
const unsigned int ti = cell_textures.indices[i];
dst_weights[i] = src_weights[ti];
}
}
return cell_textures;
}
struct TextureIndicesData {
Span<const uint16_t> buffer;
FixedArray<uint8_t, 4> default_indices;
uint32_t packed_default_indices;
};
template <unsigned int NVoxels, typename WeightSampler_T>
inline void get_cell_texture_data(CellTextureDatas<NVoxels> &cell_textures,
const TextureIndicesData &texture_indices_data, const FixedArray<unsigned int, NVoxels> &voxel_indices,
const WeightSampler_T &weights_data) {
if (texture_indices_data.buffer.size() == 0) {
// Indices are known for the whole block, just read weights directly
cell_textures.indices = texture_indices_data.default_indices;
cell_textures.packed_indices = texture_indices_data.packed_default_indices;
for (unsigned int ci = 0; ci < voxel_indices.size(); ++ci) {
const unsigned int wi = voxel_indices[ci];
cell_textures.weights[ci] = weights_data.get_weights(wi);
}
} else {
// There can be more than 4 indices or they are not known, so we have to select them
cell_textures = select_textures_4_per_voxel(voxel_indices, texture_indices_data.buffer, weights_data);
}
}
template <typename Sdf_T>
inline Sdf_T get_isolevel() = delete;
template <>
inline int8_t get_isolevel<int8_t>() {
return 0;
}
template <>
inline int16_t get_isolevel<int16_t>() {
return 0;
}
template <>
inline float get_isolevel<float>() {
return 0.f;
}
Vector3f binary_search_interpolate(const IDeepSDFSampler &sampler, float s0, float s1, Vector3i p0, Vector3i p1,
uint32_t initial_lod_index, uint32_t min_lod_index) {
for (uint32_t lod_index = initial_lod_index; lod_index > min_lod_index; --lod_index) {
const Vector3i pm = (p0 + p1) >> 1;
// TODO Optimization: this is quite slow for a small difference in the result.
// Could be improved somewhat, but for now I don't think it's worth it
const float sm = -sampler.get_single(pm, lod_index - 1);
if (sign_f(s0) != sign_f(sm)) {
p1 = pm;
s1 = sm;
} else {
p0 = pm;
s0 = sm;
}
}
const float t = s1 / (s1 - s0);
const float t0 = t;
const float t1 = 1.f - t;
return to_vec3f(p0) * t0 + to_vec3f(p1) * t1;
}
// This function is template so we avoid branches and checks when sampling voxels
template <typename Sdf_T, typename WeightSampler_T>
void build_regular_mesh(Span<const Sdf_T> sdf_data, TextureIndicesData texture_indices_data,
const WeightSampler_T &weights_sampler, const Vector3i block_size_with_padding, uint32_t lod_index,
TexturingMode texturing_mode, Cache &cache, MeshArrays &output, const IDeepSDFSampler *deep_sdf_sampler,
std::vector<CellInfo> *cell_info) {
ZN_PROFILE_SCOPE();
// This function has some comments as quotes from the Transvoxel paper.
const Vector3i block_size = block_size_with_padding - Vector3iUtil::create(MIN_PADDING + MAX_PADDING);
const Vector3i block_size_scaled = block_size << lod_index;
// Prepare vertex reuse cache
cache.reset_reuse_cells(block_size_with_padding);
// We iterate 2x2x2 voxel groups, which the paper calls "cells".
// We also reach one voxel further to compute normals, so we adjust the iterated area
const Vector3i min_pos = Vector3iUtil::create(MIN_PADDING);
const Vector3i max_pos = block_size_with_padding - Vector3iUtil::create(MAX_PADDING);
// How much to advance in the data array to get neighbor voxels
const unsigned int n010 = 1; // Y+1
const unsigned int n100 = block_size_with_padding.y; // X+1
const unsigned int n001 = block_size_with_padding.y * block_size_with_padding.x; // Z+1
const unsigned int n110 = n010 + n100;
const unsigned int n101 = n100 + n001;
const unsigned int n011 = n010 + n001;
const unsigned int n111 = n100 + n010 + n001;
// Get direct representation of the isolevel (not always zero since we are not using signed integers yet)
const Sdf_T isolevel = get_isolevel<Sdf_T>();
// Iterate all cells with padding (expected to be neighbors)
Vector3i pos;
for (pos.z = min_pos.z; pos.z < max_pos.z; ++pos.z) {
for (pos.y = min_pos.y; pos.y < max_pos.y; ++pos.y) {
// TODO Optimization: change iteration to be ZXY? (Data is laid out with Y as deepest coordinate)
unsigned int data_index =
Vector3iUtil::get_zxy_index(Vector3i(min_pos.x, pos.y, pos.z), block_size_with_padding);
for (pos.x = min_pos.x; pos.x < max_pos.x; ++pos.x, data_index += block_size_with_padding.y) {
{
// The chosen comparison here is very important. This relates to case selections where 4 samples
// are equal to the isolevel and 4 others are above or below:
// In one of these two cases, there has to be a surface to extract, otherwise no surface will be
// allowed to appear if it happens to line up with integer coordinates.
// If we used `<` instead of `>`, it would appear to work, but would break those edge cases.
// `>` is chosen because it must match the comparison we do with case selection (in Transvoxel
// it is inverted).
const bool s = sdf_data[data_index] > isolevel;
if ( //
(sdf_data[data_index + n010] > isolevel) == s &&
(sdf_data[data_index + n100] > isolevel) == s &&
(sdf_data[data_index + n110] > isolevel) == s &&
(sdf_data[data_index + n001] > isolevel) == s &&
(sdf_data[data_index + n011] > isolevel) == s &&
(sdf_data[data_index + n101] > isolevel) == s &&
(sdf_data[data_index + n111] > isolevel) == s) {
// Not crossing the isolevel, this cell won't produce any geometry.
// We must figure this out as fast as possible, because it will happen a lot.
continue;
}
}
// ZN_PROFILE_SCOPE();
// 6-------7
// /| /|
// / | / | Corners
// 4-------5 |
// | 2----|--3
// | / | / z y
// |/ |/ |/
// 0-------1 o--x
FixedArray<unsigned int, 8> corner_data_indices;
corner_data_indices[0] = data_index;
corner_data_indices[1] = data_index + n100;
corner_data_indices[2] = data_index + n010;
corner_data_indices[3] = data_index + n110;
corner_data_indices[4] = data_index + n001;
corner_data_indices[5] = data_index + n101;
corner_data_indices[6] = data_index + n011;
corner_data_indices[7] = data_index + n111;
FixedArray<float, 8> cell_samples_sdf;
for (unsigned int i = 0; i < corner_data_indices.size(); ++i) {
cell_samples_sdf[i] = sdf_as_float(sdf_data[corner_data_indices[i]]);
}
// Concatenate the sign of cell values to obtain the case code.
// Index 0 is the less significant bit, and index 7 is the most significant bit.
uint8_t case_code = sign_f(cell_samples_sdf[0]);
case_code |= (sign_f(cell_samples_sdf[1]) << 1);
case_code |= (sign_f(cell_samples_sdf[2]) << 2);
case_code |= (sign_f(cell_samples_sdf[3]) << 3);
case_code |= (sign_f(cell_samples_sdf[4]) << 4);
case_code |= (sign_f(cell_samples_sdf[5]) << 5);
case_code |= (sign_f(cell_samples_sdf[6]) << 6);
case_code |= (sign_f(cell_samples_sdf[7]) << 7);
// TODO Is this really needed now that we check isolevel earlier?
if (case_code == 0 || case_code == 255) {
// If the case_code is 0 or 255, there is no triangulation to do.
continue;
}
ReuseCell ¤t_reuse_cell = cache.get_reuse_cell(pos);
#if DEBUG_ENABLED
ZN_ASSERT(case_code <= 255);
#endif
FixedArray<Vector3i, 8> padded_corner_positions;
padded_corner_positions[0] = Vector3i(pos.x, pos.y, pos.z);
padded_corner_positions[1] = Vector3i(pos.x + 1, pos.y, pos.z);
padded_corner_positions[2] = Vector3i(pos.x, pos.y + 1, pos.z);
padded_corner_positions[3] = Vector3i(pos.x + 1, pos.y + 1, pos.z);
padded_corner_positions[4] = Vector3i(pos.x, pos.y, pos.z + 1);
padded_corner_positions[5] = Vector3i(pos.x + 1, pos.y, pos.z + 1);
padded_corner_positions[6] = Vector3i(pos.x, pos.y + 1, pos.z + 1);
padded_corner_positions[7] = Vector3i(pos.x + 1, pos.y + 1, pos.z + 1);
CellTextureDatas<8> cell_textures;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
get_cell_texture_data(cell_textures, texture_indices_data, corner_data_indices, weights_sampler);
current_reuse_cell.packed_texture_indices = cell_textures.packed_indices;
}
FixedArray<Vector3i, 8> corner_positions;
for (unsigned int i = 0; i < padded_corner_positions.size(); ++i) {
const Vector3i p = padded_corner_positions[i];
// Undo padding here. From this point, corner positions are actual positions.
corner_positions[i] = (p - min_pos) << lod_index;
}
// For cells occurring along the minimal boundaries of a block,
// the preceding cells needed for vertex reuse may not exist.
// In these cases, we allow new vertex creation on additional edges of a cell.
// While iterating through the cells in a block, a 3-bit mask is maintained whose bits indicate
// whether corresponding bits in a direction code are valid
const uint8_t direction_validity_mask = (pos.x > min_pos.x ? 1 : 0) |
((pos.y > min_pos.y ? 1 : 0) << 1) | ((pos.z > min_pos.z ? 1 : 0) << 2);
const uint8_t regular_cell_class_index = tables::get_regular_cell_class(case_code);
const tables::RegularCellData ®ular_cell_data =
tables::get_regular_cell_data(regular_cell_class_index);
const uint8_t triangle_count = regular_cell_data.geometryCounts & 0x0f;
const uint8_t vertex_count = (regular_cell_data.geometryCounts & 0xf0) >> 4;
FixedArray<int, 12> cell_vertex_indices;
fill(cell_vertex_indices, -1);
const uint8_t cell_border_mask = get_border_mask(pos - min_pos, block_size - Vector3i(1, 1, 1));
// For each vertex in the case
for (unsigned int vertex_index = 0; vertex_index < vertex_count; ++vertex_index) {
// The case index maps to a list of 16-bit codes providing information about the edges on which the
// vertices lie. The low byte of each 16-bit code contains the corner indexes of the edge’s
// endpoints in one nibble each, and the high byte contains the mapping code shown in Figure 3.8(b)
const unsigned short rvd = tables::get_regular_vertex_data(case_code, vertex_index);
const uint8_t edge_code_low = rvd & 0xff;
const uint8_t edge_code_high = (rvd >> 8) & 0xff;
// Get corner indexes in the low nibble (always ordered so the higher comes last)
const uint8_t v0 = (edge_code_low >> 4) & 0xf;
const uint8_t v1 = edge_code_low & 0xf;
#ifdef DEBUG_ENABLED
ZN_ASSERT_RETURN(v1 > v0);
#endif
// Get voxel values at the corners
const float sample0 = cell_samples_sdf[v0]; // called d0 in the paper
const float sample1 = cell_samples_sdf[v1]; // called d1 in the paper
#ifdef DEBUG_ENABLED
// TODO Zero-division is not mentionned in the paper?? (never happens tho)
ZN_ASSERT_RETURN(sample1 != sample0);
ZN_ASSERT_RETURN(sample1 != 0 || sample0 != 0);
#endif
// Get interpolation position
// We use an 8-bit fraction, allowing the new vertex to be located at one of 257 possible
// positions along the edge when both endpoints are included.
// const int t = (sample1 << 8) / (sample1 - sample0);
const float t = sample1 / (sample1 - sample0);
const Vector3i p0 = corner_positions[v0];
const Vector3i p1 = corner_positions[v1];
if (t > 0.f && t < 1.f) {
// Vertex is between p0 and p1 (inside the edge)
// Each edge of a cell is assigned an 8-bit code, as shown in Figure 3.8(b),
// that provides a mapping to a preceding cell and the coincident edge on that preceding cell
// for which new vertex creation was allowed.
// The high nibble of this code indicates which direction to go in order to reach the correct
// preceding cell. The bit values 1, 2, and 4 in this nibble indicate that we must subtract one
// from the x, y, and/or z coordinate, respectively.
const uint8_t reuse_dir = (edge_code_high >> 4) & 0xf;
const uint8_t reuse_vertex_index = edge_code_high & 0xf;
// TODO Some re-use opportunities are missed on negative sides of the block,
// but I don't really know how to fix it...
// You can check by "shaking" every vertex randomly in a shader based on its index,
// you will see vertices touching the -X, -Y or -Z sides of the block aren't connected
const bool present = (reuse_dir & direction_validity_mask) == reuse_dir;
if (present) {
const Vector3i cache_pos = pos + dir_to_prev_vec(reuse_dir);
const ReuseCell &prev_cell = cache.get_reuse_cell(cache_pos);
if (prev_cell.packed_texture_indices == cell_textures.packed_indices) {
// Will reuse a previous vertice
cell_vertex_indices[vertex_index] = prev_cell.vertices[reuse_vertex_index];
}
}
if (!present || cell_vertex_indices[vertex_index] == -1) {
// Create new vertex
const float t0 = t; // static_cast<float>(t) / 256.f;
const float t1 = 1.f - t; // static_cast<float>(0x100 - t) / 256.f;
// const int ti0 = t;
// const int ti1 = 0x100 - t;
// const Vector3i primary = p0 * ti0 + p1 * ti1;
Vector3f primaryf;
if (deep_sdf_sampler != nullptr) {
primaryf = binary_search_interpolate(
*deep_sdf_sampler, sample0, sample1, p0, p1, lod_index, 0);
} else {
primaryf = to_vec3f(p0) * t0 + to_vec3f(p1) * t1;
}
// TODO Binary search gives better positional results, but does not improve normals.
// I'm not sure how to overcome this because if we sample low-detail normals, we get a
// "blocky" result due to SDF clipping. If we sample high-detail gradients, we get details,
// but if details are bumpy, we also get noisy results.
const Vector3f cg0 = get_corner_gradient<Sdf_T>(
corner_data_indices[v0], sdf_data, block_size_with_padding);
const Vector3f cg1 = get_corner_gradient<Sdf_T>(
corner_data_indices[v1], sdf_data, block_size_with_padding);
const Vector3f normal = normalized_not_null(cg0 * t0 + cg1 * t1);
Vector3f secondary;
uint8_t vertex_border_mask = 0;
if (cell_border_mask > 0) {
secondary = get_secondary_position(primaryf, normal, lod_index, block_size);
vertex_border_mask = (get_border_mask(p0, block_size_scaled) &
get_border_mask(p1, block_size_scaled));
}
cell_vertex_indices[vertex_index] = output.add_vertex(
primaryf, normal, cell_border_mask, vertex_border_mask, 0, secondary);
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights0 = cell_textures.weights[v0];
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights1 = cell_textures.weights[v1];
FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights;
for (unsigned int i = 0; i < MAX_TEXTURE_BLENDS; ++i) {
weights[i] = static_cast<uint8_t>(
math::clamp(Math::lerp(weights0[i], weights1[i], t1), 0.f, 255.f));
}
add_texture_data(output.texturing_data, cell_textures.packed_indices, weights);
}
if (reuse_dir & 8) {
// Store the generated vertex so that other cells can reuse it.
current_reuse_cell.vertices[reuse_vertex_index] = cell_vertex_indices[vertex_index];
}
}
} else if (t == 0 && v1 == 7) {
// t == 0: the vertex is on p1
// v1 == 7: p1 on the max corner of the cell
// This cell owns the vertex, so it should be created.
const Vector3i primary = p1;
const Vector3f primaryf = to_vec3f(primary);
const Vector3f cg1 =
get_corner_gradient<Sdf_T>(corner_data_indices[v1], sdf_data, block_size_with_padding);
const Vector3f normal = normalized_not_null(cg1);
Vector3f secondary;
uint8_t vertex_border_mask = 0;
if (cell_border_mask > 0) {
secondary = get_secondary_position(primaryf, normal, lod_index, block_size);
vertex_border_mask = get_border_mask(p1, block_size_scaled);
}
cell_vertex_indices[vertex_index] =
output.add_vertex(primaryf, normal, cell_border_mask, vertex_border_mask, 0, secondary);
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights1 = cell_textures.weights[v1];
add_texture_data(output.texturing_data, cell_textures.packed_indices, weights1);
}
current_reuse_cell.vertices[0] = cell_vertex_indices[vertex_index];
} else {
// The vertex is either on p0 or p1.
// The original Transvoxel tries to reuse previous vertices in these cases,
// however here we don't do it because of ambiguous cases that makes artifacts appear.
// It's not a common case so it shouldn't be too bad
// (unless you do a lot of grid-aligned shapes?).
// What do we do if the vertex we would re-use is on a cell that had no triangulation?
// The previous cell might have had all corners of the same sign, except one being 0.
// Forcing `present=false` seems to fix cases of holes that would be caused by that.
// Resetting the cache before processing each deck also works, but is slightly slower.
// Otherwise the code would try to re-use a vertex that hasn't been written as re-usable,
// so it picks up some garbage from earlier decks.
#ifdef VOXEL_TRANSVOXEL_REUSE_VERTEX_ON_COINCIDENT_CASES
// A 3-bit direction code leading to the proper cell can easily be obtained by
// inverting the 3-bit corner index (bitwise, by exclusive ORing with the number 7).
// The corner index depends on the value of t, t = 0 means that we're at the higher
// numbered endpoint.
const uint8_t reuse_dir = (t == 0 ? v1 ^ 7 : v0 ^ 7);
const bool present = (reuse_dir & direction_validity_mask) == reuse_dir;
// Note: the only difference with similar code above is that we take vertice 0 in the `else`
if (present) {
const Vector3i cache_pos = pos + dir_to_prev_vec(reuse_dir);
const ReuseCell &prev_cell = cache.get_reuse_cell(cache_pos);
cell_vertex_indices[vertex_index] = prev_cell.vertices[0];
}
if (!present || cell_vertex_indices[vertex_index] == -1)
#endif
{
// Create new vertex
// TODO Earlier we associated t==0 to p0, why are we doing p1 here?
const unsigned int vi = t == 0 ? v1 : v0;
const Vector3i primary = t == 0 ? p1 : p0;
const Vector3f primaryf = to_vec3f(primary);
const Vector3f cg = get_corner_gradient<Sdf_T>(
corner_data_indices[vi], sdf_data, block_size_with_padding);
const Vector3f normal = normalized_not_null(cg);
// TODO This bit of code is repeated several times, factor it?
Vector3f secondary;
uint8_t vertex_border_mask = 0;
if (cell_border_mask > 0) {
secondary = get_secondary_position(primaryf, normal, lod_index, block_size);
vertex_border_mask = get_border_mask(primary, block_size_scaled);
}
cell_vertex_indices[vertex_index] = output.add_vertex(
primaryf, normal, cell_border_mask, vertex_border_mask, 0, secondary);
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights = cell_textures.weights[vi];
add_texture_data(output.texturing_data, cell_textures.packed_indices, weights);
}
}
}
} // for each cell vertex
for (int t = 0; t < triangle_count; ++t) {
const int t0 = t * 3;
const int i0 = cell_vertex_indices[regular_cell_data.get_vertex_index(t0)];
const int i1 = cell_vertex_indices[regular_cell_data.get_vertex_index(t0 + 1)];
const int i2 = cell_vertex_indices[regular_cell_data.get_vertex_index(t0 + 2)];
output.indices.push_back(i0);
output.indices.push_back(i1);
output.indices.push_back(i2);
}
if (cell_info != nullptr) {
cell_info->push_back(CellInfo{ pos - min_pos, triangle_count });
}
} // x
} // y
} // z
}
// y y
// | | z
// | |/ OpenGL axis convention
// o---x x---o
// /
// z
// Convert from face-space to block-space coordinates, considering which face we are working on.
inline Vector3i face_to_block(int x, int y, int z, int dir, const Vector3i &bs) {
// There are several possible solutions to this, because we can rotate the axes.
// We'll take configurations where XY map different axes at the same relative orientations,
// so only Z is flipped in half cases.
switch (dir) {
case Cube::SIDE_NEGATIVE_X:
return Vector3i(z, x, y);
case Cube::SIDE_POSITIVE_X:
return Vector3i(bs.x - 1 - z, y, x);
case Cube::SIDE_NEGATIVE_Y:
return Vector3i(y, z, x);
case Cube::SIDE_POSITIVE_Y:
return Vector3i(x, bs.y - 1 - z, y);
case Cube::SIDE_NEGATIVE_Z:
return Vector3i(x, y, z);
case Cube::SIDE_POSITIVE_Z:
return Vector3i(y, x, bs.z - 1 - z);
default:
CRASH_NOW();
return Vector3i();
}
}
// I took the choice of supporting non-cubic area, so...
inline void get_face_axes(int &ax, int &ay, int dir) {
switch (dir) {
case Cube::SIDE_NEGATIVE_X:
ax = Vector3i::AXIS_Y;
ay = Vector3i::AXIS_Z;
break;
case Cube::SIDE_POSITIVE_X:
ax = Vector3i::AXIS_Z;
ay = Vector3i::AXIS_Y;
break;
case Cube::SIDE_NEGATIVE_Y:
ax = Vector3i::AXIS_Z;
ay = Vector3i::AXIS_X;
break;
case Cube::SIDE_POSITIVE_Y:
ax = Vector3i::AXIS_X;
ay = Vector3i::AXIS_Z;
break;
case Cube::SIDE_NEGATIVE_Z:
ax = Vector3i::AXIS_X;
ay = Vector3i::AXIS_Y;
break;
case Cube::SIDE_POSITIVE_Z:
ax = Vector3i::AXIS_Y;
ay = Vector3i::AXIS_X;
break;
default:
ZN_CRASH();
}
}
// TODO Cube::Side has a legacy issue where Y axes are inverted compared to the others
inline uint8_t get_face_index(int cube_dir) {
switch (cube_dir) {
case Cube::SIDE_NEGATIVE_X:
return 0;
case Cube::SIDE_POSITIVE_X:
return 1;
case Cube::SIDE_NEGATIVE_Y:
return 2;
case Cube::SIDE_POSITIVE_Y:
return 3;
case Cube::SIDE_NEGATIVE_Z:
return 4;
case Cube::SIDE_POSITIVE_Z:
return 5;
default:
ZN_CRASH();
return 0;
}
}
template <typename Sdf_T, typename WeightSampler_T>
void build_transition_mesh(Span<const Sdf_T> sdf_data, TextureIndicesData texture_indices_data,
const WeightSampler_T &weights_sampler, const Vector3i block_size_with_padding, int direction, int lod_index,
TexturingMode texturing_mode, Cache &cache, MeshArrays &output) {
// From this point, we expect the buffer to contain allocated data.
// This function has some comments as quotes from the Transvoxel paper.
const Vector3i block_size_without_padding =
block_size_with_padding - Vector3iUtil::create(MIN_PADDING + MAX_PADDING);
const Vector3i block_size_scaled = block_size_without_padding << lod_index;
ZN_ASSERT_RETURN(block_size_with_padding.x >= 3);
ZN_ASSERT_RETURN(block_size_with_padding.y >= 3);
ZN_ASSERT_RETURN(block_size_with_padding.z >= 3);
cache.reset_reuse_cells_2d(block_size_with_padding);
// This part works in "face space", which is 2D along local X and Y axes.
// In this space, -Z points towards the half resolution cells, while +Z points towards full-resolution cells.
// Conversion is used to map this space to block space using a direction enum.
// Note: I made a few changes compared to the paper.
// Instead of making transition meshes go from low-res blocks to high-res blocks,
// I do the opposite, going from high-res to low-res. It's easier because half-res voxels are available for free,
// if we compute the transition meshes right after the regular mesh, with the same voxel data.
// TODO One issue with this change however, is a "bump" of mesh density which can be noticeable.
// This represents the actual box of voxels we are working on.
// It also represents positions of the minimum and maximum vertices that can be generated.
// Padding is present to allow reaching 1 voxel further for calculating normals
const Vector3i min_pos = Vector3iUtil::create(MIN_PADDING);
const Vector3i max_pos = block_size_with_padding - Vector3iUtil::create(MAX_PADDING);
int axis_x, axis_y;
get_face_axes(axis_x, axis_y, direction);
const int min_fpos_x = min_pos[axis_x];
const int min_fpos_y = min_pos[axis_y];
const int max_fpos_x = max_pos[axis_x] - 1; // Another -1 here, because the 2D kernel is 3x3
const int max_fpos_y = max_pos[axis_y] - 1;
// How much to advance in the data array to get neighbor voxels
const unsigned int n010 = 1; // Y+1
const unsigned int n100 = block_size_with_padding.y; // X+1
const unsigned int n001 = block_size_with_padding.y * block_size_with_padding.x; // Z+1
// const unsigned int n110 = n010 + n100;
// const unsigned int n101 = n100 + n001;
// const unsigned int n011 = n010 + n001;
// const unsigned int n111 = n100 + n010 + n001;
// Using temporay locals otherwise clang-format makes it hard to read
const Vector3i ftb_000 = face_to_block(0, 0, 0, direction, block_size_with_padding);
const Vector3i ftb_x00 = face_to_block(1, 0, 0, direction, block_size_with_padding);
const Vector3i ftb_0y0 = face_to_block(0, 1, 0, direction, block_size_with_padding);
// How much to advance in the data array to get neighbor voxels, using face coordinates
const int fn00 = Vector3iUtil::get_zxy_index(ftb_000, block_size_with_padding);
const int fn10 = Vector3iUtil::get_zxy_index(ftb_x00, block_size_with_padding) - fn00;
const int fn01 = Vector3iUtil::get_zxy_index(ftb_0y0, block_size_with_padding) - fn00;
const int fn11 = fn10 + fn01;
const int fn21 = 2 * fn10 + fn01;
const int fn22 = 2 * fn10 + 2 * fn01;
const int fn12 = fn10 + 2 * fn01;
const int fn20 = 2 * fn10;
const int fn02 = 2 * fn01;
FixedArray<Vector3i, 13> cell_positions;
const int fz = MIN_PADDING;
const Sdf_T isolevel = get_isolevel<Sdf_T>();
const uint8_t transition_hint_mask = 1 << get_face_index(direction);
// Iterating in face space
for (int fy = min_fpos_y; fy < max_fpos_y; fy += 2) {
for (int fx = min_fpos_x; fx < max_fpos_x; fx += 2) {
// Cell positions in block space
// Warning: temporarily includes padding. It is undone later.
cell_positions[0] = face_to_block(fx, fy, fz, direction, block_size_with_padding);
const int data_index = Vector3iUtil::get_zxy_index(cell_positions[0], block_size_with_padding);
{
const bool s = sdf_data[data_index] > isolevel;
// `//` prevents clang-format from messing up
if ( //
(sdf_data[data_index + fn10] > isolevel) == s && //
(sdf_data[data_index + fn20] > isolevel) == s && //
(sdf_data[data_index + fn01] > isolevel) == s && //
(sdf_data[data_index + fn11] > isolevel) == s && //
(sdf_data[data_index + fn21] > isolevel) == s && //
(sdf_data[data_index + fn02] > isolevel) == s && //
(sdf_data[data_index + fn12] > isolevel) == s && //
(sdf_data[data_index + fn22] > isolevel) == s) {
// Not crossing the isolevel, this cell won't produce any geometry.
// We must figure this out as fast as possible, because it will happen a lot.
continue;
}
}
FixedArray<unsigned int, 9> cell_data_indices;
cell_data_indices[0] = data_index;
cell_data_indices[1] = data_index + fn10;
cell_data_indices[2] = data_index + fn20;
cell_data_indices[3] = data_index + fn01;
cell_data_indices[4] = data_index + fn11;
cell_data_indices[5] = data_index + fn21;
cell_data_indices[6] = data_index + fn02;
cell_data_indices[7] = data_index + fn12;
cell_data_indices[8] = data_index + fn22;
// 6---7---8
// | | |
// 3---4---5
// | | |
// 0---1---2
// Full-resolution samples 0..8
FixedArray<float, 13> cell_samples;
for (unsigned int i = 0; i < 9; ++i) {
cell_samples[i] = sdf_as_float(sdf_data[cell_data_indices[i]]);
}
// B-------C
// | |
// | |
// | |
// 9-------A
// Half-resolution samples 9..C: they are the same
cell_samples[0x9] = cell_samples[0];
cell_samples[0xA] = cell_samples[2];
cell_samples[0xB] = cell_samples[6];
cell_samples[0xC] = cell_samples[8];
uint16_t case_code = sign_f(cell_samples[0]);
case_code |= (sign_f(cell_samples[1]) << 1);
case_code |= (sign_f(cell_samples[2]) << 2);
case_code |= (sign_f(cell_samples[5]) << 3);
case_code |= (sign_f(cell_samples[8]) << 4);
case_code |= (sign_f(cell_samples[7]) << 5);
case_code |= (sign_f(cell_samples[6]) << 6);
case_code |= (sign_f(cell_samples[3]) << 7);
case_code |= (sign_f(cell_samples[4]) << 8);
if (case_code == 0 || case_code == 511) {
// The cell contains no triangles.
continue;
}
CellTextureDatas<13> cell_textures;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
CellTextureDatas<9> cell_textures_partial;
get_cell_texture_data(cell_textures_partial, texture_indices_data, cell_data_indices, weights_sampler);
cell_textures.indices = cell_textures_partial.indices;
cell_textures.packed_indices = cell_textures_partial.packed_indices;
for (unsigned int i = 0; i < cell_textures_partial.weights.size(); ++i) {
cell_textures.weights[i] = cell_textures_partial.weights[i];
}
cell_textures.weights[0x9] = cell_textures_partial.weights[0];
cell_textures.weights[0xA] = cell_textures_partial.weights[2];
cell_textures.weights[0xB] = cell_textures_partial.weights[6];
cell_textures.weights[0xC] = cell_textures_partial.weights[8];
ReuseTransitionCell ¤t_reuse_cell = cache.get_reuse_cell_2d(fx, fy);
current_reuse_cell.packed_texture_indices = cell_textures.packed_indices;
}
ZN_ASSERT(case_code <= 511);
// TODO We may not need all of them!
FixedArray<Vector3f, 13> cell_gradients;
for (unsigned int i = 0; i < 9; ++i) {
const unsigned int di = cell_data_indices[i];
const float nx = sdf_as_float(sdf_data[di - n100]);
const float ny = sdf_as_float(sdf_data[di - n010]);
const float nz = sdf_as_float(sdf_data[di - n001]);
const float px = sdf_as_float(sdf_data[di + n100]);
const float py = sdf_as_float(sdf_data[di + n010]);
const float pz = sdf_as_float(sdf_data[di + n001]);
cell_gradients[i] = Vector3f(nx - px, ny - py, nz - pz);
}
cell_gradients[0x9] = cell_gradients[0];
cell_gradients[0xA] = cell_gradients[2];
cell_gradients[0xB] = cell_gradients[6];
cell_gradients[0xC] = cell_gradients[8];
// TODO Optimization: get rid of conditionals involved in face_to_block
cell_positions[1] = face_to_block(fx + 1, fy + 0, fz, direction, block_size_with_padding);
cell_positions[2] = face_to_block(fx + 2, fy + 0, fz, direction, block_size_with_padding);
cell_positions[3] = face_to_block(fx + 0, fy + 1, fz, direction, block_size_with_padding);
cell_positions[4] = face_to_block(fx + 1, fy + 1, fz, direction, block_size_with_padding);
cell_positions[5] = face_to_block(fx + 2, fy + 1, fz, direction, block_size_with_padding);
cell_positions[6] = face_to_block(fx + 0, fy + 2, fz, direction, block_size_with_padding);
cell_positions[7] = face_to_block(fx + 1, fy + 2, fz, direction, block_size_with_padding);
cell_positions[8] = face_to_block(fx + 2, fy + 2, fz, direction, block_size_with_padding);
for (unsigned int i = 0; i < 9; ++i) {
cell_positions[i] = (cell_positions[i] - min_pos) << lod_index;
}
cell_positions[0x9] = cell_positions[0];
cell_positions[0xA] = cell_positions[2];
cell_positions[0xB] = cell_positions[6];
cell_positions[0xC] = cell_positions[8];
const uint8_t cell_class = tables::get_transition_cell_class(case_code);
CRASH_COND((cell_class & 0x7f) > 55);
const tables::TransitionCellData cell_data = tables::get_transition_cell_data(cell_class & 0x7f);
const bool flip_triangles = ((cell_class & 128) != 0);
const unsigned int vertex_count = cell_data.GetVertexCount();
FixedArray<int, 12> cell_vertex_indices;
fill(cell_vertex_indices, -1);
CRASH_COND(vertex_count > cell_vertex_indices.size());
const uint8_t direction_validity_mask = (fx > min_fpos_x ? 1 : 0) | ((fy > min_fpos_y ? 1 : 0) << 1);
const uint8_t cell_border_mask = get_border_mask(cell_positions[0], block_size_scaled);
for (unsigned int vertex_index = 0; vertex_index < vertex_count; ++vertex_index) {
const uint16_t edge_code = tables::get_transition_vertex_data(case_code, vertex_index);
const uint8_t index_vertex_a = (edge_code >> 4) & 0xf;
const uint8_t index_vertex_b = (edge_code & 0xf);
const float sample_a = cell_samples[index_vertex_a]; // d0 and d1 in the paper
const float sample_b = cell_samples[index_vertex_b];
// TODO Zero-division is not mentionned in the paper??
ZN_ASSERT_RETURN(sample_a != sample_b);
ZN_ASSERT_RETURN(sample_a != 0 || sample_b != 0);
// Get interpolation position
// We use an 8-bit fraction, allowing the new vertex to be located at one of 257 possible
// positions along the edge when both endpoints are included.
// const int t = (sample_b << 8) / (sample_b - sample_a);
const float t = sample_b / (sample_b - sample_a);
const float t0 = t; // static_cast<float>(t) / 256.f;
const float t1 = 1.f - t; // static_cast<float>(0x100 - t) / 256.f;
// const int ti0 = t;
// const int ti1 = 0x100 - t;
if (t > 0.f && t < 1.f) {
// Vertex lies in the interior of the edge.
// (i.e t is either 0 or 257, meaning it's either directly on vertex a or vertex b)
const uint8_t vertex_index_to_reuse_or_create = (edge_code >> 8) & 0xf;
// The bit values 1 and 2 in this nibble indicate that we must subtract one from the x or y
// coordinate, respectively, and these two bits are never simultaneously set.
// The bit value 4 indicates that a new vertex is to be created on an interior edge
// where it cannot be reused, and the bit value 8 indicates that a new vertex is to be created on a
// maximal edge where it can be reused.
//
// Bit 0 (0x1): need to subtract one to X
// Bit 1 (0x2): need to subtract one to Y
// Bit 2 (0x4): vertex is on an interior edge, won't be reused
// Bit 3 (0x8): vertex is on a maximal edge, it can be reused
const uint8_t reuse_direction = (edge_code >> 12);
const bool present = (reuse_direction & direction_validity_mask) == reuse_direction;
if (present) {
// The previous cell is available. Retrieve the cached cell
// from which to retrieve the reused vertex index from.
const ReuseTransitionCell &prev =
cache.get_reuse_cell_2d(fx - (reuse_direction & 1), fy - ((reuse_direction >> 1) & 1));
if (prev.packed_texture_indices == cell_textures.packed_indices) {
// Reuse the vertex index from the previous cell.
cell_vertex_indices[vertex_index] = prev.vertices[vertex_index_to_reuse_or_create];
}
}
if (!present || cell_vertex_indices[vertex_index] == -1) {
// Going to create a new vertex
const Vector3i p0 = cell_positions[index_vertex_a];
const Vector3i p1 = cell_positions[index_vertex_b];
const Vector3f n0 = cell_gradients[index_vertex_a];
const Vector3f n1 = cell_gradients[index_vertex_b];
// Vector3i primary = p0 * ti0 + p1 * ti1;
const Vector3f primaryf = to_vec3f(p0) * t0 + to_vec3f(p1) * t1;
const Vector3f normal = normalized_not_null(n0 * t0 + n1 * t1);
const bool fullres_side = (index_vertex_a < 9 || index_vertex_b < 9);
Vector3f secondary;
uint8_t cell_border_mask2 = cell_border_mask;
uint8_t vertex_border_mask = 0;
if (fullres_side) {
secondary = get_secondary_position(primaryf, normal, lod_index, block_size_without_padding);
vertex_border_mask =
(get_border_mask(p0, block_size_scaled) & get_border_mask(p1, block_size_scaled));
} else {
// If the vertex is on the half-res side (in our implementation,
// it's the side of the block), then we make the mask 0 so that the vertex is never moved.
// We only move the full-res side to connect with the regular mesh,
// which will also be moved by the same amount to fit the transition mesh.
cell_border_mask2 = 0;
}
cell_vertex_indices[vertex_index] = output.add_vertex(primaryf, normal, cell_border_mask2,
vertex_border_mask, transition_hint_mask, secondary);
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights0 =
cell_textures.weights[index_vertex_a];
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights1 =
cell_textures.weights[index_vertex_b];
FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights;
for (unsigned int i = 0; i < cell_textures.indices.size(); ++i) {
weights[i] = static_cast<uint8_t>(
math::clamp(Math::lerp(weights0[i], weights1[i], t1), 0.f, 255.f));
}
add_texture_data(output.texturing_data, cell_textures.packed_indices, weights);
}
if (reuse_direction & 0x8) {
// The vertex can be re-used later
ReuseTransitionCell &r = cache.get_reuse_cell_2d(fx, fy);
r.vertices[vertex_index_to_reuse_or_create] = cell_vertex_indices[vertex_index];
}
}
} else {
// The vertex is exactly on one of the edge endpoints.
// Try to reuse corner vertex from a preceding cell.
// Use the reuse information in transitionCornerData.
const uint8_t cell_index = (t == 0 ? index_vertex_b : index_vertex_a);
CRASH_COND(cell_index >= 13);
const uint8_t corner_data = tables::get_transition_corner_data(cell_index);
const uint8_t vertex_index_to_reuse_or_create = (corner_data & 0xf);
const uint8_t reuse_direction = ((corner_data >> 4) & 0xf);
const bool present = (reuse_direction & direction_validity_mask) == reuse_direction;
if (present) {
// The previous cell is available. Retrieve the cached cell
// from which to retrieve the reused vertex index from.
const ReuseTransitionCell &prev =
cache.get_reuse_cell_2d(fx - (reuse_direction & 1), fy - ((reuse_direction >> 1) & 1));
// Reuse the vertex index from the previous cell.
cell_vertex_indices[vertex_index] = prev.vertices[vertex_index_to_reuse_or_create];
}
if (!present || cell_vertex_indices[vertex_index] == -1) {
// Going to create a new vertex
const Vector3i primary = cell_positions[cell_index];
const Vector3f primaryf = to_vec3f(primary);
const Vector3f normal = normalized_not_null(cell_gradients[cell_index]);
const bool fullres_side = (cell_index < 9);
Vector3f secondary;
uint8_t vertex_border_mask = 0;
uint8_t cell_border_mask2 = cell_border_mask;
if (fullres_side) {
secondary = get_secondary_position(primaryf, normal, lod_index, block_size_without_padding);
vertex_border_mask = get_border_mask(primary, block_size_scaled);
} else {
cell_border_mask2 = 0;
}
cell_vertex_indices[vertex_index] = output.add_vertex(primaryf, normal, cell_border_mask2,
vertex_border_mask, transition_hint_mask, secondary);
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
const FixedArray<uint8_t, MAX_TEXTURE_BLENDS> weights = cell_textures.weights[cell_index];
add_texture_data(output.texturing_data, cell_textures.packed_indices, weights);
}
// We are on a corner so the vertex will be re-usable later
ReuseTransitionCell &r = cache.get_reuse_cell_2d(fx, fy);
r.vertices[vertex_index_to_reuse_or_create] = cell_vertex_indices[vertex_index];
}
}
} // for vertex
const unsigned int triangle_count = cell_data.GetTriangleCount();
for (unsigned int ti = 0; ti < triangle_count; ++ti) {
if (flip_triangles) {
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3)]);
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3 + 1)]);
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3 + 2)]);
} else {
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3 + 2)]);
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3 + 1)]);
output.indices.push_back(cell_vertex_indices[cell_data.get_vertex_index(ti * 3)]);
}
}
} // for x
} // for y
}
template <typename T>
Span<const T> get_or_decompress_channel(
const VoxelBufferInternal &voxels, std::vector<T> &backing_buffer, unsigned int channel) {
//
ZN_ASSERT_RETURN_V(
voxels.get_channel_depth(channel) == VoxelBufferInternal::get_depth_from_size(sizeof(T)), Span<const T>());
if (voxels.get_channel_compression(channel) == VoxelBufferInternal::COMPRESSION_UNIFORM) {
backing_buffer.resize(Vector3iUtil::get_volume(voxels.get_size()));
const T v = voxels.get_voxel(Vector3i(), channel);
// TODO Could use a fast fill using 8-byte blocks or intrinsics?
for (unsigned int i = 0; i < backing_buffer.size(); ++i) {
backing_buffer[i] = v;
}
return to_span_const(backing_buffer);
} else {
Span<uint8_t> data_bytes;
ZN_ASSERT(voxels.get_channel_raw(channel, data_bytes) == true);
return data_bytes.reinterpret_cast_to<const T>();
}
}
TextureIndicesData get_texture_indices_data(const VoxelBufferInternal &voxels, unsigned int channel,
DefaultTextureIndicesData &out_default_texture_indices_data) {
ZN_ASSERT_RETURN_V(voxels.get_channel_depth(channel) == VoxelBufferInternal::DEPTH_16_BIT, TextureIndicesData());
TextureIndicesData data;
if (voxels.is_uniform(channel)) {
const uint16_t encoded_indices = voxels.get_voxel(Vector3i(), channel);
data.default_indices = decode_indices_from_packed_u16(encoded_indices);
data.packed_default_indices = pack_bytes(data.default_indices);
out_default_texture_indices_data.indices = data.default_indices;
out_default_texture_indices_data.packed_indices = data.packed_default_indices;
out_default_texture_indices_data.use = true;
} else {
Span<uint8_t> data_bytes;
ZN_ASSERT(voxels.get_channel_raw(channel, data_bytes) == true);
data.buffer = data_bytes.reinterpret_cast_to<const uint16_t>();
out_default_texture_indices_data.use = false;
}
return data;
}
// I'm not really decided if doing this is better or not yet?
//#define USE_TRICHANNEL
#ifdef USE_TRICHANNEL
// TODO Is this a faster/equivalent option with better precision?
struct WeightSampler3U8 {
Span<const uint8_t> u8_data0;
Span<const uint8_t> u8_data1;
Span<const uint8_t> u8_data2;
inline FixedArray<uint8_t, 4> get_weights(int i) const {
FixedArray<uint8_t, 4> w;
w[0] = u8_data0[i];
w[1] = u8_data1[i];
w[2] = u8_data2[i];
w[3] = 255 - (w[0] + w[1] + w[2]);
return w;
}
};
thread_local std::vector<uint8_t> s_weights_backing_buffer_u8_0;
thread_local std::vector<uint8_t> s_weights_backing_buffer_u8_1;
thread_local std::vector<uint8_t> s_weights_backing_buffer_u8_2;
#else
struct WeightSamplerPackedU16 {
Span<const uint16_t> u16_data;
inline FixedArray<uint8_t, 4> get_weights(int i) const {
return decode_weights_from_packed_u16(u16_data[i]);
}
};
std::vector<uint16_t> &get_tls_weights_backing_buffer_u16() {
thread_local std::vector<uint16_t> tls_weights_backing_buffer_u16;
return tls_weights_backing_buffer_u16;
}
#endif
// Presence of zeroes in samples occurs more often when precision is scarce
// (8-bit, scaled SDF, or slow gradients).
// This causes two symptoms:
// - Degenerate triangles. Potentially bad for systems using the mesh later (MeshOptimizer, physics)
// - Glitched triangles. Wrong vertices get re-used.
// Needs closer investigation to know why, maybe related to case selection
//
// See also https://github.com/zeux/meshoptimizer/issues/312
//
// A quick fix to avoid it is to add a tiny offset to values equal to the isolevel.
// It must be done on the whole buffer to ensure consistency (and not after early cell rejection),
// otherwise it can create gaps in the final mesh.
//
// Not used anymore for now, but if we get this problem again we may have to investigate
//
/*template <typename Sdf_T>
Span<const Sdf_T> apply_zero_sdf_fix(Span<const Sdf_T> p_sdf_data) {
ZN_PROFILE_SCOPE();
static thread_local std::vector<Sdf_T> s_sdf_backing_buffer;
std::vector<Sdf_T> &sdf_data = s_sdf_backing_buffer;
sdf_data.resize(p_sdf_data.size());
memcpy(sdf_data.data(), p_sdf_data.data(), p_sdf_data.size());
for (auto it = sdf_data.begin(); it != sdf_data.end(); ++it) {
if (*it == get_isolevel<Sdf_T>()) {
// Assuming Sdf_T is an integer. Might not be needed for floats.
*it += 1;
}
}
return to_span_const(sdf_data);
}*/
DefaultTextureIndicesData build_regular_mesh(const VoxelBufferInternal &voxels, unsigned int sdf_channel,
uint32_t lod_index, TexturingMode texturing_mode, Cache &cache, MeshArrays &output,
const IDeepSDFSampler *deep_sdf_sampler, std::vector<CellInfo> *cell_infos) {
ZN_PROFILE_SCOPE();
// From this point, we expect the buffer to contain allocated data in the relevant channels.
Span<uint8_t> sdf_data_raw;
ZN_ASSERT(voxels.get_channel_raw(sdf_channel, sdf_data_raw) == true);
const unsigned int voxels_count = Vector3iUtil::get_volume(voxels.get_size());
DefaultTextureIndicesData default_texture_indices_data;
default_texture_indices_data.use = false;
TextureIndicesData indices_data;
#ifdef USE_TRICHANNEL
WeightSampler3U8 weights_data;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
// From this point we know SDF is not uniform so it has an allocated buffer,
// but it might have uniform indices or weights so we need to ensure there is a backing buffer.
indices_data =
get_texture_indices_data(voxels, VoxelBufferInternal::CHANNEL_INDICES, default_texture_indices_data);
weights_data.u8_data0 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_0, VoxelBufferInternal::CHANNEL_WEIGHTS);
weights_data.u8_data1 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_1, VoxelBufferInternal::CHANNEL_DATA5);
weights_data.u8_data2 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_2, VoxelBufferInternal::CHANNEL_DATA6);
ERR_FAIL_COND_V(weights_data.u8_data0.size() != voxels_count, default_texture_indices_data);
ERR_FAIL_COND_V(weights_data.u8_data1.size() != voxels_count, default_texture_indices_data);
ERR_FAIL_COND_V(weights_data.u8_data2.size() != voxels_count, default_texture_indices_data);
}
#else
WeightSamplerPackedU16 weights_data;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
// From this point we know SDF is not uniform so it has an allocated buffer,
// but it might have uniform indices or weights so we need to ensure there is a backing buffer.
indices_data =
get_texture_indices_data(voxels, VoxelBufferInternal::CHANNEL_INDICES, default_texture_indices_data);
weights_data.u16_data = get_or_decompress_channel(
voxels, get_tls_weights_backing_buffer_u16(), VoxelBufferInternal::CHANNEL_WEIGHTS);
ZN_ASSERT_RETURN_V(weights_data.u16_data.size() == voxels_count, default_texture_indices_data);
}
#endif
// We settle data types up-front so we can get rid of abstraction layers and conditionals,
// which would otherwise harm performance in tight iterations
switch (voxels.get_channel_depth(sdf_channel)) {
case VoxelBufferInternal::DEPTH_8_BIT: {
Span<const int8_t> sdf_data = sdf_data_raw.reinterpret_cast_to<const int8_t>();
build_regular_mesh<int8_t>(sdf_data, indices_data, weights_data, voxels.get_size(), lod_index,
texturing_mode, cache, output, deep_sdf_sampler, cell_infos);
} break;
case VoxelBufferInternal::DEPTH_16_BIT: {
Span<const int16_t> sdf_data = sdf_data_raw.reinterpret_cast_to<const int16_t>();
build_regular_mesh<int16_t>(sdf_data, indices_data, weights_data, voxels.get_size(), lod_index,
texturing_mode, cache, output, deep_sdf_sampler, cell_infos);
} break;
// TODO Remove support for 32-bit SDF in Transvoxel?
// I don't think it's worth it. And it could reduce executable size significantly
// (the optimized obj size for just transvoxel.cpp is 1.2 Mb on Windows)
case VoxelBufferInternal::DEPTH_32_BIT: {
Span<const float> sdf_data = sdf_data_raw.reinterpret_cast_to<const float>();
build_regular_mesh<float>(sdf_data, indices_data, weights_data, voxels.get_size(), lod_index,
texturing_mode, cache, output, deep_sdf_sampler, cell_infos);
} break;
case VoxelBufferInternal::DEPTH_64_BIT:
ZN_PRINT_ERROR("Double-precision SDF channel is not supported");
// Not worth growing executable size for relatively pointless double-precision sdf
break;
default:
ZN_PRINT_ERROR("Invalid channel");
break;
}
return default_texture_indices_data;
}
void build_transition_mesh(const VoxelBufferInternal &voxels, unsigned int sdf_channel, int direction,
uint32_t lod_index, TexturingMode texturing_mode, Cache &cache, MeshArrays &output,
DefaultTextureIndicesData default_texture_indices_data) {
ZN_PROFILE_SCOPE();
// From this point, we expect the buffer to contain allocated data in the relevant channels.
Span<uint8_t> sdf_data_raw;
ZN_ASSERT(voxels.get_channel_raw(sdf_channel, sdf_data_raw) == true);
const unsigned int voxels_count = Vector3iUtil::get_volume(voxels.get_size());
// TODO Support more texturing data configurations
TextureIndicesData indices_data;
#ifdef USE_TRICHANNEL
WeightSampler3U8 weights_data;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
if (default_texture_indices_data.use) {
indices_data.default_indices = default_texture_indices_data.indices;
indices_data.packed_default_indices = default_texture_indices_data.packed_indices;
} else {
// From this point we know SDF is not uniform so it has an allocated buffer,
// but it might have uniform indices or weights so we need to ensure there is a backing buffer.
// TODO Is it worth doing conditionnals instead during meshing?
indices_data = get_texture_indices_data(
voxels, VoxelBufferInternal::CHANNEL_INDICES, default_texture_indices_data);
}
weights_data.u8_data0 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_0, VoxelBufferInternal::CHANNEL_WEIGHTS);
weights_data.u8_data1 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_1, VoxelBufferInternal::CHANNEL_DATA5);
weights_data.u8_data2 =
get_or_decompress_channel(voxels, s_weights_backing_buffer_u8_2, VoxelBufferInternal::CHANNEL_DATA6);
ERR_FAIL_COND(weights_data.u8_data0.size() != voxels_count);
ERR_FAIL_COND(weights_data.u8_data1.size() != voxels_count);
ERR_FAIL_COND(weights_data.u8_data2.size() != voxels_count);
}
#else
WeightSamplerPackedU16 weights_data;
if (texturing_mode == TEXTURES_BLEND_4_OVER_16) {
if (default_texture_indices_data.use) {
indices_data.default_indices = default_texture_indices_data.indices;
indices_data.packed_default_indices = default_texture_indices_data.packed_indices;
} else {
// From this point we know SDF is not uniform so it has an allocated buffer,
// but it might have uniform indices or weights so we need to ensure there is a backing buffer.
// TODO Is it worth doing conditionnals instead during meshing?
indices_data = get_texture_indices_data(
voxels, VoxelBufferInternal::CHANNEL_INDICES, default_texture_indices_data);
}
weights_data.u16_data = get_or_decompress_channel(
voxels, get_tls_weights_backing_buffer_u16(), VoxelBufferInternal::CHANNEL_WEIGHTS);
ZN_ASSERT_RETURN(weights_data.u16_data.size() == voxels_count);
}
#endif
switch (voxels.get_channel_depth(sdf_channel)) {
case VoxelBufferInternal::DEPTH_8_BIT: {
Span<const int8_t> sdf_data = sdf_data_raw.reinterpret_cast_to<const int8_t>();
build_transition_mesh<int8_t>(sdf_data, indices_data, weights_data, voxels.get_size(), direction, lod_index,
texturing_mode, cache, output);
} break;
case VoxelBufferInternal::DEPTH_16_BIT: {
Span<const int16_t> sdf_data = sdf_data_raw.reinterpret_cast_to<const int16_t>();
build_transition_mesh<int16_t>(sdf_data, indices_data, weights_data, voxels.get_size(), direction,
lod_index, texturing_mode, cache, output);
} break;
case VoxelBufferInternal::DEPTH_32_BIT: {
Span<const float> sdf_data = sdf_data_raw.reinterpret_cast_to<const float>();
build_transition_mesh<float>(sdf_data, indices_data, weights_data, voxels.get_size(), direction, lod_index,
texturing_mode, cache, output);
} break;
case VoxelBufferInternal::DEPTH_64_BIT:
ZN_PRINT_ERROR("Double-precision SDF channel is not supported");
// Not worth growing executable size for relatively pointless double-precision sdf
break;
default:
ZN_PRINT_ERROR("Invalid channel");
break;
}
}
} // namespace zylann::voxel::transvoxel
| true |
79cca773eb80492f3b03c1ec975fc92b0058e28d | C++ | jmoak3/HashTable | /HashTable/HashTable.cpp | UTF-8 | 1,137 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include "Table.h"
int main()
{
Table hashTable;
std::cout << "storing 5 into 'hash'" << std::endl;
hashTable.insert("hash", 5);
hashTable.displayContents();
std::cout << std::endl << "storing 4 3 2 9 0 -1 -5 into 'hello' 'my' 'name' 'uh' 'borat' 'I like you' 'I like sex'" << std::endl;
hashTable.insert("hello", 4);
hashTable.insert("my", 3);
hashTable.insert("name", 2);
hashTable.insert("uh", 9);
hashTable.insert("borat", 0);
hashTable.insert("I like you", -1);
hashTable.insert("I like sex", -5);
hashTable.displayContents();
std::cout << std::endl << "removing 'hello'" << std::endl;
hashTable.remove("hello");
hashTable.displayContents();
std::cout << std::endl << "is 'hello' in table? " << hashTable.contains("hello") << std::endl;
std::cout << std::endl << "is 'hash' in table? " << hashTable.contains("hash") << std::endl;
std::cout << std::endl << "getting the value in 'hash' " << hashTable.getValue("hash") << std::endl << std::endl;
std::cout << std::endl << "getting the value in 'uh' " << hashTable.getValue("uh") << std::endl << std::endl;
std::cin.get();
return 0;
} | true |
bd42ca659c8533c081477161737f5931fe635a2a | C++ | AntonPiccardoSelg/SortMPI | /inc/sort.h | UTF-8 | 614 | 2.953125 | 3 | [] | no_license | #ifndef SORT_SORT_MPI_H
#define SORT_SORT_MPI_H
#include <boost/mpi.hpp>
#include <type_traits>
#include <vector>
namespace SortMPI {
template <typename SORT> class Sort {
public:
Sort(const boost::mpi::communicator &world) : world(world) {}
template <typename T> void sort(std::vector<T> &toSort) {
static_assert(std::is_arithmetic<T>::value,
"Requires either integral or floating point vector");
if (toSort.size() == 0) {
return;
}
static_cast<SORT *>(this)->doSort(toSort);
}
protected:
const boost::mpi::communicator &world;
};
}
#endif // SORT_SORT_MPI_H
| true |
33bbe4b4ba197c144899e4de4d4d9764152683e1 | C++ | Ahmad45123/codeforces-submissions | /codeforces/1362/A.cpp | UTF-8 | 641 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool IsPowerOfTwo(ll x)
{
return (x != 0) && ((x & (x - 1)) == 0);
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t; cin >> t;
while(t--) {
ll a, b; cin >> a >> b;
if(b < a) swap(a, b);
if(b % a == 0 && IsPowerOfTwo(b/a)) {
ll twos = log2(b/a);
ll eights = twos/3;
twos %= 3;
ll fours = twos/2;
twos %= 2;
cout << eights+fours+twos << "\n";
} else {
cout << -1 << "\n";
}
}
return 0;
} | true |
04f166d1304a473b7abb991f3ddae8d8b8f7485f | C++ | FelipeFL96/SE202_Projet_Dragon_Tiger | /lab3/dragon-tiger/src/ast/escaper.cc | UTF-8 | 1,798 | 2.75 | 3 | [] | no_license | #include "escaper.hh"
namespace ast {
namespace escaper {
Escaper::Escaper() {}
void Escaper::escape_decls(FunDecl *main) {
main->accept(*this);
}
void Escaper::visit(IntegerLiteral &literal) {
}
void Escaper::visit(StringLiteral &literal) {
}
void Escaper::visit(BinaryOperator &op) {
op.get_left().accept(*this);
op.get_right().accept(*this);
}
void Escaper::visit(Sequence &seq) {
for (auto expr : seq.get_exprs()) {
expr->accept(*this);
}
}
void Escaper::visit(Let &let) {
for (auto decl : let.get_decls()) {
decl->accept(*this);
}
let.get_sequence().accept(*this);
}
void Escaper::visit(Identifier &id) {
}
void Escaper::visit(IfThenElse &ite) {
ite.get_condition().accept(*this);
ite.get_then_part().accept(*this);
ite.get_else_part().accept(*this);
}
void Escaper::visit(VarDecl &decl) {
if (decl.get_escapes()) {
current_function->get_escaping_decls().push_back(&decl);
}
if (decl.get_expr()) {
decl.get_expr()->accept(*this);
}
}
void Escaper::visit(FunDecl &decl) {
current_function = &decl;
for (auto param : decl.get_params()) {
param->accept(*this);
}
decl.get_expr()->accept(*this);
}
void Escaper::visit(FunCall &call) {
for (auto arg : call.get_args()) {
arg->accept(*this);
}
}
void Escaper::visit(WhileLoop &loop) {
loop.get_condition().accept(*this);
loop.get_body().accept(*this);
}
void Escaper::visit(ForLoop &loop) {
loop.get_variable().accept(*this);
loop.get_high().accept(*this);
loop.get_body().accept(*this);
}
void Escaper::visit(Break &b) {
}
void Escaper::visit(Assign &assign) {
assign.get_lhs().accept(*this);
assign.get_rhs().accept(*this);
}
} // namespace escaper
} // namespace ast | true |
55bb56d03847f568652e73e2e3a4da10e4a6bf02 | C++ | w0dm4n/Thanadolos | /Thanadolos World/Config.cpp | UTF-8 | 1,452 | 3.109375 | 3 | [] | no_license | #include "Globals.h"
#include "Config.hpp"
std::string Config::getCorrectValue(std::string value)
{
std::string newValue;
char *str = (char*)value.c_str();
int len = strlen(str) - 1;
int i = 1;
while (i < (len - 1))
newValue += str[i++];
return newValue;
}
Config::Config(std::string file_name)
{
std::ifstream t(file_name);
std::stringstream buffer;
if (t)
{
buffer << t.rdbuf();
std::istringstream is_file(buffer.str());
std::string line;
while (std::getline(is_file, line))
{
std::istringstream is_line(line);
std::string key;
if (std::getline(is_line, key, '('))
{
std::string value;
if (std::getline(is_line, value))
{
value = this->getCorrectValue(value);
if (!key.empty() && !value.empty())
{
std::pair<std::string, std::string> data;
data.first = key;
data.second = value;
this->datas.push_back(data);
}
}
}
}
Logger::Infos("Configuration file successfully loaded !", 11);
}
else
throw WrongConfigFile();
}
std::string Config::getData(std::string key)
{
std::lock_guard<std::mutex> locker(this->m);
std::list<std::pair<std::string, std::string>>::iterator iter = this->datas.begin();
std::list<std::pair<std::string, std::string>>::iterator end = this->datas.end();
while (iter != this->datas.end())
{
std::pair<std::string, std::string> data = *iter;
if (data.first == key)
return data.second;
++iter;
}
return "";
} | true |
d99e47c94affdd56897fc2ef2db1cf93049d8aeb | C++ | phoboz/dragonscurse | /src/dragonscurse/room.cpp | UTF-8 | 837 | 2.765625 | 3 | [] | no_license | #include "room.h"
Room::Room(const char *image, const char *font, MediaDB *media, const char *src,
int sx, int sy, int tx, int ty)
: m_media(media),
m_src(src),
m_sx(sx), m_sy(sy),
m_tx(tx), m_ty(ty)
{
m_spr = m_media->get_sprite(image);
if (m_spr) {
m_loaded = true;
m_media->play_music("room.ogg");
m_text = new Text(font, media);
}
else {
m_loaded = false;
}
}
Room::~Room()
{
if (m_loaded) {
m_loaded = false;
m_media->leave_sprite(m_spr);
delete m_text;
}
}
void Room::draw(Surface *dest, int x, int y,
int clip_x, int clip_y, int clip_w, int clip_h)
{
m_spr->draw(dest, x, y, 0, clip_x, clip_y, clip_w, clip_h);
m_text->draw(dest, x + m_tx, y + m_ty, clip_x, clip_y, clip_w, clip_h);
}
| true |
646fbf7bf59230e2b65b7bd6cd2435215f6fc6c3 | C++ | MSUNDGR1/CUDA-accelerated-Voxelization | /VoxelizationTesting/VoxelizationTesting.cpp | UTF-8 | 4,473 | 2.953125 | 3 | [] | no_license | // VoxelizationTesting.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <vector>
#include <fstream>
#include <stdlib.h>
#include "tri3D.h"
#include "vector3D.h"
#include "voxelMap.h"
#include "gif.h"
using namespace std;
//reads in STL file and converts it into component triangles.
void stl_in(string fname, vector<tri3D>& out) {
//!!
//don't forget ios::binary
//!!
ifstream myFile(fname.c_str(), ios::in | ios::binary);
char header_info[80] = "";
char nTri[4];
unsigned long nTriLong;
//read 80 byte header
if (myFile) {
myFile.read(header_info, 80);
cout << "header: " << header_info << endl;
}
else {
cout << "error" << endl;
}
//read 4-byte ulong
if (myFile) {
myFile.read(nTri, 4);
nTriLong = *((unsigned long*)nTri);
cout << "n Tri: " << nTriLong << endl;
}
else {
cout << "error" << endl;
}
for (unsigned int i = 0; i < nTriLong; i++) {
char facet[50];
if (myFile) {
myFile.read(facet, 50);
vector3D normal(facet, true);
vector3D point1(facet + 12);
vector3D point2(facet + 24);
vector3D point3(facet + 36);
out.push_back(tri3D(point1, point2, point3, normal));
}
}
return;
}
//level printer for output voxelmap
void print(bool*** fills, int width, int height, int printLev) {
system("CLS");
bool** currLev = fills[printLev];
string printLine;
for (int h = 0; h < height; h++) {
printLine = "";
for (int w = 0; w < width; w++) {
if (currLev[h][w] == true) printLine += "*";
else printLine += "_";
}
cout << printLine << endl;
}
}
//converts voxelmap to gif file, 1 filled voxel becomes 1 white pixel in that gif frame
void gifWrite(bool*** fills, int width, int height, int depth) {
GifWriter out;
int delay = 10;
GifBegin(&out, "nozzOut.gif", width, height, delay);
for (int d = 0; d < depth; d++) {
vector<uint8_t> currFrame;
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
if (fills[d][h][w]) {
currFrame.push_back(255);
currFrame.push_back(255);
currFrame.push_back(255);
currFrame.push_back(255);
}
else {
currFrame.push_back(0);
currFrame.push_back(0);
currFrame.push_back(0);
currFrame.push_back(0);
}
}
}
GifWriteFrame(&out, currFrame.data(), width, height, delay);
currFrame.clear();
}
GifEnd(&out);
}
void gifWriteOffaxis(bool*** fills, int width, int height, int depth) {
GifWriter out;
int delay = 10;
GifBegin(&out, "nozzOutOA.gif", depth, height, delay);
for (int w = 0; w < width; w++) {
vector<uint8_t> currFrame;
for (int h = 0; h < height; h++) {
for (int d = 0; d < depth; d++) {
if (fills[d][h][w]) {
currFrame.push_back(255);
currFrame.push_back(255);
currFrame.push_back(255);
currFrame.push_back(255);
}
else {
currFrame.push_back(0);
currFrame.push_back(0);
currFrame.push_back(0);
currFrame.push_back(0);
}
}
}
GifWriteFrame(&out, currFrame.data(), depth, height, delay);
currFrame.clear();
}
GifEnd(&out);
}
int main()
{
vector<tri3D> tris;
//stl_in("encoderMount.stl", tris);
stl_in("rocketNozzle.stl", tris);
voxelMap cubeMap(tris);
int levPrint = 0;
int gifOut = 0;
while (levPrint != 1000) {
cout << "enter level to print:";
cin >> levPrint;
if (levPrint <0){
gifOut = levPrint;
break;
}
print(cubeMap.fills, cubeMap.width, cubeMap.height, levPrint);
}
if (gifOut ==-1) {
gifWrite(cubeMap.fills, cubeMap.width, cubeMap.height, cubeMap.depth);
}
else if (gifOut == -2) {
gifWriteOffaxis(cubeMap.fills, cubeMap.width, cubeMap.height, cubeMap.depth);
}
}
| true |
6d50921d1f027f81a8f842122ff65c0e3db26ab0 | C++ | TigranTunyan/Test | /ClassWork1/Three Numbers.cpp | UTF-8 | 169 | 2.984375 | 3 | [] | no_license | #include <iostream>
int main()
{
int a,b,c;
std::cin>>a>>b>>c;
if((a <= b && b <= c) || (a >= b && b >= c))
std::cout<<"Sorted";
else
std::cout<<"UnSorted";
} | true |
84248c71dcdedb5c2785844ee4e34f77e6fa28a9 | C++ | JarateKing/Competitive-Programming-Textbook | /code/graph/floodfill_count.cpp | UTF-8 | 480 | 3.515625 | 4 | [] | no_license | int countRegions(vector<string>& grid, int w, int h) {
int count = 0;
// iterate over every point
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// if the point is a '.' we increment count and floodfill
// so that anything else in the region is no longer a '.'
if (grid[i][j] == '.') {
count++;
floodfill(grid, w, h, j, i);
}
}
}
return count;
}
| true |
5b7ca0c62e4f109c90d3833474f9c563d5e5fa1c | C++ | ofgabriel/graph-theory | /include/UnweightedGraph.h | UTF-8 | 820 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Graph.h"
#include <vector>
class UnweightedGraph: public Graph
{
public:
UnweightedGraph();
bool loadGraphFromFilePath(string filePath) override;
list<list<int> > getConnectedComponents();
int getDistance(int nodeId1, int nodeId2);
float getGraphDiameter() override;
void breadthFirstSearch(
int initialVertexIndex,
vector<int>& parent,
vector<int>& level
);
void depthFirstSearch(
int initialVertexIndex,
vector<int>& parent,
vector<int>& level
);
protected:
virtual void addEdge(int vertex1, int vertex2);
void DFSUtil(int startNodeIndex, vector<int>& parent);
int BFSUtil(int startNodeIndex, vector<int>& level, int goalIndex);
virtual vector<int> getNeighbors(int vertexIndex) = 0;
};
| true |
40c88a858def5ebbaf74a2a9b879515cee7314e2 | C++ | wendazhou/reducers | /reducers/include/wenda/reducers/transformers/filter.h | UTF-8 | 6,201 | 3.03125 | 3 | [
"MIT"
] | permissive | #ifndef WENDA_REDUCERS_TRANSFORMERS_FILTER_H_INCLUDED
#define WENDA_REDUCERS_TRANSFORMERS_FILTER_H_INCLUDED
/**
* @file filter.h
* This file implements the filter() reducible transformer.
*/
#include "../reducers_common.h"
#include <utility>
#include <type_traits>
#include "../reduce.h"
#include "../fold.h"
WENDA_REDUCERS_NAMESPACE_BEGIN
namespace detail
{
template<typename Predicate, typename Reducer>
struct filter_reducible_function
{
Predicate predicate;
Reducer reducer;
filter_reducible_function(Predicate predicate, Reducer reducer)
: predicate(std::move(predicate)), reducer(std::move(reducer))
{
}
template<typename Seed, typename Value>
typename std::decay<Seed>::type operator ()(Seed&& seed, Value&& value) const
{
if (predicate(value))
{
return reducer(std::forward<Value>(seed), std::forward<Seed>(value));
}
else
{
return std::forward<Seed>(seed);
}
}
};
}
/**
* This class implements a reducible that, when reduced
* reduces the original reducible with its elements filtered
* by a predicate.
*/
template<typename Reducible, typename Predicate>
struct filter_reducible
{
Reducible reducible;
Predicate predicate;
filter_reducible(Reducible reducible, Predicate predicate)
: reducible(std::move(reducible)), predicate(std::move(predicate))
{
}
};
/**
* Overloads the reduce() function to reduce reducibles of type @ref filter_reducible.
*/
template<typename Reducible, typename Predicate, typename Reducer, typename Seed>
typename std::decay<Seed>::type reduce(filter_reducible<Reducible, Predicate> const& reducible, Reducer&& reducer, Seed&& seed)
{
typedef detail::filter_reducible_function<Predicate, typename std::decay<Reducer>::type> filter_reducer_t;
return reduce(
reducible.reducible,
filter_reducer_t(reducible.predicate, std::forward<Reducer>(reducer)),
std::forward<Seed>(seed));
}
/**
* Overloads the reduce() function to reduce r-value references to reducibles of type @ref filter_reducible.
*/
template<typename Reducible, typename Predicate, typename Reducer, typename Seed>
typename std::decay<Seed>::type reduce(filter_reducible<Reducible, Predicate>&& reducible, Reducer&& reducer, Seed&& seed)
{
typedef detail::filter_reducible_function<Predicate, typename std::decay<Reducer>::type> filter_reducer_t;
return reduce(
std::move(reducible.reducible),
filter_reducer_t(std::move(reducible.predicate), std::forward<Reducer>(reducer)),
std::forward<Seed>(seed));
}
/**
* Overloads the fold() function to fold @ref filter_reducible
*/
template<typename Foldable, typename Predicate, typename Reduce, typename Combine>
typename detail::fold_return_type<filter_reducible<Foldable, Predicate>, Reduce, Combine>::type
fold(filter_reducible<Foldable, Predicate> const& foldable, Reduce&& reduce, Combine&& combine)
{
typedef detail::filter_reducible_function<Predicate, typename std::decay<Reduce>::type> filter_fold_t;
return fold(
foldable.reducible,
filter_fold_t(foldable.predicate, std::forward<Reduce>(reduce)),
std::forward<Combine>(combine));
}
/**
* Overloads the fold() function to fold r-value references to @ref filter_reducible
*/
template<typename Foldable, typename Predicate, typename Reduce, typename Combine>
typename detail::fold_return_type<filter_reducible<Foldable, Predicate>, Reduce, Combine>::type
fold(filter_reducible<Foldable, Predicate>&& foldable, Reduce&& reduce, Combine&& combine)
{
typedef detail::filter_reducible_function<Predicate, typename std::decay<Reduce>::type> filter_fold_t;
return fold(
std::move(foldable.reducible),
filter_fold_t(std::move(foldable.predicate), std::forward<Reduce>(reduce)),
std::forward<Combine>(combine));
}
namespace detail
{
template<typename Predicate>
struct filter_reducible_expression
{
Predicate predicate;
filter_reducible_expression(Predicate predicate)
: predicate(std::move(predicate))
{
}
};
}
/**
* Creates a new reducible that when reduced, reduces the original reducible
* and only keeps elements corresponding to the given predicate.
* @param reducible The original reducible to filter.
* @param predicate The filtering predicate. It must be a function of signature (Value) -> (convertible-to-bool).
* @returns A new reducible that implements the filtering reduce behaviour.
*/
template<typename Reducible, typename Predicate>
filter_reducible<typename std::decay<Reducible>::type, typename std::decay<Predicate>::type>
filter(Reducible&& reducible, Predicate&& predicate)
{
typedef filter_reducible<typename std::decay<Reducible>::type, typename std::decay<Predicate>::type> return_type;
return return_type(std::forward<Reducible>(reducible), std::forward<Predicate>(predicate));
}
/**
* Filters the given reducible.
* This function is similar to the two-argument version, but should have
* the reducible passed in by pipeing.
* @param predicate The filtering predicate. It must be a function of signature (Value) -> (convertible-to-bool)
* @returns A implementation helper object that enables pipeing.
*/
template<typename Predicate>
detail::filter_reducible_expression<typename std::decay<Predicate>::type>
filter(Predicate&& predicate)
{
typedef detail::filter_reducible_expression<typename std::decay<Predicate>::type> return_t;
return return_t(std::forward<Predicate>(predicate));
}
namespace detail
{
template<typename Reducible, typename Predicate>
filter_reducible<typename std::decay<Reducible>::type, Predicate>
operator|(Reducible&& reducible, filter_reducible_expression<Predicate> const& expr)
{
typedef filter_reducible<typename std::decay<Reducible>::type, Predicate> return_t;
return return_t(std::forward<Reducible>(reducible), expr.predicate);
}
template<typename Reducible, typename Predicate>
filter_reducible<typename std::decay<Reducible>::type, Predicate>
operator|(Reducible&& reducible, filter_reducible_expression<Predicate>&& expr)
{
typedef filter_reducible<typename std::decay<Reducible>::type, Predicate> return_t;
return return_t(std::forward<Reducible>(reducible), std::move(expr.predicate));
}
}
WENDA_REDUCERS_NAMESPACE_END
#endif // WENDA_REDUCERS_TRANSFORMERS_FILTER_H_INCLUDED | true |
f996128cd1eca124b1834f39c6b82bc3f5de3c36 | C++ | SccsAtmtn/leetcode | /75.cpp | UTF-8 | 809 | 2.78125 | 3 | [] | no_license | class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
if (n==0) return;
int start = 0, end = n-1, pre = -1;
while (start<end) {
while (start<end && nums[start]==0) pre = start++;
while (start<end && nums[end]!=0) --end;
if (start==end) break;
swap(nums[start], nums[end]);
pre = start++;
--end;
}
start = pre+1;
while (start<n && nums[start]==0) ++start;
end = n-1;
while (start<end) {
while (start<end && nums[start]==1) ++start;
while (start<end && nums[end]==2) --end;
if (start==end) break;
swap(nums[start], nums[end]);
++start;
--end;
}
}
}; | true |
b8a658207e6d59c5f9803283e332512318385beb | C++ | jvanns/oodles | /common/Exceptions.hpp | UTF-8 | 1,615 | 2.53125 | 3 | [] | no_license | #ifndef OODLES_EXCEPTIONS_HPP
#define OODLES_EXCEPTIONS_HPP
// oodles
#include "Exception.hpp"
namespace oodles {
// General oodles exceptions
struct OpenError : public NonFatalException
{
OpenError(const std::string &from, int error, const char *format, ...);
};
struct ReadError : public NonFatalException
{
ReadError(const std::string &from, int error, const char *format, ...);
};
struct WriteError : public NonFatalException
{
WriteError(const std::string &from, int error, const char *format, ...);
};
struct TypeError : public NonFatalException
{
TypeError(const std::string &from, int error, const char *format, ...);
};
struct RangeError : public NonFatalException
{
RangeError(const std::string &from, int error, const char *format, ...);
};
// Net-specific exceptions
namespace net {
struct InvalidService : public FatalException
{
InvalidService(const std::string &from, int error, const char *format, ...);
};
struct DNSFailure : public NonFatalException
{
DNSFailure(const std::string &from, int error, const char *format, ...);
};
struct DialogError : public NonFatalException
{
DialogError(const std::string &from, int error, const char *format, ...);
};
// HTTP-specific exceptions
namespace http {
struct HeaderError : public NonFatalException
{
HeaderError(const std::string &from, int error, const char *format, ...);
};
} // http
} // net
// URL-specific exceptions
namespace url {
struct ParseError : public NonFatalException
{
ParseError(const std::string &from, int error, const char *format, ...);
};
} // url
} // oodles
#endif
| true |
4fca988c84f3b8eb869a0f977f3c24225a8d5447 | C++ | raffimolero/towers_of_hanoi | /main.cpp | UTF-8 | 3,758 | 3.265625 | 3 | [] | no_license | #include <stdio.h>
#include <thread>
using namespace std;
const int STACK_SIZE = 8;
const int SLEEP_DURATION = 20;
int max;
int stacks[3][STACK_SIZE];
void sleep() {
this_thread::sleep_for(chrono::milliseconds(SLEEP_DURATION));
}
void repeatChar(char* str, int &start, int length, char c) {
for (int i = start; i < start + length; i++) {
str[i] = c;
}
start += length;
}
char* toBlockStr(int val) {
char* out = new char[STACK_SIZE * 2 + 2];
out[STACK_SIZE * 2 + 1] = 0;
int next = 0;
if (val == 0) {
repeatChar(out, next, STACK_SIZE * 2 + 1, ' ');
out[STACK_SIZE] = '|';
}
else {
repeatChar(out, next, STACK_SIZE - val, ' ');
out[next++] = '(';
repeatChar(out, next, val - 1, '[');
out[next++] = '|';
repeatChar(out, next, val - 1, ']');
out[next++] = ')';
repeatChar(out, next, STACK_SIZE - val, ' ');
}
return out;
}
void show() {
system("clear");
for (int i = 0; i < 3; i++) {
printf("%s", toBlockStr(0));
}
printf("\n");
for (int y = STACK_SIZE - 1; y >= 0; y--) {
for (int x = 0; x < 3; x++) {
printf("%s", toBlockStr(stacks[x][y]));
}
printf("\n");
}
sleep();
}
int topIndex(int stk) {
for (int i = STACK_SIZE - 1; i >= 0; i--) {
if (stacks[stk][i] != 0) {
return i;
}
}
return -1;
}
int top(int stk) {
for (int i = STACK_SIZE - 1; i >= 0; i--) {
if (stacks[stk][i] != 0) {
return stacks[stk][i];
}
}
return 0;
}
int pop(int stk) {
for (int i = STACK_SIZE - 1; i >= 0; i--) {
if (stacks[stk][i] != 0) {
int ret = stacks[stk][i];
stacks[stk][i] = 0;
return ret;
}
}
throw underflow_error("Stack empty, cannot pop any more.\n");
}
void push(int stk, int val) {
for (int i = 0; i < STACK_SIZE; i++) {
if (stacks[stk][i] == 0) {
stacks[stk][i] = val;
return;
}
}
throw overflow_error("Stack full, cannot push any more.\n");
}
bool isEmpty(int peg) {
return top(peg) == 0;
}
bool isValid(int src, int dst) {
return isEmpty(dst) || top(src) < top(dst);
}
void moveBlock(int src, int dst) {
show();
if (isValid(src, dst)) {
push(dst, pop(src));
}
else {
throw invalid_argument("Can't put a bigger block over a smaller block");
}
}
bool underBlock(int level, int peg) {
return top(peg) < stacks[peg][level];
}
void moveStack(int y, int src, int dst, int tmp);
void moveStack(int y, int src, int dst, int tmp) {
if (underBlock(y, src)) {
int tmpTop = topIndex(tmp);
moveStack(y + 1, src, tmp, dst);
moveBlock(src, dst);
moveStack(tmpTop + 1, tmp, dst, src);
}
else {
moveBlock(src, dst);
}
}
void test_push() {
push(1, 3);
push(1, 1);
push(1, 2);
}
void test_pop() {
test_push();
show();
// cout << "Top=" << top(1) << '\n';
// cout << "Pop=" << pop(1) << '\n';
// cout << "Top=" << top(1) << '\n';
// cout << "Pop=" << pop(1) << '\n';
// cout << "Top=" << top(1) << '\n';
// cout << "Pop=" << pop(1) << '\n';
// cout << "Top=" << top(1) << '\n';
// cout << "Pop=" << pop(1) << '\n';
}
void test_move() {
test_push();
show();
moveBlock(1, 2);
sleep();
show();
moveBlock(1, 2);
sleep();
show();
moveBlock(1, 2);
sleep();
show();
moveBlock(1, 2);
sleep();
}
void initStack() {
for (int i = STACK_SIZE; i > 0; i--) {
push(0, i);
}
}
int main() {
initStack();
moveStack(0, 0, 2, 1);
show();
return 0;
} | true |
d7bd065e8ec8bd8e1ea4190046486a9391b80a1b | C++ | jrsnail/u2project_logic | /u2/engine/include/core/U2MemoryStdAlloc.h | UTF-8 | 3,172 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef __U2MemoryStdAlloc_H__
#define __U2MemoryStdAlloc_H__
#include "U2Prerequisites.h"
#include "U2AlignedAllocator.h"
#include "U2MemoryTracker.h"
#include "U2HeaderPrefix.h"
U2EG_NAMESPACE_BEGIN
#if U2_MEMORY_ALLOCATOR == U2_MEMORY_ALLOCATOR_STD
/** \addtogroup Core
* @{
*/
/** \addtogroup Memory
* @{
*/
/** A "standard" allocation policy for use with AllocatedObject and
STLAllocator. This is the class that actually does the allocation
and deallocation of physical memory, and is what you will want to
provide a custom version of if you wish to change how memory is allocated.
@par
This class just delegates to the global malloc/free.
*/
class _U2Export StdAllocPolicy
{
public:
static inline void* allocateBytes(size_t count,
#if U2_MEMORY_TRACKER
const char* file = 0, int line = 0, const char* func = 0
#else
const char* = 0, int = 0, const char* = 0
#endif
)
{
void* ptr = new unsigned char[count];
#if U2_MEMORY_TRACKER
// this alloc policy doesn't do pools
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#endif
return ptr;
}
static inline void deallocateBytes(void* ptr)
{
#if U2_MEMORY_TRACKER
MemoryTracker::get()._recordDealloc(ptr);
#endif
delete[]((unsigned char*)ptr);
}
/// Get the maximum size of a single allocation
static inline size_t getMaxAllocationSize()
{
return std::numeric_limits<size_t>::max();
}
private:
// no instantiation
StdAllocPolicy()
{ }
};
/** A "standard" allocation policy for use with AllocatedObject and
STLAllocator, which aligns memory at a given boundary (which should be
a power of 2). This is the class that actually does the allocation
and deallocation of physical memory, and is what you will want to
provide a custom version of if you wish to change how memory is allocated.
@par
This class just delegates to the global malloc/free, via AlignedMemory.
@note
template parameter Alignment equal to zero means use default
platform dependent alignment.
*/
template <size_t Alignment = 0>
class StdAlignedAllocPolicy
{
public:
// compile-time check alignment is available.
typedef int IsValidAlignment
[Alignment <= 128 && ((Alignment & (Alignment-1)) == 0) ? +1 : -1];
static inline void* allocateBytes(size_t count,
#if U2_MEMORY_TRACKER
const char* file = 0, int line = 0, const char* func = 0
#else
const char* = 0, int = 0, const char* = 0
#endif
)
{
void* ptr = Alignment ? AlignedMemory::allocate(count, Alignment)
: AlignedMemory::allocate(count);
#if U2_MEMORY_TRACKER
// this alloc policy doesn't do pools
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#endif
return ptr;
}
static inline void deallocateBytes(void* ptr)
{
#if U2_MEMORY_TRACKER
MemoryTracker::get()._recordDealloc(ptr);
#endif
AlignedMemory::deallocate(ptr);
}
/// Get the maximum size of a single allocation
static inline size_t getMaxAllocationSize()
{
return std::numeric_limits<size_t>::max();
}
private:
// No instantiation
StdAlignedAllocPolicy()
{ }
};
#endif
/** @} */
/** @} */
U2EG_NAMESPACE_END
#include "U2HeaderSuffix.h"
#endif // __MemoryStdAlloc_H__
| true |
18439be939b6375cd0646ce713ff815728d83872 | C++ | saturn1mc/puls4r | /C++/src/Triangle.cpp | UTF-8 | 1,284 | 2.578125 | 3 | [] | no_license | /*
* Triangle.cpp
* puls4r
*
* Created by Camille on 27/01/08.
* Copyright 2008 __MyCompanyName__. All rights reserved.
*
*/
#include "Triangle.h"
Intersection* Triangle::intersection(Ray* ray){
Intersection* intersection = plan->intersection(ray);
if(intersection == 0){
return 0;
}
else{
Point b(*points[1] - points[0]);
Point c(*points[2] - points[0]);
Point p(*intersection->getPoint() - points[0]);
double u = ((p.getY() * c.getX()) - (p.getX() * c.getY())) / ((b.getY() * c.getX()) - (b.getX() * c.getY()));
double v = ((p.getY() * b.getX()) - (p.getX() * b.getY())) / ((c.getY() * b.getX()) - (c.getX() * b.getY()));
if((u>=0) && (v >= 0) && ((u+v) <= 1)){
intersection->setObject(this);
if(perlin != 0){
perlin->disruptNormal(intersection->getNormal(), epsilon);
}
return intersection;
}
else{
delete(intersection);
return 0;
}
}
}
std::string Triangle::toString(void) const{
std::stringstream ss;
ss << "---------------------------" << std::endl;
ss << "Triangle :" << std::endl;
ss << "---------------------------" << std::endl;
ss << "Points : " << points[0] << ","<< points[1] << "," << points[2] << std::endl;
ss << "---------------------------" << std::endl;
return ss.str();
}
| true |
6239b6c6f740f0d3dad826f2f41570bec2f5657c | C++ | aradhanapradhan/lab-3 | /lab3 question 10.cpp | UTF-8 | 226 | 3.3125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char c;
cout<<"enter a character";
cin>>c;
if(c>='a'&&c<='z')
{
cout<<"the character is small"<<c;
}
else
{
cout<<"the character is capital"<<c;
}
return 0;
}
| true |
efb0e491730fb245b3dd12ea348c1bb05b173963 | C++ | jungchunkim/study_algorithm | /Bruteforce/bruteforce_14888.cpp | UHC | 1,241 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#define MAX 1000000000
#define MIN -1000000000
using namespace std;
int main()
{
int N;
cin >> N;
vector<int> arr(N);
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
vector <int> oper(4);
// ʴ + - * /
for (int i = 0; i < 4; i++)
{
cin >> oper[i];
}
vector <int> real;
for (int i = 0; i < N - 1; i++)
{
if (oper[0] != 0)
{
real.push_back(0);
oper[0]--;
}
else if (oper[1] != 0)
{
real.push_back(1);
oper[1]--;
}
else if (oper[2] != 0)
{
real.push_back(2);
oper[2]--;
}
else
{
real.push_back(3);
oper[3]--;
}
}
sort(real.begin(), real.end());
int sum;
//ʱⰪ ־ش.
int max = MIN;
int min = MAX;
do {
sum = arr[0];
for (int i = 0; i < N - 1; i++)
{
if (real[i] == 0)
{
sum = sum + arr[i + 1];
}
else if (real[i] == 1)
{
sum = sum - arr[i + 1];
}
else if (real[i] == 2)
{
sum = sum * arr[i + 1];
}
else
{
sum = sum / arr[i + 1];
}
}
if (sum > max)
{
max = sum;
}
if (sum < min)
{
min = sum;
}
} while (next_permutation(real.begin(), real.end()));
cout << max << endl << min;
} | true |
288ea9fd1738a654a2c70db21731806e17ff7c3f | C++ | zjc960118/algorithm | /leetcode/90.subsets-ii.cpp | UTF-8 | 800 | 2.828125 | 3 | [
"MIT"
] | permissive | class Solution {
private:
void dfs(vector<int>& nums, int start, vector<int>& ans, vector<vector<int>>& results)
{
results.push_back(ans);
for (auto i = start; i < nums.size(); ++i)
{
if (i != start && nums[i] == nums[i - 1])
{
continue;
}
ans.push_back(nums[i]);
dfs(nums, i + 1, ans, results);
ans.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
if (nums.size() == 0)
{
return vector<vector<int>>(1, vector<int>());
}
sort(nums.begin(), nums.end());
vector<vector<int>> results;
vector<int> ans;
dfs(nums, 0, ans, results);
return results;
}
};
| true |
2f855e26c576062bdcba5e3f0aedb47f9727d106 | C++ | Podginator/Cattle | /transpiler/ExpressionGenerators/BasicExpressionGenerator.h | UTF-8 | 4,035 | 2.75 | 3 | [] | no_license | #ifndef RATTLE_CPP_BASICEXPRESSIONCOMBINER_H
#define RATTLE_CPP_BASICEXPRESSIONCOMBINER_H
#include "DefaultStateExpressionGenerator.h"
namespace RattleLang {
// The expression combiner for simple statements like a = 2 + 4
class BasicExpressionGenerator : public DefaultStateExpressionGenerator {
public:
BasicExpressionGenerator(Context *m_context);
ExpressionGeneratorResult combine_statement(const SimpleNode *node, operands operand, bool is_multi_assign) override;
void defaultVisit(const SimpleNode *node, void *data) override {}
protected:
void visit_expression_pass(const ASTOr *node, void * data) override;
void visit_expression_pass(const ASTAnd *node, void * data) override;
void visit_expression_pass(const ASTCompEqual *node, void * data) override;
void visit_expression_pass(const ASTCompNequal *node, void * data) override;
void visit_expression_pass(const ASTCompGTE *node, void * data) override;
void visit_expression_pass(const ASTCompLTE *node, void * data) override;
void visit_expression_pass(const ASTCompGT *node, void * data) override;
void visit_expression_pass(const ASTCompLT *node, void * data) override;
void visit_expression_pass(const ASTAdd *node, void * data) override;
void visit_expression_pass(const ASTSubtract *node, void * data) override;
void visit_expression_pass(const ASTTimes *node, void * data) override;
void visit_expression_pass(const ASTDivide *node, void * data) override;
void visit_expression_pass(const ASTUnaryNot *node, void * data) override;
void visit_expression_pass(const ASTUnaryPlus *node, void * data) override;
void visit_expression_pass(const ASTUnaryMinus *node, void * data) override;
void visit_expression_pass(const ASTDereference* node, void* data) override;
void visit_expression_pass(const ASTExpression* node, void* data) override;
void visit_fn_pass(const ASTExpression* node, void* data) override;
// A function invoke should
void visit_expression_pass(const ASTFnInvoke *node, void * data) override;
void visit_fn_pass(const ASTFnInvoke *node, void * data) override;
void visit_fn_pass(const ASTArgList* node, void* data) override;
void visit_expression_pass(const ASTArgList *node, void * data) override;
void visit_expression_pass(const ASTCharacter *node, void * data) override;
void visit_expression_pass(const ASTString *node, void * data) override;
void visit_expression_pass(const ASTNumber *node, void * data) override;
void visit_expression_pass(const ASTTrue *node, void * data) override;
void visit_expression_pass(const ASTFalse *node, void * data) override;
void visit_expression_pass(const ASTIdentifier* node, void* data) override;
void visit_fn_pass(const ASTIndexedExpression* node, void* data) override;
void visit_expression_pass(const ASTIndexedExpression* node, void* data) override;
void visit_fn_pass(const ASTTupleDefine* node, void* data) override;
void visit_expression_pass(const ASTTupleDefine* node, void* data) override;
void visit_expression_pass(const ASTLambdaDefine* node, void* data) override;
private:
map<const Node*, string> m_fn_call_name;
TypeInfoPtr expected_output;
bool multi_assign = false;
void print_node(const SimpleNode* node);
void do_expression(const SimpleNode *n, const string &expression);
void do_each_expression(const SimpleNode *node);
TypeInfoPtr get_type_info(const SimpleNode *node);
bool needs_converting(TypeInfoPtr expression_info);
void convert_if_needed(SimpleNode *node);
bool is_lambda_parameter(TypeInfoPtr parameter_info, TypeInfoPtr function_info, size_t param_index);
};
}
#endif //RATTLE_CPP_BASICEXPRESSIONCOMBINER_H
| true |
b1bfd4516e5f3da3be1124960b142b52614be45c | C++ | juxbo/QTSmartHome-EmbeddedHMI | /practice/TODOList/roomlist.h | UTF-8 | 624 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef ROOMLIST_H
#define ROOMLIST_H
#include <QObject>
#include <QVector>
struct RoomItem{
bool on;
QString description;
QString color;
};
class RoomList : public QObject
{
Q_OBJECT
public:
explicit RoomList(QObject *parent = nullptr);
QVector<RoomItem> items() const;
bool setItemAt(int index, const RoomItem &item);
signals:
void preItemAppended();
void postItemAppended();
void preItemRemoved(int index);
void postItemRemoved();
public slots:
void appendItem();
//void removeCompletedItems();
private:
QVector<RoomItem> mRooms;
};
#endif // ROOMLIST_H
| true |
d208739c08084b1b61d1d2a8a4006e9e19299d36 | C++ | Frc2481/frc-2017 | /r2017/src/Commands/SetModulesForSpinInPlaceCommand.h | UTF-8 | 1,189 | 2.59375 | 3 | [] | no_license | #ifndef SetModulesForSpinInPlaceCommand_H
#define SetModulesForSpinInPlaceCommand_H
#include "../CommandBase.h"
class SetModulesForSpinInPlaceCommand : public CommandBase {
private:
SwerveModule* m_flWheel;
SwerveModule* m_frWheel;
SwerveModule* m_blWheel;
SwerveModule* m_brWheel;
public:
SetModulesForSpinInPlaceCommand() : CommandBase("SetModulesForSpinInPlaceCommand"){
//Requires(CommandBase::m_driveTrain.get());
m_flWheel = CommandBase::m_driveTrain->GetModule(DriveTrain::FRONT_LEFT_MODULE);
m_frWheel = CommandBase::m_driveTrain->GetModule(DriveTrain::FRONT_RIGHT_MODULE);
m_blWheel = CommandBase::m_driveTrain->GetModule(DriveTrain::BACK_LEFT_MODULE);
m_brWheel = CommandBase::m_driveTrain->GetModule(DriveTrain::BACK_RIGHT_MODULE);
}
void Initialize(){
m_flWheel->SetAngle(42.5, true);
m_frWheel->SetAngle(137.5, true);
m_blWheel->SetAngle(317.5, true);
m_brWheel->SetAngle(222.5, true);
}
void Execute(){}
bool IsFinished(){
return m_flWheel->IsOnTarget(42.5) && m_frWheel->IsOnTarget(137.5) && m_blWheel->IsOnTarget(317.5) && m_brWheel->IsOnTarget(222.5);
}
void End(){}
void Interrupted(){}
};
#endif // SetModulesForSpinInPlaceCommand_H
| true |
e044999821d8331c1d259cd4f60aeb22a9a9e305 | C++ | Dr0gis/ProjectParallelProgrammingAndroid | /OpenMPTasks/OpenMPTasks/MultiplyMatrix.cpp | UTF-8 | 968 | 3.015625 | 3 | [] | no_license | #include "stdafx.h"
#include "MultiplyMatrix.h"
#include <iostream>
void multiply_matrix_consistent(size_t size, int* matrix1, int* matrix2, int* result)
{
memset(result, 0, size * size * sizeof(int));
for (size_t i = 0; i < size; ++i)
{
for (size_t j = 0; j < size; ++j)
{
for (size_t l = 0; l < size; ++l)
{
result[i * size + j] += matrix1[i * size + l] * matrix2[l * size + j];
}
}
}
}
void multiply_matrix_parallel(size_t size, int *matrix1, int *matrix2, int *result)
{
memset(result, 0, size * size * sizeof(int));
#pragma omp parallel for
for (int i = 0; i < (int)size; ++i)
{
for (size_t j = 0; j < size; ++j)
{
for (size_t l = 0; l < size; ++l)
{
result[i * size + j] += matrix1[i * size + l] * matrix2[l * size + j];
}
}
}
}
void fill_matrix_random(size_t size, int *matrix1)
{
for (size_t i = 0; i < size; ++i)
{
for (size_t j = 0; j < size; ++j)
{
matrix1[i * size + j] = rand() % 10 + 1;
}
}
} | true |
ba6a0c4c3a98129c422bd8ba88e7d90eb2297833 | C++ | qwembe/moevmOOP2018 | /Vaigachev/2/battlefield.cpp | UTF-8 | 4,735 | 2.796875 | 3 | [] | no_license | #include "battlefield.h"
#include "list.cpp"
#include <fstream>
#include <iostream>
#include <string>
const struct ConsoleColor {
const string black = "\033[22;30m";
const string red = "\033[22;31m";
const string green = "\033[22;32m";
const string brown = "\033[22;33m";
const string blue = "\033[22;34m";
const string magenta = "\033[22;35m";
const string cyan = "\033[22;36m";// - cyan
const string gray = "\033[22;37m";// - gray
const string darkgrey = "\033[01;30m";// - dark gray
const string lightred = "\033[01;31m";// - light red
const string lightgreen = "\033[01;32m";// - light green
const string yellow = "\033[01;33m";// - yellow
const string lightblue = "\033[01;34m";// - light blue
const string lightmagneta = "\033[01;35m";// - light magenta
const string lightcyan = "\033[01;36m";// - light cyan
const string white = "\033[01;37m";// - white
} console;
#define DEFBACKGR console.black
#define DEFFOREGR console.white
using namespace std;
battlefield::battlefield()
{
cout << "Field fight: START" << endl;
ifstream fin("data.txt");
if (fin.eof()) {
cerr << "File not found!" << endl;
getchar();
exit(EXIT_FAILURE);
}
fin >> x_size >> y_size;
cout << " x_size = " << x_size << endl;
cout << " y_size = " << y_size << endl;
const shared_ptr<int> crown1(new int(1));
const shared_ptr<int> crown2(new int(2));
new_team(team1, fin,crown1);
new_team(team2, fin,crown2);
cout << "Field fight: END" << endl;
/*
for (auto Elem : *team1) {
cout << "-------" << endl;
cout << Elem->show_health() << endl;
Elem->get_damage(7);
cout << Elem->show_health() << endl;
}
*/
}
Object* battlefield::check_position(_2dim cor) {
for (auto Elem : *team1) {
if (Elem->is_on_position(cor)) return Elem->is_on_position(cor);
}
//return NULL;
for (auto Elem : *team2) {
if (Elem->is_on_position(cor)) return Elem->is_on_position(cor);
}
return NULL;
}
//todo: int t -> const shared_ptr t
void battlefield::new_team(List<Object*> *new_team,ifstream& fin,const shared_ptr<int> t) {
int size;
fin >> size;
for (int i = 0; i < size; i++) {
new_team->AddEnd(new Object(fin,t));
}
}
battlefield::~battlefield()
{
cout << "~Field fight: START" << endl;
delete team1;
cout << "Another ++++++" << endl;;
delete team2;
cout << "~Field fight: END" << endl;
}
void battlefield::print() {
//HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
//SetConsoleTextAttribute(hConsole, (WORD)((DEFBACKGR << 4) | DEFFOREGR));
cout << console.yellow;
cout << " + ";
for (int i = 1; i < x_size + 1; i++) {
printf("%2.d ", i);
}
cout << endl;
for (int i = 1; i < x_size + 1; i++) {
for (int j = 1; j < y_size + 1; j++) {
if (j == 1) {
cout << console.yellow;
printf("%3.d", i);
cout << DEFFOREGR;
}
Object* temp = check_position({ j,i });
if (temp) {
if (temp->show_team() == 1) {
//SetConsoleTextAttribute(hConsole, (WORD)((DEFBACKGR << 4) | Blue));
cout << console.blue;
if (check_position({ j,i })->show_health() > 0) cout << " O ";
else cout << " X ";
//SetConsoleTextAttribute(hConsole, (WORD)((DEFBACKGR << 4) | DEFFOREGR));
cout << DEFFOREGR;
}
if (check_position({ j,i })->show_team() == 2) {
//SetConsoleTextAttribute(hConsole, (WORD)((DEFBACKGR << 4) | Red));
cout << console.red;
if (check_position({ j,i })->show_health() > 0) cout << " O ";// << i << j;
else cout << "X";
//SetConsoleTextAttribute(hConsole, (WORD)((DEFBACKGR << 4) | DEFFOREGR));
cout << DEFFOREGR;
}
//cout << temp;
}
else
{
cout << " . ";
};
}
cout << endl;
}
//SetConsoleTextAttribute(hConsole, (WORD)((Black << 4) | White));
cout << console.white;
}
//todo: bad realization
int battlefield::hit(_2dim pos, int dmg) {
Object* temp = check_position(pos);
if ((temp->get_damage(dmg))) {
cout << endl << "count - " << temp->count << endl << "amount - " << temp->amount << endl << "use count " << temp->use_count() << endl;
if (temp->last_representive()) return temp->show_team();
del_from_position(pos);
};
return 0;
}
void battlefield::del_from_position(_2dim cor) {
int i = 0;
bool flag = false;
for (auto Elem : *team1) {
if (!Elem->is_on_position(cor)) i++; else {
flag = true;
break;
}
}
if (flag) {
team1->DelIndex(i);
return;
}
int j = 0;
bool mflag = false;
for (auto Elem : *team2) {
if (!Elem->is_on_position(cor)) {
j++;
}
else {
mflag = true;
break;
}
}
if (mflag) {
team2->DelIndex(j);
return;
}
}
| true |
8fbda6c613d16f37a35953ca22c63853cd6f6d52 | C++ | Jonsen-Brad/wincode | /马拦卒.cpp | UTF-8 | 672 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int chess[100][100] = {0};
int countpath(int m,int n){
int dp[100][100] = {0};
for(int i = 0;i<m;i++){
if(chess[i][0] == 1)
break;
dp[i][0] = 1;
}
for(int i = 0;i<n;i++){
if(chess[0][i] ==1)
break;
dp[0][i] = 1;
}
for(int i = 1;i <m;i++)
for(int j = 1;j < m;j++)
if(chess[i][j] == 0)
dp[i][j] = dp[i-1][j]+dp[i][j-1];
return dp[m-1][n-1];
}
int main(){
int m,n;
int x,y;
cin >> m >> n ;
cin >> x >> y;
chess[x-1][y-2] = chess[x-1][y+2] =chess[x-2][y+1] = chess[x-2][y-1] = 1;
chess[x+1][y-2] = chess[x+1][y+2] =chess[x+2][y+1] = chess[x+2][y-1] = 1;
cout <<countpath(m,n) <<endl;
}
| true |
9ada088f33fe7e561030561570a8972be9135a68 | C++ | ljktest/tmp-tests | /src/hysop++/src/utils/types.h | UTF-8 | 1,926 | 2.59375 | 3 | [] | no_license |
#ifndef HYSOP_TYPES_H
#define HYSOP_TYPES_H
#include <complex>
#include <array>
#include "utils/utils.h"
#include "utils/default.h"
namespace hysop {
/* forward declare external types */
namespace data {
template <typename T, std::size_t Dim, typename Allocator>
class multi_array;
template <typename T, std::size_t Dim>
class multi_array_ref;
template <typename T, std::size_t Dim>
class multi_array_view;
template <typename T, std::size_t Dim>
class const_multi_array_view;
template <typename T, std::size_t Dim>
class const_multi_array_ref;
} /* end of namespace data */
namespace types {
typedef double real;
typedef std::complex<real> complex;
} /* end of namespace types */
/* expose the folowwing types to namespace hysop */
/* swig does not support alias templates... */
template <std::size_t Dim>
struct Shape {
typedef std::array<std::size_t, Dim> type;
};
template <std::size_t Dim>
struct Offset {
typedef std::array<std::ptrdiff_t, Dim> type;
};
template <typename T, std::size_t Dim, typename Allocator = hysop::_default::allocator<T>>
using multi_array = hysop::data::multi_array<T,Dim,Allocator>;
template <typename T, std::size_t Dim>
using multi_array_view = hysop::data::multi_array_view<T,Dim>;
template <typename T, std::size_t Dim>
using const_multi_array_view = hysop::data::const_multi_array_view<T,Dim>;
template <typename T, std::size_t Dim>
using multi_array_ref = hysop::data::multi_array_ref<T,Dim>;
template <typename T, std::size_t Dim>
using const_multi_array_ref = hysop::data::const_multi_array_ref<T,Dim>;
} /* end of namespace hysop */
#endif /* end of include guard: HYSOP_TYPES_H */
| true |
f3da032b3a5309d8b1ddd61373620b4ce19fcea2 | C++ | PranaV-Shimpi/Second-Year-Programs-Computer-Engineering-SPPU | /Computer Graphics/CG/A10/assign10.cpp | UTF-8 | 1,115 | 3.046875 | 3 | [] | no_license | /*
* Assignment No: 10 SE B Roll No:41
Problem Statement: Write C++ program to draw any object such as flower waves using any curve generation
techniques.
*/
#include <iostream>
#include <graphics.h>
#include <math.h>
using namespace std;
void bezier(int x[4][4], int y[4][4])
{
int i,j;
double t;
for(i=0;i<4;i++)
{
for(t=0.0;t<1.0;t=t+0.005)
{
double xt=(pow(1-t,3)*x[i][0]) + (3*t*pow(1-t,2)*x[i][1]) + (3*pow(t,2)*(1-t)*x[i][2])+ (pow(t,3)*x[i][3]);
double yt=(pow(1-t,3)*y[i][0]) + (3*t*pow(1-t,2)*y[i][1]) + (3*pow(t,2)*(1-t)*y[i][2])+ (pow(t,3)*y[i][3]);
putpixel(xt,yt,CYAN);
delay(3);
}
}
}
int main()
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,NULL);
int x[4][4],y[4][4];
int i,j;
cout<<"\nEnter the x and y coordinates of four control points: ";
for(i=0;i<4;i++)
for(j=0;j<4;j++)
cin>>x[i][j]>>y[i][j];
bezier(x,y);
getch();
closegraph();
return 0;
}
/*
200 200 160 160 240 160 200 200
200 200 240 160 240 240 200 200
200 200 240 240 160 240 200 200
200 200 160 240 160 160 200 200
*/
//Program OK
| true |
f38509a77aab2d277232f947613d5da8b29e7855 | C++ | vikashkumarjha/missionpeace | /lc/lc/2021_target/companies/amazon/lc_759_employee_free_time.cpp | UTF-8 | 2,161 | 3.453125 | 3 | [] | no_license | /*
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
Example 1:
Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Explanation: There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.
Example 2:
Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]
*/
#include "header.hpp"
class Interval {
public:
int start;
int end;
Interval() {}
Interval(int _start, int _end) {
start = _start;
end = _end;
}
};
struct cmp {
bool operator() (Interval &a, Interval &b) {
if ( a.start == b.start) {
return a.end > b.end;
}
return a.start > b.start;
}
};
class Solution {
public:
vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {
vector<Interval> res;
priority_queue<Interval,vector<Interval> ,cmp> pq;
for ( auto e : schedule) {
for ( auto interval : e) {
pq.push(interval);
}
}
Interval prev = pq.top(); pq.pop();
while ( !pq.empty()) {
auto curr = pq.top();
if ( curr.start > prev.start) {
res.push_back(Interval(prev.end, curr.start));
prev = pq.top(); pq.pop();
}else {
prev = prev.end < curr.end ? curr : prev;
pq.pop();
}
}
return res;
}
}; | true |
03b6e7f53f972104d8c3174db82c9a09dca78724 | C++ | Kshitij1K/Orientation-19 | /CODE/wahmodijiwah.cpp | UTF-8 | 1,033 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void NumCombination(int& num_combinations,vector<int> denominations,int index,int sum){
if (sum == 0){
num_combinations++;
return;
}
if (sum < 0) return;
//if (sum > 0 && index==0) return;
for (int i=index;i>=0;i--){
NumCombination(num_combinations,denominations,i,sum-denominations.at(i));
}
}
int main(){
int num_denominations;
cin >> num_denominations;
vector<int> denominations;
for (int i=0;i<num_denominations;i++){
int temp;
cin >> temp;
denominations.push_back(temp);
}
int test_cases;
cin >> test_cases;
for (int i=0;i<test_cases;i++){
int sum;
cin >> sum;
int num_combinations=0;
NumCombination(num_combinations,denominations,num_denominations-1,sum);
cout << num_combinations << endl;
// for (int j=0;j<num_denominations;j++){
// cout << denominations.at(j) << " ";
// }
}
return 0;
} | true |
d0ca8214666414739085a2f58e6693fb4ca2c042 | C++ | microqq/TwinkleGraphics | /Source/Common/twRenderTexture.cpp | UTF-8 | 3,118 | 2.65625 | 3 | [
"MIT"
] | permissive |
#include "twRenderTexture.h"
#include "twConsoleLog.h"
namespace TwinkleGraphics
{
RenderTexture::RenderTexture(int32 width, int32 height
// , RTType type = RTType::COLOR
, GLenum internalformat, GLenum format
, bool usedepth, bool depthwithstencil
, bool multisample, int32 samples
, bool fixedsampledlocation)
: Object()
, _texture(nullptr)
, _depthbuf(nullptr)
, _framebuf(nullptr)
, _width(width)
, _height(height)
, _samples(samples)
, _internalformat(internalformat)
, _format(format)
, _usedepth(usedepth)
, _depthwithstencil(depthwithstencil)
, _multisample(multisample)
, _fixedsampledlocation(fixedsampledlocation)
{
}
RenderTexture::~RenderTexture()
{}
void RenderTexture::Create(FrameBufferObject::Ptr framebuf)
{
if(framebuf == nullptr)
{
_framebuf = std::make_shared<FrameBufferObject>();
}
else
{
_framebuf = framebuf;
}
_framebuf->Bind();
if(!_multisample)
{
_texture = std::make_shared<Texture2D>();
_texture->Create(_width, _height, _internalformat, _format);
}
else
{
_texture = std::make_shared<Texture2DMultiSample>(_samples);
_texture->Create(_width, _height, _internalformat, _format);
}
switch (_format)
{
case GL_DEPTH_COMPONENT:
_framebuf->AttachDepth(_texture);
break;
case GL_DEPTH_STENCIL:
_framebuf->AttachDepthStencil(_texture);
break;
case GL_STENCIL_INDEX:
break;
default:
int index = _framebuf->GetColorAttachmentsCount();
_framebuf->AttachColor(_texture, index);
break;
}
if(_usedepth)
{
if(_depthwithstencil)
{
_depthbuf = std::make_shared<RenderBufferObject>(_width, _height, GL_DEPTH24_STENCIL8, _samples, _multisample);
_framebuf->AttachDepthStencil(_depthbuf);
}
else
{
_depthbuf = std::make_shared<RenderBufferObject>(_width, _height, GL_DEPTH_COMPONENT, _samples, _multisample);
_framebuf->AttachDepth(_depthbuf);
}
}
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
Console::LogError("FrameBuffer: Framebuffer is not complete!\n");
}
_framebuf->UnBind();
}
void RenderTexture::BlitColor(RenderTexture::Ptr dest)
{
assert(_framebuf != nullptr);
_framebuf->BlitColorTo(_width, _height, dest->_framebuf, dest->_width, dest->_height, GL_NEAREST);
}
void RenderTexture::BlitDepth(RenderTexture::Ptr dest)
{
assert(_framebuf != nullptr);
_framebuf->BlitDepthTo(_width, _height, dest->_framebuf, dest->_width, dest->_height, GL_NEAREST);
}
void RenderTexture::BlitColorToBackBuffer(int backwidth, int backheight)
{
_framebuf->BlitColorToBack(_width, _height, backwidth, backheight, GL_NEAREST);
}
void RenderTexture::BlitDepthToBackBuffer(int backwidth, int backheight)
{
_framebuf->BlitDepthToBack(_width, _height, backwidth, backheight, GL_NEAREST);
}
} // namespace TwinkleGraphics
| true |
7fe870d68fb4c2e15b6cee63598a8980cb433a65 | C++ | lxdnz254/C_plus_plus_Experiments | /13.1/Pair1.h | UTF-8 | 408 | 3.015625 | 3 | [] | no_license | //
// Created by alex on 16/12/18.
//
#ifndef INC_13_1_PAIR1_H
#define INC_13_1_PAIR1_H
#include <iostream>
template <class T>
class Pair1 {
private:
T m_x;
T m_y;
public:
Pair1(const T& x, const T& y): m_x(x), m_y(y){}
T& first() {return m_x;}
const T& first() const{return m_x;}
T& second() {return m_y;}
const T& second() const {return m_y;}
};
#endif //INC_13_1_PAIR1_H
| true |
7e402e36f1800124cd28f292022e956ca3fe365b | C++ | jstark523/Comp220ADJ | /LinkedQueuePlaylist.h | UTF-8 | 1,272 | 3.171875 | 3 | [] | no_license | //
// Created by Jrsta on 12/14/2019.
//
#ifndef COMP220ADJ_LINKEDQUEUEPLAYLIST_H
#define COMP220ADJ_LINKEDQUEUEPLAYLIST_H
#include <string>
#include "Playlist.h"
#include "PlaylistNode.h"
#include "SongStorage.h"
/**
* Represents a FIFO data structure (First In First Out). Picture a line
* to wait for something (first person in is the first person out)
*/
//class PlaylistNode;
class LinkedQueuePlaylist {
private:
PlaylistNode* front;
PlaylistNode* end;
public:
//Creates an empty queue
LinkedQueuePlaylist();
//Copy Constructor
LinkedQueuePlaylist(const LinkedQueuePlaylist& queueToCopy);
//assn operator
LinkedQueuePlaylist& operator=(const LinkedQueuePlaylist& queueToCopy);
//Destructor
~LinkedQueuePlaylist();
//adds an item to the end of the queue
void enqueue(SongStorage item);
//takes an item off the front of the queue and returns it
//throws out_of_range exception if the queue is empty
SongStorage dequeue();
//returns true if the queue has no items, false otherwise
bool isEmpty();
PlaylistNode* getFront();
PlaylistNode* getEnd();
void setFront(PlaylistNode* newFront);
void setEnd(PlaylistNode* newEnd);
};
#endif //COMP220ADJ_LINKEDQUEUEPLAYLIST_H
| true |
bc4f0c1b6b75127e5a53733bd727f4d4e115d6b9 | C++ | david-waterworth/catboost | /library/cpp/l1_distance/l1_distance_ut.cpp | UTF-8 | 7,389 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include "l1_distance.h"
#include <library/cpp/testing/unittest/registar.h>
#include <util/generic/vector.h>
#include <util/random/fast.h>
Y_UNIT_TEST_SUITE(TL1DistanceTestSuite) {
inline void RandomNumber(TReallyFastRng32 & rng, i8 & value) {
value = rng.Uniform(~((ui8)0));
};
inline void RandomNumber(TReallyFastRng32 & rng, ui8 & value) {
value = rng.Uniform(~((ui8)0));
};
inline void RandomNumber(TReallyFastRng32 & rng, i32 & value) {
value = rng.Uniform(~((ui32)0));
};
inline void RandomNumber(TReallyFastRng32 & rng, ui32 & value) {
value = rng.Uniform(~((ui32)0));
};
inline void RandomNumber(TReallyFastRng32 & rng, float& value) {
value = rng.GenRandReal1();
};
inline void RandomNumber(TReallyFastRng32 & rng, double& value) {
value = rng.GenRandReal1();
};
template <typename Number>
void FillWithRandomNumbers(Number * dst, int seed, int length) {
TReallyFastRng32 Rnd(seed);
for (int i = 0; i < length; ++i) {
RandomNumber(Rnd, dst[i]);
}
}
template <typename Res, typename IRes, typename Int>
Res SimpleL1Dist(const Int* lhs, const Int* rhs, int length) {
Res sum = 0;
for (int i = 0; i < length; ++i) {
IRes diff = static_cast<IRes>(lhs[i]) - static_cast<IRes>(rhs[i]);
sum += diff >= 0 ? diff : -diff;
}
return sum;
}
bool Eq(ui64 a, ui64 b) {
return a == b;
}
bool Eq(ui32 a, ui32 b) {
return a == b;
}
bool Eq(double a, double b) {
return std::fabs(a - b) < 0.00001;
}
bool Eq(float a, float b) {
return (std::fabs(a - b) < 0.0001);
}
template <typename Res, typename IRes, typename Number, size_t seed>
bool Test() {
TVector<Number> a(100);
TVector<Number> b(100);
FillWithRandomNumbers(a.data(), seed, 100);
FillWithRandomNumbers(a.data(), ~seed & 0xffff, 100);
for (ui32 i = 0; i < 30; i++) {
for (ui32 length = 1; length + i + 1 < a.size(); ++length) {
if (!Eq(L1Distance(a.data() + i, b.data() + i, length), SimpleL1Dist<Res, IRes, Number>(a.data() + i, b.data() + i, length)))
return false;
if (!Eq(L1DistanceSlow(a.data() + i, b.data() + i, length), SimpleL1Dist<Res, IRes, Number>(a.data() + i, b.data() + i, length)))
return false;
}
}
return true;
}
Y_UNIT_TEST(TestL1Dist_i8) {
UNIT_ASSERT((Test<ui32, i32, i8, 117>()));
}
Y_UNIT_TEST(TestL1Dist_ui8) {
UNIT_ASSERT((Test<ui32, i32, ui8, 117>()));
}
Y_UNIT_TEST(TestL1Dist_i32) {
UNIT_ASSERT((Test<ui64, i64, i32, 13>()));
}
Y_UNIT_TEST(TestL1Dist_ui32) {
UNIT_ASSERT((Test<ui64, i64, ui32, 13>()));
}
Y_UNIT_TEST(TestL1Dist_float) {
UNIT_ASSERT((Test<float, float, float, 19>()));
}
Y_UNIT_TEST(TestL1Dist_double) {
UNIT_ASSERT((Test<double, double, double, 753>()));
}
Y_UNIT_TEST(TestL1Dist_zero_length) {
UNIT_ASSERT(L1Distance(static_cast<const i8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1Distance(static_cast<const ui8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1DistanceUI4(static_cast<const ui8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1Distance(static_cast<const i32*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1Distance(static_cast<const ui32*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(Eq(L1Distance(static_cast<const float*>(nullptr), nullptr, 0), static_cast<float>(0.0)));
UNIT_ASSERT(Eq(L1Distance(static_cast<const double*>(nullptr), nullptr, 0), 0.0));
UNIT_ASSERT(L1DistanceSlow(static_cast<const i8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1DistanceSlow(static_cast<const ui8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1DistanceUI4Slow(static_cast<const ui8*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1DistanceSlow(static_cast<const i32*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(L1DistanceSlow(static_cast<const ui32*>(nullptr), nullptr, 0) == 0);
UNIT_ASSERT(Eq(L1DistanceSlow(static_cast<const float*>(nullptr), nullptr, 0), static_cast<float>(0.0)));
UNIT_ASSERT(Eq(L1DistanceSlow(static_cast<const double*>(nullptr), nullptr, 0), 0.0));
}
template <typename Number>
bool Test1() {
Number n1;
Number n2 = 0;
FillWithRandomNumbers(&n1, 666, 1);
return Eq(L1Distance(&n1, &n2, 1), (n1 < 0 ? -n1 : n1)) && Eq(L1DistanceSlow(&n1, &n2, 1), (n1 < 0 ? -n1 : n1));
}
template <>
bool Test1<ui32>() {
ui32 n1;
ui32 n2 = 0;
FillWithRandomNumbers(&n1, 666, 1);
return Eq(L1Distance(&n1, &n2, 1), (ui64)n1) && Eq(L1DistanceSlow(&n1, &n2, 1), (ui64)n1);
}
Y_UNIT_TEST(TestL1Dist_length1) {
UNIT_ASSERT(Test1<i8>());
UNIT_ASSERT(Test1<ui8>());
UNIT_ASSERT(Test1<i32>());
UNIT_ASSERT(Test1<ui32>());
UNIT_ASSERT(Test1<float>());
UNIT_ASSERT(Test1<double>());
}
Y_UNIT_TEST(TestL1DistUI4_length1) {
ui8 n1;
ui8 n2 = 0;
FillWithRandomNumbers(&n1, 888, 1);
UNIT_ASSERT_VALUES_EQUAL(L1DistanceUI4(&n1, &n2, 1), (n1 & 0x0f) + ((n1 & 0xf0) >> 4));
UNIT_ASSERT_VALUES_EQUAL(L1DistanceUI4Slow(&n1, &n2, 1), (n1 & 0x0f) + ((n1 & 0xf0) >> 4));
}
Y_UNIT_TEST(TestL1DistUI4_length96) {
TVector<ui8> n1(96);
TVector<ui8> n2(96);
FillWithRandomNumbers(n1.data(), 666, 96);
FillWithRandomNumbers(n2.data(), 222, 96);
UNIT_ASSERT_VALUES_EQUAL(L1DistanceUI4(n1.data(), n2.data(), 96), L1DistanceUI4Slow(n1.data(), n2.data(), 96));
}
Y_UNIT_TEST(TestL1DistUI4_length72) {
TVector<ui8> n1(72);
TVector<ui8> n2(72);
FillWithRandomNumbers(n1.data(), 666, 72);
FillWithRandomNumbers(n2.data(), 222, 72);
UNIT_ASSERT_VALUES_EQUAL(L1DistanceUI4(n1.data(), n2.data(), 72), L1DistanceUI4Slow(n1.data(), n2.data(), 72));
}
Y_UNIT_TEST(TestL1Dist_manual_i8) {
static i8 a[4] = {0, -128, 100, 127};
static i8 b[4] = {0, 127, -100, -128};
UNIT_ASSERT_VALUES_EQUAL(L1Distance(a, b, 4), 0 + 255 + 200 + 255);
}
Y_UNIT_TEST(TestL1Dist_manual_ui8) {
static ui8 a[4] = {0, 255, 0, 100};
static ui8 b[4] = {0, 0, 255, 140};
UNIT_ASSERT_VALUES_EQUAL(L1Distance(a, b, 4), 0 + 255 + 255 + 40);
}
Y_UNIT_TEST(TestL1Dist_manual_ui4) {
static ui8 a[4] = {0 + (0 << 4), 15 + (8 << 4), 0 + (5 << 4), 3 + (1 << 4)};
static ui8 b[4] = {0 + (0 << 4), 0 + (8 << 4), 7 + (0 << 4), 1 + (4 << 4)};
UNIT_ASSERT_VALUES_EQUAL(L1DistanceUI4(a, b, 4), 0 + 15 + 0 + 7 + 5 + 2 + 3);
}
Y_UNIT_TEST(TestL1Dist_manual_i32) {
static i32 a[4] = {0, -128, 100, 127};
static i32 b[4] = {0, 127, -100, -128};
UNIT_ASSERT_VALUES_EQUAL(L1Distance(a, b, 4), 0 + 255 + 200 + 255);
}
Y_UNIT_TEST(TestL1Dist_manual_ui32) {
static ui32 a[4] = {0, 0xffffffff, 0, 10000000};
static ui32 b[4] = {0, 0, 0xffffffff, 14000000};
UNIT_ASSERT_VALUES_EQUAL(L1Distance(a, b, 4), 0 + 0xfffffffful + 0xfffffffful + 4000000);
}
}
| true |
96de9966c108fb7d1e1c7c6a903dd221c910d008 | C++ | harukoya/AOJ | /ALDS_1_8_B/ALDS_1_8_B.cpp | UTF-8 | 1,544 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct Node {
int key;
Node *parent, *left, *right;
};
Node *root, *NIL;
void insert(int value) {
Node *y = NIL; // zの親
Node *x = root; // 木の根
Node *z = new Node;
z->key = value;
z->left = NIL;
z->right = NIL;
while (x != NIL) {
y = x; // 親を設定
if (z->key < x->key) {
x = x->left; // 左の子へ移動
} else {
x = x->right; // 右の子へ移動
}
}
z->parent = y;
if (y == NIL) {
root = z;
} else if (z->key < y->key) {
y->left = z;
} else {
y->right = z;
}
}
void find(int value) {
Node *x = root;
while (x != NIL && value != x->key) {
if (value < x->key) {
x = x->left;
} else {
x = x->right;
}
}
if (x != NIL) cout << "yes" << endl;
else cout << "no" << endl;
}
// 中間順巡回
void inorder(Node *u) {
if (u == NIL) return;
inorder(u->left);
cout << " " << u->key;
inorder(u->right);
}
// 先行順巡回
void preorder(Node *u) {
if (u == NIL) return;
cout << " " << u->key;
preorder(u->left);
preorder(u->right);
}
int main() {
int m; cin >> m;
int value;
string command;
for (int i = 0; i < m; i++) {
cin >> command;
if (command == "insert") {
cin >> value;
insert(value);
} else if (command == "find") {
cin >> value;
find(value);
} else {
inorder(root);
cout << endl;
preorder(root);
cout << endl;
}
}
return 0;
} | true |