hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08500952859a6b8ba35a9eeae0e6a43d3e083a3e | 1,195 | hpp | C++ | external/armadillo-10.1.2/tmp/include/armadillo_bits/wall_clock_bones.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 55 | 2020-10-07T20:22:22.000Z | 2021-08-28T10:58:36.000Z | external/armadillo-10.1.2/tmp/include/armadillo_bits/wall_clock_bones.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 16 | 2020-12-06T22:02:38.000Z | 2021-08-19T09:37:56.000Z | external/armadillo-10.1.2/tmp/include/armadillo_bits/wall_clock_bones.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 11 | 2019-12-16T16:06:19.000Z | 2020-04-15T15:28:31.000Z | // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
//! \addtogroup wall_clock
//! @{
//! Class for measuring time intervals
class wall_clock
{
public:
inline wall_clock();
inline ~wall_clock();
inline void tic(); //!< start the timer
inline arma_warn_unused double toc(); //!< return the number of seconds since the last call to tic()
private:
bool valid = false;
std::chrono::steady_clock::time_point chrono_time1;
};
//! @}
| 28.452381 | 103 | 0.654393 | hb407 |
085083eabeed7f9f44c97d548e8690fdad894cd5 | 1,907 | cpp | C++ | circle/src/Circulo.cpp | cyrstem/OF-Experiments | 42dd5e522f5cce39f9a3448531c6e17eaa2554dc | [
"BSD-2-Clause"
] | null | null | null | circle/src/Circulo.cpp | cyrstem/OF-Experiments | 42dd5e522f5cce39f9a3448531c6e17eaa2554dc | [
"BSD-2-Clause"
] | null | null | null | circle/src/Circulo.cpp | cyrstem/OF-Experiments | 42dd5e522f5cce39f9a3448531c6e17eaa2554dc | [
"BSD-2-Clause"
] | null | null | null | //
// Circulo.cpp
// circle
//
// Created by Jacobo Heredia on 5/16/17.
//
//
#include "Circulo.h"
Circulo::Circulo(){
}
void Circulo::setup(){
}
void Circulo::update(){
}
void Circulo::draw(int _rad, int _tamLinea, int _cRess,ofColor _clr,int _anim, float _sine){
tamLinea =_tamLinea;
rad =_rad;
cReso = _cRess;
sines = _sine;
//ofBackground(30);// draw grey background
//ofSetColor(255);// set color drawing color to white
//ofTranslate(ofGetWidth()/2,ofGetHeight()/2); // move initital drawing postion to the center of the screen
int circle_resolution=cReso; // amount of points circle is made of, more points - better quality, but could decrease perfomance
int radius=rad;
ofPolyline circle;
int sine_radius=radius*sines;
int anim_shape=_anim;
float sine_pct=0.5; // setting in percantage how big is the part
float speed_increment=ofGetElapsedTimef()/2;
for(int i=0; i<circle_resolution; i++)
{
float angle=TWO_PI/circle_resolution*i;
float raidus_addon=sine_radius*sin((angle+speed_increment)*anim_shape);
float x=cos(angle+speed_increment)*radius;
float y=sin(angle+speed_increment)*radius;
float z= ofLerp(x, y, sine_pct+1);
// drawing sine wave only on a part of the circle
if(i<sine_pct*circle_resolution){
x=cos(angle+speed_increment)*(radius+raidus_addon);
y=sin(angle+speed_increment)*(radius+raidus_addon);
z=ofNoise(x+2,y+2);
}
circle.addVertex(ofPoint(x,y,z));
}
ofSetLineWidth(tamLinea);
ofColor clr= _clr;
// fromHex(0x379392);
ofSetColor(clr);
circle.close(); // to connect first and last point of our shape we need to use ‘close’ function
circle= circle.getSmoothed(10);
circle.draw();
} | 26.859155 | 131 | 0.63398 | cyrstem |
085711738e7da01286d97a2dfc0b74a98185b440 | 7,813 | cc | C++ | MyMuduo/App/Multiplexer/Demux.cc | Fragrant-Yang/git-test-copy | cc026d7dedacf8d5c798d9e80a658d6fd599812d | [
"Apache-2.0"
] | 2 | 2021-02-20T10:37:52.000Z | 2021-05-07T08:15:37.000Z | MyMuduo/App/Multiplexer/Demux.cc | Fragrant-Yang/git-test-copy | cc026d7dedacf8d5c798d9e80a658d6fd599812d | [
"Apache-2.0"
] | null | null | null | MyMuduo/App/Multiplexer/Demux.cc | Fragrant-Yang/git-test-copy | cc026d7dedacf8d5c798d9e80a658d6fd599812d | [
"Apache-2.0"
] | 1 | 2021-04-17T13:48:36.000Z | 2021-04-17T13:48:36.000Z | #include "../../Lib/lib.h"
#include "../../Tcp/lib.h"
typedef std::shared_ptr<TcpClient> TcpClientPtr;
// const int kMaxConns = 1;
const size_t s_nMaxPacketLen = 255;
const size_t s_nHeaderLen = 3;
const uint16_t s_nListenPort = 9999;
const char* socksIp = "127.0.0.1";
const uint16_t s_nSocksPort = 7777;
// 接口与责任:
// TcpClient:
// 1.设置客户端属性,如是否支持失败重连,重连次数,...
// 2.设置收到来自套接字数据的回调
// --典型使用
// 对数据进行分析,
// 若数据包含一个完整消息,则取出消息处理
// 若数据不包含一个完整消息,则忽略,等待后续达到一个消息时再在回调时进行处理
// 3.设置客户端连接建立/连接撤销回调
// --典型使用
// 连接建立时,存储作为参数传入的shared_ptr<TcpConnection>
// 连接销毁时,删除存储的shared_ptr<TcpConnection>
// TcpServer:
// 1.设置服务端属性,如是否支持线程池,线程池数目,....
// 2.设置收到来自负责的客户套接字数据的回调
// --典型使用
// 对数据进行分析,
// 若数据包含一个完整消息,则取出消息处理
// 若数据不包含一个完整消息,则忽略,等待后续达到一个消息时再在回调时进行处理
// 3.设置接收客户端连接/断开客户端连接回调
// --典型使用
// 连接建立时,存储作为参数传入的shared_ptr<TcpConnection>
// 连接销毁时,删除存储的shared_ptr<TcpConnection>
//
// 这里与TcpClient的3区别是
// 一个TcpClient其至多维护一个shared_ptr<TcpConnection>
// 一个TcpServer对与其连接的每个客户维护一个shared_ptr<TcpConnection>
// TcpServer为了标识每个与其连接的TcpConnection
// 且实现标识与TcpConnection间快速的双向定位,
// 典型做法就是:
// 为每个TcpConnection分配id,以<id, shared_ptr<TcpConnection>>形式用红黑树[map]存储shared_ptr<TcpConnection>
// 对每个TcpConnection将其id设置为对象的语境
// TcpConnection:
// 1.设置连接属性
// 2.通过接口给套接字发送数据
// 3.进行连接控制,如关闭连接/...
struct Entry
{
int connId;
TcpClientPtr client;
TcpConnectionPtr connection;
Buffer pending;
};
class DemuxServer
{
public:
DemuxServer(
EventLoop* loop,
const InetAddress& listenAddr,
const InetAddress& socksAddr)
: m_pLoop(loop),
m_nServer(
loop,
listenAddr,
"DemuxServer"),
m_nSocksAddr(socksAddr)
{
m_nServer.setConnectionCallback(
std::bind(
&DemuxServer::onServerConnection,
this,
_1));
m_nServer.setMessageCallback(
std::bind(
&DemuxServer::onServerMessage,
this,
_1,
_2,
_3));
}
// 服务器启动
void start()
{
m_nServer.start();
}
// 作为服务器只接收一个连接[只有一个服务的客户端]
void onServerConnection(
const TcpConnectionPtr& conn)
{
if (conn->connected())
{
if (m_nServerConn)
{
conn->shutdown();
}
else
{
m_nServerConn = conn;
LOG_INFO
<< "onServerConnection set m_nServerConn";
}
}
else
{
if (m_nServerConn == conn)
{
m_nServerConn.reset();
m_nSocksConns.clear();
LOG_INFO
<< "onServerConnection reset serverConn_";
}
}
}
// 收到来自客户端的消息
void onServerMessage(
const TcpConnectionPtr& conn,
Buffer* buf,
TimeStamp)
{
while (buf->readableBytes() > s_nHeaderLen)
{
int len = static_cast<uint8_t>(*buf->peek());
// 内容不足一个完整消息,忽略
// 待后续累计到一个完整消息,才再回调时处理
if (buf->readableBytes() < len + s_nHeaderLen)
{
break;
}
else
{
// 按协议提取
int connId = static_cast<uint8_t>(buf->peek()[1]);
connId |= (static_cast<uint8_t>(buf->peek()[2]) << 8);
if (connId != 0)
{
assert(m_nSocksConns.find(connId) != m_nSocksConns.end());
TcpConnectionPtr& socksConn = m_nSocksConns[connId].connection;
if (socksConn)
{
assert(m_nSocksConns[connId].pending.readableBytes() == 0);
socksConn->send(
buf->peek() + s_nHeaderLen,
len);
}
else
{
m_nSocksConns[connId].pending.append(
buf->peek() + s_nHeaderLen,
len);
}
}
else
{
// 命令处理
string cmd(
buf->peek() + s_nHeaderLen,
len);
doCommand(cmd);
}
buf->retrieve(len + s_nHeaderLen);
}
}
}
void doCommand(const string& cmd)
{
static const string s_nConn = "CONN ";
int connId = atoi(&cmd[s_nConn.size()]);
bool isUp = cmd.find(" IS UP") != string::npos;
LOG_INFO
<< "doCommand "
<< connId
<< " " << isUp;
if (isUp)
{
assert(m_nSocksConns.find(connId) == m_nSocksConns.end());
char connName[256];
snprintf(
connName,
sizeof connName,
"SocksClient %d",
connId);
Entry entry;
entry.connId = connId;
// 对命令的处理是
// 产生一个TcpConnection并发起连接请求
// 产生一个<id,Entry>组放入map
entry.client.reset(
new TcpClient(
m_pLoop,
m_nSocksAddr,
connName));
entry.client->setConnectionCallback(
std::bind(
&DemuxServer::onSocksConnection,
this,
connId,
_1));
entry.client->setMessageCallback(
std::bind(
&DemuxServer::onSocksMessage,
this,
connId,
_1,
_2,
_3));
m_nSocksConns[connId] = entry;
entry.client->connect();
}
else
{
// 对命令的处理是
// 找到id对应的Entry
// 对其包含的TcpConnection执行关闭
// 或不包含有效TcpConnection时,从map按id删除
assert(m_nSocksConns.find(connId) != m_nSocksConns.end());
TcpConnectionPtr& socksConn = m_nSocksConns[connId].connection;
if (socksConn)
{
socksConn->shutdown();
}
else
{
m_nSocksConns.erase(connId);
}
}
}
void onSocksConnection(
int connId,
const TcpConnectionPtr& conn)
{
assert(m_nSocksConns.find(connId) != m_nSocksConns.end());
// 连接建立--在对应Entry中存储shared_ptr<TcpConnection>
// 并通过TcpConnection执行数据发送
if (conn->connected())
{
m_nSocksConns[connId].connection = conn;
Buffer& pendingData = m_nSocksConns[connId].pending;
if (pendingData.readableBytes() > 0)
{
conn->send(&pendingData);
}
}
else
{
if (m_nServerConn)
{
char buf[256];
int len = snprintf(
buf,
sizeof(buf),
"DISCONNECT %d\r\n",
connId);
Buffer buffer;
buffer.append(buf, len);
sendServerPacket(0, &buffer);
}
else
{
m_nSocksConns.erase(connId);
}
}
}
void onSocksMessage(
int connId,
const TcpConnectionPtr& conn,
Buffer* buf,
TimeStamp)
{
assert(m_nSocksConns.find(connId) != m_nSocksConns.end());
while (buf->readableBytes() > s_nMaxPacketLen)
{
Buffer packet;
packet.append(
buf->peek(),
s_nMaxPacketLen);
buf->retrieve(s_nMaxPacketLen);
sendServerPacket(
connId,
&packet);
}
if (buf->readableBytes() > 0)
{
sendServerPacket(connId, buf);
}
}
void sendServerPacket(
int connId,
Buffer* buf)
{
size_t len = buf->readableBytes();
LOG_DEBUG << len;
assert(len <= s_nMaxPacketLen);
uint8_t header[s_nHeaderLen] =
{
static_cast<uint8_t>(len),
static_cast<uint8_t>(connId & 0xFF),
static_cast<uint8_t>((connId & 0xFF00) >> 8)
};
buf->prepend(header, s_nHeaderLen);
if (m_nServerConn)
{
m_nServerConn->send(buf);
}
}
private:
EventLoop* m_pLoop;
TcpServer m_nServer;
TcpConnectionPtr m_nServerConn;
const InetAddress m_nSocksAddr;
std::map<int, Entry> m_nSocksConns;
};
/*int main(int argc, char* argv[])
{
LOG_INFO
<< "pid = "
<< getpid();
EventLoop loop;
InetAddress listenAddr(s_nListenPort);
if (argc > 1)
{
socksIp = argv[1];
}
InetAddress socksAddr(
socksIp,
s_nSocksPort);
DemuxServer server(
&loop,
listenAddr,
socksAddr);
server.start();
loop.loop();
}*/
| 21.763231 | 94 | 0.564444 | Fragrant-Yang |
085997f6cf1f369ae3e53c7adf4a994b509334d5 | 2,644 | cpp | C++ | cli.cpp | seanpringle/rela | 134d45647caa642e1dd6f8b7a45fda3d70265f6c | [
"MIT"
] | 3 | 2022-01-15T12:55:49.000Z | 2022-01-17T15:44:51.000Z | cli.cpp | seanpringle/rela | 134d45647caa642e1dd6f8b7a45fda3d70265f6c | [
"MIT"
] | null | null | null | cli.cpp | seanpringle/rela | 134d45647caa642e1dd6f8b7a45fda3d70265f6c | [
"MIT"
] | null | null | null | // Rela, MIT License
//
// Copyright (c) 2021 Sean Pringle <sean.pringle@gmail.com> github:seanpringle
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "rela.hpp"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
static char* slurp(const char* script);
class RelaCLI : public Rela {
public:
struct {
int main = 0;
} modules;
RelaCLI(const char* source) : Rela() {
map_set(map_core(), make_string("hello"), make_function(1));
modules.main = module(source);
}
void execute(int id) override {
if (id == 1) hello();
}
void hello() {
stack_push(make_string("hello world"));
}
};
int run(const char* source, bool decompile) {
RelaCLI rela(source);
if (decompile) rela.decompile();
return rela.run();
}
int main(int argc, char* argv[]) {
bool decompile = false;
const char* script = NULL;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-d")) { decompile = true; continue; }
script = argv[i];
}
if (!script) {
fprintf(stderr, "missing script file");
exit(1);
}
char* source = slurp(script);
if (!source) {
fprintf(stderr, "cannot read script file: %s", script);
exit(1);
}
int rc = run(source, decompile);
free(source);
return rc;
}
static char* slurp(const char* script) {
char* source = NULL;
struct stat st;
if (stat(script, &st) == 0) {
FILE *file = fopen(script, "r");
if (file) {
size_t bytes = st.st_size;
source = (char*)malloc(bytes + 1);
size_t read = fread(source, 1, bytes, file);
source[bytes] = 0;
if (read != bytes) {
free(source);
source = NULL;
}
}
fclose(file);
}
return source;
}
| 25.921569 | 81 | 0.6823 | seanpringle |
085aa39f7d608dd596b358f93e42cb3f512e0997 | 29 | hpp | C++ | include/assets/icon.hpp | Zenith80/initial_emulator | 2c2bfbed9fe0ed55c856a02b52a5fdd97f328e72 | [
"Apache-2.0"
] | 9 | 2017-11-12T23:16:14.000Z | 2017-12-08T19:42:44.000Z | include/assets/icon.hpp | Zenith80/Zenith80 | 2c2bfbed9fe0ed55c856a02b52a5fdd97f328e72 | [
"Apache-2.0"
] | null | null | null | include/assets/icon.hpp | Zenith80/Zenith80 | 2c2bfbed9fe0ed55c856a02b52a5fdd97f328e72 | [
"Apache-2.0"
] | null | null | null | extern unsigned char icon[];
| 14.5 | 28 | 0.758621 | Zenith80 |
0862382ccc54958ce4825c1793fca6500abd157b | 3,893 | cpp | C++ | tests/test_gemm0.cpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 52 | 2017-06-30T06:45:19.000Z | 2021-11-04T01:53:48.000Z | tests/test_gemm0.cpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 31 | 2017-08-01T03:17:25.000Z | 2022-03-22T18:19:41.000Z | tests/test_gemm0.cpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 23 | 2017-07-17T02:09:17.000Z | 2021-11-10T00:38:19.000Z | /*******************************************************************************
* Copyright (C) 2017 Advanced Micro Devices, Inc. All rights reserved.
*******************************************************************************/
#include <iomanip>
#include <mutex>
#include <thread>
#include <miopengemm/apitest.hpp>
#include <miopengemm/geometries.hpp>
#include <miopengemm/geometry.hpp>
#include <miopengemm/hint.hpp>
#include <miopengemm/oclutil.hpp>
#include <miopengemm/timer.hpp>
// NOTE : compiling kernels is the bottleneck here (when OpenBLAS is used for CPU),
// precomputing CPU results will not accelerate significantly.
int main()
{
using namespace MIOpenGEMM;
auto toff = get_padding_offsets();
owrite::Writer mowri(Ver::E::TERMINAL, "");
CLHint devhint(0, 0);
cl_command_queue_properties cqps = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE;
oclutil::CommandQueueInContext cqic(mowri, cqps, devhint, "test_gemm0");
std::vector<float> alphas;
std::vector<float> betas;
std::vector<size_t> n_runs;
std::vector<bool> run_accus;
std::vector<apitest::GemmImpl> impls;
std::vector<bool> run_event_timers;
std::vector<Geometry> geometries = get_conv_geometries();
geometries.resize(20);
geometries.emplace_back("tC0_tA1_tB1_colMaj0_m400_n500_k600_lda1002_ldb1004_ldc1008_ws0_f32");
// std::vector<Geometry> geometries = get_deepbench(0);
auto n_problems = geometries.size();
for (auto i = 0; i < n_problems; ++i)
{
alphas.emplace_back(2.0);
if (i % 3 == 0)
{
betas.emplace_back(0);
}
else if (i % 3 == 1)
{
betas.emplace_back(1);
}
else
{
betas.emplace_back(0.5);
}
n_runs.emplace_back(3 + 3 * (i % 3 == 2));
run_accus.emplace_back(true);
if (i % 3 == 0)
{
impls.emplace_back(apitest::GemmImpl::XGEMM);
}
else
{
impls.emplace_back(apitest::GemmImpl::GEMM0);
}
run_event_timers.emplace_back(false);
}
std::vector<apitest::RunStats> all_runstats;
all_runstats.resize(n_problems);
std::vector<std::thread> threads;
const setabcw::CpuMemBundle<float> cmb(geometries, toff);
auto run = [&](size_t i) {
mowri << '(' << i << " of " << n_problems << ')' << Endl;
mowri << '\n' << Flush << geometries[i].get_string();
auto x = apitest::supa_gemm0<float>(cqic.command_queue,
geometries[i],
toff,
alphas[i],
betas[i],
n_runs[i],
run_accus[i],
impls[i],
run_event_timers[i],
mowri,
&cmb);
all_runstats[i] = x;
};
Timer timer;
timer.start();
// join the threads is blocks of block_size.
size_t block_size = 3;
for (auto i = 0; i < n_problems / block_size; ++i)
{
for (auto j = i * block_size; j < (i + 1) * block_size; ++j)
{
threads.emplace_back(std::thread(run, j));
}
for (auto j = i * block_size; j < (i + 1) * block_size; ++j)
{
threads[j].join();
}
}
for (auto j = block_size * (n_problems / block_size); j < n_problems; ++j)
{
threads.emplace_back(std::thread(run, j));
}
for (auto j = block_size * (n_problems / block_size); j < n_problems; ++j)
{
threads[j].join();
}
mowri << "\ntime elapsed : " << timer.get_elapsed();
mowri << std::setw(30) << "All tests passed. Summary: " << Endl;
mowri << apitest::get_summary_deepstyle(geometries, all_runstats, impls, betas);
return 0;
}
| 28.210145 | 96 | 0.532751 | pruthvistony |
08659db0ce1208349e489f9fd02aeabf4c622c9d | 2,940 | cpp | C++ | tests/extension/oneapi_sub_group_mask/sub_group_mask_insert_bits.cpp | AidanBeltonS/SYCL-CTS | f8d877560d82e2e4a7eacefe9d252178a7d602c1 | [
"Apache-2.0"
] | null | null | null | tests/extension/oneapi_sub_group_mask/sub_group_mask_insert_bits.cpp | AidanBeltonS/SYCL-CTS | f8d877560d82e2e4a7eacefe9d252178a7d602c1 | [
"Apache-2.0"
] | null | null | null | tests/extension/oneapi_sub_group_mask/sub_group_mask_insert_bits.cpp | AidanBeltonS/SYCL-CTS | f8d877560d82e2e4a7eacefe9d252178a7d602c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
//
// SYCL 2020 Conformance Test Suite
//
// Provides tests to check sub_group_mask insert_bits()
//
*******************************************************************************/
#include "sub_group_mask_common.h"
#define TEST_NAME sub_group_mask_insert_bits
namespace TEST_NAMESPACE {
using namespace sycl_cts;
#ifdef SYCL_EXT_ONEAPI_SUB_GROUP_MASK
// to get 0b0101.. to insert
template <typename T>
void get_bits(T &out) {
out = 1;
for (size_t i = 2; i + 2 <= sizeof(T) * CHAR_BIT; i = i + 2) {
out <<= 2;
out++;
}
}
template <typename T, size_t nElements>
void get_bits(sycl::marray<T, nElements> &out) {
T val;
get_bits(val);
std::fill(out.begin(), out.end(), val);
}
template <typename T>
struct check_result_insert_bits {
bool operator()(const sycl::ext::oneapi::sub_group_mask &sub_group_mask,
const sycl::sub_group &) {
for (size_t pos = 0; pos < sub_group_mask.size(); pos++) {
sycl::ext::oneapi::sub_group_mask mask = sub_group_mask;
T bits;
get_bits(bits);
mask.insert_bits(bits, sycl::id(pos));
for (size_t K = 0; K < mask.size(); K++)
if (K >= pos && K < pos + CHAR_BIT * sizeof(T)) {
if (mask.test(sycl::id(K)) != ((K - pos) % 2 == 0)) return false;
} else {
if (mask.test(sycl::id(K)) != (K % 3 == 0)) return false;
}
}
return true;
}
};
template <typename T>
struct check_type_insert_bits {
bool operator()(const sycl::ext::oneapi::sub_group_mask &sub_group_mask) {
return std::is_same_v<void, decltype(sub_group_mask.insert_bits(T()))>;
}
};
template <typename T>
struct check_for_type {
template <size_t SGSize>
using verification_func_for_mod3_predicate =
check_mask_api<SGSize, check_result_insert_bits<T>,
check_type_insert_bits<T>, mod3_predicate,
const sycl::ext::oneapi::sub_group_mask>;
void operator()(util::logger &log, const std::string &typeName) {
log.note("testing: " + type_name_string<T>::get(typeName));
check_diff_sub_group_sizes<verification_func_for_mod3_predicate>(log);
}
};
#endif // SYCL_EXT_ONEAPI_SUB_GROUP_MASK
/** test sycl::oneapi::sub_group_mask interface
*/
class TEST_NAME : public util::test_base {
public:
/** return information about this test
*/
void get_info(test_base::info &out) const override {
set_test_info(out, TOSTRING(TEST_NAME), TEST_FILE);
}
/** execute the test
*/
void run(util::logger &log) override {
#ifdef SYCL_EXT_ONEAPI_SUB_GROUP_MASK
for_all_types_and_marrays<check_for_type>(types, log);
#else
log.note("SYCL_EXT_ONEAPI_SUB_GROUP_MASK is not defined, test is skipped");
#endif // SYCL_EXT_ONEAPI_SUB_GROUP_MASK
}
};
// register this test with the test_collection.
util::test_proxy<TEST_NAME> proxy;
} /* namespace TEST_NAMESPACE */
| 28.823529 | 80 | 0.632993 | AidanBeltonS |
08660c13d2cbafde7585fe89836363e170947627 | 3,037 | hpp | C++ | openstudiocore/src/model/ShadingControl.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/ShadingControl.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/ShadingControl.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2013, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_SHADINGCONTROL_HPP
#define MODEL_SHADINGCONTROL_HPP
#include <model/ModelAPI.hpp>
#include <model/ResourceObject.hpp>
namespace openstudio {
namespace model {
class Construction;
class ShadingMaterial;
class Schedule;
namespace detail {
class ShadingControl_Impl;
} // detail
/** ShadingControl is a ResourceObject that wraps the OpenStudio IDD object 'OS:ShadingControl'. */
class MODEL_API ShadingControl : public ResourceObject {
public:
/** @name Constructors and Destructors */
//@{
explicit ShadingControl(const Construction& construction);
explicit ShadingControl(const ShadingMaterial& shadingMaterial);
virtual ~ShadingControl() {}
//@}
static IddObjectType iddObjectType();
static std::vector<std::string> shadingTypeValues();
static std::vector<std::string> shadingControlTypeValues();
/** @name Getters */
//@{
boost::optional<Construction> construction() const;
boost::optional<ShadingMaterial> shadingMaterial() const;
std::string shadingType() const;
std::string shadingControlType() const;
boost::optional<Schedule> schedule() const;
//@}
/** @name Setters */
//@{
bool setShadingType(const std::string& shadingType);
bool setShadingControlType(const std::string& shadingControlType);
bool setSchedule(const Schedule& schedule);
void resetSchedule();
//@}
/** @name Other */
//@{
//@}
protected:
/// @cond
typedef detail::ShadingControl_Impl ImplType;
explicit ShadingControl(boost::shared_ptr<detail::ShadingControl_Impl> impl);
friend class detail::ShadingControl_Impl;
friend class Model;
friend class IdfObject;
friend class openstudio::detail::IdfObject_Impl;
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.ShadingControl");
};
/** \relates ShadingControl*/
typedef boost::optional<ShadingControl> OptionalShadingControl;
/** \relates ShadingControl*/
typedef std::vector<ShadingControl> ShadingControlVector;
} // model
} // openstudio
#endif // MODEL_SHADINGCONTROL_HPP
| 25.957265 | 99 | 0.699374 | bobzabcik |
086774bebde2eb92d95f195791463fd495d45a59 | 1,510 | cpp | C++ | STL/Maps/Maps.cpp | saubhagya0111/Competitive-Progmramming | ca429f0ef89a3e6a93b3cbd7297f1ffae80616ab | [
"MIT"
] | null | null | null | STL/Maps/Maps.cpp | saubhagya0111/Competitive-Progmramming | ca429f0ef89a3e6a93b3cbd7297f1ffae80616ab | [
"MIT"
] | null | null | null | STL/Maps/Maps.cpp | saubhagya0111/Competitive-Progmramming | ca429f0ef89a3e6a93b3cbd7297f1ffae80616ab | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
//Map is used to store the values corresponding to a particular key
//Elements in the map are stored in the sorted order by default to store the keys in unsorted order can be used
map<int, string> m;
m = {{1, "abc"}, {69, "saubhagya"}, {45, "Moreover"}};
m.insert(make_pair(70, "jam"));
//Keys in the entire map are unique and duplicate values cannot be
//Each insertion operation takes O(log N) time where n is the size of the map
// for (auto i1 = m.begin(); i1 != m.end();i1++)
// {
// cout << i1->first << " " << i1->second << " " << endl;
// }
// m[5];
//Total time complexity O(N logN)
//Insertion's time complexity generally depends on the type of key being used for the
for (auto &pr : m)
{
//Acessing the element takes O(log N) time
cout << pr.first << " " << pr.second << endl;
}
auto i2 = m.find(5);
if (i2 == m.end())
{
cout << "Not found" << endl;
}
else
{
cout << i2->first << " " << i2->second << endl;
}
auto i3 = m.erase(3);
//3 has been deleted from the array
auto i4 = m.find(69);
//The entire pair of the values present pointed by i4
if (i4 != m.end())
{
//If the given element is not found in the map it gives a segmentation fault as the iterator points to the m.end() position
m.erase(i4);
}
//m.clear() function is used to clear the entire map
}
| 34.318182 | 131 | 0.576159 | saubhagya0111 |
0867dc18da2ac286267eb8ba38d5e7ebb216538c | 1,541 | cpp | C++ | Sources/Uis/UiStartLogo.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | 1 | 2019-03-13T08:26:38.000Z | 2019-03-13T08:26:38.000Z | Sources/Uis/UiStartLogo.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | Sources/Uis/UiStartLogo.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | #include "UiStartLogo.hpp"
#include "Events/EventTime.hpp"
#include "Events/Events.hpp"
#include "Maths/Visual/DriverConstant.hpp"
#include "Maths/Visual/DriverSlide.hpp"
namespace acid
{
UiStartLogo::UiStartLogo(UiObject *parent) :
UiObject(parent, UiBound(Vector2(0.5f, 0.5f), "Centre", true, true, Vector2(1.0f, 1.0f))),
m_guiBackground(new Gui(this, UiBound(Vector2(0.5f, 0.5f), "Centre", true, true, Vector2(1.0f, 1.0f)), Texture::Resource("Guis/Black.png"))),
m_guiLogo(new Gui(this, UiBound(Vector2(0.5f, 0.5f), "Centre", true, true, Vector2(0.4f, 0.4f)), Texture::Resource("Logos/Flask-02.png"))),
m_textCopyright(new Text(this, UiBound(Vector2(0.5f, 0.2f), "Centre", true), 1.6f, "Copyright (C) 2018, Equilibrium Games - All Rights Reserved. This product uses technology from Khronos Group, Bullet Physics, Nothings, and GLFW.", FontType::Resource("Fonts/ProximaNova", "Regular"), JUSTIFY_CENTRE, 0.8f, 0.0012f, 0.024f)),
m_starting(true)
{
#ifdef ACID_BUILD_DEBUG
Events::Get()->AddEvent<EventTime>(1.65f, false, [&]()
#else
Events::Get()->AddEvent<EventTime>(3.6f, false, [&]()
#endif
{
SetAlphaDriver<DriverSlide>(1.0f, 0.0f, 1.4f);
});
}
UiStartLogo::~UiStartLogo()
{
delete m_guiBackground;
delete m_guiLogo;
delete m_textCopyright;
}
void UiStartLogo::UpdateObject()
{
m_guiBackground->GetRectangle().m_dimensions.m_x = Display::Get()->GetAspectRatio();
m_guiBackground->SetScaleDriver<DriverConstant>(1.6f);
m_guiBackground->SetVisible(true);
m_guiLogo->SetVisible(true);
}
}
| 36.690476 | 326 | 0.713173 | hhYanGG |
086d5d65775a5d530caefde0e90c4b1ee7517857 | 672 | cpp | C++ | libraries/chain/omnibazaar/exchange.cpp | OmniBazaar/OmniCoin2--Core | f54e125f5672519632b7a7cbbddb1123af80a9a4 | [
"MIT"
] | null | null | null | libraries/chain/omnibazaar/exchange.cpp | OmniBazaar/OmniCoin2--Core | f54e125f5672519632b7a7cbbddb1123af80a9a4 | [
"MIT"
] | null | null | null | libraries/chain/omnibazaar/exchange.cpp | OmniBazaar/OmniCoin2--Core | f54e125f5672519632b7a7cbbddb1123af80a9a4 | [
"MIT"
] | null | null | null | #include <exchange.hpp>
namespace omnibazaar {
void exchange_create_operation::validate()const
{
FC_ASSERT( fee.amount >= 0 );
FC_ASSERT( coin_name.length(), "Coin name is empty." );
FC_ASSERT( tx_id.length(), "Transaction ID is empty." );
FC_ASSERT( amount.amount > 0 );
}
graphene::chain::share_type exchange_create_operation::calculate_fee(const fee_parameters_type& k)const
{
return k.fee + calculate_data_fee( fc::raw::pack_size(coin_name) + fc::raw::pack_size(tx_id), k.price_per_kbyte );
}
void exchange_complete_operation::validate()const
{
FC_ASSERT( fee.amount >= 0 );
}
}
| 28 | 122 | 0.653274 | OmniBazaar |
0877f62c3f61ccaf688236f1a2315bf62a3cd8d7 | 2,829 | cpp | C++ | Sem2/ds/Assignment2/050/3.cpp | shashi-kant10/nit_lab | 2c4c587b23325c26bbf4958b9a19636486ee4b00 | [
"MIT"
] | null | null | null | Sem2/ds/Assignment2/050/3.cpp | shashi-kant10/nit_lab | 2c4c587b23325c26bbf4958b9a19636486ee4b00 | [
"MIT"
] | null | null | null | Sem2/ds/Assignment2/050/3.cpp | shashi-kant10/nit_lab | 2c4c587b23325c26bbf4958b9a19636486ee4b00 | [
"MIT"
] | 1 | 2021-12-23T08:08:04.000Z | 2021-12-23T08:08:04.000Z | // Assignment 2 Program 3
// Shashi Kant | 2021PGCACA050
#include <bits/stdc++.h>
using namespace std;
#define N 1000
// Display Memory storage
void displayMemoryStorage(int a[][N], int r, int c)
{
cout << endl
<< "Memory storage representation" << endl;
// vr : vector that stores rows whose element is non zero
// vr : vector that stores columns whose value is non zero
// vr : vector stores non zero elements
vector<int> vr, vc, vv;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (a[i][j] != 0)
{
vr.push_back(i);
vc.push_back(j);
vv.push_back(a[i][j]);
}
// Print row
cout << "Row: ";
for (int i : vr)
cout
<< i << " ";
cout << endl;
// Print column
cout << "Col: ";
for (int i : vc)
cout
<< i << " ";
cout << endl;
// Print value
cout << "Val: ";
for (int i : vv)
cout
<< i << " ";
cout << endl;
}
int main()
{
while (1)
{
// Menu
cout << endl;
cout << "1. Input Upper triangular matrix" << endl;
cout << "2. Input Lower triangular matrix" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
int choice;
cin >> choice;
switch (choice)
{
case 1:
// User Input for Matrix
{
int r, c, a[N][N];
cout << "Enter total number of rows: ";
cin >> r;
cout << "Enter total number of columns: ";
cin >> c;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
{
cout << "Enter row " << i + 1 << ", element " << j + 1 << " : ";
cin >> a[i][j];
}
displayMemoryStorage(a, r, c);
}
break;
case 2:
// User Input for Matrix
{
int r, c, a[N][N];
cout << "Enter total number of rows: ";
cin >> r;
cout << "Enter total number of columns: ";
cin >> c;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
{
cout << "Enter row " << i + 1 << ", element " << j + 1 << " : ";
cin >> a[i][j];
}
displayMemoryStorage(a, r, c);
}
break;
case 3:
cout << "Exiting.." << endl;
exit(0);
break;
default:
cout << "Invalid Input. Please try again.";
}
}
return 0;
}
| 24.815789 | 88 | 0.377519 | shashi-kant10 |
087d5c9cc629f09c552733d042b0baa54a4f7272 | 6,104 | cpp | C++ | src/Core.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | src/Core.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | src/Core.cpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | #include "Core.hpp"
#include <cstddef>
#include <memory>
#include <utility>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>
#include "TaskManager/Module.hpp"
#include "GameConstant.hpp"
#include "app/command/CommandDispatcher.hpp"
#include "world/entity/Factory.hpp"
#include "configParser/detail/BindModule.hpp"
#include "input/Manager.hpp"
#include "input/detail/ActionDispatcher.hpp"
#include "util/EnumCast.hpp"
Core::Core()
: _inputManager(std::make_shared<Input::Detail::ActionDispatcher<Action>>())
, _tileManager(std::make_shared<Ressource::TileManager>())
, _hitboxManager(std::make_shared<Hitbox::Manager>())
, _taskManager(Task::Module::makeManager(4)) {
auto commandDispatcher = std::make_shared<App::Command::Dispatcher>(_taskManager);
auto entityFactory = std::make_unique<World::Entity::Factory>(
_tileManager, _hitboxManager, _inputManager.dispatcher(), *commandDispatcher);
_world = std::make_shared<World::Core>(std::move(entityFactory), sf::FloatRect(0, 0, 1000, 1000));
_serviceFactory = std::make_unique<App::Service::Factory>(std::move(commandDispatcher));
_serviceFactory->registerAll(_world);
}
Core::~Core() {
auto f = _taskManager->stop();
f.get();
}
void Core::run() {
this->createWindow();
this->registerParserModules();
this->parseConfigFile(kConfigDir + "Game.cfg");
if (!this->loadRessources()) {
return;
}
_inputManager.dispatcher()->registerHandler(Action::ESCAPE, std::make_shared<ShutdownModule>(this));
this->runGameLoop();
}
void Core::runGameLoop() {
const size_t maxFrameSkip = 5;
_world->loadMap(kMapDir + "TestMap.map");
sf::Event event;
auto nextGameTick = std::chrono::steady_clock::now();
while (_window.isOpen()) {
while (_window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
this->shutdown();
}
}
for (size_t loopCount = 0; std::chrono::steady_clock::now() > nextGameTick && loopCount < maxFrameSkip;
++loopCount) {
_world->update();
nextGameTick += kTimeStepDuration;
}
// Checks the key pressed and dispatches the associated actions.
_inputManager.run();
_window.clear();
_window.draw(*_world);
_window.display();
}
}
void Core::shutdown() {
_window.close();
}
void Core::createWindow() {
_window.create(sf::VideoMode(1000, 1000), "GameCore");
_window.setFramerateLimit(60);
}
void Core::parseConfigFile(const std::string& file) {
using Key = sf::Keyboard::Key;
_configParser.parse(file);
const auto bindModule =
std::static_pointer_cast<ConfigParser::Detail::BindModule<Key, Action>>(_configParser.module("bind"));
const auto bindMapping = bindModule->mapping();
// Bind keys on actions.
for (const auto& mapping : bindMapping) {
_inputManager.bind(mapping.first, mapping.second);
}
}
bool Core::loadRessources() {
if (!_textureManager.load("mainAsset", kAssetDir + "asset.png")) {
return false;
}
const auto& mainTexture = _textureManager.get("mainAsset");
_tileManager->parse(mainTexture, 32);
for (auto id = enum_cast(Tile::PLAYER); id < enum_cast(Tile::LAST); ++id) {
_hitboxManager->load(static_cast<size_t>(id), _tileManager->tile(static_cast<Tile>(id)), 90);
}
return true;
}
void Core::registerParserModules() {
using Key = sf::Keyboard::Key;
auto bindModule = std::make_shared<ConfigParser::Detail::BindModule<Key, Action>>();
bindModule->configureActions({
{ "Escape", Action::ESCAPE },
{ "Use", Action::USE },
{ "MoveUp", Action::UP },
{ "MoveDown", Action::DOWN },
{ "MoveLeft", Action::LEFT },
{ "MoveRight", Action::RIGHT },
{ "Jump", Action::JUMP },
});
bindModule->configureKeys({
{ "0", Key::Num0 },
{ "1", Key::Num1 },
{ "2", Key::Num2 },
{ "3", Key::Num3 },
{ "4", Key::Num4 },
{ "5", Key::Num5 },
{ "6", Key::Num6 },
{ "7", Key::Num7 },
{ "8", Key::Num8 },
{ "9", Key::Num9 },
//
{ "A", Key::A },
{ "B", Key::B },
{ "C", Key::C },
{ "D", Key::D },
{ "E", Key::E },
{ "F", Key::F },
{ "G", Key::G },
{ "H", Key::H },
{ "I", Key::I },
{ "J", Key::J },
{ "K", Key::K },
{ "L", Key::L },
{ "M", Key::M },
{ "N", Key::N },
{ "O", Key::O },
{ "P", Key::P },
{ "Q", Key::Q },
{ "R", Key::R },
{ "S", Key::S },
{ "T", Key::T },
{ "U", Key::U },
{ "V", Key::V },
{ "W", Key::W },
{ "X", Key::X },
{ "Y", Key::Y },
{ "Z", Key::Z },
//
{ "F1", Key::F1 },
{ "F2", Key::F2 },
{ "F3", Key::F3 },
{ "F4", Key::F4 },
{ "F5", Key::F5 },
{ "F6", Key::F6 },
{ "F7", Key::F7 },
{ "F8", Key::F8 },
{ "F9", Key::F9 },
{ "F10", Key::F10 },
{ "F11", Key::F11 },
{ "F12", Key::F12 },
{ "F13", Key::F13 },
{ "F14", Key::F14 },
{ "F15", Key::F15 },
//
{ "ESCAPE", Key::Escape },
{ "L_CTRL", Key::LControl },
{ "L_SHIFT", Key::LShift },
{ "L_ALT", Key::LAlt },
{ "L_SYSTEM", Key::LSystem },
{ "R_CTRL", Key::RControl },
{ "R_SHIFT", Key::RShift },
{ "R_ALT", Key::RAlt },
{ "R_SYSTEM", Key::RSystem },
{ "MENU", Key::Menu },
{ "LBRACKET", Key::LBracket },
{ "RBRACKET", Key::RBracket },
{ "SEMICOLON", Key::SemiColon },
{ "COMMA", Key::Comma },
{ "PERIOD", Key::Period },
{ "SLASH", Key::Slash },
{ "BACKSLASH", Key::BackSlash },
{ "TILDE", Key::Tilde },
{ "EQUAL", Key::Equal },
{ "DASH", Key::Dash },
{ "SPACE", Key::Space },
{ "ENTER", Key::Return },
{ "BACKSPACE", Key::BackSpace },
{ "TAB", Key::Tab },
{ "PGUP", Key::PageUp },
{ "PGDN", Key::PageDown },
{ "HOME", Key::Home },
{ "INS", Key::Insert },
{ "DEL", Key::Delete },
{ "PLUS", Key::Add },
{ "MINUS", Key::Subtract },
{ "MULT", Key::Multiply },
{ "DIV", Key::Divide },
//
{ "UPARROW", Key::Up },
{ "DOWNARROW", Key::Down },
{ "LEFTARROW", Key::Left },
{ "RIGHTARROW", Key::Right },
});
_configParser.registerModule(std::move(bindModule));
}
| 26.197425 | 107 | 0.569626 | Tastyep |
0881303d86055f97be1b3572b74b650e237018f7 | 4,848 | cpp | C++ | Code/Libs/HTTP/request_handler.cpp | cpp-rakesh/opendatacon | 0fabe335ab5d358c1c6ea3c5b09437c0b059c38f | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2018-01-23T20:16:03.000Z | 2020-08-01T16:31:56.000Z | Code/Libs/HTTP/request_handler.cpp | cpp-rakesh/opendatacon | 0fabe335ab5d358c1c6ea3c5b09437c0b059c38f | [
"ECL-2.0",
"Apache-2.0"
] | 83 | 2015-07-16T07:41:05.000Z | 2022-02-21T06:26:03.000Z | Code/Libs/HTTP/request_handler.cpp | cpp-rakesh/opendatacon | 0fabe335ab5d358c1c6ea3c5b09437c0b059c38f | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2018-01-22T00:48:53.000Z | 2021-02-03T11:06:39.000Z | //
// request_handler.cpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "mime_types.hpp"
#include "reply.hpp"
#include "request.hpp"
#include "request_handler.hpp"
#include <opendatacon/ODCLogMacros.h>
#include <fstream>
#include <sstream>
#include <string>
namespace http
{
request_handler::request_handler()
{}
void request_handler::register_handler(const std::string& uripattern, const pHandlerCallbackType& handler)
{
if (HandlerMap.find(uripattern) != HandlerMap.end())
{
LOGDEBUG("Trying to insert a handler twice {} ", uripattern);
return;
}
HandlerMap.emplace(std::make_pair(uripattern, handler));
}
// Strip any parameters before handing to this method
// The matching here will need to be better in future...
// We only look for the first part of the HandlerMap key to match
pHandlerCallbackType request_handler::find_matching_handler(const std::string& uripattern)
{
pHandlerCallbackType result = nullptr;
size_t matchlength = 0;
std::string matchkey;
for (const auto& key : HandlerMap)
{
// The key match string should be at the start of the path.
// We need to find the longest match.
if ((uripattern.find(key.first) == 0) && (key.first.length() > matchlength))
{
matchlength = key.first.length();
matchkey = key.first;
result = key.second;
}
}
if (matchlength == 0)
{
LOGDEBUG("Failed to find a Handler {} ", uripattern);
}
else
{
LOGTRACE("Found Handler {} for {}", matchkey, uripattern);
}
return result;
}
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
ParameterMapType request_handler::SplitParams(std::string ¶mstring)
{
// Split into a map of keys and values.
ParameterMapType p;
//LOGDEBUG("Splitting Params {}", paramstring);
std::vector<std::string> tokens = split(paramstring, '&');
for (auto token : tokens)
{
std::vector<std::string>keyval = split(token, '=');
if (keyval.size() == 2)
{
std::string key = keyval[0];
std::string value = keyval[1];
p[key] = value;
}
}
return p;
}
// We only need to do simple decoding, the first part of the url after the address will give us the port name, we look for this in a map
// once we find it call the registered method. What is returned is what we send back as the response.
// Remembering that we are going to pass this into and back from Python code, so a little different than if we were planning to do everything
void request_handler::handle_request(const request& req, reply& rep)
{
LOGDEBUG("Request Method {} - Uri {}", req.method, req.uri);
// Decode url to path.
std::string request_path, request_params;
if (!url_decode(req.uri, request_path, request_params))
{
rep = reply::stock_reply(reply::bad_request);
LOGDEBUG("Bad Request");
return;
}
//LOGDEBUG("Path {} - Params {}", request_path, request_params);
// Request path must be absolute and not contain "..".
if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos)
{
rep = reply::stock_reply(reply::bad_request);
LOGDEBUG("Invalid Path/Url");
return;
}
// Do the method/path matching
if (auto fn = find_matching_handler(req.method + " " + request_path))
{
// Pass everything so it can be handled/passed to python
// What about req.headers[] - a vector
ParameterMapType params = SplitParams(request_params);
(*fn)(req.method + " " + req.uri, params, req.content, rep);
return;
}
// If not found, return that
rep = reply::stock_reply(reply::bad_request);
LOGDEBUG("Matching Method/Url not found");
return;
}
// Everything after the http://something:10000 and before the ?var1=value1&var2=value2&var3=value3 part (if it exists)
bool request_handler::url_decode(const std::string& in, std::string& out, std::string& params)
{
out.clear();
params.clear();
out.reserve(in.size());
params.reserve(in.size());
bool inquery = false;
std::string* p = &out;
for (std::size_t i = 0; i < in.size(); ++i)
{
if (in[i] == '%')
{
if (i + 3 <= in.size())
{
int value = 0;
std::istringstream is(in.substr(i + 1, 2));
if (is >> std::hex >> value)
{
*p += static_cast<char>(value);
i += 2;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (in[i] == '+')
{
*p += ' ';
}
else if ((in[i] == '?') && !inquery)
{
inquery = true;
p = ¶ms;
}
else
*p += in[i];
}
return true;
}
} // namespace http
| 25.650794 | 141 | 0.667492 | cpp-rakesh |
0889ec82aa4889dbb9e4edb68a5df1db77ed4189 | 970 | cpp | C++ | src-parameter-list/parameter.cpp | XavierCai1996/signal-pool | 16afac9580e38a9a6e2d698382869b11f0322d4e | [
"Apache-2.0"
] | 1 | 2018-10-25T10:10:32.000Z | 2018-10-25T10:10:32.000Z | src-parameter-list/parameter.cpp | XavierCai1996/signal-pool | 16afac9580e38a9a6e2d698382869b11f0322d4e | [
"Apache-2.0"
] | null | null | null | src-parameter-list/parameter.cpp | XavierCai1996/signal-pool | 16afac9580e38a9a6e2d698382869b11f0322d4e | [
"Apache-2.0"
] | null | null | null | #include "parameter.h"
Parameter::~Parameter()
{
#ifdef MEM_SAFE_PARAMETER
m_impls.GetDeleteImpl()(m_value);
#else
FunctionStorage::Delete(m_value, m_verify);
#endif
}
Parameter::Parameter(const Parameter &o)
: m_verify(o.m_verify), m_value(
#ifndef MEM_SAFE_PARAMETER
FunctionStorage::Copy(o.m_value, o.m_verify))
#else
o.m_impls.GetCopyImpl()(o.m_value)),
m_impls(o.m_impls)
#endif
{ }
const char* Parameter::GetName() const
{
return m_verify.GetName();
}
Parameter& Parameter::operator = (const Parameter &o)
{
#ifndef MEM_SAFE_PARAMETER
FunctionStorage::Delete(m_value, m_verify);
m_value = FunctionStorage::Copy(o.m_value, o.m_verify);
#else
m_impls.GetDeleteImpl()(m_value);
m_value = o.m_impls.GetCopyImpl()(o.m_value);
m_impls = o.m_impls;
#endif
m_verify = o.m_verify;
return *this;
}
TypeVerify Parameter::GetTypeVerify() const
{
return m_verify;
}
bool Parameter::CompareType(const Parameter &o) const
{
return m_verify == o.m_verify;
}
| 19.4 | 56 | 0.745361 | XavierCai1996 |
088f36851b883bf13f6af1a60c195890ce751cb3 | 1,659 | cpp | C++ | src/osc_general.cpp | Zeken/Musical-Tabletop-Coding-Framework | c0e2d64cf3ac6dcf2d0b3e5fe142a7b4c4bab7c5 | [
"MIT"
] | null | null | null | src/osc_general.cpp | Zeken/Musical-Tabletop-Coding-Framework | c0e2d64cf3ac6dcf2d0b3e5fe142a7b4c4bab7c5 | [
"MIT"
] | null | null | null | src/osc_general.cpp | Zeken/Musical-Tabletop-Coding-Framework | c0e2d64cf3ac6dcf2d0b3e5fe142a7b4c4bab7c5 | [
"MIT"
] | null | null | null | #include "osc_general.hpp"
#include "osc_polygon.hpp"
#include "osc_text.hpp"
#include "osc_line.hpp"
#include "ofxGlobalConfig.hpp"
OscGeneral::OscGeneral() : OSCCMD("/mtcf"),
textsize(ofxGlobalConfig::getRef("PROGRAM:TEXTSIZE", 1.0f)){
buildBackground();
}
void OscGeneral::buildBackground(){
background.unregisterEvents();
ofxOscMessage parms;
// Layer
parms.addIntArg(0);
background.run("layer", parms);
parms.clear();
// Color
parms.addIntArg(51);
parms.addIntArg(102);
parms.addIntArg(153);
background.run("color", parms);
parms.clear();
// Geometry
parms.addFloatArg(0.5f);
parms.addFloatArg(0.5f);
parms.addFloatArg(1.0f);
parms.addFloatArg(1.0f);
background.run("addrectangle", parms);
}
void OscGeneral::run(ofxOscMessage & m)
{
static int & R = ofxGlobalConfig::getRef("FEEDBACK:CURSOR:COLOR:R",255);
static int & G = ofxGlobalConfig::getRef("FEEDBACK:CURSOR:COLOR:G",0);
static int & B = ofxGlobalConfig::getRef("FEEDBACK:CURSOR:COLOR:B",0);
OscOptionalUnpacker msg(m);
std::string cmd;
msg >> cmd;
if (cmd == "reset")
{
OscPolygonDraw::Instance().o.reset();
OscTextDraw::Instance().o.reset();
OscLineDraw::Instance().o.reset();
}
else if (cmd == "background")
{
msg >> cmd;
background.run(cmd, msg);
}
else if (cmd == "fingercolor")
{
msg >> R >> G >> B;
}
else if (cmd == "textsize")
{
msg >> textsize;
}
else
{
std::cout << "/mtcf: command " << cmd << " not found" << std::endl;
}
}
| 23.366197 | 88 | 0.590115 | Zeken |
088f56eda2317ecf733268f19a7a15f4d372730d | 8,224 | cpp | C++ | editor/echo/Editor/UI/ProjectWindow/ProjectWnd.cpp | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | editor/echo/Editor/UI/ProjectWindow/ProjectWnd.cpp | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | editor/echo/Editor/UI/ProjectWindow/ProjectWnd.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | #include <QMessageBox>
#include <QStandardItem>
#include <QDesktopServices>
#include <QPainter>
#include "ProjectWnd.h"
#include <qfiledialog.h>
#include "Studio.h"
#include "Update.h"
#include "MacHelper.h"
#include <engine/core/log/Log.h>
#include <engine/core/util/PathUtil.h>
#include <engine/core/main/game_settings.h>
namespace Studio
{
ProjectWnd::ProjectWnd(QMainWindow* parent /* = 0 */)
: QMainWindow(parent)
{
setupUi(this);
#ifdef ECHO_PLATFORM_WINDOWS
// hide window hwnd
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
#elif defined(ECHO_PLATFORM_MAC)
// set title bar color
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
//macChangeTitleBarColor( winId(), 0.0, 0.0, 0.0);
m_menuBar->setNativeMenuBar(false);
m_versionListWidget->setAttribute(Qt::WA_MacShowFocusRect,0);
// adjust size
// adjustWidgetSizeByOS(this);
#endif
// set top left corner icon
m_menuBar->setTopLeftCornerIcon(":/icon/Icon/icon.png");
m_previewerWidget = new QT_UI::QPreviewWidget(m_recentProject);
m_previewerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
m_previewerWidget->isNeedFullPath(true);
m_layout->addWidget(m_previewerWidget);
QObject::connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(openNewProject(int)));
QObject::connect(m_previewerWidget, SIGNAL(Signal_onDoubleClickedItem(const QString&)), this, SLOT(onDoubleClicked(const QString&)));
QObject::connect(m_previewerWidget, SIGNAL(Signal_onClickedItem(const QString&)), this, SLOT(onClicked(const QString&)));
QObject::connect(m_previewerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showMenu(const QPoint&)));
QObject::connect(m_versionListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(onDownloadNewVersion(QListWidgetItem*)));
QObject::connect(m_actionRemoveProject, SIGNAL(triggered()), this, SLOT(onRemoveProject()));
QObject::connect(m_actionShowInExplorer, SIGNAL(triggered()), this, SLOT(onShowProjectInExplorer()));
// show all updateable version echo
showAllUpdateableVersion();
}
ProjectWnd::~ProjectWnd()
{
delete m_previewerWidget;
m_previewerWidget = NULL;
}
void ProjectWnd::loadAllRecentProjects()
{
Echo::list<Echo::String>::type recentProjects;
EditorConfig::instance()->getAllRecentProject(recentProjects);
m_previewerWidget->clearAllItems();
for ( Echo::String& project : recentProjects)
{
addRecentProject(project.c_str());
}
}
void ProjectWnd::addRecentProject(const char* project)
{
if ( m_previewerWidget && NULL != project && 0 != project[0])
{
Echo::String icon = Echo::PathUtil::GetFileDirPath(project) + "icon.png";
icon = Echo::PathUtil::IsFileExist(icon) ? icon : ":/icon/Icon/error/delete.png";
m_previewerWidget->addItem(project, icon.c_str());
}
}
void ProjectWnd::openNewProject(int index)
{
if ( 2 == index )
{
Echo::String defaultDir = Echo::PathUtil::GetCurrentDir() + "/examples/";
QString projectName = QFileDialog::getOpenFileName(this, tr("Open Project"), defaultDir.c_str(), tr("(*.echo)"));
if ( !projectName.isEmpty())
{
openProject(projectName.toStdString().c_str());
}
else
{
tabWidget->setCurrentIndex(0);
}
}
// create project
else if (1 == index)
{
Echo::String newProjectPathName = newProject();
if (!newProjectPathName.empty())
{
// 5.open project
AStudio::instance()->getMainWindow()->showMaximized();
AStudio::instance()->OpenProject(newProjectPathName.c_str());
AStudio::instance()->getRenderWindow();
close();
}
else
{
tabWidget->setCurrentIndex(0);
}
}
}
static void copyQtFile(const Echo::String& qtFile, const Echo::String& writePath)
{
QFile qfile(qtFile.c_str());
if (qfile.open(QIODevice::ReadOnly))
{
// write files
QFile writeFile(writePath.c_str());
if (writeFile.open(QIODevice::WriteOnly))
{
writeFile.write(qfile.readAll());
writeFile.close();
}
qfile.close();
}
}
Echo::String ProjectWnd::newProject()
{
QString projectName = QFileDialog::getSaveFileName(this, tr("New Project"), "", tr("(*.echo)"));
if (!projectName.isEmpty())
{
// 0.confirm path and file name
Echo::String fullPath = projectName.toStdString().c_str();
Echo::String filePath = Echo::PathUtil::GetFileDirPath(fullPath);
Echo::String fileName = Echo::PathUtil::GetPureFilename(fullPath, false);
// 1.create directory
Echo::String newFilePath = filePath + fileName + "/";
if (!Echo::PathUtil::IsDirExist(newFilePath))
{
Echo::PathUtil::CreateDir(newFilePath);
// 2.copy file
copyQtFile(":/project/project/blank.echo", newFilePath + "blank.echo");
copyQtFile(":/project/project/icon.png", newFilePath + "icon.png");
// 3.rename
Echo::String projectPathName = newFilePath + "blank.echo";
Echo::String destProjectPathName = newFilePath + fileName + ".echo";
if (Echo::PathUtil::IsFileExist(projectPathName))
Echo::PathUtil::RenameFile(projectPathName, destProjectPathName);
return destProjectPathName;
}
else
{
EchoLogError("[%s] has existed", newFilePath.c_str());
}
}
return "";
}
void ProjectWnd::openProject(const Echo::String& projectFile)
{
AStudio::instance()->getMainWindow()->showMaximized();
AStudio::instance()->OpenProject(projectFile.c_str());
AStudio::instance()->getRenderWindow();
close();
}
void ProjectWnd::onDoubleClicked(const QString& name)
{
Echo::String projectName = name.toStdString().c_str();
if (Echo::PathUtil::IsFileExist(projectName))
{
AStudio::instance()->getMainWindow()->showMaximized();
AStudio::instance()->OpenProject(name.toStdString().c_str());
AStudio::instance()->getRenderWindow();
close();
}
else
{
Echo::String alertMsg = Echo::StringUtil::Format("project file [%s] not found", projectName.c_str());
QMessageBox msgBox;
msgBox.setText(alertMsg.c_str());
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
}
void ProjectWnd::onRemoveProject()
{
if(!m_selectedProject.empty())
{
EditorConfig::instance()->removeRencentProject(m_selectedProject.c_str());
loadAllRecentProjects();
}
}
void ProjectWnd::onShowProjectInExplorer()
{
QString openDir = Echo::PathUtil::GetFileDirPath(m_selectedProject).c_str();
if (!openDir.isEmpty())
{
#ifdef ECHO_PLATFORM_WINDOWS
QDesktopServices::openUrl(openDir);
#else
QDesktopServices::openUrl(QUrl("file://" + openDir));
#endif
}
}
void ProjectWnd::showMenu(const QPoint& point)
{
QStandardItem* item = m_previewerWidget->itemAt( point);
if(item)
{
m_selectedProject = item->data(Qt::UserRole).toString().toStdString().c_str();// data(Qt::UserRole).toString()
EchoSafeDelete(m_projectMenu, QMenu);
m_projectMenu = EchoNew(QMenu);
m_projectMenu->addAction(m_actionRemoveProject);
m_projectMenu->addSeparator();
m_projectMenu->addAction(m_actionShowInExplorer);
m_projectMenu->exec(QCursor::pos());
}
}
void ProjectWnd::onClicked(const QString& name)
{
Echo::String msg = name.toStdString().c_str();
m_statusBar->showMessage(name);
}
void ProjectWnd::showAllUpdateableVersion()
{
Studio::Update updater;
Echo::StringArray allVersions = updater.getAllEnabledVersions();
for (Echo::String& version : allVersions)
{
QListWidgetItem* item = new QListWidgetItem(version.c_str());
m_versionListWidget->addItem(item);
}
}
// QTBUG-39220
void ProjectWnd::showEvent(QShowEvent* event)
{
setAttribute(Qt::WA_Mapped);
QMainWindow::showEvent(event);
}
void ProjectWnd::onDownloadNewVersion(QListWidgetItem* item)
{
Echo::String resName = item->text().toStdString().c_str();
Studio::Update updater;
updater.downloadVersion(resName);
close();
}
}
| 29.266904 | 137 | 0.672544 | Texas-C |
0891683146be2a42bc5c4518261771994520330f | 3,210 | hpp | C++ | boost/lib/include/boost/asio/execution/detail/as_operation.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 177 | 2021-02-19T02:01:04.000Z | 2022-03-30T07:31:21.000Z | boost/lib/include/boost/asio/execution/detail/as_operation.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 188 | 2021-02-19T04:15:55.000Z | 2022-03-26T09:42:15.000Z | boost/lib/include/boost/asio/execution/detail/as_operation.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 78 | 2021-03-05T03:01:13.000Z | 2022-03-29T07:10:01.000Z | //
// execution/detail/as_operation.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_EXECUTION_DETAIL_AS_OPERATION_HPP
#define BOOST_ASIO_EXECUTION_DETAIL_AS_OPERATION_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/memory.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/execution/detail/as_invocable.hpp>
#include <boost/asio/execution/execute.hpp>
#include <boost/asio/execution/set_error.hpp>
#include <boost/asio/traits/start_member.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace execution {
namespace detail {
template <typename Executor, typename Receiver>
struct as_operation
{
typename remove_cvref<Executor>::type ex_;
typename remove_cvref<Receiver>::type receiver_;
#if !defined(BOOST_ASIO_HAS_MOVE)
boost::asio::detail::shared_ptr<boost::asio::detail::atomic_count> ref_count_;
#endif // !defined(BOOST_ASIO_HAS_MOVE)
template <typename E, typename R>
explicit as_operation(BOOST_ASIO_MOVE_ARG(E) e, BOOST_ASIO_MOVE_ARG(R) r)
: ex_(BOOST_ASIO_MOVE_CAST(E)(e)),
receiver_(BOOST_ASIO_MOVE_CAST(R)(r))
#if !defined(BOOST_ASIO_HAS_MOVE)
, ref_count_(new boost::asio::detail::atomic_count(1))
#endif // !defined(BOOST_ASIO_HAS_MOVE)
{
}
void start() BOOST_ASIO_NOEXCEPT
{
#if !defined(BOOST_ASIO_NO_EXCEPTIONS)
try
{
#endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
execution::execute(
BOOST_ASIO_MOVE_CAST(typename remove_cvref<Executor>::type)(ex_),
as_invocable<typename remove_cvref<Receiver>::type,
Executor>(receiver_
#if !defined(BOOST_ASIO_HAS_MOVE)
, ref_count_
#endif // !defined(BOOST_ASIO_HAS_MOVE)
));
#if !defined(BOOST_ASIO_NO_EXCEPTIONS)
}
catch (...)
{
#if defined(BOOST_ASIO_HAS_STD_EXCEPTION_PTR)
execution::set_error(
BOOST_ASIO_MOVE_OR_LVALUE(
typename remove_cvref<Receiver>::type)(
receiver_),
std::current_exception());
#else // defined(BOOST_ASIO_HAS_STD_EXCEPTION_PTR)
std::terminate();
#endif // defined(BOOST_ASIO_HAS_STD_EXCEPTION_PTR)
}
#endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
}
};
} // namespace detail
} // namespace execution
namespace traits {
#if !defined(BOOST_ASIO_HAS_DEDUCED_START_MEMBER_TRAIT)
template <typename Executor, typename Receiver>
struct start_member<
boost::asio::execution::detail::as_operation<Executor, Receiver> >
{
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
typedef void result_type;
};
#endif // !defined(BOOST_ASIO_HAS_DEDUCED_START_MEMBER_TRAIT)
} // namespace traits
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_EXECUTION_DETAIL_AS_OPERATION_HPP
| 29.722222 | 80 | 0.73053 | mamil |
089592bb6f81385ce46ba7c2ced37396da4af143 | 10,682 | cc | C++ | lib/aligner.cc | ctSkennerton/khmer | f5428c5bdfe009ce39b125fa6e18077c534dc747 | [
"BSD-3-Clause"
] | 1 | 2019-11-02T15:12:44.000Z | 2019-11-02T15:12:44.000Z | lib/aligner.cc | ibest/khmer | fbc307abd64363b329745709846d77444ce0c025 | [
"BSD-3-Clause"
] | null | null | null | lib/aligner.cc | ibest/khmer | fbc307abd64363b329745709846d77444ce0c025 | [
"BSD-3-Clause"
] | null | null | null | //
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt.
// Contact: khmer-project@idyll.org
//
#include "aligner.hh"
namespace khmer
{
// http://www.wesleysteiner.com/professional/del_fun.html
template<class T>
struct del_fun_t {
del_fun_t& operator()(T* p) {
delete p;
return *this;
}
};
template<class T>
del_fun_t<T> del_fun()
{
return del_fun_t<T>();
}
std::set<Node*>::iterator node_set_find(std::set<Node*>& a,
Node* val)
{
std::set<Node*>::iterator it;
for (it = a.begin(); it != a.end(); it++) {
if (**it == *val) {
return it;
}
}
return a.end();
}
std::vector<Node*>::iterator node_vector_find(std::vector<Node*>& a,
Node* val)
{
std::vector<Node*>::iterator it;
for (it = a.begin(); it != a.end(); it++) {
if (**it == *val) {
return it;
}
}
return a.end();
}
Node * Aligner::subalign(Node * startVert,
unsigned long seqLen,
unsigned char forward,
std::set<Node*>& closed,
std::vector<Node*>& open,
const std::string& seq)
{
make_heap(open.begin(), open.end());
open.push_back(startVert);
std::push_heap(open.begin(), open.end(), NodeCompare());
while (!open.empty()) {
Node * curr = open.front();
std::pop_heap(open.begin(), open.end(), NodeCompare());
open.pop_back();
closed.insert(curr);
if (curr->stateNo == seqLen-1 ||
curr->stateNo == 0) {
return curr;
}
std::queue<Node*> nodes = curr->enumerate(ch, sm, forward, seq,
lambdaOne,
lambdaTwo);
while (!nodes.empty()) {
Node * next = nodes.front();
nodes.pop();
std::vector<Node*>::iterator where = node_vector_find(open, next);
std::set<Node*>::iterator in_closed = node_set_find(closed, next);
if (in_closed == closed.end() &&
(where == open.end() ||
next->gval < (*where)->gval)) {
open.push_back(next);
std::push_heap(open.begin(), open.end(), NodeCompare());
} else {
delete next;
}
}
}
return NULL;
}
std::string Aligner::extractString(Node* goal,
unsigned char forward,
std::map<unsigned long,unsigned long>* readDeletions)
{
std::string ret;
while (goal->parent != NULL) {
char b = goal->emission;
ret += b;
if (goal->state == 'i' && readDeletions != NULL) {
if (readDeletions->count(goal->stateNo) == 0) {
(*readDeletions)[goal->stateNo] = 1;
} else {
(*readDeletions)[goal->stateNo]++;
}
}
goal = goal->parent;
}
// reverse the string if we are going in the forward direction
if (forward) {
std::string tmp;
for (long long i = ret.length()-1; i >= 0; i--) {
tmp += ret[i];
}
ret = tmp;
}
return ret;
}
CandidateAlignment Aligner::align(CountingHash * ch,
const std::string& seq,
const std::string& kmer,
int index)
{
std::set<Node*> leftClosed;
std::set<Node*> rightClosed;
std::vector<Node*> leftOpen;
std::vector<Node*> rightOpen;
Node * leftStart = new Node(NULL,
kmer[0],
index,
'm',
Kmer(kmer));
Node * rightStart = new Node(NULL,
kmer[kmer.length()-1],
index + kmer.length()-1,
'm',
Kmer(kmer));
Node * leftGoal = subalign(leftStart,
seq.length(),
0,
leftClosed,
leftOpen,
seq);
Node * rightGoal = subalign(rightStart,
seq.length(),
1,
rightClosed,
rightOpen,
seq);
if (leftGoal == NULL || rightGoal == NULL) {
for_each(leftOpen.begin(), leftOpen.end(), del_fun<Node>());
for_each(rightOpen.begin(), rightOpen.end(), del_fun<Node>());
for_each(leftClosed.begin(), leftClosed.end(), del_fun<Node>());
for_each(rightClosed.begin(), rightClosed.end(), del_fun<Node>());
return CandidateAlignment();
}
std::map<unsigned long,unsigned long> readDels;
std::string align = extractString(leftGoal, 0, &readDels) +
kmer +
extractString(rightGoal, 1, &readDels);
/*
// score up the alignment
double score = 0;
int readIndex = 0;
int tmpDels = 0;
for (int i = 0; i < (int)align.length(); i++) {
if (tmpDels > 0) {
score += sm->score(align[i], '-');
tmpDels--;
} else if (readDels.count(i) == 0) {
score += sm->score(align[i], seq[readIndex]);
readIndex++;
} else {
score += sm->score(align[i], seq[readIndex]);
tmpDels = readDels[i];
readIndex++;
}
}
*/
// memory cleanup!
for_each(leftOpen.begin(), leftOpen.end(), del_fun<Node>());
for_each(rightOpen.begin(), rightOpen.end(), del_fun<Node>());
for_each(leftClosed.begin(), leftClosed.end(), del_fun<Node>());
for_each(rightClosed.begin(), rightClosed.end(), del_fun<Node>());
return CandidateAlignment(readDels, align);
}
void Aligner::printErrorFootprint(const std::string& read)
{
unsigned int k = ch->ksize();
for (unsigned int i = 0; i < read.length() - k + 1; i++) {
std::string kmer = read.substr(i, k);
if (!(kmer.length() == k)) {
throw std::exception();
}
BoundedCounterType kCov = ch->get_count(kmer.c_str());
bool isCorrect = isCorrectKmer(kCov, lambdaOne, lambdaTwo);
std::cout << isCorrect;
}
std::cout << std::endl;
}
CandidateAlignment Aligner::alignRead(const std::string& read)
{
std::vector<unsigned int> markers;
bool toggleError = 1;
unsigned int longestErrorRegion = 0;
unsigned int currentErrorRegion = 0;
WordLength k = ch->ksize();
std::set<CandidateAlignment> alignments;
CandidateAlignment best = CandidateAlignment();
std::string graphAlign = "";
for (unsigned int i = 0; i < read.length() - k + 1; i++) {
std::string kmer = read.substr(i, k);
if (!(kmer.length() == k)) {
throw std::exception();
}
BoundedCounterType kCov = ch->get_count(kmer.c_str());
bool isCorrect = isCorrectKmer(kCov, lambdaOne, lambdaTwo);
if (isCorrect && currentErrorRegion) {
currentErrorRegion = 0;
}
if (!isCorrect) {
currentErrorRegion++;
if (currentErrorRegion > longestErrorRegion) {
longestErrorRegion = currentErrorRegion;
}
}
if (toggleError && isCorrect) {
markers.push_back(i);
toggleError = 0;
} else if (!toggleError && !isCorrect) {
markers.push_back(i-1);
toggleError = 1;
}
}
// couldn't find a seed k-mer
if (markers.size() == 0) {
//std::cout << "Couldn't find a seed k-mer." << std::endl;
return best;
}
// exceeded max error region parameter
#if (0) // Jason's original code
if (longestErrorRegion > maxErrorRegion && maxErrorRegion >= 0) {
#else
if (longestErrorRegion > maxErrorRegion && maxErrorRegion < UINT_MAX) {
#endif
return best;
}
// read appears to be error free
if (markers.size() == 1 && markers[0] == 0) {
std::map<unsigned long,unsigned long> readDels;
CandidateAlignment retAln = CandidateAlignment(readDels, read);
return retAln;
}
unsigned int startIndex = 0;
if (markers[0] != 0) {
unsigned int index = markers[0];
CandidateAlignment aln = align(ch,
read.substr(0, index+k),
read.substr(index, k),
index);
graphAlign += aln.alignment.substr(0,aln.alignment.length()-k);
startIndex++;
if (markers.size() > 1) {
graphAlign += read.substr(index, markers[1]-index);
} else {
graphAlign += read.substr(index);
}
} else {
graphAlign += read.substr(0, markers[1]-markers[0]);
startIndex++;
}
for (unsigned int i = startIndex; i < markers.size(); i+=2) {
unsigned int index = markers[i];
if (i == markers.size()-1) {
CandidateAlignment aln = align(ch,
read.substr(index),
read.substr(index, k),
0);
graphAlign += aln.alignment.substr(0,aln.alignment.length());
break;
} else {
CandidateAlignment aln = align(ch,
read.substr(index, markers[i+1]-index+k),
read.substr(index, k),
0);
size_t kmerInd = aln.alignment.rfind(read.substr(markers[i+1], k));
if (kmerInd == std::string::npos) {
return best;
} else {
graphAlign += aln.alignment.substr(0, kmerInd);
}
}
// add next correct region to alignment
if (i+1 != markers.size()-1) {
graphAlign += read.substr(markers[i+1], markers[i+2]-markers[i+1]);
} else {
graphAlign += read.substr(markers[i+1]);
}
}
std::map<unsigned long,unsigned long> readDels;
CandidateAlignment retAln = CandidateAlignment(readDels, graphAlign);
return retAln;
}
};
| 29.106267 | 88 | 0.487924 | ctSkennerton |
089b7be83623653d30a06bc6a411760e83a3f0bc | 1,670 | cpp | C++ | Data Structures/segtree + lazy + add + mul.cpp | PauliusGasiukevicius/Algorithms-and-Data-Structures | 11d8e47f8db6a744e4e50065e8fe0c44ca4f0ea2 | [
"MIT"
] | 2 | 2017-11-23T09:36:10.000Z | 2018-08-01T12:10:45.000Z | Data Structures/segtree + lazy + add + mul.cpp | PauliusGasiukevicius/Algorithms-and-Data-Structures | 11d8e47f8db6a744e4e50065e8fe0c44ca4f0ea2 | [
"MIT"
] | null | null | null | Data Structures/segtree + lazy + add + mul.cpp | PauliusGasiukevicius/Algorithms-and-Data-Structures | 11d8e47f8db6a744e4e50065e8fe0c44ca4f0ea2 | [
"MIT"
] | 2 | 2018-08-01T12:11:15.000Z | 2018-12-21T07:43:09.000Z | ll A[200005];
ll seg[4*200005][6]; //[val][mul][add]
//so every node is val*mul + add
//addition: add+=x
//setRange: mul*=0, add+=x;
void build(int c, int l, int r)
{
seg[c][1]=1;
if(l==r)
{
seg[c][0]=A[r];
return;
}
int m = (l+r)/2;
build(2*c,l,m);
build(2*c+1,m+1,r);
seg[c][0]=seg[2*c][0]+seg[2*c+1][0];
}
void Lazy(int c, int l, int r)
{
seg[c][0] = seg[c][0]*seg[c][1] + seg[c][2]*(r-l+1);
if(l!=r)
{
seg[2*c][1]*=seg[c][1];
seg[2*c][2]*=seg[c][1];
seg[2*c][2]+=seg[c][2];
seg[2*c+1][1]*=seg[c][1];
seg[2*c+1][2]*=seg[c][1];
seg[2*c+1][2]+=seg[c][2];
}
seg[c][1]=1;
seg[c][2]=0;
}
void mul(int c, int l, int r, int L, int R, int x)
{
Lazy(c,l,r);
if(l > r || l > R || r < L)return;
if(l >= L && r <= R)
{
seg[c][1]*=x;
seg[c][2]*=x;
Lazy(c,l,r);
return;
}
int m = (l+r)/2;
mul(2*c,l,m,L,R,x);
mul(2*c+1,m+1,r,L,R,x);
seg[c][0] = seg[2*c][0] + seg[2*c+1][0];
}
void add(int c, int l, int r, int L, int R, int x)
{
Lazy(c,l,r);
if(l > r || l > R || r < L)return;
if(l >= L && r <= R)
{
seg[c][2]+=x;
Lazy(c,l,r);
return;
}
int m = (l+r)/2;
add(2*c,l,m,L,R,x);
add(2*c+1,m+1,r,L,R,x);
seg[c][0] = seg[2*c][0] + seg[2*c+1][0];
}
ll Get(int c, int l, int r, int L, int R)
{
Lazy(c,l,r);
if(l > r || l > R || r < L)return 0;
if(l >= L && r <= R) return seg[c][0];
int m = (l+r)/2;
ll res = Get(2*c,l,m,L,R) + Get(2*c+1,m+1,r,L,R);
seg[c][0] = seg[2*c][0] + seg[2*c+1][0];
return res;
} | 21.139241 | 56 | 0.404192 | PauliusGasiukevicius |
089cf528d65570f2f9f6a4b7ad20b8a1a3c7f2bb | 6,397 | cpp | C++ | Firmware/Marlin/src/core/utility.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | 1 | 2019-10-22T11:04:05.000Z | 2019-10-22T11:04:05.000Z | Firmware/Marlin/src/core/utility.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | null | null | null | Firmware/Marlin/src/core/utility.cpp | PavelTajdus/Anet-A8-PLUS-Dual-Color-Rebuild | 76ce07b6c8f52962c1251d40beb6de26301409ef | [
"MIT"
] | 2 | 2019-07-22T20:31:15.000Z | 2021-08-01T00:15:38.000Z | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "utility.h"
#include "../Marlin.h"
#include "../module/temperature.h"
void safe_delay(millis_t ms) {
while (ms > 50) {
ms -= 50;
delay(50);
thermalManager.manage_heater();
}
delay(ms);
thermalManager.manage_heater(); // This keeps us safe if too many small safe_delay() calls are made
}
#if ENABLED(DEBUG_LEVELING_FEATURE)
#include "../module/probe.h"
#include "../module/motion.h"
#include "../module/stepper.h"
#include "../module/stepper.h"
#include "../libs/numtostr.h"
#include "../feature/bedlevel/bedlevel.h"
void log_machine_info() {
SERIAL_ECHOLNPGM("Machine Type: "
#if ENABLED(DELTA)
"Delta"
#elif IS_SCARA
"SCARA"
#elif IS_CORE
"Core"
#else
"Cartesian"
#endif
);
SERIAL_ECHOLNPGM("Probe: "
#if ENABLED(PROBE_MANUALLY)
"PROBE_MANUALLY"
#elif ENABLED(FIX_MOUNTED_PROBE)
"FIX_MOUNTED_PROBE"
#elif ENABLED(BLTOUCH)
"BLTOUCH"
#elif HAS_Z_SERVO_PROBE
"SERVO PROBE"
#elif ENABLED(TOUCH_MI_PROBE)
"TOUCH_MI_PROBE"
#elif ENABLED(Z_PROBE_SLED)
"Z_PROBE_SLED"
#elif ENABLED(Z_PROBE_ALLEN_KEY)
"Z_PROBE_ALLEN_KEY"
#elif ENABLED(SOLENOID_PROBE)
"SOLENOID_PROBE"
#else
"NONE"
#endif
);
#if HAS_BED_PROBE
SERIAL_ECHOPAIR(
"Probe Offset X:" STRINGIFY(X_PROBE_OFFSET_FROM_EXTRUDER)
" Y:" STRINGIFY(Y_PROBE_OFFSET_FROM_EXTRUDER)
" Z:", zprobe_zoffset
);
if ((X_PROBE_OFFSET_FROM_EXTRUDER) > 0)
SERIAL_ECHOPGM(" (Right");
else if ((X_PROBE_OFFSET_FROM_EXTRUDER) < 0)
SERIAL_ECHOPGM(" (Left");
else if ((Y_PROBE_OFFSET_FROM_EXTRUDER) != 0)
SERIAL_ECHOPGM(" (Middle");
else
SERIAL_ECHOPGM(" (Aligned With");
if ((Y_PROBE_OFFSET_FROM_EXTRUDER) > 0) {
#if IS_SCARA
SERIAL_ECHOPGM("-Distal");
#else
SERIAL_ECHOPGM("-Back");
#endif
}
else if ((Y_PROBE_OFFSET_FROM_EXTRUDER) < 0) {
#if IS_SCARA
SERIAL_ECHOPGM("-Proximal");
#else
SERIAL_ECHOPGM("-Front");
#endif
}
else if ((X_PROBE_OFFSET_FROM_EXTRUDER) != 0)
SERIAL_ECHOPGM("-Center");
if (zprobe_zoffset < 0)
SERIAL_ECHOPGM(" & Below");
else if (zprobe_zoffset > 0)
SERIAL_ECHOPGM(" & Above");
else
SERIAL_ECHOPGM(" & Same Z as");
SERIAL_ECHOLNPGM(" Nozzle)");
#endif
#if HAS_ABL_OR_UBL
SERIAL_ECHOLNPGM("Auto Bed Leveling: "
#if ENABLED(AUTO_BED_LEVELING_LINEAR)
"LINEAR"
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
"BILINEAR"
#elif ENABLED(AUTO_BED_LEVELING_3POINT)
"3POINT"
#elif ENABLED(AUTO_BED_LEVELING_UBL)
"UBL"
#endif
);
if (planner.leveling_active) {
SERIAL_ECHOLNPGM(" (enabled)");
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height)
SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height);
#endif
#if ABL_PLANAR
const float diff[XYZ] = {
planner.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
planner.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
planner.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
};
SERIAL_ECHOPGM("ABL Adjustment X");
if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
SERIAL_ECHO(diff[X_AXIS]);
SERIAL_ECHOPGM(" Y");
if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
SERIAL_ECHO(diff[Y_AXIS]);
SERIAL_ECHOPGM(" Z");
if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
SERIAL_ECHO(diff[Z_AXIS]);
#else
#if ENABLED(AUTO_BED_LEVELING_UBL)
SERIAL_ECHOPGM("UBL Adjustment Z");
const float rz = ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]);
#elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
SERIAL_ECHOPGM("ABL Adjustment Z");
const float rz = bilinear_z_offset(current_position);
#endif
SERIAL_ECHO(ftostr43sign(rz, '+'));
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height) {
SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position[Z_AXIS]), '+'));
SERIAL_CHAR(')');
}
#endif
#endif
}
else
SERIAL_ECHOLNPGM(" (disabled)");
SERIAL_EOL();
#elif ENABLED(MESH_BED_LEVELING)
SERIAL_ECHOPGM("Mesh Bed Leveling");
if (planner.leveling_active) {
SERIAL_ECHOLNPGM(" (enabled)");
SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
, 1.0
#endif
), '+'));
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (planner.z_fade_height) {
SERIAL_ECHOPAIR(" (", ftostr43sign(
mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS], planner.fade_scaling_factor_for_z(current_position[Z_AXIS])), '+'
));
SERIAL_CHAR(')');
}
#endif
}
else
SERIAL_ECHOPGM(" (disabled)");
SERIAL_EOL();
#endif // MESH_BED_LEVELING
}
#endif // DEBUG_LEVELING_FEATURE
| 31.053398 | 141 | 0.609348 | PavelTajdus |
089eb8c4b76c40311b7ff605da0ad17f80bd4fb5 | 1,907 | cpp | C++ | luogu/1903.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | luogu/1903.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | luogu/1903.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 400020
#define ll long long
using namespace std;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
struct nodejs {
ll pos, w;
} ask[N];
struct webpack {
ll l, r, id, cur;
} w[N];
ll ctc, q, n, Q, a[N], lbc[N], sum[N], answ[N], zyy;
map <ll, ll> mp;
bool cmp(webpack a, webpack b) {
return a.l / 3000 == b.l / 3000
? (a.r / 3000 == b.r / 3000
? a.cur < b.cur
: a.r / 3000 < b.r / 3000)
: a.l < b.l;
}
ll ans;
void add(int x) {
if (!sum[x]) ans ++;
sum[x] ++;
}
void del(int x) {
sum[x] --;
if (!sum[x]) ans --;
}
void change(ll x, ll l, ll r) {
if (ask[x].pos >= l && ask[x].pos <= r)
del(a[ask[x].pos]);
swap(a[ask[x].pos], ask[x].w);
if (ask[x].pos >= l && ask[x].pos <= r)
add(a[ask[x].pos]);
}
void solve() {
ll l = 1, r = 1, k = 0;
add(a[1]);
for (int i = 1; i <= q; i++) {
while (r > w[i].r) del(a[r--]);
while (r < w[i].r) add(a[++r]);
while (l > w[i].l) add(a[--l]);
while (l < w[i].l) del(a[l++]);
while (k < w[i].cur) change(++k, l, r);
while (k > w[i].cur) change(k--, l, r);
answ[w[i].id] = ans;
}
}
char op[2];
int main(int argc, char const *argv[]) {
n = read(), Q = read();
for (int i = 1; i <= n; i++) {
int x = read();
a[i] = mp[x] ? mp[x] : (mp[x] = ++ctc);
}
for (int i = 1; i <= Q; i++) {
scanf("%s", op);
if (op[0] == 'R') {
ask[++zyy].pos = read();
ask[zyy].w = read();
ask[zyy].w = mp[ask[zyy].w]
? mp[ask[zyy].w]
: (mp[ask[zyy].w] = ++ctc);
} else {
w[++q].l = read();
w[q].r = read();
w[q].id = q;
w[q].cur = zyy;
}
}
sort(w + 1, w + q + 1, cmp);
solve();
for (int i = 1; i <= q; i++)
cout << answ[i] << endl;
return 0;
} | 23.256098 | 61 | 0.441007 | swwind |
08a5d07583a211424568c6d97b31cd6567103f59 | 209 | cpp | C++ | game/gameConfig.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | game/gameConfig.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | game/gameConfig.cpp | jjimenezg93/ai-pathfinding | e32ae8be30d3df21c7e64be987134049b585f1e6 | [
"MIT"
] | null | null | null | #include <stdafx.h>
#include "gameConfig.h"
#include "character.h"
#include "pathfinding/pathfinder.h"
void Configure(MOAIGlobals* globals) {
REGISTER_LUA_CLASS(Character)
REGISTER_LUA_CLASS(Pathfinder)
} | 20.9 | 38 | 0.784689 | jjimenezg93 |
08ac220cf98ce5651f4d13b9018e63792f9b7395 | 222 | cpp | C++ | for(case #n).cpp | honeysquid/programming | 2bf08444d2706c738002d5f3fd726e4a289fe674 | [
"MIT"
] | null | null | null | for(case #n).cpp | honeysquid/programming | 2bf08444d2706c738002d5f3fd726e4a289fe674 | [
"MIT"
] | null | null | null | for(case #n).cpp | honeysquid/programming | 2bf08444d2706c738002d5f3fd726e4a289fe674 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main()
{
int a,b,i;
scanf("%d",&i);
for(i=1; i<=10; i++)
{
while(i<=i)
{
scanf("%d %d", &a, &b);
printf("Case #%d: %d + %d = %d\n",l,a,b,a+b);
l++;
}
}
return 0;
}
| 13.058824 | 48 | 0.387387 | honeysquid |
08b1b0f5990270f4507afcd25cf9a4d451e00216 | 2,237 | hxx | C++ | Legolas/Matrix/MatrixStructures/Diagonal/DiagonalMatrixContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/MatrixStructures/Diagonal/DiagonalMatrixContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/MatrixStructures/Diagonal/DiagonalMatrixContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | /**
* project DESCARTES
*
* @file DiagonalMatrixContainer.hxx
*
* @author Laurent PLAGNE
* @date june 2004 - january 2005
*
* @par Modifications
* - author date object
*
* (c) Copyright EDF R&D - CEA 2001-2005
*/
#ifndef __LEGOLAS_DIAGONALMATRIXCONTAINER_HXX__
#define __LEGOLAS_DIAGONALMATRIXCONTAINER_HXX__
#include "UTILITES.hxx"
#include "Legolas/Matrix/MatrixStructures/MatrixBasicContainer/MatrixBasicEngine.hxx"
#include "Legolas/Matrix/MatrixStructures/MatrixBasicContainer/MatrixBasicData.hxx"
namespace Legolas{
class DiagonalMatrixContainer
{
public:
template < class MATRIX_OPTIONS, class ELEMENT_DATA_DRIVER>
class Engine : public MatrixBasicEngine<ELEMENT_DATA_DRIVER>
{
public:
typedef typename ELEMENT_DATA_DRIVER::Data ElementData;
typedef typename ELEMENT_DATA_DRIVER::RealType RealType;
typedef typename MATRIX_OPTIONS::VectorContainer VectorContainer;
typedef typename VectorContainer::template Engine<ElementData> VectorInterface;
typedef typename VectorInterface::Vector Vector;
class Data : public MatrixBasicData<ELEMENT_DATA_DRIVER>{
public:
Data( void ):diagonal_()
{
MESSAGE("DiagonalMatrixContainer.. Ctor");
}
inline Vector & diagonal( void ) { return diagonal_ ;}
inline const Vector & diagonal( void ) const { return diagonal_ ;}
inline void push_back(const ElementData & inputElement){
diagonal_.push_back(inputElement);
}
private:
int nrows_;
Vector diagonal_;
};
template <int LEVEL>
static inline void resize(const MatrixShape<LEVEL> & shape, Data & data){
data.setColShape()=shape.getColShape();
data.setRowShape()=shape.getRowShape();
VectorInterface::resize(shape.nrows(),data.diagonal());
}
static inline ElementData & diagonalGetElement(int row, Data & data){
return VectorInterface::getElement(row,data.diagonal());
}
static inline const ElementData & diagonalGetElement(int row, const Data & data){
return VectorInterface::getElement(row,data.diagonal());
}
};
};
}
#endif
| 25.420455 | 88 | 0.683952 | LaurentPlagne |
08b7ae9fe7da33e0cee28a342115cc3fd2618f15 | 2,319 | cpp | C++ | LeetCode/SetMatrixZeroes.cpp | Michael-Ma/Coding-Practice | 6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f | [
"MIT"
] | null | null | null | LeetCode/SetMatrixZeroes.cpp | Michael-Ma/Coding-Practice | 6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f | [
"MIT"
] | null | null | null | LeetCode/SetMatrixZeroes.cpp | Michael-Ma/Coding-Practice | 6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f | [
"MIT"
] | null | null | null | #include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <climits>
//#include <unordered_set>
//#include <unordered_map>
using namespace std;
/*
Time Complexity : O(n)
Space Complexity : O(1)
Trick:
if you want to use O(1) space, one trick the is to reuse the input data. use the first column and first row to store those
column and row which should be set to 0, and use 2 bool variable to set first row and column.
Special Cases :
Summary:
*/
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.size()==0 || matrix[0].size()==0){
return;
}
//using first row and first column to store whether it's 0 or not
bool isFirstRowZero = false;
bool isFirstColZero = false;
for(int i=0; i<matrix[0].size(); i++){
if(matrix[0][i] == 0){
isFirstRowZero = true;
break;
}
}
for(int i=0; i<matrix.size(); i++){
if(matrix[i][0] == 0){
isFirstColZero = true;
break;
}
}
for(int i=0; i<matrix.size(); i++){
for(int j=0; j<matrix[0].size(); j++){
if(matrix[i][j] == 0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
//set first row and column in the end
for(int i=1; i<matrix[0].size(); i++){
if(matrix[0][i] == 0){
for(int j=1; j<matrix.size(); j++){
matrix[j][i] = 0;
}
}
}
for(int i=1; i<matrix.size(); i++){
if(matrix[i][0] == 0){
for(int j=1; j<matrix[0].size(); j++){
matrix[i][j] = 0;
}
}
}
if(isFirstRowZero){
for(int i=0; i<matrix[0].size(); i++){
matrix[0][i] = 0;
}
}
if(isFirstColZero){
for(int i=0; i<matrix.size(); i++){
matrix[i][0] = 0;
}
}
}
}; | 26.965116 | 130 | 0.457094 | Michael-Ma |
08badd4356f3b85cb2f95fa6e2a6b9ceee7b7016 | 19,977 | cpp | C++ | extern/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp | chip5441/clReflect | d366cced2fff9aefcfc5ec6a0c97ed6c827263eb | [
"MIT"
] | null | null | null | extern/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp | chip5441/clReflect | d366cced2fff9aefcfc5ec6a0c97ed6c827263eb | [
"MIT"
] | 1 | 2020-02-22T09:59:21.000Z | 2020-02-22T09:59:21.000Z | extern/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp | chip5441/clReflect | d366cced2fff9aefcfc5ec6a0c97ed6c827263eb | [
"MIT"
] | null | null | null | //===-- MipsISelDAGToDAG.cpp - A Dag to Dag Inst Selector for Mips --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the MIPS target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "mips-isel"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsMachineFunction.h"
#include "MipsRegisterInfo.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "llvm/GlobalValue.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Support/CFG.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Instruction Selector Implementation
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// MipsDAGToDAGISel - MIPS specific code to select MIPS machine
// instructions for SelectionDAG operations.
//===----------------------------------------------------------------------===//
namespace {
class MipsDAGToDAGISel : public SelectionDAGISel {
/// TM - Keep a reference to MipsTargetMachine.
MipsTargetMachine &TM;
/// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
/// make the right decision when generating code for different targets.
const MipsSubtarget &Subtarget;
public:
explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
SelectionDAGISel(tm),
TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
// Pass Name
virtual const char *getPassName() const {
return "MIPS DAG->DAG Pattern Instruction Selection";
}
virtual bool runOnMachineFunction(MachineFunction &MF);
private:
// Include the pieces autogenerated from the target description.
#include "MipsGenDAGISel.inc"
/// getTargetMachine - Return a reference to the TargetMachine, casted
/// to the target-specific type.
const MipsTargetMachine &getTargetMachine() {
return static_cast<const MipsTargetMachine &>(TM);
}
/// getInstrInfo - Return a reference to the TargetInstrInfo, casted
/// to the target-specific type.
const MipsInstrInfo *getInstrInfo() {
return getTargetMachine().getInstrInfo();
}
SDNode *getGlobalBaseReg();
std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
EVT Ty, bool HasLo, bool HasHi);
SDNode *Select(SDNode *N);
// Complex Pattern.
bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset);
// getImm - Return a target constant with the specified value.
inline SDValue getImm(const SDNode *Node, unsigned Imm) {
return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
}
void ProcessFunctionAfterISel(MachineFunction &MF);
bool ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI, const MachineInstr&);
void InitGlobalBaseReg(MachineFunction &MF);
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
char ConstraintCode,
std::vector<SDValue> &OutOps);
};
}
// Insert instructions to initialize the global base register in the
// first MBB of the function. When the ABI is O32 and the relocation model is
// PIC, the necessary instructions are emitted later to prevent optimization
// passes from moving them.
void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
if (!MipsFI->globalBaseRegSet())
return;
MachineBasicBlock &MBB = MF.front();
MachineBasicBlock::iterator I = MBB.begin();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
bool FixGlobalBaseReg = MipsFI->globalBaseRegFixed();
if (Subtarget.isABI_O32() && FixGlobalBaseReg)
// $gp is the global base register.
V0 = V1 = GlobalBaseReg;
else {
const TargetRegisterClass *RC;
RC = Subtarget.isABI_N64() ?
Mips::CPU64RegsRegisterClass : Mips::CPURegsRegisterClass;
V0 = RegInfo.createVirtualRegister(RC);
V1 = RegInfo.createVirtualRegister(RC);
}
if (Subtarget.isABI_N64()) {
MF.getRegInfo().addLiveIn(Mips::T9_64);
MBB.addLiveIn(Mips::T9_64);
// lui $v0, %hi(%neg(%gp_rel(fname)))
// daddu $v1, $v0, $t9
// daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
const GlobalValue *FName = MF.getFunction();
BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
.addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0).addReg(Mips::T9_64);
BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
.addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
} else if (MF.getTarget().getRelocationModel() == Reloc::Static) {
// Set global register to __gnu_local_gp.
//
// lui $v0, %hi(__gnu_local_gp)
// addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
.addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
.addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
} else {
MF.getRegInfo().addLiveIn(Mips::T9);
MBB.addLiveIn(Mips::T9);
if (Subtarget.isABI_N32()) {
// lui $v0, %hi(%neg(%gp_rel(fname)))
// addu $v1, $v0, $t9
// addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
const GlobalValue *FName = MF.getFunction();
BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
.addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
.addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
} else if (!MipsFI->globalBaseRegFixed()) {
assert(Subtarget.isABI_O32());
BuildMI(MBB, I, DL, TII.get(Mips::SETGP2), GlobalBaseReg)
.addReg(Mips::T9);
}
}
}
bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
const MachineInstr& MI) {
unsigned DstReg = 0, ZeroReg = 0;
// Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
if ((MI.getOpcode() == Mips::ADDiu) &&
(MI.getOperand(1).getReg() == Mips::ZERO) &&
(MI.getOperand(2).getImm() == 0)) {
DstReg = MI.getOperand(0).getReg();
ZeroReg = Mips::ZERO;
} else if ((MI.getOpcode() == Mips::DADDiu) &&
(MI.getOperand(1).getReg() == Mips::ZERO_64) &&
(MI.getOperand(2).getImm() == 0)) {
DstReg = MI.getOperand(0).getReg();
ZeroReg = Mips::ZERO_64;
}
if (!DstReg)
return false;
// Replace uses with ZeroReg.
for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
E = MRI->use_end(); U != E; ++U) {
MachineOperand &MO = U.getOperand();
MachineInstr *MI = MO.getParent();
// Do not replace if it is a phi's operand or is tied to def operand.
if (MI->isPHI() || MI->isRegTiedToDefOperand(U.getOperandNo()))
continue;
MO.setReg(ZeroReg);
}
return true;
}
void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
InitGlobalBaseReg(MF);
MachineRegisterInfo *MRI = &MF.getRegInfo();
for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
++MFI)
for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
ReplaceUsesWithZeroReg(MRI, *I);
}
bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
ProcessFunctionAfterISel(MF);
return Ret;
}
/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
}
/// ComplexPattern used on MipsInstrInfo
/// Used on Mips Load/Store instructions
bool MipsDAGToDAGISel::
SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) {
EVT ValTy = Addr.getValueType();
// If Parent is an unaligned f32 load or store, select a (base + index)
// floating point load/store instruction (luxc1 or suxc1).
const LSBaseSDNode* LS = 0;
if (Parent && (LS = dyn_cast<LSBaseSDNode>(Parent))) {
EVT VT = LS->getMemoryVT();
if (VT.getSizeInBits() / 8 > LS->getAlignment()) {
assert(TLI.allowsUnalignedMemoryAccesses(VT) &&
"Unaligned loads/stores not supported for this type.");
if (VT == MVT::f32)
return false;
}
}
// if Address is FI, get the TargetFrameIndex.
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
Offset = CurDAG->getTargetConstant(0, ValTy);
return true;
}
// on PIC code Load GA
if (Addr.getOpcode() == MipsISD::Wrapper) {
Base = Addr.getOperand(0);
Offset = Addr.getOperand(1);
return true;
}
if (TM.getRelocationModel() != Reloc::PIC_) {
if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress))
return false;
}
// Addresses of the form FI+const or FI|const
if (CurDAG->isBaseWithConstantOffset(Addr)) {
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
if (isInt<16>(CN->getSExtValue())) {
// If the first operand is a FI, get the TargetFI Node
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
(Addr.getOperand(0)))
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
else
Base = Addr.getOperand(0);
Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
return true;
}
}
// Operand is a result from an ADD.
if (Addr.getOpcode() == ISD::ADD) {
// When loading from constant pools, load the lower address part in
// the instruction itself. Example, instead of:
// lui $2, %hi($CPI1_0)
// addiu $2, $2, %lo($CPI1_0)
// lwc1 $f0, 0($2)
// Generate:
// lui $2, %hi($CPI1_0)
// lwc1 $f0, %lo($CPI1_0)($2)
if (Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
SDValue LoVal = Addr.getOperand(1);
if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
Base = Addr.getOperand(0);
Offset = LoVal.getOperand(0);
return true;
}
}
// If an indexed floating point load/store can be emitted, return false.
if (LS && (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
Subtarget.hasMips32r2Or64())
return false;
}
Base = Addr;
Offset = CurDAG->getTargetConstant(0, ValTy);
return true;
}
/// Select multiply instructions.
std::pair<SDNode*, SDNode*>
MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
bool HasLo, bool HasHi) {
SDNode *Lo = 0, *Hi = 0;
SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
N->getOperand(1));
SDValue InFlag = SDValue(Mul, 0);
if (HasLo) {
Lo = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64, dl,
Ty, MVT::Glue, InFlag);
InFlag = SDValue(Lo, 1);
}
if (HasHi)
Hi = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64, dl,
Ty, InFlag);
return std::make_pair(Lo, Hi);
}
/// Select instructions not customized! Used for
/// expanded, promoted and normal instructions
SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
unsigned Opcode = Node->getOpcode();
DebugLoc dl = Node->getDebugLoc();
// Dump information about the Node being selected
DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
// If we have a custom node, we already have selected!
if (Node->isMachineOpcode()) {
DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
return NULL;
}
///
// Instruction Selection not handled by the auto-generated
// tablegen selection should be handled here.
///
EVT NodeTy = Node->getValueType(0);
unsigned MultOpc;
switch(Opcode) {
default: break;
case ISD::SUBE:
case ISD::ADDE: {
SDValue InFlag = Node->getOperand(2), CmpLHS;
unsigned Opc = InFlag.getOpcode(); (void)Opc;
assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
(Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
"(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
unsigned MOp;
if (Opcode == ISD::ADDE) {
CmpLHS = InFlag.getValue(0);
MOp = Mips::ADDu;
} else {
CmpLHS = InFlag.getOperand(0);
MOp = Mips::SUBu;
}
SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
SDValue LHS = Node->getOperand(0);
SDValue RHS = Node->getOperand(1);
EVT VT = LHS.getValueType();
SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
SDValue(Carry,0), RHS);
return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
LHS, SDValue(AddCarry,0));
}
/// Mul with two results
case ISD::SMUL_LOHI:
case ISD::UMUL_LOHI: {
if (NodeTy == MVT::i32)
MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
else
MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
true, true);
if (!SDValue(Node, 0).use_empty())
ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
if (!SDValue(Node, 1).use_empty())
ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
return NULL;
}
/// Special Muls
case ISD::MUL: {
// Mips32 has a 32-bit three operand mul instruction.
if (Subtarget.hasMips32() && NodeTy == MVT::i32)
break;
return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
dl, NodeTy, true, false).first;
}
case ISD::MULHS:
case ISD::MULHU: {
if (NodeTy == MVT::i32)
MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
else
MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
}
// Get target GOT address.
case ISD::GLOBAL_OFFSET_TABLE:
return getGlobalBaseReg();
case ISD::ConstantFP: {
ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
if (Subtarget.hasMips64()) {
SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
Mips::ZERO_64, MVT::i64);
return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
}
SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
Mips::ZERO, MVT::i32);
return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
Zero);
}
break;
}
case ISD::Constant: {
const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
unsigned Size = CN->getValueSizeInBits(0);
if (Size == 32)
break;
MipsAnalyzeImmediate AnalyzeImm;
int64_t Imm = CN->getSExtValue();
const MipsAnalyzeImmediate::InstSeq &Seq =
AnalyzeImm.Analyze(Imm, Size, false);
MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
DebugLoc DL = CN->getDebugLoc();
SDNode *RegOpnd;
SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
MVT::i64);
// The first instruction can be a LUi which is different from other
// instructions (ADDiu, ORI and SLL) in that it does not have a register
// operand.
if (Inst->Opc == Mips::LUi64)
RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
else
RegOpnd =
CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
ImmOpnd);
// The remaining instructions in the sequence are handled here.
for (++Inst; Inst != Seq.end(); ++Inst) {
ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
MVT::i64);
RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
SDValue(RegOpnd, 0), ImmOpnd);
}
return RegOpnd;
}
case MipsISD::ThreadPointer: {
EVT PtrVT = TLI.getPointerTy();
unsigned RdhwrOpc, SrcReg, DestReg;
if (PtrVT == MVT::i32) {
RdhwrOpc = Mips::RDHWR;
SrcReg = Mips::HWR29;
DestReg = Mips::V1;
} else {
RdhwrOpc = Mips::RDHWR64;
SrcReg = Mips::HWR29_64;
DestReg = Mips::V1_64;
}
SDNode *Rdhwr =
CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
Node->getValueType(0),
CurDAG->getRegister(SrcReg, PtrVT));
SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
SDValue(Rdhwr, 0));
SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
ReplaceUses(SDValue(Node, 0), ResNode);
return ResNode.getNode();
}
}
// Select the default instruction
SDNode *ResNode = SelectCode(Node);
DEBUG(errs() << "=> ");
if (ResNode == NULL || ResNode == Node)
DEBUG(Node->dump(CurDAG));
else
DEBUG(ResNode->dump(CurDAG));
DEBUG(errs() << "\n");
return ResNode;
}
bool MipsDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
std::vector<SDValue> &OutOps) {
assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
OutOps.push_back(Op);
return false;
}
/// createMipsISelDag - This pass converts a legalized DAG into a
/// MIPS-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
return new MipsDAGToDAGISel(TM);
}
| 35.170775 | 82 | 0.598488 | chip5441 |
08be40c8edbf4415282db7f0e44e578e09c4228f | 2,246 | cpp | C++ | code/engine.vc2008/xrGame/Level_network_messages.cpp | StalkerEz/xray-oxygen | 77f7791fa71ad08eacc1330b5441d29cd8ce79ef | [
"Apache-2.0"
] | 6 | 2020-07-06T13:34:28.000Z | 2021-07-12T10:36:23.000Z | code/engine.vc2008/xrGame/Level_network_messages.cpp | StalkerEz/xray-oxygen | 77f7791fa71ad08eacc1330b5441d29cd8ce79ef | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/Level_network_messages.cpp | StalkerEz/xray-oxygen | 77f7791fa71ad08eacc1330b5441d29cd8ce79ef | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | #include "stdafx.h"
#include "entity.h"
#include "xrserver_objects.h"
#include "level.h"
#include "xrmessages.h"
#include "net_queue.h"
#include "xrServer.h"
#include "Actor.h"
#include "Artefact.h"
#include "ai_space.h"
#include "saved_game_wrapper.h"
#include "level_graph.h"
#include "../xrphysics/iphworld.h"
#include "GamePersistent.h"
void CLevel::ClientReceive()
{
m_dwRPC = 0;
m_dwRPS = 0;
StartProcessQueue();
for (NET_Packet* P = net_msg_Retreive(); P; P=net_msg_Retreive())
{
//-----------------------------------------------------
m_dwRPC++;
m_dwRPS += (u32)P->B.count;
//-----------------------------------------------------
u16 m_type;
P->r_begin (m_type);
switch (m_type)
{
case M_SPAWN:
{
if (!bReady)
{
Msg ("! Unconventional M_SPAWN received : map_data[%s] | bReady[%s] | deny_m_spawn[%s]",
(map_data.m_map_sync_received) ? "true" : "false",
(bReady) ? "true" : "false", deny_m_spawn ? "true" : "false");
break;
}
game_events->insert (*P);
if (g_bDebugEvents) ProcessGameEvents();
}
break;
case M_EVENT: game_events->insert(*P); if (g_bDebugEvents) ProcessGameEvents(); break;
case M_EVENT_PACK:
{
NET_Packet tmpP;
while (!P->r_eof())
{
tmpP.B.count = P->r_u8();
P->r(&tmpP.B.data, tmpP.B.count);
tmpP.timeReceive = P->timeReceive;
game_events->insert (tmpP);
if (g_bDebugEvents) ProcessGameEvents();
};
}break;
case M_UPDATE:
{
game->net_import_GameTime(*P);
}break;
case M_SV_CONFIG_GAME: game->net_import_state(*P); break;
case M_LOAD_GAME:
case M_CHANGE_LEVEL:
{
if(m_type==M_LOAD_GAME)
{
string256 saved_name;
P->r_stringZ_s (saved_name);
if(xr_strlen(saved_name) && ai().get_alife())
{
CSavedGameWrapper wrapper(saved_name);
if (wrapper.level_id() == ai().level_graph().level_id())
{
Engine.Event.Defer ("Game:QuickLoad", size_t(xr_strdup(saved_name)), 0);
break;
}
}
}
MakeReconnect();
}break;
}
net_msg_Release();
}
EndProcessQueue();
if (g_bDebugEvents) ProcessGameSpawns();
}
void CLevel::OnMessage(void* data, u32 size)
{
IPureClient::OnMessage(data, size);
};
| 23.395833 | 93 | 0.599288 | StalkerEz |
08c15099d5f35ebbc591bd1b501cdfcaf03f4305 | 1,563 | cpp | C++ | source/Graphics/Windows/WindowsCpuWindow.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | source/Graphics/Windows/WindowsCpuWindow.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | source/Graphics/Windows/WindowsCpuWindow.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | #include "../include/LDL/Graphics/Windows/WindowsCpuWindow.h"
LDL::Graphics::WindowsCpuWindow::WindowsCpuWindow(const Point& pos, const Point& size, const std::string& title):
_WindowsWindow(pos, size, title)
{
}
LDL::Graphics::WindowsCpuWindow::~WindowsCpuWindow()
{
}
void LDL::Graphics::WindowsCpuWindow::Present(LDL::Graphics::Color* pixels)
{
ZeroMemory(&_BITMAPINFO, sizeof(_BITMAPINFO));
_BITMAPINFO.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
_BITMAPINFO.bmiHeader.biWidth = _WindowsWindow.Size().PosX();
_BITMAPINFO.bmiHeader.biHeight = -(int32_t)_WindowsWindow.Size().PosY();
_BITMAPINFO.bmiHeader.biPlanes = 1;
_BITMAPINFO.bmiHeader.biBitCount = 32;
_BITMAPINFO.bmiHeader.biCompression = BI_RGB;
SetDIBitsToDevice(_WindowsWindow._HDC, 0, 0, _WindowsWindow.Size().PosX(), _WindowsWindow.Size().PosY(), 0, 0, 0, _WindowsWindow.Size().PosY(), pixels, &_BITMAPINFO, DIB_RGB_COLORS);
}
const LDL::Graphics::Point& LDL::Graphics::WindowsCpuWindow::Size()
{
return _WindowsWindow.Size();
}
bool LDL::Graphics::WindowsCpuWindow::GetEvent(LDL::Events::Event& event)
{
return _WindowsWindow.GetEvent(event);
}
void LDL::Graphics::WindowsCpuWindow::StopEvent()
{
_WindowsWindow.StopEvent();
}
const std::string& LDL::Graphics::WindowsCpuWindow::Title()
{
return _WindowsWindow.Title();
}
void LDL::Graphics::WindowsCpuWindow::Title(const std::string& title)
{
_WindowsWindow.Title(title);
}
bool LDL::Graphics::WindowsCpuWindow::Ok()
{
return _WindowsWindow.Ok();
} | 28.944444 | 186 | 0.723608 | JordanCpp |
08c25cdf19274a6fa452a1e0267b31430639acf8 | 1,475 | cpp | C++ | Scheduler/main.cpp | maxkofler/AVRScheduler | 122a3138ba2536dc383a6eb4d560551df05cd37f | [
"Apache-2.0"
] | null | null | null | Scheduler/main.cpp | maxkofler/AVRScheduler | 122a3138ba2536dc383a6eb4d560551df05cd37f | [
"Apache-2.0"
] | null | null | null | Scheduler/main.cpp | maxkofler/AVRScheduler | 122a3138ba2536dc383a6eb4d560551df05cd37f | [
"Apache-2.0"
] | null | null | null | /*
* Scheduler.cpp
*
* Created: 01.06.2021 19:57:05
* Author : Kofle
*/
#include <avr/io.h>
#include "scheduler.h"
#include <avr/interrupt.h>
void proc1();
void proc2();
void sleep(int ms);
#define F_CPU 16000000
#define sl_12 1
#define sl_13 150
ISR (TIMER1_OVF_vect) // Timer1 ISR
{
asm volatile("pop r29");
asm volatile("pop r28");
asm volatile("pop r0");
asm volatile("sts 0x005f, r0");
asm volatile("pop r0");
asm volatile("pop r1");
//Jump to scheduler switch command. You CAN do stuff before this, but clean the stack!!!
asm volatile("push r25");
asm volatile("ldi r25, 1");
asm volatile("jmp scheduler_switch");
}
int main()
{
DDRB = 0xFF;
cli();
scheduler_init(0x03, 0x200);
scheduler_new_process(proc1, 0x200);
scheduler_new_process(proc2, 0x200);
TCCR1A = 0x00; //No pin connections for this timer
TCCR1B = (1<<CS12);; //No prescaler
TIMSK1 = (1 << TOV1) ; //Timer1 on every 16-bit overflow
asm volatile("push r25");
asm volatile("ldi r25, 1");
asm volatile("jmp scheduler_switch");
sei();
int a = 0;
asm volatile("ldi r29, 0xFF");
asm volatile("push r29");
while(1)
{
;
}
}
void proc1(){
int b = 0;
while(1){
PORTB |= (1 << PB7);
sleep(sl_13);
PORTB &= ~(1 << PB7);
sleep(sl_13);
}
}
void proc2(){
int b = 0;
while(1){
PORTB |= (1 << PB6);
sleep(sl_12);
PORTB &= ~(1 << PB6);
sleep(sl_12);
}
}
void sleep(int ms){
long its = ms*(F_CPU/1000)/100;
for (long i = 0; i < its; i++);
} | 17.352941 | 89 | 0.623051 | maxkofler |
08c337c585adafd686ae293be516c148f1237d56 | 1,277 | hpp | C++ | rt/include/spiral/fun.hpp | honzasp/spiral | ed506c02aa90a248799f6b84fb0de19ad6f396ab | [
"Unlicense"
] | 3 | 2018-01-11T07:30:41.000Z | 2019-09-19T04:40:59.000Z | rt/include/spiral/fun.hpp | honzasp/spiral | ed506c02aa90a248799f6b84fb0de19ad6f396ab | [
"Unlicense"
] | null | null | null | rt/include/spiral/fun.hpp | honzasp/spiral | ed506c02aa90a248799f6b84fb0de19ad6f396ab | [
"Unlicense"
] | null | null | null | #ifndef HAVE_spiral_fun_hpp
#define HAVE_spiral_fun_hpp
#include "spiral/core.hpp"
namespace spiral {
struct FunObj {
const ObjTable* otable;
void* fun_addr;
Val captures[0];
};
struct FunTable {
uint32_t slot_count;
uint32_t arg_count;
uint32_t capture_count;
const char* fun_name;
uint8_t padding_0[16];
};
auto fun_from_val(Bg* bg, Val val) -> FunObj*;
auto fun_from_obj_ptr(void* obj_ptr) -> FunObj*;
auto fun_to_val(FunObj* fun) -> Val;
auto fun_table_from_addr(void* fun_addr) -> const FunTable*;
void fun_stringify(Bg* bg, Buffer* buf, void* obj_ptr);
auto fun_length(void* obj_ptr) -> uint32_t;
auto fun_evacuate(GcCtx* gc_ctx, void* obj_ptr) -> Val;
void fun_scavenge(GcCtx* gc_ctx, void* obj_ptr);
void fun_drop(Bg* bg, void* obj_ptr);
auto fun_eqv(Bg* bg, void* l_ptr, void* r_ptr) -> bool;
auto fun_addr_call(Bg* bg, const void* fun_addr, void* last_sp) -> Val;
void panic_invalid_fun(Bg* bg, uint32_t val);
void panic_argc_mismatch(Bg* bg, void* fun_addr,
uint32_t expected_argc_, uint32_t received_argc_);
extern const ObjTable fun_otable;
extern "C" {
auto spiral_rt_alloc_closure(Bg* bg, void* sp, void* fun_addr,
uint32_t capture_count) -> uint32_t;
}
}
#endif
| 28.377778 | 73 | 0.700861 | honzasp |
08c68e4ed61c47c638f9dfd7d6f16ab481b5a207 | 27,308 | cpp | C++ | propcov/lib/propcov-cpp/Spacecraft.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 4 | 2021-12-23T16:49:06.000Z | 2022-02-09T21:36:31.000Z | propcov/lib/propcov-cpp/Spacecraft.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 15 | 2022-01-14T17:28:14.000Z | 2022-02-11T02:39:25.000Z | propcov/lib/propcov-cpp/Spacecraft.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 1 | 2022-02-03T15:44:16.000Z | 2022-02-03T15:44:16.000Z | //------------------------------------------------------------------------------
// Spacecraft
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2017 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Author: Wendy Shoan, NASA/GSFC
// Created: 2016.05.02
//
/**
* Implementation of the Spacecraft class.
*/
//------------------------------------------------------------------------------
#include "gmatdefs.hpp"
#include "Spacecraft.hpp"
#include "TATCException.hpp"
#include "MessageInterface.hpp"
#include "AttitudeConversionUtility.hpp"
#include "GmatConstants.hpp"
#include <iostream>
//#define DEBUG_STATES
//#define DEBUG_CAN_INTERPOLATE
//------------------------------------------------------------------------------
// static data
//------------------------------------------------------------------------------
// None
//------------------------------------------------------------------------------
// public methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Spacecraft(AbsoluteDate *epoch, OrbitState *state, Attitude *att,
// LagrangeInterpolator *interp,
// Real angle1, Real angle2, Real angle3,
// Integer seq1, Integer seq2, Integer seq3)
//------------------------------------------------------------------------------
/**
* Default constructor for Spacecraft.
*
* @param epoch The orbit epoch object
* @param state The orbit state object
* @param att The attitude object
* @param interp The LagrangeInterpolator
* @param angle1 The euler angle 1 (degrees)
* @param angle2 The euler angle 2 (degrees)
* @param angle3 The euler angle 3 (degrees)
* @param seq1 Euler sequence 1
* @param seq2 Euler sequence 2
* @param seq3 Euler sequence 3
*
*/
//------------------------------------------------------------------------------
Spacecraft::Spacecraft(AbsoluteDate *epoch, OrbitState *state, Attitude *att,
LagrangeInterpolator *interp,
Real angle1, Real angle2, Real angle3,
Integer seq1, Integer seq2, Integer seq3) :
dragCoefficient (2.0),
dragArea (2.0),
totalMass (200.0),
orbitState (state),
orbitEpoch (epoch),
numSensors (0),
attitude (att),
interpolator (interp)
{
// sensorList is empty at start
// R_BN is identity at start
offsetAngle1 = angle1;
offsetAngle2 = angle2;
offsetAngle3 = angle3;
eulerSeq1 = seq1;
eulerSeq2 = seq2;
eulerSeq3 = seq3;
ComputeNadirToBodyMatrix();
}
//------------------------------------------------------------------------------
// Spacecraft(const Spacecraft ©)
//------------------------------------------------------------------------------
/**
* Copy constructor for Spacecraft.
*
* @param copy The spacecraft of which to create a copy
*
*/
//------------------------------------------------------------------------------
Spacecraft::Spacecraft(const Spacecraft ©) :
dragCoefficient (copy.dragCoefficient),
dragArea (copy.dragArea),
totalMass (copy.totalMass),
orbitState ((copy.orbitState)->Clone()),
orbitEpoch ((copy.orbitEpoch)->Clone()),
numSensors (copy.numSensors),
offsetAngle1 (copy.offsetAngle1),
offsetAngle2 (copy.offsetAngle2),
offsetAngle3 (copy.offsetAngle3),
eulerSeq1 (copy.eulerSeq1),
eulerSeq2 (copy.eulerSeq2),
eulerSeq3 (copy.eulerSeq3),
R_BN (copy.R_BN)
{
if (copy.numSensors > 0)
{
sensorList.clear();
for (Integer ii = 0; ii < copy.numSensors; ii++)
sensorList.push_back(copy.sensorList.at(ii));
}
if (copy.interpolator)
{
interpolator = (LagrangeInterpolator*) (copy.interpolator)->Clone();
}
if (copy.attitude)
{
attitude = (Attitude*) (copy.attitude)->Clone();
}
}
//------------------------------------------------------------------------------
// Spacecraft& operator=(const Spacecraft ©)
//------------------------------------------------------------------------------
/**
* operator= for Spacecraft.
*
* @param copy The spacecraft whose values to copy
*
*/
//------------------------------------------------------------------------------
Spacecraft& Spacecraft::operator=(const Spacecraft ©)
{
if (© == this)
return *this;
dragCoefficient = copy.dragCoefficient;
dragArea = copy.dragArea;
totalMass = copy.totalMass;
orbitState = (copy.orbitState)->Clone(); // Clone these?
orbitEpoch = (copy.orbitEpoch)->Clone(); // Clone these?
numSensors = copy.numSensors;
offsetAngle1 = copy.offsetAngle1;
offsetAngle2 = copy.offsetAngle2;
offsetAngle3 = copy.offsetAngle3;
eulerSeq1 = copy.eulerSeq1;
eulerSeq2 = copy.eulerSeq2;
eulerSeq3 = copy.eulerSeq3;
R_BN = copy.R_BN;
sensorList.clear();
for (Integer ii = 0; ii < copy.numSensors; ii++)
sensorList.push_back(copy.sensorList.at(ii));
if (copy.interpolator)
{
interpolator = (LagrangeInterpolator*) (copy.interpolator)->Clone();
}
if (copy.attitude)
{
attitude = (Attitude*) (copy.attitude)->Clone();
}
return *this;
}
//------------------------------------------------------------------------------
// ~Spacecraft()
//------------------------------------------------------------------------------
/**
* destructor for Spacecraft.
*
*/
//------------------------------------------------------------------------------
Spacecraft::~Spacecraft()
{
// VInay: commented out to make it work with pybind11
/*
if (orbitState)
delete orbitState;
if (orbitEpoch)
delete orbitEpoch;
if (interpolator)
delete interpolator;
if (attitude)
delete attitude;
*/
}
//------------------------------------------------------------------------------
// OrbitState* GetOrbitState()
//------------------------------------------------------------------------------
/**
* Returns a pointer to the Spacecraft's OrbitState object.
*
* @return pointer to the spacecraft's OrbitState
*
*/
//------------------------------------------------------------------------------
OrbitState* Spacecraft::GetOrbitState()
{
return orbitState;
}
//------------------------------------------------------------------------------
// AbsoluteDate* GetOrbitEpoch()
//------------------------------------------------------------------------------
/**
* Returns a pointer to the Spacecraft's AbsoluteDate object.
*
* @return pointer to the spacecraft's AbsoluteDate
*
*/
//------------------------------------------------------------------------------
AbsoluteDate* Spacecraft::GetOrbitEpoch()
{
return orbitEpoch;
}
//------------------------------------------------------------------------------
// Real GetJulianDate()
//------------------------------------------------------------------------------
/**
* Returns the Spacecraft's Julian Date at Epoch.
*
* @return Spacecraft's JulianDate
*
*/
//------------------------------------------------------------------------------
Real Spacecraft::GetJulianDate()
{
return orbitEpoch->GetJulianDate();
}
//------------------------------------------------------------------------------
// Attitude GetAttitude()
//------------------------------------------------------------------------------
/**
* Returns the Spacecraft's attitude.
*
* @return Spacecraft's attitude
*
*/
//------------------------------------------------------------------------------
Attitude* Spacecraft::GetAttitude()
{
return attitude;
}
//------------------------------------------------------------------------------
// Rvector6 GetCartesianState()
//------------------------------------------------------------------------------
/**
* Returns the Spacecraft's cartesian state.
*
* @return Spacecraft's cartesian state
*
*/
//------------------------------------------------------------------------------
Rvector6 Spacecraft::GetCartesianState()
{
return orbitState->GetCartesianState();
}
//------------------------------------------------------------------------------
// Rvector6 GetKeplerianState()
//------------------------------------------------------------------------------
/**
* Returns the Spacecraft's cartesian state. Author: Vinay.
*
* @return Spacecraft's cartesian state
*
*/
//------------------------------------------------------------------------------
Rvector6 Spacecraft::GetKeplerianState()
{
return orbitState->GetKeplerianState();
}
//------------------------------------------------------------------------------
// void AddSensor(Sensor* sensor)
//------------------------------------------------------------------------------
/**
* Adds the input sensor to the Spacecraft's sensor list.
*
* @param sensor Sensor to add to the list
*
*/
//------------------------------------------------------------------------------
void Spacecraft::AddSensor(Sensor* sensor)
{
/// @todo - check for sensor already on list!!
sensorList.push_back(sensor);
numSensors++;
}
//------------------------------------------------------------------------------
// bool HasSensors()
//------------------------------------------------------------------------------
/**
* Returns a flag indicating whether or not the spacecraft has sensors.
*
* @return flag indicating whether or not the spacecraft has sensors.
*
*/
//------------------------------------------------------------------------------
bool Spacecraft::HasSensors()
{
return (numSensors > 0);
}
//------------------------------------------------------------------------------
// void SetDragArea(Real area)
//------------------------------------------------------------------------------
/**
* Sets the Spacecraft's drag area.
*
* @param the drag area in m^2
*
*/
//------------------------------------------------------------------------------
void Spacecraft::SetDragArea(Real area)
{
dragArea = area;
}
//------------------------------------------------------------------------------
// void SetDragCoefficient(Real Cr)
//------------------------------------------------------------------------------
/**
* Sets the Spacecraft's drag coefficient.
*
* @param the drag coefficient
*
*/
//------------------------------------------------------------------------------
void Spacecraft::SetDragCoefficient(Real Cd)
{
dragCoefficient = Cd;
}
//------------------------------------------------------------------------------
// void SetTotalMass(Real mass);
//------------------------------------------------------------------------------
/**
* Sets the Spacecraft's total mass.
*
* @param the total mass
*
*/
//------------------------------------------------------------------------------
void Spacecraft::SetTotalMass(Real mass)
{
totalMass = mass;
}
//------------------------------------------------------------------------------
// void SetAttitude(Attitude *att)
//------------------------------------------------------------------------------
/**
* Sets the Spacecraft's attitude object
*
* @param att the attitude object
*
*/
//------------------------------------------------------------------------------
void Spacecraft::SetAttitude(Attitude *att)
{
attitude = att;
}
//------------------------------------------------------------------------------
// Real GetDragArea()
//------------------------------------------------------------------------------
/**
* Gets the Spacecraft's drag area.
*
* @return the drag area in m^2
*
*/
//------------------------------------------------------------------------------
Real Spacecraft::GetDragArea()
{
return dragArea;
}
//------------------------------------------------------------------------------
// Real GetDragCoefficient()
//------------------------------------------------------------------------------
/**
* Gets the Spacecraft's drag coefficient.
*
* @return the drag coefficient
*
*/
//------------------------------------------------------------------------------
Real Spacecraft::GetDragCoefficient()
{
return dragCoefficient;
}
//------------------------------------------------------------------------------
// Real GetTotalMass();
//------------------------------------------------------------------------------
/**
* Gets the Spacecraft's total mass.
*
* @return the total mass
*
*/
//------------------------------------------------------------------------------
Real Spacecraft::GetTotalMass()
{
return totalMass;
}
//------------------------------------------------------------------------------
// Rvector6 GetCartesianStateAtEpoch(const AbsoluteDate &atDate)
//------------------------------------------------------------------------------
/**
* Gets the Spacecraft's cartesian state (Earth MJ2000Eq) at the input time
*
* @param atDate the date for which to get the cartesian state
*
* @return state
*
*/
//------------------------------------------------------------------------------
Rvector6 Spacecraft::GetCartesianStateAtEpoch(const AbsoluteDate &atDate)
{
return Interpolate(atDate.GetJulianDate());
}
//------------------------------------------------------------------------------
// bool CheckTargetVisibility(Real targetConeAngle,
// Real targetClockAngle,
// Integer sensorNumber)
//------------------------------------------------------------------------------
/**
* Returns a flag indicating whether or not the point is within the
*
* @param targetConeAngle the cone angle
* @param targetClockAngle the clock angle
* @param sensorNumber sensor for which to check target visibility
*
* @return true if point is visible, false otherwise
*
*/
//------------------------------------------------------------------------------
bool Spacecraft::CheckTargetVisibility(Real targetConeAngle,
Real targetClockAngle,
Integer sensorNumber)
{
if (numSensors == 0)
{
throw TATCException("ERROR - Spacecraft has no sensors\n");
}
if ((sensorNumber < 0) || (sensorNumber >= numSensors))
throw TATCException(
"ERROR - sensor number out-of-bounds in Spacecraft\n");
return sensorList.at(sensorNumber)->CheckTargetVisibility(targetConeAngle,
targetClockAngle);
}
//------------------------------------------------------------------------------
// bool CheckTargetVisibility(const Rvector6 &bodyFixedState,
// const Rvector3 &satToTargetVec,
// Real atTime,
// Integer sensorNumber)
//------------------------------------------------------------------------------
/**
* Returns a flag indicating whether or not the point is within the
* visible to the sensor at the given time, given the satToTargetVec.
*
* @param bodyFixedState input body fixed state
* @param satToTargetVec spacecraft-to-target vector
* @param atTime time for which to check the target visibility
* @param sensorNumber sensor for which to check target visibility
*
* @return true if point is visible, false otherwise
*
*/
//------------------------------------------------------------------------------
bool Spacecraft::CheckTargetVisibility(const Rvector6 &bodyFixedState,
const Rvector3 &satToTargetVec,
Real atTime,
Integer sensorNumber)
{
// VINAY: Error? R_NI here may actually be the rotation matrix from Earth-Fixed to Nadir. Correspondingly GetBodyFixedToInertial() must be named as `GetBodyFixedToReference`?
// where BodyFixed refers to EarthFixed and Reference refers to Nadir.
Rmatrix33 R_NI = GetBodyFixedToInertial(bodyFixedState);
Rvector3 satToTarget_Sensor = // Vinay: satToTarget_Sensor is vector in Sensor frame
sensorList.at(sensorNumber)->GetBodyToSensorMatrix(atTime) *
(R_BN * (R_NI * satToTargetVec));
Real cone, clock;
InertialToConeClock(satToTarget_Sensor, cone, clock);
return CheckTargetVisibility(cone, clock, sensorNumber);
}
//------------------------------------------------------------------------------
// Rmatrix33 GetBodyFixedToInertial(const Rvector6 &bfState)
//------------------------------------------------------------------------------
/**
* Returns the bodyfixed-to-inertial matrix, given the input state
*
* @param bfState body-fixed state
*
* @return bodyfixed-to-inertial matrix
*
*/
//------------------------------------------------------------------------------
Rmatrix33 Spacecraft::GetBodyFixedToInertial(const Rvector6 &bfState) // Vinay: Error? Should be GetBodyFixedtoReference, where BodyFixed in EarthFixed and Reference would become Nadir.
{
return attitude->InertialToReference(bfState); // misnamed??
}
/// Author: Vinay, Adapted from Spacecraft::GetBodyFixedToInertial(const Rvector6 &bfState)
Rmatrix33 Spacecraft::GetBodyFixedToReference(const Rvector6 &bfState)
{
return attitude->BodyFixedToReference(bfState); // misnamed??
}
//------------------------------------------------------------------------------
// bool SetOrbitState(const AbsoluteDate &t,
// const Rvector6 &kepl)
//------------------------------------------------------------------------------
/**
* Sets the orbit state on the Spacecraft
*
* @param t input time
* @param kepl input keplerian elements
*
* @return true if set; false otherwise
*
*/
//------------------------------------------------------------------------------ @TODO: Vinay: Set date also?
bool Spacecraft::SetOrbitState(const AbsoluteDate &t,
const Rvector6 &kepl)
{
if (!interpolator)
throw TATCException(
"Cannot interpolate - no interpolator set on spacecraft\n");
// Set the state on the Spacecraft's orbitState parameter
orbitState->SetKeplerianVectorState(kepl);
// pass data to the interpolator, in Cartesian state
Rvector6 cart = orbitState->GetCartesianState();
#ifdef DEBUG_STATES
MessageInterface::ShowMessage(
"About to set date and state on the interpolator:\n");
MessageInterface::ShowMessage("date: %12.10f\n", t.GetJulianDate());
for (Integer ii = 0; ii < 6; ii++)
MessageInterface::ShowMessage(" %12.10f\n", cart[ii]);
#endif
Real cartReal[6];
for (Integer ii = 0; ii < 6; ii++)
cartReal[ii] = cart[ii];
interpolator->AddPoint(t.GetJulianDate(), cartReal);
return true;
}
// Author: Vinay: Similar to the SetOrbitState(.) function, except that date is also set.
bool Spacecraft::SetOrbitStateCartesian(const AbsoluteDate &t,
const Rvector6 &cart)
{
if (!interpolator)
throw TATCException(
"Cannot interpolate - no interpolator set on spacecraft\n");
// Set the state on the Spacecraft's orbitState parameter
orbitEpoch->SetJulianDate(t.GetJulianDate()); // Vinay: Added by me
orbitState->SetCartesianState(cart);
#ifdef DEBUG_STATES
MessageInterface::ShowMessage(
"About to set date and state on the interpolator:\n");
MessageInterface::ShowMessage("date: %12.10f\n", t.GetJulianDate());
for (Integer ii = 0; ii < 6; ii++)
MessageInterface::ShowMessage(" %12.10f\n", cart[ii]);
#endif
Real cartReal[6];
for (Integer ii = 0; ii < 6; ii++)
cartReal[ii] = cart[ii];
interpolator->AddPoint(t.GetJulianDate(), cartReal);
return true;
}
//------------------------------------------------------------------------------
// void SetBodyNadirOffsetAngles(Real angle1, Real angle2, Real angle3,
// Integer seq1, Integer seq2,
// Integer seq3)
//------------------------------------------------------------------------------
/**
* Sets the body nadir offset angles
*
* @param angle1 euler angle 1 (degrees)
* @param angle2 euler angle 2 (degrees)
* @param angle3 euler angle 3 (degrees)
* @param seq1 euler msequence 1
* @param seq2 euler msequence 2
* @param seq3 euler msequence 3
*
*/
//------------------------------------------------------------------------------
void Spacecraft::SetBodyNadirOffsetAngles(Real angle1, Real angle2, Real angle3,
Integer seq1, Integer seq2,
Integer seq3)
{
offsetAngle1 = angle1;
offsetAngle2 = angle2;
offsetAngle3 = angle3;
eulerSeq1 = seq1;
eulerSeq2 = seq2;
eulerSeq3 = seq3;
ComputeNadirToBodyMatrix();
}
//------------------------------------------------------------------------------
// bool CanInterpolate(Real atTime)
//------------------------------------------------------------------------------
/**
* Can the orbit be interpolated (is it feasible given the number of points,
* etc.?)
*
* @param atTime input time
* @param checkRange check the range to see if we need to interpolate
*
* @return true if interpolation is feasible; false otherwise
*
*/
//------------------------------------------------------------------------------
bool Spacecraft::CanInterpolate(Real atTime)
{
if (!interpolator)
return false;
Integer canInterp = interpolator->IsInterpolationFeasible(atTime);
#ifdef DEBUG_CAN_INTERPOLATE
MessageInterface::ShowMessage(" ----- canInterp = %d\n",
canInterp);
Real lower, upper;
interpolator->GetRange(lower, upper);
MessageInterface::ShowMessage(" lower, upper = %12.10f %12.10f\n",
lower, upper);
#endif
if (canInterp != 1)
return false;
return true;
}
//------------------------------------------------------------------------------
// bool TimeToInterpolate(Real atTime, Real &midRange)
//------------------------------------------------------------------------------
/**
* Get the midpoint time to interpolate to, if
*
* @param atTime [in] input time
* @param midRange [out] middle of the interpolation range size
*
* @return true if interpolation should be performed at the input time;
* false otherwise
*/
//------------------------------------------------------------------------------
bool Spacecraft::TimeToInterpolate(Real atTime, Real &midRange)
{
if (!CanInterpolate(atTime))
return false;
Real lower, upper;
interpolator->GetRange(lower, upper);
midRange = (upper - lower) / 2.0;
#ifdef DEBUG_CAN_INTERPOLATE
MessageInterface::ShowMessage(" ----- midRange = %12.10f\n",
midRange);
#endif
return true;
}
//------------------------------------------------------------------------------
// Rvector6 Interpolate(Real toTime)
//------------------------------------------------------------------------------
/**
* Interpolate the orbit data at the input time
*
* @param atTime input time
*
* @return interpolated state data
*
*/
//------------------------------------------------------------------------------
Rvector6 Spacecraft::Interpolate(Real toTime)
{
Rvector6 theResults;
Real interpResults[6];
for (Integer ii = 0; ii < 6; ii++)
interpResults[ii] = 0.0;
if (!interpolator)
throw TATCException(
"Cannot interpolate - no GMAT interpolator set on spacecraft\n");
if (!CanInterpolate(toTime))
throw TATCException(
"Cannot interpolate - interpolator does not have enough data\n");
bool isInterpolated = interpolator->Interpolate(toTime, interpResults);
#ifdef DEBUG_STATES
if (!isInterpolated)
MessageInterface::ShowMessage(" ---- did not interpolate!!!!!!!\n");
#endif
theResults.Set(interpResults);
#ifdef DEBUG_STATES
MessageInterface::ShowMessage("Results:\n"); // ***
for (Integer ii = 0; ii < 6; ii++)
MessageInterface::ShowMessage(" %12.10f\n", theResults[ii]);
#endif
return theResults;
}
//------------------------------------------------------------------------------
// protected methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// void InertialToConeClock(const Rvector3 &viewVec,
// Real &cone, Real &clock)
//------------------------------------------------------------------------------
/**
* Computes the rotation matrix from the body frame to the sensor frame.
*
* @param viewVec [in] input view vector
* @param cone [out] cone angle
* @param clock [out] clock angle
*
*/
//------------------------------------------------------------------------------
void Spacecraft::InertialToConeClock(const Rvector3 &viewVec,
Real &cone,
Real &clock)
{
Real targetDEC = GmatMathUtil::ASin(viewVec(2) / viewVec.GetMagnitude());
cone = GmatMathConstants::PI_OVER_TWO - targetDEC;
clock = GmatMathUtil::ATan2(viewVec(1), viewVec(0));
}
//------------------------------------------------------------------------------
// void ComputeBodyToSensorMatrix()
//------------------------------------------------------------------------------
/**
* Computes the rotation matrix from the body frame to the sensor frame.
*/
//---------------------------------------------------------------------------
void Spacecraft::ComputeNadirToBodyMatrix()
{
Rvector3 angles(offsetAngle1 * GmatMathConstants::RAD_PER_DEG,
offsetAngle2 * GmatMathConstants::RAD_PER_DEG,
offsetAngle3 * GmatMathConstants::RAD_PER_DEG);
R_BN = AttitudeConversionUtility::ToCosineMatrix(angles, eulerSeq1,
eulerSeq2, eulerSeq3);
}
Rmatrix33 Spacecraft::GetNadirToBodyMatrix(){
return R_BN;
}
| 33.922981 | 185 | 0.454299 | EarthObservationSimulator |
08c804512a8249c8bf55bd060a50b5315159a412 | 709 | cpp | C++ | tests/format-io-tests/molality-tests/molality-tests.cpp | LoliGothick/mitama-dimensional | 46b9ae3764bd472da9ed5372afd82e6b5d542543 | [
"MIT"
] | 34 | 2019-01-18T11:51:02.000Z | 2021-09-17T02:46:43.000Z | tests/format-io-tests/molality-tests/molality-tests.cpp | LoliGothick/mitama-dimensional | 46b9ae3764bd472da9ed5372afd82e6b5d542543 | [
"MIT"
] | 11 | 2019-02-10T23:12:07.000Z | 2019-05-06T21:05:09.000Z | tests/format-io-tests/molality-tests/molality-tests.cpp | LoliGothick/mitama-dimensional | 46b9ae3764bd472da9ed5372afd82e6b5d542543 | [
"MIT"
] | 5 | 2019-02-27T11:53:20.000Z | 2021-03-20T21:59:59.000Z | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <mitama/dimensional/systems/si/derived_units/molality.hpp>
#include <mitama/dimensional/systems/si/quantity.hpp>
#include "../format_io_common.hpp"
TEST_CASE("molality format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molality_t{}) == "1 [mol/kg]");
}
TEST_CASE("molality quantifier format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molality) == "1 [mol/kg]");
}
TEST_CASE("molality type test", "[quantity][abbreviation]") {
REQUIRE(mitama::is_same_dimensional_v<std::decay_t<decltype(1|systems::si::molality)>, mitama::systems::si::quantity_t<std::decay_t<decltype(kilogram<-1>*mol<>)>>>);
}
| 44.3125 | 167 | 0.726375 | LoliGothick |
08c88e5fda9f8ccdb2a6d1132f16ab8aaf1b94a0 | 3,062 | cpp | C++ | contrib/opensigcomp/src/test/test_osc_ReadWriteLockable.cpp | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | contrib/opensigcomp/src/test/test_osc_ReadWriteLockable.cpp | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | contrib/opensigcomp/src/test/test_osc_ReadWriteLockable.cpp | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | /* ***********************************************************************
Open SigComp -- Implementation of RFC 3320 Signaling Compression
Copyright 2005 Estacado Systems, LLC
Your use of this code is governed by the license under which it
has been provided to you. Unless you have a written and signed
document from Estacado Systems, LLC stating otherwise, your license
is as provided by the GNU General Public License version 2, a copy
of which is available in this project in the file named "LICENSE."
Alternately, a copy of the licence is available by writing to
the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02110-1307 USA
Unless your use of this code is goverened by a written and signed
contract containing provisions to the contrary, this program is
distributed WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY of FITNESS FOR A PARTICULAR PURPOSE. See the
license for additional details.
To discuss alternate licensing terms, contact info@estacado.net
*********************************************************************** */
#include <iostream>
#ifdef USE_POSIX_LOCKING
#include <pthread.h>
#include <unistd.h>
#include "ReadWriteLockable.h"
#include "TestList.h"
class TestRWLock : public osc::ReadWriteLockable {};
static TestRWLock *rwlock;
static int value;
static void *increment(void *arg)
{
rwlock->writeLock();
value++;
rwlock->unlock();
return 0;
}
static void *check(void *arg)
{
rwlock->readLock();
int val = value;
rwlock->unlock();
return (void *)(val);
}
bool test_osc_ReadWriteLockable()
{
rwlock = new TestRWLock();
value = 0;
int status;
pthread_t t1, t2, t3;
void *result;
// Check read lock interaction with write lock.
rwlock->readLock();
status = pthread_create(&t1, 0, increment, 0);
TEST_ASSERT_EQUAL(status, 0);
sched_yield();
usleep(20);
TEST_ASSERT_EQUAL(value, 0);
rwlock->unlock();
sched_yield();
usleep(20);
TEST_ASSERT_EQUAL(value, 1);
TEST_ASSERT_EQUAL(status, 0);
status = pthread_join(t1, &result);
TEST_ASSERT_EQUAL(((int)(result)),0);
// Check precidence of read versus write lock
rwlock->writeLock();
status = pthread_create(&t1, 0, increment, 0);
TEST_ASSERT_EQUAL(status, 0);
status = pthread_create(&t2, 0, check, 0);
TEST_ASSERT_EQUAL(status, 0);
status = pthread_create(&t3, 0, check, 0);
TEST_ASSERT_EQUAL(status, 0);
sched_yield();
usleep(20);
TEST_ASSERT_EQUAL(value, 1);
rwlock->unlock();
sched_yield();
usleep(20);
status = pthread_join(t1, &result);
TEST_ASSERT_EQUAL(((int)(result)),0);
TEST_ASSERT_EQUAL(value, 2);
status = pthread_join(t2, &result);
TEST_ASSERT_EQUAL(((int)(result)),2);
status = pthread_join(t3, &result);
TEST_ASSERT_EQUAL(((int)(result)),2);
delete rwlock;
return true;
}
static bool ReadWriteLockableTestInitStatus =
osc::TestList::instance()->addTest(test_osc_ReadWriteLockable,
"test_osc_ReadWriteLockable");
#endif
| 28.091743 | 75 | 0.676682 | dulton |
c0941f5596bbe947a367cb3df6a777e5ab9e4acf | 841 | cpp | C++ | euler076.cpp | suihan74/ProjectEuler | 0ccd2470206a606700ab5c2a7162b2a3d3de2f8d | [
"MIT"
] | null | null | null | euler076.cpp | suihan74/ProjectEuler | 0ccd2470206a606700ab5c2a7162b2a3d3de2f8d | [
"MIT"
] | null | null | null | euler076.cpp | suihan74/ProjectEuler | 0ccd2470206a606700ab5c2a7162b2a3d3de2f8d | [
"MIT"
] | null | null | null | /**
* Problem 76 「和の数え上げ」
* 5は数の和として6通りに書くことができる:
*
* 4 + 1
* 3 + 2
* 3 + 1 + 1
* 2 + 2 + 1
* 2 + 1 + 1 + 1
* 1 + 1 + 1 + 1 + 1
*
* 2つ以上の正整数の和としての100の表し方は何通りか.
*/
#include <array>
#include <cstdint>
#include <iostream>
using uInt = std::uint_fast64_t;
// 類題: Problem 31 「硬貨の和」
// -> e076では,硬貨が 1,2,...,99 で,これを足し合わせて100を作る問題と捉えることができる
/**
* https://ja.wikipedia.org/wiki/分割数
* k > n のとき: p(k, n) = 0
* k = n のとき: p(k, n) = 1
* それ以外: p(k, n) = p(k+1, n) + p(k, n − k)
* p(n) = Σp(k,n); k=1~n
* 求めるものはp(n)-1 (n+0のケースを含めない)
*/
int main(void)
{
constexpr uInt TARGET = 100;
std::array<uInt, TARGET + 1> memo = {1};
for (uInt n = 1; n < TARGET; n++) {
for (uInt i = n; i <= TARGET; i++) {
memo.at(i) += memo.at(i - n);
}
}
std::cout << "Euler076: " << memo.at(TARGET) << std::endl;
return 0;
}
| 18.282609 | 60 | 0.51962 | suihan74 |
c0956a1b2bcc20bb25c68a54d25ecc618f41ba7e | 2,796 | cpp | C++ | src/animation/property_animation.cpp | santaclose/LumixEngine | f163e673d7ebc451c134db8d2fbb55ac38962137 | [
"MIT"
] | 3,112 | 2015-01-15T20:19:35.000Z | 2022-03-31T15:16:27.000Z | src/animation/property_animation.cpp | santaclose/LumixEngine | f163e673d7ebc451c134db8d2fbb55ac38962137 | [
"MIT"
] | 996 | 2015-01-02T22:19:35.000Z | 2022-03-20T09:57:46.000Z | src/animation/property_animation.cpp | santaclose/LumixEngine | f163e673d7ebc451c134db8d2fbb55ac38962137 | [
"MIT"
] | 445 | 2015-08-22T14:24:37.000Z | 2022-03-25T08:42:07.000Z | #include "animation/property_animation.h"
#include "engine/crc32.h"
#include "engine/allocator.h"
#include "engine/log.h"
#include "engine/lua_wrapper.h"
#include "engine/reflection.h"
#include "engine/stream.h"
namespace Lumix {
const ResourceType PropertyAnimation::TYPE("property_animation");
PropertyAnimation::PropertyAnimation(const Path& path, ResourceManager& resource_manager, IAllocator& allocator)
: Resource(path, resource_manager, allocator)
, m_allocator(allocator)
, fps(30)
, curves(allocator)
{
}
PropertyAnimation::Curve& PropertyAnimation::addCurve()
{
return curves.emplace(m_allocator);
}
bool PropertyAnimation::save(OutputMemoryStream& blob) {
if (!isReady()) return false;
for (Curve& curve : curves) {
blob << "curve {\n";
blob << "\t component = \"" << reflection::getComponent(curve.cmp_type)->name << "\",\n";
blob << "\t property = \"" << curve.property->name << "\",\n";
blob << "\tkeyframes = {\n";
for (int i = 0; i < curve.frames.size(); ++i) {
if (i != 0) blob << ", ";
blob << curve.frames[i];
}
blob << "},\n";
blob << "\tvalues = {\n";
for (int i = 0; i < curve.values.size(); ++i) {
if (i != 0) blob << ", ";
blob << curve.values[i];
}
blob << "}\n}\n\n";
}
return true;
}
void PropertyAnimation::LUA_curve(lua_State* L) {
LuaWrapper::DebugGuard guard(L);
LuaWrapper::checkTableArg(L, 1);
const char* cmp_name;
const char* prop_name;
if (!LuaWrapper::checkField<const char*>(L, 1, "component", &cmp_name)) {
luaL_argerror(L, 1, "`component` field must be a string");
}
if (!LuaWrapper::checkField<const char*>(L, 1, "prop_name", &prop_name)) {
luaL_argerror(L, 1, "`property` field must be a string");
}
Curve& curve = curves.emplace(m_allocator);
curve.cmp_type = reflection::getComponentType(cmp_name);
// TODO property
if (!LuaWrapper::getField(L, 1, "keyframes")) {
luaL_argerror(L, 1, "`keyframes` field must be an array");
}
LuaWrapper::forEachArrayItem<i32>(L, -1, "`keyframes` field must be an array of keyframes", [&](i32 v){
curve.frames.emplace(v);
});
lua_pop(L, 1);
if (!LuaWrapper::getField(L, 1, "values")) {
luaL_argerror(L, 1, "`values` field must be an array");
}
LuaWrapper::forEachArrayItem<float>(L, -1, "`values` field must be an array of numbers", [&](float v){
curve.values.emplace(v);
});
lua_pop(L, 1);
}
bool PropertyAnimation::load(u64 size, const u8* mem)
{
lua_State* L = luaL_newstate(); // TODO reuse
auto fn = &LuaWrapper::wrapMethodClosure<&PropertyAnimation::LUA_curve>;
lua_pushlightuserdata(L, this);
lua_pushcclosure(L, fn, 1);
lua_setglobal(L, "curve");
return LuaWrapper::execute(L, Span((const char*)mem, (u32)size), getPath().c_str(), 0);
}
void PropertyAnimation::unload()
{
curves.clear();
}
} // namespace Lumix
| 27.145631 | 112 | 0.667382 | santaclose |
c0a03fe1ce84519dc37c704250cc1ec04c849015 | 1,069 | cpp | C++ | Misc/Overloading/OperatorOverloading.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | 1 | 2021-01-25T14:26:56.000Z | 2021-01-25T14:26:56.000Z | Misc/Overloading/OperatorOverloading.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | null | null | null | Misc/Overloading/OperatorOverloading.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | 1 | 2021-01-25T14:27:08.000Z | 2021-01-25T14:27:08.000Z | /**
* Operator Overloading: C++ provides option to overload operators. For example, we can make the operator ('+') for string
* class to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So a
* single operator '+' when placed between integer operands, adds them and when placed between string operands, concatenates
* them.
*/
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imaginary;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imaginary = i;
}
// This is automatically called when '+' is used between two complex objects
Complex operator + (Complex const &obj) {
Complex result;
result.real = real + obj.real;
result.imaginary = imaginary + obj.imaginary;
return result;
}
void print()
{
cout << real << " + i" << imaginary << endl;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // an example call to the overloaded operator
c3.print();
} | 26.073171 | 124 | 0.631431 | karan2808 |
c0a4dbd689af39b383447b0fa329612225b047bc | 611 | cpp | C++ | archive/3/zagadka_nicola_tartaglii.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/3/zagadka_nicola_tartaglii.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/3/zagadka_nicola_tartaglii.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int I;
int main()
{
I n;
cin >> n;
for(I i = 0; i < n; ++i) {
I p, q;
cin >> p >> q;
I lo = 0, hi = (I)2e6;
while(lo < hi) {
I x = (lo + hi) / 2;
I val = x * x * x + p * x;
if(q <= val) {
hi = x;
} else {
lo = x + 1;
}
}
I val = lo * lo * lo + p * lo;
if(val == q) {
cout << lo << '\n';
} else {
cout << "NIE\n";
}
}
return 0;
}
| 15.275 | 38 | 0.292962 | Aleshkev |
c0a83fd79ff515bf99d880c5192957f50bcf136b | 42,679 | cc | C++ | src_fused/ozz_animation_fbx.cc | fabiopolimeni/ozz-animation | 7199d867be158b977e3ef5958ca3cf96e4dd5da7 | [
"MIT"
] | null | null | null | src_fused/ozz_animation_fbx.cc | fabiopolimeni/ozz-animation | 7199d867be158b977e3ef5958ca3cf96e4dd5da7 | [
"MIT"
] | null | null | null | src_fused/ozz_animation_fbx.cc | fabiopolimeni/ozz-animation | 7199d867be158b977e3ef5958ca3cf96e4dd5da7 | [
"MIT"
] | null | null | null | // This file is autogenerated. Do not modify it.
// Including fbx.cc file.
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers.
#include "ozz/animation/offline/fbx/fbx.h"
#include "ozz/animation/offline/fbx/fbx_base.h"
// Includes internal include file animation/offline/fbx/fbx_animation.h
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#ifndef OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
#define OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
#ifndef OZZ_INCLUDE_PRIVATE_HEADER
#error "This header is private, it cannot be included from public headers."
#endif // OZZ_INCLUDE_PRIVATE_HEADER
#include "ozz/animation/offline/fbx/fbx.h"
#include "ozz/animation/offline/fbx/fbx_base.h"
namespace ozz {
namespace animation {
class Skeleton;
namespace offline {
struct RawAnimation;
namespace fbx {
bool ExtractAnimations(FbxSceneLoader* _scene_loader, const Skeleton& _skeleton,
float _sampling_rate, Animations* _animations);
} // fbx
} // offline
} // animation
} // ozz
#endif // OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
// Includes internal include file animation/offline/fbx/fbx_skeleton.h
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#ifndef OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#define OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#ifndef OZZ_INCLUDE_PRIVATE_HEADER
#error "This header is private, it cannot be included from public headers."
#endif // OZZ_INCLUDE_PRIVATE_HEADER
#include "ozz/animation/offline/fbx/fbx_base.h"
namespace ozz {
namespace animation {
namespace offline {
struct RawSkeleton;
namespace fbx {
bool ExtractSkeleton(FbxSceneLoader& _loader, RawSkeleton* _skeleton);
} // fbx
} // offline
} // animation
} // ozz
#endif // OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#include "ozz/base/log.h"
#include "ozz/animation/offline/raw_animation.h"
#include "ozz/animation/offline/raw_skeleton.h"
namespace ozz {
namespace animation {
namespace offline {
namespace fbx {
bool ImportFromFile(const char* _filename, RawSkeleton* _skeleton) {
if (!_skeleton) {
return false;
}
// Reset skeleton.
*_skeleton = RawSkeleton();
// Import Fbx content.
FbxManagerInstance fbx_manager;
FbxSkeletonIOSettings settings(fbx_manager);
FbxSceneLoader scene_loader(_filename, "", fbx_manager, settings);
if (!scene_loader.scene()) {
ozz::log::Err() << "Failed to import file " << _filename << "."
<< std::endl;
return false;
}
if (!ExtractSkeleton(scene_loader, _skeleton)) {
log::Err() << "Fbx skeleton extraction failed." << std::endl;
return false;
}
return true;
}
bool ImportFromFile(const char* _filename, const Skeleton& _skeleton,
float _sampling_rate, Animations* _animations) {
if (!_animations) {
return false;
}
// Reset animation.
_animations->clear();
// Import Fbx content.
FbxManagerInstance fbx_manager;
FbxAnimationIOSettings settings(fbx_manager);
FbxSceneLoader scene_loader(_filename, "", fbx_manager, settings);
if (!scene_loader.scene()) {
ozz::log::Err() << "Failed to import file " << _filename << "."
<< std::endl;
return false;
}
if (!ExtractAnimations(&scene_loader, _skeleton, _sampling_rate,
_animations)) {
log::Err() << "Fbx animation extraction failed." << std::endl;
return false;
}
return true;
}
} // fbx
} // offline
} // animation
} // ozz
// Including fbx_animation.cc file.
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers.
// Includes internal include file animation/offline/fbx/fbx_animation.h
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#ifndef OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
#define OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
#ifndef OZZ_INCLUDE_PRIVATE_HEADER
#error "This header is private, it cannot be included from public headers."
#endif // OZZ_INCLUDE_PRIVATE_HEADER
#include "ozz/animation/offline/fbx/fbx.h"
#include "ozz/animation/offline/fbx/fbx_base.h"
namespace ozz {
namespace animation {
class Skeleton;
namespace offline {
struct RawAnimation;
namespace fbx {
bool ExtractAnimations(FbxSceneLoader* _scene_loader, const Skeleton& _skeleton,
float _sampling_rate, Animations* _animations);
} // fbx
} // offline
} // animation
} // ozz
#endif // OZZ_ANIMATION_OFFLINE_FBX_FBX_ANIMATION_H_
#include "ozz/animation/offline/raw_animation.h"
#include "ozz/animation/runtime/skeleton.h"
#include "ozz/animation/runtime/skeleton_utils.h"
#include "ozz/base/log.h"
#include "ozz/base/maths/transform.h"
namespace ozz {
namespace animation {
namespace offline {
namespace fbx {
namespace {
bool ExtractAnimation(FbxSceneLoader* _scene_loader, FbxAnimStack* anim_stack,
const Skeleton& _skeleton, float _sampling_rate,
RawAnimation* _animation) {
FbxScene* scene = _scene_loader->scene();
assert(scene);
ozz::log::Log() << "Extracting animation \"" << anim_stack->GetName() << "\""
<< std::endl;
// Setup Fbx animation evaluator.
scene->SetCurrentAnimationStack(anim_stack);
// Set animation name.
_animation->name = anim_stack->GetName();
// Extract animation duration.
FbxTimeSpan time_spawn;
const FbxTakeInfo* take_info = scene->GetTakeInfo(anim_stack->GetName());
if (take_info) {
time_spawn = take_info->mLocalTimeSpan;
} else {
scene->GetGlobalSettings().GetTimelineDefaultTimeSpan(time_spawn);
}
// Get frame rate from the scene.
FbxTime::EMode mode = scene->GetGlobalSettings().GetTimeMode();
const float scene_frame_rate =
static_cast<float>((mode == FbxTime::eCustom)
? scene->GetGlobalSettings().GetCustomFrameRate()
: FbxTime::GetFrameRate(mode));
// Deduce sampling period.
// Scene frame rate is used when provided argument is <= 0.
float sampling_rate;
if (_sampling_rate > 0.f) {
sampling_rate = _sampling_rate;
log::Log() << "Using sampling rate of " << sampling_rate << "hz."
<< std::endl;
} else {
sampling_rate = scene_frame_rate;
log::Log() << "Using scene sampling rate of " << sampling_rate << "hz."
<< std::endl;
}
const float sampling_period = 1.f / sampling_rate;
// Get scene start and end.
const float start =
static_cast<float>(time_spawn.GetStart().GetSecondDouble());
const float end = static_cast<float>(time_spawn.GetStop().GetSecondDouble());
// Animation duration could be 0 if it's just a pose. In this case we'll set a
// default 1s duration.
if (end > start) {
_animation->duration = end - start;
} else {
_animation->duration = 1.f;
}
// Allocates all tracks with the same number of joints as the skeleton.
// Tracks that would not be found will be set to skeleton bind-pose
// transformation.
_animation->tracks.resize(_skeleton.num_joints());
// Iterate all skeleton joints and fills there track with key frames.
FbxAnimEvaluator* evaluator = scene->GetAnimationEvaluator();
for (int i = 0; i < _skeleton.num_joints(); i++) {
RawAnimation::JointTrack& track = _animation->tracks[i];
// Find a node that matches skeleton joint.
const char* joint_name = _skeleton.joint_names()[i];
FbxNode* node = scene->FindNodeByName(joint_name);
if (!node) {
// Empty joint track.
ozz::log::LogV() << "No animation track found for joint \"" << joint_name
<< "\". Using skeleton bind pose instead." << std::endl;
// Get joint's bind pose.
const ozz::math::Transform& bind_pose =
ozz::animation::GetJointLocalBindPose(_skeleton, i);
const RawAnimation::TranslationKey tkey = {0.f, bind_pose.translation};
track.translations.push_back(tkey);
const RawAnimation::RotationKey rkey = {0.f, bind_pose.rotation};
track.rotations.push_back(rkey);
const RawAnimation::ScaleKey skey = {0.f, bind_pose.scale};
track.scales.push_back(skey);
continue;
}
// Reserve keys in animation tracks (allocation strategy optimization
// purpose).
const int max_keys =
static_cast<int>(3.f + (end - start) / sampling_period);
track.translations.reserve(max_keys);
track.rotations.reserve(max_keys);
track.scales.reserve(max_keys);
// Evaluate joint transformation at the specified time.
// Make sure to include "end" time, and enter the loop once at least.
bool loop_again = true;
for (float t = start; loop_again; t += sampling_period) {
if (t >= end) {
t = end;
loop_again = false;
}
// Evaluate transform matric at t.
const FbxAMatrix matrix =
_skeleton.joint_properties()[i].parent == Skeleton::kNoParentIndex
? evaluator->GetNodeGlobalTransform(node, FbxTimeSeconds(t))
: evaluator->GetNodeLocalTransform(node, FbxTimeSeconds(t));
// Convert to a transform obejct in ozz unit/axis system.
ozz::math::Transform transform;
if (!_scene_loader->converter()->ConvertTransform(matrix, &transform)) {
ozz::log::Err() << "Failed to extract animation transform for joint \""
<< joint_name << "\" at t = " << t << "s." << std::endl;
return false;
}
// Fills corresponding track.
const float local_time = t - start;
const RawAnimation::TranslationKey translation = {local_time,
transform.translation};
track.translations.push_back(translation);
const RawAnimation::RotationKey rotation = {local_time,
transform.rotation};
track.rotations.push_back(rotation);
const RawAnimation::ScaleKey scale = {local_time, transform.scale};
track.scales.push_back(scale);
}
}
// Output animation must be valid at that point.
assert(_animation->Validate());
return true;
}
}
bool ExtractAnimations(FbxSceneLoader* _scene_loader, const Skeleton& _skeleton,
float _sampling_rate, Animations* _animations) {
// Clears output
_animations->clear();
FbxScene* scene = _scene_loader->scene();
assert(scene);
int anim_stacks_count = scene->GetSrcObjectCount<FbxAnimStack>();
// Early out if no animation's found.
if (anim_stacks_count == 0) {
ozz::log::Err() << "No animation found." << std::endl;
return false;
}
// Prepares ouputs.
_animations->resize(anim_stacks_count);
// Sequentially import all available animations.
bool success = true;
for (int i = 0; i < anim_stacks_count && success; ++i) {
FbxAnimStack* anim_stack = scene->GetSrcObject<FbxAnimStack>(i);
success &= ExtractAnimation(_scene_loader, anim_stack, _skeleton,
_sampling_rate, &_animations->at(i));
}
// Clears output if somthing failed during import, avoids partial data.
if (!success) {
_animations->clear();
}
return success;
}
} // fbx
} // offline
} // animation
} // ozz
// Including fbx_base.cc file.
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers.
#include "ozz/animation/offline/fbx/fbx_base.h"
#include "ozz/base/log.h"
#include "ozz/base/memory/allocator.h"
#include "ozz/base/maths/transform.h"
namespace ozz {
namespace animation {
namespace offline {
namespace fbx {
FbxManagerInstance::FbxManagerInstance() : fbx_manager_(NULL) {
// Instantiate Fbx manager, mostly a memory manager.
fbx_manager_ = FbxManager::Create();
// Logs SDK version.
ozz::log::Log() << "FBX importer version " << fbx_manager_->GetVersion()
<< "." << std::endl;
}
FbxManagerInstance::~FbxManagerInstance() {
// Destroy the manager and all associated objects.
fbx_manager_->Destroy();
fbx_manager_ = NULL;
}
FbxDefaultIOSettings::FbxDefaultIOSettings(const FbxManagerInstance& _manager)
: io_settings_(NULL) {
io_settings_ = FbxIOSettings::Create(_manager, IOSROOT);
}
FbxDefaultIOSettings::~FbxDefaultIOSettings() {
io_settings_->Destroy();
io_settings_ = NULL;
}
FbxAnimationIOSettings::FbxAnimationIOSettings(
const FbxManagerInstance& _manager)
: FbxDefaultIOSettings(_manager) {
settings()->SetBoolProp(IMP_FBX_MATERIAL, false);
settings()->SetBoolProp(IMP_FBX_TEXTURE, false);
settings()->SetBoolProp(IMP_FBX_MODEL, false);
settings()->SetBoolProp(IMP_FBX_SHAPE, false);
settings()->SetBoolProp(IMP_FBX_LINK, false);
settings()->SetBoolProp(IMP_FBX_GOBO, false);
}
FbxSkeletonIOSettings::FbxSkeletonIOSettings(const FbxManagerInstance& _manager)
: FbxDefaultIOSettings(_manager) {
settings()->SetBoolProp(IMP_FBX_MATERIAL, false);
settings()->SetBoolProp(IMP_FBX_TEXTURE, false);
settings()->SetBoolProp(IMP_FBX_MODEL, false);
settings()->SetBoolProp(IMP_FBX_SHAPE, false);
settings()->SetBoolProp(IMP_FBX_LINK, false);
settings()->SetBoolProp(IMP_FBX_GOBO, false);
settings()->SetBoolProp(IMP_FBX_ANIMATION, false);
}
FbxSceneLoader::FbxSceneLoader(const char* _filename, const char* _password,
const FbxManagerInstance& _manager,
const FbxDefaultIOSettings& _io_settings)
: scene_(NULL), converter_(NULL) {
// Create an importer.
FbxImporter* importer = FbxImporter::Create(_manager, "ozz file importer");
const bool initialized = importer->Initialize(_filename, -1, _io_settings);
ImportScene(importer, initialized, _password, _manager, _io_settings);
// Destroy the importer
importer->Destroy();
}
FbxSceneLoader::FbxSceneLoader(FbxStream* _stream, const char* _password,
const FbxManagerInstance& _manager,
const FbxDefaultIOSettings& _io_settings)
: scene_(NULL), converter_(NULL) {
// Create an importer.
FbxImporter* importer = FbxImporter::Create(_manager, "ozz stream importer");
const bool initialized =
importer->Initialize(_stream, NULL, -1, _io_settings);
ImportScene(importer, initialized, _password, _manager, _io_settings);
// Destroy the importer
importer->Destroy();
}
void FbxSceneLoader::ImportScene(FbxImporter* _importer,
const bool _initialized, const char* _password,
const FbxManagerInstance& _manager,
const FbxDefaultIOSettings& _io_settings) {
// Get the version of the FBX file format.
int major, minor, revision;
_importer->GetFileVersion(major, minor, revision);
if (!_initialized) // Problem with the file to be imported.
{
const FbxString error = _importer->GetStatus().GetErrorString();
ozz::log::Err() << "FbxImporter initialization failed with error: "
<< error.Buffer() << std::endl;
if (_importer->GetStatus().GetCode() == FbxStatus::eInvalidFileVersion) {
ozz::log::Err() << "FBX file version is " << major << "." << minor << "."
<< revision << "." << std::endl;
}
} else {
if (_importer->IsFBX()) {
ozz::log::Log() << "FBX file version is " << major << "." << minor << "."
<< revision << "." << std::endl;
}
// Load the scene.
scene_ = FbxScene::Create(_manager, "ozz scene");
bool imported = _importer->Import(scene_);
if (!imported && // The import file may have a password
_importer->GetStatus().GetCode() == FbxStatus::ePasswordError) {
_io_settings.settings()->SetStringProp(IMP_FBX_PASSWORD, _password);
_io_settings.settings()->SetBoolProp(IMP_FBX_PASSWORD_ENABLE, true);
// Retries to import the scene.
imported = _importer->Import(scene_);
if (!imported &&
_importer->GetStatus().GetCode() == FbxStatus::ePasswordError) {
ozz::log::Err() << "Incorrect password." << std::endl;
// scene_ will be destroyed because imported is false.
}
}
// Setup axis and system converter.
if (imported) {
FbxGlobalSettings& settings = scene_->GetGlobalSettings();
converter_ = ozz::memory::default_allocator()->New<FbxSystemConverter>(
settings.GetAxisSystem(), settings.GetSystemUnit());
}
// Clear the scene if import failed.
if (!imported) {
scene_->Destroy();
scene_ = NULL;
}
}
}
FbxSceneLoader::~FbxSceneLoader() {
if (scene_) {
scene_->Destroy();
scene_ = NULL;
}
if (converter_) {
ozz::memory::default_allocator()->Delete(converter_);
converter_ = NULL;
}
}
namespace {
ozz::math::Float4x4 BuildAxisSystemMatrix(const FbxAxisSystem& _system) {
int sign;
ozz::math::SimdFloat4 up = ozz::math::simd_float4::y_axis();
ozz::math::SimdFloat4 at = ozz::math::simd_float4::z_axis();
// The EUpVector specifies which axis has the up and down direction in the
// system (typically this is the Y or Z axis). The sign of the EUpVector is
// applied to represent the direction (1 is up and -1 is down relative to the
// observer).
const FbxAxisSystem::EUpVector eup = _system.GetUpVector(sign);
switch (eup) {
case FbxAxisSystem::eXAxis: {
up = math::simd_float4::Load(1.f * sign, 0.f, 0.f, 0.f);
// If the up axis is X, the remain two axes will be Y And Z, so the
// ParityEven is Y, and the ParityOdd is Z
if (_system.GetFrontVector(sign) == FbxAxisSystem::eParityEven) {
at = math::simd_float4::Load(0.f, 1.f * sign, 0.f, 0.f);
} else {
at = math::simd_float4::Load(0.f, 0.f, 1.f * sign, 0.f);
}
break;
}
case FbxAxisSystem::eYAxis: {
up = math::simd_float4::Load(0.f, 1.f * sign, 0.f, 0.f);
// If the up axis is Y, the remain two axes will X And Z, so the
// ParityEven is X, and the ParityOdd is Z
if (_system.GetFrontVector(sign) == FbxAxisSystem::eParityEven) {
at = math::simd_float4::Load(1.f * sign, 0.f, 0.f, 0.f);
} else {
at = math::simd_float4::Load(0.f, 0.f, 1.f * sign, 0.f);
}
break;
}
case FbxAxisSystem::eZAxis: {
up = math::simd_float4::Load(0.f, 0.f, 1.f * sign, 0.f);
// If the up axis is Z, the remain two axes will X And Y, so the
// ParityEven is X, and the ParityOdd is Y
if (_system.GetFrontVector(sign) == FbxAxisSystem::eParityEven) {
at = math::simd_float4::Load(1.f * sign, 0.f, 0.f, 0.f);
} else {
at = math::simd_float4::Load(0.f, 1.f * sign, 0.f, 0.f);
}
break;
}
default: {
assert(false && "Invalid FbxAxisSystem");
break;
}
}
// If the front axis and the up axis are determined, the third axis will be
// automatically determined as the left one. The ECoordSystem enum is a
// parameter to determine the direction of the third axis just as the
// EUpVector sign. It determines if the axis system is right-handed or
// left-handed just as the enum values.
ozz::math::SimdFloat4 right;
if (_system.GetCoorSystem() == FbxAxisSystem::eRightHanded) {
right = math::Cross3(up, at);
} else {
right = math::Cross3(at, up);
}
const ozz::math::Float4x4 matrix = {
{right, up, at, ozz::math::simd_float4::w_axis()}};
return matrix;
}
}
FbxSystemConverter::FbxSystemConverter(const FbxAxisSystem& _from_axis,
const FbxSystemUnit& _from_unit) {
// Build axis system conversion matrix.
const math::Float4x4 from_matrix = BuildAxisSystemMatrix(_from_axis);
// Finds unit conversion ratio to meters, where GetScaleFactor() is in cm.
const float to_meters =
static_cast<float>(_from_unit.GetScaleFactor()) * .01f;
// Builds conversion matrices.
convert_ = Invert(from_matrix) *
math::Float4x4::Scaling(math::simd_float4::Load1(to_meters));
inverse_convert_ = Invert(convert_);
inverse_transpose_convert_ = Transpose(inverse_convert_);
}
math::Float4x4 FbxSystemConverter::ConvertMatrix(const FbxAMatrix& _m) const {
const ozz::math::Float4x4 m = {{
ozz::math::simd_float4::Load(
static_cast<float>(_m[0][0]), static_cast<float>(_m[0][1]),
static_cast<float>(_m[0][2]), static_cast<float>(_m[0][3])),
ozz::math::simd_float4::Load(
static_cast<float>(_m[1][0]), static_cast<float>(_m[1][1]),
static_cast<float>(_m[1][2]), static_cast<float>(_m[1][3])),
ozz::math::simd_float4::Load(
static_cast<float>(_m[2][0]), static_cast<float>(_m[2][1]),
static_cast<float>(_m[2][2]), static_cast<float>(_m[2][3])),
ozz::math::simd_float4::Load(
static_cast<float>(_m[3][0]), static_cast<float>(_m[3][1]),
static_cast<float>(_m[3][2]), static_cast<float>(_m[3][3])),
}};
return convert_ * m * inverse_convert_;
}
math::Float3 FbxSystemConverter::ConvertPoint(const FbxVector4& _p) const {
const math::SimdFloat4 p_in = math::simd_float4::Load(
static_cast<float>(_p[0]), static_cast<float>(_p[1]),
static_cast<float>(_p[2]), 1.f);
const math::SimdFloat4 p_out = convert_ * p_in;
math::Float3 ret;
math::Store3PtrU(p_out, &ret.x);
return ret;
}
math::Float3 FbxSystemConverter::ConvertNormal(const FbxVector4& _p) const {
const math::SimdFloat4 p_in = math::simd_float4::Load(
static_cast<float>(_p[0]), static_cast<float>(_p[1]),
static_cast<float>(_p[2]), 0.f);
const math::SimdFloat4 p_out = inverse_transpose_convert_ * p_in;
math::Float3 ret;
math::Store3PtrU(p_out, &ret.x);
return ret;
}
bool FbxSystemConverter::ConvertTransform(const FbxAMatrix& _m,
math::Transform* _transform) const {
assert(_transform);
const math::Float4x4 matrix = ConvertMatrix(_m);
math::SimdFloat4 translation, rotation, scale;
if (ToAffine(matrix, &translation, &rotation, &scale)) {
ozz::math::Transform transform;
math::Store3PtrU(translation, &_transform->translation.x);
math::StorePtrU(math::Normalize4(rotation), &_transform->rotation.x);
math::Store3PtrU(scale, &_transform->scale.x);
return true;
}
// Failed to decompose matrix, reset transform to identity.
*_transform = ozz::math::Transform::identity();
return false;
}
} // fbx
} // ozz
} // offline
} // animation
// Including fbx_skeleton.cc file.
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers.
// Includes internal include file animation/offline/fbx/fbx_skeleton.h
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#ifndef OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#define OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#ifndef OZZ_INCLUDE_PRIVATE_HEADER
#error "This header is private, it cannot be included from public headers."
#endif // OZZ_INCLUDE_PRIVATE_HEADER
#include "ozz/animation/offline/fbx/fbx_base.h"
namespace ozz {
namespace animation {
namespace offline {
struct RawSkeleton;
namespace fbx {
bool ExtractSkeleton(FbxSceneLoader& _loader, RawSkeleton* _skeleton);
} // fbx
} // offline
} // animation
} // ozz
#endif // OZZ_ANIMATION_OFFLINE_FBX_FBX_SKELETON_H_
#include "ozz/animation/offline/raw_skeleton.h"
#include "ozz/base/log.h"
namespace ozz {
namespace animation {
namespace offline {
namespace fbx {
namespace {
enum RecurseReturn { kError, kSkeletonFound, kNoSkeleton };
RecurseReturn RecurseNode(FbxNode* _node, FbxSystemConverter* _converter,
RawSkeleton* _skeleton, RawSkeleton::Joint* _parent,
int _depth) {
bool skeleton_found = false;
RawSkeleton::Joint* this_joint = NULL;
bool process_node = false;
// Push this node if it's below a skeleton root (aka has a parent).
process_node |= _parent != NULL;
// Push this node as a new joint if it has a joint compatible attribute.
FbxNodeAttribute* node_attribute = _node->GetNodeAttribute();
process_node |=
node_attribute &&
node_attribute->GetAttributeType() == FbxNodeAttribute::eSkeleton;
// Process node if required.
if (process_node) {
skeleton_found = true;
RawSkeleton::Joint::Children* sibling = NULL;
if (_parent) {
sibling = &_parent->children;
} else {
sibling = &_skeleton->roots;
}
// Adds a new child.
sibling->resize(sibling->size() + 1);
this_joint = &sibling->back(); // Will not be resized inside recursion.
this_joint->name = _node->GetName();
// Outputs hierarchy on verbose stream.
for (int i = 0; i < _depth; ++i) {
ozz::log::LogV() << '.';
}
ozz::log::LogV() << this_joint->name.c_str() << std::endl;
// Extract bind pose.
const FbxAMatrix matrix = _parent ? _node->EvaluateLocalTransform()
: _node->EvaluateGlobalTransform();
if (!_converter->ConvertTransform(matrix, &this_joint->transform)) {
ozz::log::Err() << "Failed to extract skeleton transform for joint \""
<< this_joint->name << "\"." << std::endl;
return kError;
}
// One level deeper in the hierarchy.
_depth++;
}
// Iterate node's children.
for (int i = 0; i < _node->GetChildCount(); i++) {
FbxNode* child = _node->GetChild(i);
const RecurseReturn ret =
RecurseNode(child, _converter, _skeleton, this_joint, _depth);
if (ret == kError) {
return ret;
}
skeleton_found |= (ret == kSkeletonFound);
}
return skeleton_found ? kSkeletonFound : kNoSkeleton;
}
}
bool ExtractSkeleton(FbxSceneLoader& _loader, RawSkeleton* _skeleton) {
RecurseReturn ret = RecurseNode(_loader.scene()->GetRootNode(),
_loader.converter(), _skeleton, NULL, 0);
if (ret == kNoSkeleton) {
ozz::log::Err() << "No skeleton found in Fbx scene." << std::endl;
return false;
} else if (ret == kError) {
ozz::log::Err() << "Failed to extract skeleton." << std::endl;
return false;
}
return true;
}
} // fbx
} // ozz
} // offline
} // animation
| 41.395732 | 80 | 0.580567 | fabiopolimeni |
c0aa02476b6307647f8b625382d734fcebd0bb07 | 888 | cpp | C++ | test/std/utilities/memory/allocator.tag/allocator_arg.fail.cpp | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | test/std/utilities/memory/allocator.tag/allocator_arg.fail.cpp | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | test/std/utilities/memory/allocator.tag/allocator_arg.fail.cpp | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// Before GCC 6, aggregate initialization kicks in.
// See https://stackoverflow.com/q/41799015/627587.
// UNSUPPORTED: gcc-5
// <memory>
// struct allocator_arg_t { explicit allocator_arg_t() = default; };
// const allocator_arg_t allocator_arg = allocator_arg_t();
// This test checks for LWG 2510.
#include <memory.hxx>
std::allocator_arg_t f() { return {}; } // expected-error 1 {{chosen constructor is explicit in copy-initialization}}
int main(int, char**) {
return 0;
}
| 29.6 | 117 | 0.582207 | K-Wu |
c0ac781a6b9b30a9a05e3eddf8ba0775de723dd3 | 416 | cpp | C++ | YorozuyaGSLib/source/_be_damaged_player.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/_be_damaged_player.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/_be_damaged_player.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <_be_damaged_player.hpp>
START_ATF_NAMESPACE
_be_damaged_player::_be_damaged_player()
{
using org_ptr = void (WINAPIV*)(struct _be_damaged_player*);
(org_ptr(0x14013e450L))(this);
};
void _be_damaged_player::ctor__be_damaged_player()
{
using org_ptr = void (WINAPIV*)(struct _be_damaged_player*);
(org_ptr(0x14013e450L))(this);
};
END_ATF_NAMESPACE
| 26 | 68 | 0.685096 | lemkova |
c0aeb25758531829c5eb13205d2612aff196252a | 441 | cpp | C++ | fuzzing/macho_fuzzer.cpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | fuzzing/macho_fuzzer.cpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | fuzzing/macho_fuzzer.cpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | #include <LIEF/LIEF.hpp>
#include <memory>
#include <vector>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
std::vector<uint8_t> raw = {data, data + size};
std::unique_ptr<LIEF::MachO::FatBinary> binaries;
try {
binaries = std::unique_ptr<LIEF::MachO::FatBinary>(
LIEF::MachO::Parser::parse(raw));
} catch (const LIEF::exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
| 27.5625 | 73 | 0.650794 | ahawad |
c0b030a6ccb2e105111a88450fa72c8780ca95c3 | 17,011 | cpp | C++ | Assets/IntermediateAssets.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | 1 | 2016-06-01T10:41:12.000Z | 2016-06-01T10:41:12.000Z | Assets/IntermediateAssets.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | Assets/IntermediateAssets.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#define _SCL_SECURE_NO_WARNINGS
#include "IntermediateAssets.h"
#include "CompileAndAsyncManager.h" // for ~PendingCompileMarker -- remove
#include "../ConsoleRig/Log.h"
#include "../Assets/AssetUtils.h"
#include "../Utility/Streams/FileUtils.h"
#include "../Utility/Streams/Data.h"
#include "../Utility/Streams/PathUtils.h"
#include "../Utility/Threading/Mutex.h"
#include "../Utility/IteratorUtils.h"
#include "../Utility/PtrUtils.h"
#include "../Utility/ExceptionLogging.h"
#include "../Core/WinAPI/IncludeWindows.h"
#include <memory>
namespace Assets { namespace IntermediateAssets
{
static ResChar ConvChar(ResChar input)
{
return (ResChar)((input == '\\')?'/':tolower(input));
}
void Store::MakeIntermediateName(ResChar buffer[], unsigned bufferMaxCount, const ResChar firstInitializer[]) const
{
// calculate the intermediate file for this request name (normally just a file with the
// same name in our branch directory
if (buffer == firstInitializer) {
assert(bufferMaxCount >= (_baseDirectory.size()+1));
auto length = XlStringLen(firstInitializer);
auto moveSize = std::min(unsigned(length), unsigned(bufferMaxCount-1-(_baseDirectory.size()+1)));
XlMoveMemory(&buffer[_baseDirectory.size()+1], buffer, moveSize);
buffer[_baseDirectory.size()+1+moveSize] = ResChar('\0');
std::copy(_baseDirectory.begin(), _baseDirectory.end(), buffer);
buffer[_baseDirectory.size()] = ResChar('/');
} else {
_snprintf_s(buffer, sizeof(ResChar)*bufferMaxCount, _TRUNCATE, "%s/%s", _baseDirectory.c_str(), firstInitializer);
}
}
template <int DestCount>
static void MakeDepFileName(ResChar (&destination)[DestCount], const ResChar baseDirectory[], const ResChar depFileName[])
{
// if the prefix of "baseDirectory" and "intermediateFileName" match, we should skip over that
const ResChar* f = depFileName, *b = baseDirectory;
while (ConvChar(*f) == ConvChar(*b) && *f != '\0') { ++f; ++b; }
while (ConvChar(*f) == '/') { ++f; }
_snprintf_s(destination, DestCount, _TRUNCATE, "%s/.deps/%s", baseDirectory, f);
}
class RetainedFileRecord : public DependencyValidation
{
public:
DependentFileState _state;
void OnChange()
{
// on change, update the modification time record
_state._timeMarker = GetFileModificationTime(_state._filename.c_str());
DependencyValidation::OnChange();
}
RetainedFileRecord(const ResChar filename[])
: _state(filename, 0ull) {}
};
static std::vector<std::pair<uint64, std::shared_ptr<RetainedFileRecord>>> RetainedRecords;
static Threading::Mutex RetainedRecordsLock;
static std::shared_ptr<RetainedFileRecord>& GetRetainedFileRecord(const char filename[])
{
// We should normalize to avoid problems related to
// case insensitivity and slash differences
ResolvedAssetFile assetName;
MakeAssetName(assetName, filename);
auto hash = Hash64(assetName._fn);
{
ScopedLock(RetainedRecordsLock);
auto i = LowerBound(RetainedRecords, hash);
if (i!=RetainedRecords.end() && i->first == hash) {
return i->second;
}
// we should call "AttachFileSystemMonitor" before we query for the
// file's current modification time
auto newRecord = std::make_shared<RetainedFileRecord>(assetName._fn);
RegisterFileDependency(newRecord, assetName._fn);
newRecord->_state._timeMarker = GetFileModificationTime(assetName._fn);
return RetainedRecords.insert(i, std::make_pair(hash, std::move(newRecord)))->second;
}
}
const DependentFileState& Store::GetDependentFileState(const ResChar filename[]) const
{
return GetRetainedFileRecord(filename)->_state;
}
void Store::ShadowFile(const ResChar filename[])
{
auto& record = GetRetainedFileRecord(filename);
record->_state._status = DependentFileState::Status::Shadowed;
// propagate change messages...
// (duplicating processing from RegisterFileDependency)
ResChar directoryName[MaxPath];
FileNameSplitter<ResChar> splitter(filename);
SplitPath<ResChar>(splitter.DriveAndPath()).Simplify().Rebuild(directoryName);
FakeFileChange(StringSection<ResChar>(directoryName), splitter.FileAndExtension());
record->OnChange();
}
std::shared_ptr<DependencyValidation> Store::MakeDependencyValidation(const ResChar intermediateFileName[]) const
{
// When we process a file, we write a little text file to the
// ".deps" directory. This contains a list of dependency files, and
// the state of those files when this file was compiled.
// If the current files don't match the state that's recorded in
// the .deps file, then we can assume that it is out of date and
// must be recompiled.
ResChar buffer[MaxPath];
MakeDepFileName(buffer, _baseDirectory.c_str(), intermediateFileName);
TRY {
Data data;
data.LoadFromFile(buffer);
auto* basePath = data.StrAttribute("BasePath");
auto validation = std::make_shared<DependencyValidation>();
auto* dependenciesBlock = data.ChildWithValue("Dependencies");
if (dependenciesBlock) {
for (auto* dependency = dependenciesBlock->child; dependency; dependency = dependency->next) {
auto* depName = dependency->value;
if (!depName || !depName[0]) continue;
auto dateLow = (unsigned)dependency->IntAttribute("ModTimeL");
auto dateHigh = (unsigned)dependency->IntAttribute("ModTimeH");
const RetainedFileRecord* record;
if (basePath && basePath[0]) {
XlConcatPath(buffer, dimof(buffer), basePath, depName, &depName[XlStringLen(depName)]);
auto& ptr = GetRetainedFileRecord(buffer);
RegisterAssetDependency(validation, ptr);
record = ptr.get();
} else {
auto& ptr = GetRetainedFileRecord(depName);
RegisterAssetDependency(validation, ptr);
record = ptr.get();
}
if (record->_state._status == DependentFileState::Status::Shadowed) {
LogInfo << "Asset (" << intermediateFileName << ") is invalidated because dependency (" << depName << ") is marked shadowed";
return nullptr;
}
if (!record->_state._timeMarker) {
LogInfo
<< "Asset (" << intermediateFileName
<< ") is invalidated because of missing dependency (" << depName << ")";
return nullptr;
} else if (record->_state._timeMarker != ((uint64(dateHigh) << 32ull) | uint64(dateLow))) {
LogInfo
<< "Asset (" << intermediateFileName
<< ") is invalidated because of file data on dependency (" << depName << ")";
return nullptr;
}
}
}
return validation;
} CATCH(const std::exception&) {
// If there is no dependencies file, let's assume there are
// no dependencies at all
// ... though maybe this exception could have come from a badly formatted file?
return std::make_shared<DependencyValidation>();
} CATCH_END
}
std::shared_ptr<DependencyValidation> Store::WriteDependencies(
const ResChar intermediateFileName[], const ResChar baseDir[],
const DependentFileState* depsBegin, const DependentFileState* depsEnd,
bool makeDepValidation) const
{
Data data;
std::shared_ptr<DependencyValidation> result;
if (makeDepValidation)
result = std::make_shared<DependencyValidation>();
// we have to write the base directory to the dependencies file as well
// to keep it short, most filenames should be expressed as relative files
char buffer[MaxPath];
data.SetAttribute("BasePath", baseDir);
SplitPath<ResChar> baseSplitPath(baseDir);
auto dependenciesBlock = std::make_unique<Data>("Dependencies");
for (auto s=depsBegin; s!=depsEnd; ++s) {
auto c = std::make_unique<Data>();
auto relPath = MakeRelativePath(
baseSplitPath,
SplitPath<ResChar>(s->_filename));
c->SetValue(relPath.c_str());
if (s->_status != DependentFileState::Status::Shadowed) {
c->SetAttribute("ModTimeH", (int)(s->_timeMarker>>32ull));
c->SetAttribute("ModTimeL", (int)(s->_timeMarker));
}
dependenciesBlock->Add(c.release());
if (makeDepValidation) RegisterFileDependency(result, s->_filename.c_str());
}
data.Add(dependenciesBlock.release());
MakeDepFileName(buffer, _baseDirectory.c_str(), intermediateFileName);
// first, create the directory if we need to
char dirName[MaxPath];
XlDirname(dirName, dimof(dirName), buffer);
CreateDirectoryRecursive(dirName);
// now, write --
data.Save(buffer);
return result;
}
Store::Store(const ResChar baseDirectory[], const ResChar versionString[])
{
// First, we need to find an output directory to use.
// We want a directory that isn't currently being used, and
// that matches the version string.
char buffer[MaxPath];
_snprintf_s(buffer, _TRUNCATE, "%s/d*", baseDirectory);
std::string goodBranchDir;
{
// Look for existing directories that could match the version
// string we have.
WIN32_FIND_DATAA findData;
XlZeroMemory(findData);
HANDLE findHandle = FindFirstFileA(buffer, &findData);
if (findHandle != INVALID_HANDLE_VALUE) {
do {
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
_snprintf_s(buffer, _TRUNCATE, "%s/%s/.store", baseDirectory, findData.cFileName);
TRY
{
// Note -- Ideally we want to prevent two different instances of the
// same app from using the same intermediate assets store.
// We can do this by use a "non-shareable" file mode when
// we load these files.
BasicFile markerFile(buffer, "r+b");
auto fileSize = markerFile.GetSize();
if (fileSize != 0) {
auto rawData = std::unique_ptr<uint8[]>(new uint8[int(fileSize)]);
markerFile.Read(rawData.get(), 1, size_t(fileSize));
Data data;
data.Load((const char*)rawData.get(), (int)fileSize);
auto* compareVersion = data.StrAttribute("VersionString");
if (!_stricmp(versionString, compareVersion)) {
// this branch is already present, and is good... so use it
goodBranchDir = std::string(baseDirectory) + "/" + findData.cFileName;
break;
}
// it's a store for some other version of the executable. Try the next one
continue;
}
}
CATCH (...) {}
CATCH_END
}
} while (FindNextFileA(findHandle, &findData));
FindClose(findHandle);
}
}
if (goodBranchDir.empty()) {
// if we didn't find an existing folder we can use, we need to create a new one
// search through to find the first unused directory
for (unsigned d=0;;++d) {
_snprintf_s(buffer, _TRUNCATE, "%s/d%i", baseDirectory, d);
DWORD dwAttrib = GetFileAttributes(buffer);
if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
continue;
}
CreateDirectoryRecursive(buffer);
goodBranchDir = buffer;
_snprintf_s(buffer, _TRUNCATE, "%s/d%i/.store", baseDirectory, d);
Data newData;
newData.SetAttribute("VersionString", versionString);
newData.Save(buffer);
break;
}
}
_baseDirectory = goodBranchDir;
}
Store::~Store()
{
decltype(RetainedRecords) temp;
temp.swap(RetainedRecords);
}
////////////////////////////////////////////////////////////////////////////////////////
class CompilerSet::Pimpl
{
public:
std::vector<std::pair<uint64, std::shared_ptr<IAssetCompiler>>> _compilers;
};
void CompilerSet::AddCompiler(uint64 typeCode, const std::shared_ptr<IAssetCompiler>& processor)
{
auto i = LowerBound(_pimpl->_compilers, typeCode);
if (i != _pimpl->_compilers.cend() && i->first == typeCode) {
i->second = processor;
} else {
_pimpl->_compilers.insert(i, std::make_pair(typeCode, processor));
}
}
std::shared_ptr<PendingCompileMarker> CompilerSet::PrepareAsset(
uint64 typeCode, const ResChar* initializers[], unsigned initializerCount,
Store& store)
{
// look for a "processor" object with the given type code, and rebuild the file
// write the .deps file containing dependencies information
// Note that there's a slight race condition type problem here. We are querying
// the dependency files for their state after the processing has completed. So
// if the dependency file changes state during processing, we might not recognize
// that change properly. It's probably ignorable, however.
// note that ideally we want to be able to schedule this in the background
auto i = LowerBound(_pimpl->_compilers, typeCode);
if (i != _pimpl->_compilers.cend() && i->first == typeCode) {
TRY {
return i->second->PrepareAsset(typeCode, initializers, initializerCount, store);
} CATCH (const std::exception& e) {
LogAlwaysError << "Exception during processing of (" << initializers[0] << "). Exception details: (" << e.what() << ")";
} CATCH (...) {
LogAlwaysError << "Unknown exception during processing of (" << initializers[0] << ").";
} CATCH_END
} else {
assert(0); // couldn't find a processor for this asset type
}
return nullptr;
}
void CompilerSet::StallOnPendingOperations(bool cancelAll)
{
for (auto i=_pimpl->_compilers.cbegin(); i!=_pimpl->_compilers.cend(); ++i)
i->second->StallOnPendingOperations(cancelAll);
}
CompilerSet::CompilerSet()
{
auto pimpl = std::make_unique<Pimpl>();
_pimpl = std::move(pimpl);
}
CompilerSet::~CompilerSet()
{
}
IAssetCompiler::~IAssetCompiler() {}
}}
////////////////////////////////////////////////////////////
namespace Assets
{
PendingCompileMarker::PendingCompileMarker() : _sourceID1(0)
{
DEBUG_ONLY(_initializer[0] = '\0');
}
PendingCompileMarker::PendingCompileMarker(AssetState state, const char sourceID0[], uint64 sourceID1, std::shared_ptr<Assets::DependencyValidation> depVal)
: PendingOperationMarker(state, std::move(depVal)), _sourceID1(sourceID1)
{
XlCopyString(_sourceID0, sourceID0);
}
PendingCompileMarker::~PendingCompileMarker() {}
} | 41.089372 | 160 | 0.566927 | yorung |
c0bb6990f38f0d6965cf7b5c113f566e2378cd62 | 483 | cpp | C++ | lib/hyperscale/syntax/token_kinds.cpp | hyperscale/hyperscale | 0ae6eaa7ef93af665a60fff14cb35afefb4124aa | [
"MIT"
] | 3 | 2018-05-07T00:53:05.000Z | 2019-05-27T20:02:28.000Z | lib/hyperscale/syntax/token_kinds.cpp | hyperscale/hyperscale | 0ae6eaa7ef93af665a60fff14cb35afefb4124aa | [
"MIT"
] | 1 | 2018-05-05T23:55:31.000Z | 2021-07-20T22:28:15.000Z | lib/hyperscale/syntax/token_kinds.cpp | hyperscale/hyperscale | 0ae6eaa7ef93af665a60fff14cb35afefb4124aa | [
"MIT"
] | null | null | null | /**
* Hyperscale
*
* (c) 2015-2017 Axel Etcheverry
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include <type_traits>
#include <hyperscale/syntax/token_kinds.hpp>
namespace hyperscale {
namespace syntax {
std::ostream& operator<<(std::ostream& os, const TokenKind kind) {
return os << TokenNames.at(kind);
}
} // end of syntax namespace
} // end of hyperscale namespace
| 21.954545 | 74 | 0.699793 | hyperscale |
c0bc83e40ba2292e5c54cded354f36c1e7816cb7 | 560 | cpp | C++ | C++/ways-to-make-a-fair-array.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/ways-to-make-a-fair-array.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/ways-to-make-a-fair-array.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
int waysToMakeFair(vector<int>& nums) {
vector<int> prefix(2), suffix(2);
for (int k = 0; k < 2; ++k) {
for (int i = k; i < size(nums); i += 2) {
suffix[k] += nums[i];
}
}
int result = 0;
for (int i = 0; i < size(nums); ++i) {
suffix[i % 2] -= nums[i];
result += int(prefix[0] + suffix[1] == prefix[1] + suffix[0]);
prefix[i % 2] += nums[i];
}
return result;
}
};
| 25.454545 | 74 | 0.410714 | Priyansh2 |
c0bd295b1b1ad41aaeaaba9d5bff134727a1068c | 406 | cpp | C++ | solutions/246.strobogrammatic-number.364981221.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/246.strobogrammatic-number.364981221.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/246.strobogrammatic-number.364981221.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
bool isStrobogrammatic(string num) {
unordered_map<char, char> mp = {
{'6', '9'}, {'9', '6'}, {'8', '8'}, {'0', '0'}, {'1', '1'},
};
int n = num.size();
for (int i = 0; i < n; i++) {
if (!mp.count(num[i]) || !mp.count(num[n - i - 1]))
return false;
if (mp[num[i]] != num[n - i - 1])
return false;
}
return true;
}
};
| 23.882353 | 67 | 0.433498 | satu0king |
c0bedab87d7b43265bc00cbfe4eb3018943cca03 | 9,937 | cc | C++ | SourceCode/src/app/tide/mass_constants.cc | Tide-for-PTM-search/Tide-for-PTM-search | b41957fec1ed333ae976e8d5b14c1c7cd481fc75 | [
"Apache-2.0"
] | 8 | 2018-02-26T00:56:14.000Z | 2021-10-31T03:45:53.000Z | SourceCode/src/app/tide/mass_constants.cc | Tide-for-PTM-search/Tide-for-PTM-search | b41957fec1ed333ae976e8d5b14c1c7cd481fc75 | [
"Apache-2.0"
] | null | null | null | SourceCode/src/app/tide/mass_constants.cc | Tide-for-PTM-search/Tide-for-PTM-search | b41957fec1ed333ae976e8d5b14c1c7cd481fc75 | [
"Apache-2.0"
] | null | null | null | #include <limits>
#include "io/carp.h"
#include "mass_constants.h"
#include "header.pb.h"
#include "stdio.h"
using namespace std;
double const MassConstants::proton = 1.00727646688;
double const MassConstants::kFixedPointScalar = 1e5;
const double MassConstants::elts_mono[] = {
1.007825035, // H
12.0, // C
14.003074, // N
15.99491463, // O
30.973762, // P
31.9720707 // S
};
const double MassConstants::elts_avg[] = {
1.00794, // H
12.0107, // C
14.0067, // N
15.9994, // O
30.973761, // P
32.065 // S
};
double MassConstants::mono_table[256];
double MassConstants::avg_table[256];
double MassConstants::nterm_mono_table[256];
double MassConstants::cterm_mono_table[256];
double MassConstants::nterm_avg_table[256];
double MassConstants::cterm_avg_table[256];
//double* MassConstants::aa_mass_table = NULL;
//double MassConstants::aa_bin_1[256];
//double MassConstants::aa_bin_2[256];
const double MassConstants::mono_h2o = 2*MassConstants::elts_mono[0] + MassConstants::elts_mono[3];
const double MassConstants::avg_h2o = 2*MassConstants::elts_avg[0] + MassConstants::elts_avg[3];
const double MassConstants::mono_nh3 = 3*MassConstants::elts_mono[0] + MassConstants::elts_mono[2];
const double MassConstants::mono_co = MassConstants::elts_mono[1] + MassConstants::elts_mono[3];
const double MassConstants::mono_oh = MassConstants::elts_mono[0] + MassConstants::elts_mono[3];
const double MassConstants::mono_h = MassConstants::elts_mono[0] ;
const double MassConstants::A = 0 - 28.0;
//const double MassConstants::B_H2O = 0 - MassConstants::mono_h2o;
//const double MassConstants::B_NH3 = 0 - MassConstants::mono_nh3;
const double MassConstants::B = 0.0;
//const double MassConstants::Y_H2O = MassConstants::mono_h2o - 18.0;
//const double MassConstants::Y_NH3 = MassConstants::mono_h2o - 17.0;
const double MassConstants::Y = MassConstants::mono_h2o;
/*const double MassConstants::BIN_SHIFT_A_ION_CHG_1 = 28;
const double MassConstants::BIN_SHIFT_A_ION_CHG_2 = 14;
const double MassConstants::BIN_SHIFT_H2O_CHG_1 = 18;
const double MassConstants::BIN_SHIFT_H2O_CHG_2 = 9;
const double MassConstants::BIN_SHIFT_NH3_CHG_1 = 17;
const double MassConstants::BIN_SHIFT_NH3_CHG_2_CASE_A = 9;
const double MassConstants::BIN_SHIFT_NH3_CHG_2_CASE_B = 8;
*/
double MassConstants::BIN_H2O = 18;
double MassConstants::BIN_NH3 = 17;
//default parameter settings, will be changed during parameter parsing
double MassConstants::bin_width_ = BIN_WIDTH; // 1.0005079;
double MassConstants::bin_offset_ = BIN_OFFSET; //0.40;
FixPt MassConstants::fixp_mono_table[256];
FixPt MassConstants::fixp_avg_table[256];
FixPt MassConstants::fixp_nterm_mono_table[256];
FixPt MassConstants::fixp_cterm_mono_table[256];
FixPt MassConstants::fixp_nterm_avg_table[256];
FixPt MassConstants::fixp_cterm_avg_table[256];
const FixPt MassConstants::fixp_mono_h2o = ToFixPt(MassConstants::mono_h2o);
const FixPt MassConstants::fixp_avg_h2o = ToFixPt(MassConstants::avg_h2o);
const FixPt MassConstants::fixp_mono_nh3 = ToFixPt(MassConstants::mono_nh3);
const FixPt MassConstants::fixp_mono_co = ToFixPt(MassConstants::mono_co);
const FixPt MassConstants::fixp_proton = ToFixPt(MassConstants::proton);
ModCoder MassConstants::mod_coder_;
vector<double> MassConstants::unique_deltas_;
//double* MassConstants::unique_deltas_bin_;
static bool CheckModTable(const pb::ModTable& mod_table);
void MassConstants::FillMassTable(const double* elements, double* table) {
const double* e = elements;
double H = e[0], C = e[1], N = e[2], O = e[3], P = e[4], S = e[5];
for (int i = 0; i < 256; ++i)
table[i] = numeric_limits<double>::signaling_NaN();
table['A'] = C*3 + H*5 + N + O ;
table['C'] = C*3 + H*5 + N + O + S ;
table['D'] = C*4 + H*5 + N + O*3 ;
table['E'] = C*5 + H*7 + N + O*3 ;
table['F'] = C*9 + H*9 + N + O ;
table['G'] = C*2 + H*3 + N + O ;
table['H'] = C*6 + H*7 + N*3 + O ;
table['I'] = C*6 + H*11 + N + O ;
table['K'] = C*6 + H*12 + N*2 + O ;
table['L'] = C*6 + H*11 + N + O ;
table['M'] = C*5 + H*9 + N + O + S ;
table['N'] = C*4 + H*6 + N*2 + O*2 ;
table['P'] = C*5 + H*7 + N + O ;
table['Q'] = C*5 + H*8 + N*2 + O*2 ;
table['R'] = C*6 + H*12 + N*4 + O ;
table['S'] = C*3 + H*5 + N + O*2 ;
table['T'] = C*4 + H*7 + N + O*2 ;
table['V'] = C*5 + H*9 + N + O ;
table['W'] = C*11 + H*10 + N*2 + O ;
table['Y'] = C*9 + H*9 + N + O*2 ;
table['w'] = H*2 + O ; // water
table['a'] = H*3 + N ; // ammonia
table['c'] = C + O ; // carbon monoxide
}
bool MassConstants::Init(const pb::ModTable* mod_table,
const pb::ModTable* n_mod_table,
const pb::ModTable* c_mod_table,
const double bin_width, const double bin_offset) {
if (mod_table && !CheckModTable(*mod_table))
return false;
if (!n_mod_table || !c_mod_table) {
carp(CARP_FATAL, "We could not find nterm or cterm mod tables. "
"This is a [relatively] new requirement in attempt to fix static "
"mod discrepancies - 5/19/2015.");
}
if (n_mod_table && !CheckModTable(*n_mod_table))
return false;
if (c_mod_table && !CheckModTable(*c_mod_table))
return false;
for (int i = 0; i < 256; ++i) {
mono_table[i] = avg_table[i] = nterm_mono_table[i] =
cterm_mono_table[i] = nterm_avg_table[i] = cterm_avg_table[i] = 0;
}
FillMassTable(elts_mono, mono_table);
FillMassTable(elts_avg, avg_table);
FillMassTable(elts_mono, nterm_mono_table);
FillMassTable(elts_mono, cterm_mono_table);
FillMassTable(elts_avg, nterm_avg_table);
FillMassTable(elts_avg, cterm_avg_table);
if (mod_table) {
// TODO: consider handling average and monoisotopic masses
// differently (e.g. with different mod tables). We're deferring
// this for now, since we haven't sorted out how to handle average
// vs. monoisotopic masses generally.
for (int i = 0; i < mod_table->static_mod_size(); ++i) {
char aa = mod_table->static_mod(i).amino_acids()[0];
double delta = mod_table->static_mod(i).delta();
mono_table[aa] += delta;
avg_table[aa] += delta;
nterm_mono_table[aa] += delta;
cterm_mono_table[aa] += delta;
nterm_avg_table[aa] += delta;
cterm_avg_table[aa] += delta;
}
carp(CARP_DEBUG, "Number of unique modification masses: %d\n", mod_table->unique_deltas_size());
mod_coder_.Init(mod_table->unique_deltas_size());
unique_deltas_.clear();
unique_deltas_.reserve(mod_table->unique_deltas_size());
for (int i = 0; i < mod_table->unique_deltas_size(); ++i) {
unique_deltas_.push_back(mod_table->unique_deltas(i));
}
}
ApplyTerminusStaticMods(n_mod_table, nterm_mono_table, nterm_avg_table);
ApplyTerminusStaticMods(c_mod_table, cterm_mono_table, cterm_avg_table);
SetFixPt(mono_table, avg_table, fixp_mono_table, fixp_avg_table);
SetFixPt(nterm_mono_table, nterm_avg_table, fixp_nterm_mono_table, fixp_nterm_avg_table);
SetFixPt(cterm_mono_table, cterm_avg_table, fixp_cterm_mono_table, fixp_cterm_avg_table);
bin_width_ = bin_width;
bin_offset_ = bin_offset;
BIN_H2O = mass2bin(mono_h2o,1);
BIN_NH3 = mass2bin(mono_nh3,1);
return true;
}
/* Updates the masses for the respective table to include the
static mod information from the mod table. */
void MassConstants::ApplyTerminusStaticMods(const pb::ModTable* mod_table,
double* mono_table, double* avg_table) {
for (int i = 0; i < mod_table->static_mod_size(); ++i) {
char aa = (mod_table->static_mod(i).amino_acids())[0];
double delta = mod_table->static_mod(i).delta();
if (aa == 'X') {
const char* AA = "ACDEFGHIKLMNPQRSTVWY";
for (int currAA = 0; AA[currAA] != '\0'; currAA++) {
mono_table[AA[currAA]] += delta;
avg_table[AA[currAA]] += delta;
}
} else {
mono_table[aa] += delta;
avg_table[aa] += delta;
}
}
}
/* Sets the fixpt for the given mono and avg tables */
void MassConstants::SetFixPt(double* mono_table, double* avg_table,
FixPt* fixp_mono_table, FixPt* fixp_avg_table) {
for (int i = 0; i < 256; ++i) {
if (mono_table[i] == 0) {
mono_table[i] = avg_table[i]/* = aa_bin_1[i] = aa_bin_2[i]*/
= numeric_limits<double>::signaling_NaN();
fixp_mono_table[i] = fixp_avg_table[i] = 0;
} else {
fixp_mono_table[i] = ToFixPt(mono_table[i]);
fixp_avg_table[i] = ToFixPt(avg_table[i]);
}
}
}
static bool CheckModification(const pb::Modification& mod,
bool* repeats = NULL) {
string aa_str = mod.amino_acids();
if (aa_str.length() != 1)
return false;
char aa = aa_str[0];
const char* AA = "ACDEFGHIKLMNPQRSTVWY";
for (; (*AA != '\0') && (*AA != aa); ++AA); // find aa in AA
if (*AA == '\0')
return false;
if (repeats != NULL) {
if (repeats[aa])
return false;
repeats[aa] = true;
}
return true;
}
static bool CheckModTable(const pb::ModTable& mod_table) {
// static mods table should not have repeated amino acids
bool repeats[256];
for (int i = 0; i < 256; ++i)
repeats[i] = false;
bool usingXMod = false;
for (int i = 0; i < mod_table.static_mod_size(); ++i) {
const pb::Modification& mod = mod_table.static_mod(i);
string aa_str = mod.amino_acids();
if (aa_str.length() != 1) {
return false;
} else if (aa_str[0] == 'X') {
usingXMod = true;
} else if (!CheckModification(mod, repeats)) {
carp(CARP_FATAL, "Multiple static mods on same residue detected");
return false;
}
}
if (usingXMod && mod_table.static_mod_size() > 1) {
carp(CARP_FATAL, "We are using X static mod, but we have detected "
"other static mods as well. Only one static mod is allowed.");
}
return true;
}
| 36.399267 | 100 | 0.658348 | Tide-for-PTM-search |
c0c1e584aabd5f3ac8a663c82729d52c056cb51e | 8,850 | cpp | C++ | node/functionaltests/send_wrong_tx_test.cpp | hadescoincom/hds-core | 383a38da9a5e40de66ba2277b54fea41b7c32537 | [
"Apache-2.0"
] | null | null | null | node/functionaltests/send_wrong_tx_test.cpp | hadescoincom/hds-core | 383a38da9a5e40de66ba2277b54fea41b7c32537 | [
"Apache-2.0"
] | null | null | null | node/functionaltests/send_wrong_tx_test.cpp | hadescoincom/hds-core | 383a38da9a5e40de66ba2277b54fea41b7c32537 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Hds Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "node/node.h"
#include "utility/logger.h"
#include "tools/base_node_connection.h"
#include "tools/tx_generator.h"
#include "tools/new_tx_tests.h"
using namespace hds;
class TestNodeConnection : public NewTxConnection
{
public:
TestNodeConnection(int argc, char* argv[]);
private:
void GenerateTests() override;
void GenerateTx();
};
TestNodeConnection::TestNodeConnection(int argc, char* argv[])
: NewTxConnection(argc, argv)
{
}
void TestNodeConnection::GenerateTests()
{
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = empty, output = 1, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs are empty
// Outputs
gen.GenerateOutputInTx(1, 1);
// Kernels
gen.GenerateKernel(1);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 1, output = empty, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(2, 1);
// Outputs are empty
// Kernels
gen.GenerateKernel(2);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 1, output = 1, fee = 1";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(3, 1);
// Outputs
gen.GenerateOutputInTx(3, 1);
// Kernels
gen.GenerateKernel(3);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with 2 inputs, 2 ouputs and 1 kernel";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(4, 1);
gen.GenerateInputInTx(4, 1);
// Outputs
gen.GenerateOutputInTx(5, 1);
gen.GenerateOutputInTx(5, 1);
// Kernels
gen.GenerateKernel(5);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with 2 inputs, 1 ouputs and 1 kernel";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(6, 1);
gen.GenerateInputInTx(6, 1);
// Outputs
gen.GenerateOutputInTx(6, 2);
// Kernels
gen.GenerateKernel(6);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with 1 inputs, 2 ouputs and 1 kernel";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(7, 2);
// Outputs
gen.GenerateOutputInTx(7, 1);
gen.GenerateOutputInTx(7, 1);
// Kernels
gen.GenerateKernel(7);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 1, output = 2, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(8, 1);
// Outputs
gen.GenerateOutputInTx(8, 2);
// Kernels
gen.GenerateKernel(8);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 2, output = 1, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(9, 2);
// Outputs
gen.GenerateOutputInTx(9, 1);
// Kernels
gen.GenerateKernel(9);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 2, output = 3, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(10, 2);
// Outputs
gen.GenerateOutputInTx(10, 3);
// Kernels
gen.GenerateKernel(10);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 4, output = 2, fee = 2";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(11, 4);
// Outputs
gen.GenerateOutputInTx(11, 2);
// Kernels
gen.GenerateKernel(11, 2);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 4, output = 2, fee = 1, fee = 1";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(12, 4);
// Outputs
gen.GenerateOutputInTx(12, 2);
// Kernels
gen.GenerateKernel(12, 1);
gen.GenerateKernel(12, 1);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(true);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 4, output = 2, fee = 1, fee = 1, fee = 1";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(13, 4);
// Outputs
gen.GenerateOutputInTx(13, 2);
// Kernels
gen.GenerateKernel(13, 1);
gen.GenerateKernel(13, 1);
gen.GenerateKernel(13, 1);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 4, output = 2, fee = 3";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(14, 4);
// Outputs
gen.GenerateOutputInTx(14, 2);
// Kernels
gen.GenerateKernel(14, 3);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 2, without output, fee = 2";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(15, 2);
// Kernels
gen.GenerateKernel(15, 2);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 2, output = 1, fee = 1, offset of tx = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(16, 2);
// Outputs
gen.GenerateOutputInTx(16, 2);
// Kernels
gen.GenerateKernel(16, 1);
gen.ZeroOffset();
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx without input, output , fee ";
TxGenerator gen(*m_pKdf);
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input.m_Commitment = ouput.m_Commitment, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(17, 2, Key::Type::Coinbase);
// Outputs
gen.GenerateOutputInTx(17, 2, Key::Type::Coinbase);
// Kernels
gen.GenerateKernel(17, 0);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 0, ouput = 0, fee = 0";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(18, 0);
// Outputs
gen.GenerateOutputInTx(18, 0, Key::Type::Regular, false);
// Kernels
gen.GenerateKernel(18, 0);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
m_Tests.push_back([this]()
{
LOG_INFO() << "Send tx with input = 2, ouput = 0, fee = 2";
TxGenerator gen(*m_pKdf);
// Inputs
gen.GenerateInputInTx(19, 2);
// Outputs
gen.GenerateOutputInTx(19, 0, Key::Type::Regular, false);
// Kernels
gen.GenerateKernel(19, 2);
gen.Sort();
LOG_INFO() << "tx.IsValid == " << gen.IsValid();
Send(gen.GetTransaction());
});
m_Results.push_back(false);
}
int main(int argc, char* argv[])
{
int logLevel = LOG_LEVEL_DEBUG;
auto logger = Logger::create(logLevel, logLevel);
TestNodeConnection connection(argc, argv);
connection.Run();
return connection.CheckOnFailed();
} | 18.829787 | 80 | 0.638757 | hadescoincom |
c0c1f6997d8097eef2caaa5ae8ef123c0b30389b | 6,090 | cpp | C++ | ngraph/test/backend/space_to_depth.in.cpp | uikilin100/openvino | afc5191b8c75b1de4adc8cb07c6269b52882ddfe | [
"Apache-2.0"
] | 1 | 2021-12-30T05:47:43.000Z | 2021-12-30T05:47:43.000Z | ngraph/test/backend/space_to_depth.in.cpp | uikilin100/openvino | afc5191b8c75b1de4adc8cb07c6269b52882ddfe | [
"Apache-2.0"
] | 42 | 2020-11-23T08:09:57.000Z | 2022-02-21T13:03:34.000Z | ngraph/test/backend/space_to_depth.in.cpp | tsocha/openvino | 3081fac7581933568b496a3c4e744d1cee481619 | [
"Apache-2.0"
] | 4 | 2021-04-02T08:48:38.000Z | 2021-07-01T06:59:02.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/op/space_to_depth.hpp"
#include "util/engine/test_engines.hpp"
#include "util/test_case.hpp"
#include "util/test_control.hpp"
using namespace ngraph;
static std::string s_manifest = "${MANIFEST}";
using TestEngine = test::ENGINE_CLASS_NAME(${BACKEND_NAME});
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_block_first_K2_BS2) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 4, 4});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 2);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f,
11.f, 12.f, 13.f, 14.f, 15.f, 16.f, 17.f, 18.f, 19.f, 20.f, 21.f,
22.f, 23.f, 24.f, 25.f, 26.f, 27.f, 28.f, 29.f, 30.f, 31.f});
test_case.add_expected_output<float>(
Shape{1, 8, 2, 2},
{0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f, 1.f, 3.f, 9.f, 11.f, 17.f, 19.f, 25.f, 27.f,
4.f, 6.f, 12.f, 14.f, 20.f, 22.f, 28.f, 30.f, 5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_block_first_K2_BS3) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 6, 3});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 3);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 4.f, 8.f, 12.f, 16.f, 20.f, 24.f, 28.f, 32.f, 1.f, 5.f, 9.f,
13.f, 17.f, 21.f, 25.f, 29.f, 33.f, 2.f, 6.f, 10.f, 14.f, 18.f, 22.f,
26.f, 30.f, 34.f, 3.f, 7.f, 11.f, 15.f, 19.f, 23.f, 27.f, 31.f, 35.f});
test_case.add_expected_output<float>(
Shape{1, 18, 2, 1},
{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f, 16.f, 17.f,
18.f, 19.f, 20.f, 21.f, 22.f, 23.f, 24.f, 25.f, 26.f, 27.f, 28.f, 29.f, 30.f, 31.f, 32.f, 33.f, 34.f, 35.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_block_first_K1_BS3) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 6});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 3);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 4.f, 8.f, 1.f, 5.f, 9.f, 2.f, 6.f, 10.f, 3.f, 7.f, 11.f});
test_case.add_expected_output<float>(Shape{1, 6, 2},
{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_depth_first_K2_BS2) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 4, 4});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 2);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 16.f, 2.f, 18.f, 1.f, 17.f, 3.f, 19.f, 8.f, 24.f, 10.f,
26.f, 9.f, 25.f, 11.f, 27.f, 4.f, 20.f, 6.f, 22.f, 5.f, 21.f,
7.f, 23.f, 12.f, 28.f, 14.f, 30.f, 13.f, 29.f, 15.f, 31.f});
test_case.add_expected_output<float>(
Shape{1, 8, 2, 2},
{0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f, 1.f, 3.f, 9.f, 11.f, 17.f, 19.f, 25.f, 27.f,
4.f, 6.f, 12.f, 14.f, 20.f, 22.f, 28.f, 30.f, 5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_depth_first_K2_BS3) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 6, 3});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 3);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 2.f, 4.f, 6.f, 8.f, 10.f, 12.f, 14.f, 16.f, 1.f, 3.f, 5.f,
7.f, 9.f, 11.f, 13.f, 15.f, 17.f, 18.f, 20.f, 22.f, 24.f, 26.f, 28.f,
30.f, 32.f, 34.f, 19.f, 21.f, 23.f, 25.f, 27.f, 29.f, 31.f, 33.f, 35.f});
test_case.add_expected_output<float>(
Shape{1, 18, 2, 1},
{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f, 16.f, 17.f,
18.f, 19.f, 20.f, 21.f, 22.f, 23.f, 24.f, 25.f, 26.f, 27.f, 28.f, 29.f, 30.f, 31.f, 32.f, 33.f, 34.f, 35.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_depth_first_K1_BS3) {
auto A = std::make_shared<op::Parameter>(element::f32, Shape{1, 2, 6});
const auto mode = op::SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST;
auto space_to_depth = std::make_shared<op::SpaceToDepth>(A, mode, 3);
auto function = std::make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 2.f, 4.f, 1.f, 3.f, 5.f, 6.f, 8.f, 10.f, 7.f, 9.f, 11.f});
test_case.add_expected_output<float>(Shape{1, 6, 2},
{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f});
test_case.run();
}
| 55.363636 | 118 | 0.58555 | uikilin100 |
c0c2d64937611ef52e171082ad849068ea8cf7a1 | 9,965 | cc | C++ | src/cvplot/window.cc | TimmvonderMehden/caffe2_cpp_tutorial | d207768adaf13ae6bc8e49ba0868234001a43ce9 | [
"BSD-2-Clause"
] | 23 | 2020-09-10T14:33:18.000Z | 2022-03-09T09:07:30.000Z | src/cvplot/window.cc | TimmvonderMehden/caffe2_cpp_tutorial | d207768adaf13ae6bc8e49ba0868234001a43ce9 | [
"BSD-2-Clause"
] | 2 | 2020-09-11T03:01:20.000Z | 2020-09-30T03:04:19.000Z | src/cvplot/window.cc | TimmvonderMehden/caffe2_cpp_tutorial | d207768adaf13ae6bc8e49ba0868234001a43ce9 | [
"BSD-2-Clause"
] | 7 | 2020-09-17T20:53:50.000Z | 2021-11-19T15:32:49.000Z | #include "cvplot/window.h"
#include "internal.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <ctime>
namespace cvplot {
namespace {
Window *shared_window = NULL;
int shared_index = 0;
clock_t shared_time = clock();
} // namespace
float runtime() { return (float)(clock() - shared_time) / CLOCKS_PER_SEC; }
void mouse_callback(int event, int x, int y, int flags, void *window) {
((Window *)window)->onmouse(event, x, y, flags);
}
// View
View &View::resize(Rect rect) {
rect_ = rect;
window_.dirty();
return *this;
}
View &View::size(Size size) {
rect_.width = size.width;
rect_.height = size.height;
window_.dirty();
return *this;
}
View &View::offset(Offset offset) {
rect_.x = offset.x;
rect_.y = offset.y;
window_.dirty();
return *this;
}
View &View::autosize() {
size({0, 0});
return *this;
}
View &View::title(const std::string &title) {
title_ = title;
window_.dirty();
return *this;
}
View &View::alpha(int alpha) {
background_color_ = background_color_.alpha(alpha);
frame_color_ = frame_color_.alpha(alpha);
text_color_ = text_color_.alpha(alpha);
window_.dirty();
return *this;
}
View &View::backgroundColor(Color color) {
background_color_ = color;
window_.dirty();
return *this;
}
View &View::frameColor(Color color) {
frame_color_ = color;
window_.dirty();
return *this;
}
View &View::textColor(Color color) {
text_color_ = color;
window_.dirty();
return *this;
}
View &View::mouse(MouseCallback callback, void *param) {
mouse_callback_ = callback;
mouse_param_ = (param == NULL ? this : param);
return *this;
}
Color View::backgroundColor() { return background_color_; }
Color View::frameColor() { return frame_color_; }
Color View::textColor() { return text_color_; }
std::string &View::title() { return title_; }
void View::drawRect(Rect rect, Color color) {
Trans trans(window_.buffer());
cv::rectangle(trans.with(color), {rect_.x + rect.x, rect_.y + rect.y},
{rect_.x + rect.x + rect.width, rect_.y + rect.y + rect.height},
color2scalar(color), -1);
window_.dirty();
}
void View::drawText(const std::string &text, Offset offset, Color color) const {
auto face = cv::FONT_HERSHEY_SIMPLEX;
auto scale = 0.4f;
auto thickness = 1.f;
int baseline;
cv::Size size = getTextSize(text, face, scale, thickness, &baseline);
cv::Point org(rect_.x + offset.x, rect_.y + size.height + offset.y);
Trans trans(window_.buffer());
cv::putText(trans.with(color), text.c_str(), org, face, scale,
color2scalar(color), thickness);
window_.dirty();
}
void View::drawFrame(const std::string &title) const {
Trans trans(window_.buffer());
cv::rectangle(trans.with(background_color_), {rect_.x, rect_.y},
{rect_.x + rect_.width - 1, rect_.y + rect_.height - 1},
color2scalar(background_color_), 1);
cv::rectangle(trans.with(frame_color_), {rect_.x + 1, rect_.y + 1},
{rect_.x + rect_.width - 2, rect_.y + rect_.height - 2},
color2scalar(frame_color_), 1);
cv::rectangle(trans.with(frame_color_), {rect_.x + 2, rect_.y + 2},
{rect_.x + rect_.width - 3, rect_.y + 16},
color2scalar(frame_color_), -1);
int baseline;
cv::Size size =
getTextSize(title.c_str(), cv::FONT_HERSHEY_PLAIN, 1.f, 1.f, &baseline);
cv::putText(trans.with(text_color_), title.c_str(),
{rect_.x + 2 + (rect_.width - size.width) / 2, rect_.y + 14},
cv::FONT_HERSHEY_PLAIN, 1.f, color2scalar(text_color_), 1.f);
window_.dirty();
}
void View::drawImage(const void *image, int alpha) {
auto &img = *(cv::Mat *)image;
if (rect_.width == 0 && rect_.height == 0) {
rect_.width = img.cols;
rect_.height = img.rows;
}
window_.ensure(rect_);
Trans trans(window_.buffer());
if (img.cols != rect_.width || img.rows != rect_.height) {
cv::Mat resized;
cv::resize(img, resized, {rect_.width, rect_.height});
resized.copyTo(
trans.with(alpha)({rect_.x, rect_.y, rect_.width, rect_.height}));
} else {
img.copyTo(
trans.with(alpha)({rect_.x, rect_.y, rect_.width, rect_.height}));
}
window_.dirty();
}
void View::drawFill(Color color) {
Trans trans(window_.buffer());
cv::rectangle(trans.with(color), {rect_.x, rect_.y},
{rect_.x + rect_.width - 1, rect_.y + rect_.height - 1},
color2scalar(color), -1);
window_.dirty();
}
void *View::buffer(Rect &rect) {
window_.ensure(rect_);
rect = rect_;
return window_.buffer();
}
void View::finish() {
if (!frameless_) {
drawFrame(title_);
}
window_.dirty();
}
void View::flush() { window_.flush(); }
bool View::has(Offset offset) {
return offset.x >= rect_.x && offset.y >= rect_.y &&
offset.x < rect_.x + rect_.width && offset.y < rect_.y + rect_.height;
}
void View::onmouse(int event, int x, int y, int flags) {
if (mouse_callback_ != NULL) {
mouse_callback_(event, x, y, flags, mouse_param_);
}
}
void View::hide(bool hidden) {
if (hidden_ != hidden) {
hidden_ = hidden;
drawFill();
}
}
// Window
Window::Window(const std::string &title)
: offset_(0, 0),
buffer_(NULL),
title_(title),
dirty_(false),
flush_time_(0),
fps_(1),
hidden_(false),
show_cursor_(false),
cursor_(-10, -10),
name_("cvplot_" + std::to_string(shared_index++)) {}
void *Window::buffer() { return buffer_; }
Window &Window::resize(Rect rect) {
offset({rect.x, rect.y});
size({rect.width, rect.height});
return *this;
}
Window &Window::size(Size size) {
auto &buffer = *(new cv::Mat(cv::Size(size.width, size.height), CV_8UC3,
color2scalar(Gray)));
if (buffer_ != NULL) {
auto ¤t = *(cv::Mat *)buffer_;
if (current.cols > 0 && current.rows > 0 && size.width > 0 &&
size.height > 0) {
cv::Rect inter(0, 0, std::min(current.cols, size.width),
std::min(current.rows, size.height));
current(inter).copyTo(buffer(inter));
}
delete ¤t;
}
buffer_ = &buffer;
dirty();
return *this;
}
Window &Window::offset(Offset offset) {
offset_ = offset;
cv::namedWindow(name_, cv::WINDOW_AUTOSIZE);
cv::moveWindow(name_, offset.x, offset.y);
return *this;
}
Window &Window::title(const std::string &title) {
title_ = title;
return *this;
}
Window &Window::fps(float fps) {
fps_ = fps;
return *this;
}
Window &Window::cursor(bool cursor) {
show_cursor_ = cursor;
return *this;
}
Window &Window::ensure(Rect rect) {
if (buffer_ == NULL) {
size({rect.x + rect.width, rect.y + rect.height});
} else {
auto &b = *(cv::Mat *)buffer_;
if (rect.x + rect.width > b.cols || rect.y + rect.height > b.rows) {
size({std::max(b.cols, rect.x + rect.width),
std::max(b.rows, rect.y + rect.height)});
}
}
return *this;
}
void Window::onmouse(int event, int x, int y, int flags) {
for (auto &pair : views_) {
auto &view = pair.second;
if (view.has({x, y})) {
view.onmouse(event, x, y, flags);
break;
}
}
cursor_ = {x, y};
if (show_cursor_) {
dirty();
flush();
}
}
void Window::flush() {
if (dirty_ && buffer_ != NULL) {
auto b = (cv::Mat *)buffer_;
if (b->cols > 0 && b->rows > 0) {
cv::Mat mat;
if (show_cursor_) {
b->copyTo(mat);
cv::line(mat, {cursor_.x - 4, cursor_.y + 1},
{cursor_.x + 6, cursor_.y + 1}, color2scalar(White), 1);
cv::line(mat, {cursor_.x + 1, cursor_.y - 4},
{cursor_.x + 1, cursor_.y + 6}, color2scalar(White), 1);
cv::line(mat, {cursor_.x - 5, cursor_.y}, {cursor_.x + 5, cursor_.y},
color2scalar(Black), 1);
cv::line(mat, {cursor_.x, cursor_.y - 5}, {cursor_.x, cursor_.y + 5},
color2scalar(Black), 1);
b = &mat;
}
cv::namedWindow(name_, cv::WINDOW_AUTOSIZE);
#if CV_MAJOR_VERSION > 2
cv::setWindowTitle(name_, title_);
#endif
cv::imshow(name_.c_str(), *b);
cv::setMouseCallback(name_.c_str(), mouse_callback, this);
Util::sleep();
}
}
dirty_ = false;
flush_time_ = runtime();
}
View &Window::view(const std::string &name, Size size) {
if (views_.count(name) == 0) {
views_.insert(
std::map<std::string, View>::value_type(name, View(*this, name, size)));
}
return views_.at(name);
}
void Window::tick() {
if (fps_ > 0 && (runtime() - flush_time_) > 1.f / fps_) {
flush();
}
}
void Window::dirty() { dirty_ = true; }
void Window::hide(bool hidden) {
if (hidden_ != hidden) {
hidden_ = hidden;
if (hidden) {
cv::destroyWindow(name_.c_str());
} else {
dirty();
flush();
}
}
}
Window &Window::current() {
if (shared_window == NULL) {
shared_window = new Window("");
}
return *(Window *)shared_window;
}
Window &Window::current(const std::string &title) {
shared_window = new Window(title);
return *(Window *)shared_window;
}
void Window::current(Window &window) { shared_window = &window; }
// Util
void Util::sleep(float seconds) {
cvWaitKey(std::max(1, (int)(seconds * 1000)));
}
char Util::key(float timeout) {
return cvWaitKey(std::max(0, (int)(timeout * 1000)));
}
std::string Util::line(float timeout) {
std::stringstream stream;
auto ms = (timeout > 0 ? std::max(1, (int)(timeout * 1000)) : -1);
while (ms != 0) {
auto key = cvWaitKey(1);
if (key == -1) {
ms--;
continue;
}
if (key == '\r' || key <= '\n') {
break;
} else if (key == '\b' || key == 127) {
auto s = stream.str();
stream = std::stringstream();
if (s.length() > 0) {
stream << s.substr(0, s.length() - 1);
}
} else {
stream << (char)key;
}
}
return stream.str();
}
} // namespace cvplot
| 25.291878 | 80 | 0.598093 | TimmvonderMehden |
c0c3ca34fb0f1c55cb67b0693de9e42d5b6503cf | 731 | cpp | C++ | src/BasicLNS.cpp | YimingXieUSC/curve_lns | 5ac334a3500a9d7582bca6310ef13e0f6a117417 | [
"MIT"
] | 8 | 2021-12-29T03:42:37.000Z | 2022-02-17T00:39:26.000Z | src/BasicLNS.cpp | YimingXieUSC/curve_lns | 5ac334a3500a9d7582bca6310ef13e0f6a117417 | [
"MIT"
] | null | null | null | src/BasicLNS.cpp | YimingXieUSC/curve_lns | 5ac334a3500a9d7582bca6310ef13e0f6a117417 | [
"MIT"
] | 1 | 2022-02-26T00:20:38.000Z | 2022-02-26T00:20:38.000Z | #include "BasicLNS.h"
BasicLNS::BasicLNS(const Instance& instance, double time_limit, int neighbor_size, int screen) :
instance(instance), time_limit(time_limit), neighbor_size(neighbor_size), screen(screen) {}
void BasicLNS::rouletteWheel()
{
double sum = 0;
for (const auto& h : destroy_weights)
sum += h;
if (screen >= 2)
{
cout << "destroy weights = ";
for (const auto& h : destroy_weights)
cout << h / sum << ",";
}
double r = (double) rand() / RAND_MAX;
double threshold = destroy_weights[0];
selected_neighbor = 0;
while (threshold < r * sum)
{
selected_neighbor++;
threshold += destroy_weights[selected_neighbor];
}
}
| 29.24 | 99 | 0.612859 | YimingXieUSC |
c0c464b1d1141fbac983bb1aefe32332d7194361 | 1,266 | cc | C++ | burger/net/tests/tcpConnection_test01.cc | BurgerGroup/Burger | b9159ea8855122a32091d40eb24439456f8879a9 | [
"MIT"
] | 30 | 2021-05-07T16:54:30.000Z | 2022-03-12T01:55:49.000Z | burger/net/tests/tcpConnection_test01.cc | chanchann/Burger | b9159ea8855122a32091d40eb24439456f8879a9 | [
"MIT"
] | 1 | 2021-07-27T16:27:14.000Z | 2021-07-27T16:27:14.000Z | burger/net/tests/tcpConnection_test01.cc | chanchann/Burger | b9159ea8855122a32091d40eb24439456f8879a9 | [
"MIT"
] | 9 | 2021-06-07T09:20:46.000Z | 2022-03-01T06:30:36.000Z | #include "burger/net/TcpServer.h"
#include "burger/net/EventLoop.h"
#include "burger/net/InetAddress.h"
#include <iostream>
using namespace burger;
using namespace burger::net;
void onConnection(const TcpConnectionPtr& conn) {
if(conn->isConnected()) {
std::cout << "onConnection(): new connection ["
<< conn->getName() << "] from "
<< conn->getPeerAddress().getIpPortStr() << std::endl;
} else {
std::cout << "onConnection() : connection "
<< conn->getName() << " is down" << std::endl;
}
}
void onMessage(const TcpConnectionPtr& conn,
Buffer& buf,
Timestamp recieveTime) {
std::cout << "onMessage(): received " << buf.getReadableBytes()
<< " bytes from connection " << conn->getName()
<< " at " << recieveTime.toFormatTime() <<std::endl;
std::cout << "onMessage() : " << buf.retrieveAllAsString() << std::endl;
}
int main() {
std::cout << "main() : pid = " << ::getpid() << std::endl;
InetAddress listenAddr(8888);
EventLoop loop;
TcpServer server(&loop, listenAddr, "TcpServer");
server.setConnectionCallback(onConnection);
server.setMessageCallback(onMessage);
server.start();
loop.loop();
} | 32.461538 | 76 | 0.596367 | BurgerGroup |
c0c5057bdf6c8388eb0c9d6a21f9fa960e46d911 | 690 | cpp | C++ | 202105/2/_88_MergeSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202105/2/_88_MergeSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202105/2/_88_MergeSortedArray.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | //
// Created by GYC on 2021/5/11.
//
#include "../../common.h"
class Solution {
public:
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
int i = m - 1, j = n - 1, curr = m + n - 1;
while (i > -1 || j > -1) {
if (i == -1) {
nums1[curr--] = nums2[j--];
} else if (j == -1) {
nums1[curr--] = nums1[i--];
} else if (nums1[i] > nums2[j]) {
nums1[curr--] = nums1[i--];
} else {
nums1[curr--] = nums2[j--];
}
}
}
};
int main() {
vector<int> v1{1, 2, 3, 0, 0, 0}, v2{2, 5, 6};
Solution().merge(v1, 3, v2, 3);
} | 23 | 70 | 0.385507 | uaniheng |
c0c51a8dfd23552cb35c4b8498c010596b1fc269 | 637 | cpp | C++ | MOFA/Utility/Global.cpp | C6H5-NO2/MOFA | dcd6c886a255e49986f0914e2bca6bee6f628b45 | [
"MIT"
] | 1 | 2021-04-03T11:57:50.000Z | 2021-04-03T11:57:50.000Z | MOFA/Utility/Global.cpp | C6H5-NO2/MOFA | dcd6c886a255e49986f0914e2bca6bee6f628b45 | [
"MIT"
] | null | null | null | MOFA/Utility/Global.cpp | C6H5-NO2/MOFA | dcd6c886a255e49986f0914e2bca6bee6f628b45 | [
"MIT"
] | null | null | null | #include "Global.h"
#include "../Instruction/InstructionSet.h"
#include "../Register/RegisterFile.h"
namespace MOFA {
std::unique_ptr<const InstructionSet> Global::instrset(new InstructionSet);
std::unique_ptr<const RegisterFile> Global::regfile(new RegisterFile);
const InstructionSet& Global::getInstructionSet() noexcept {
if(!instrset)
instrset = std::make_unique<const InstructionSet>();
return *instrset;
}
const RegisterFile& Global::getRegisterFile() noexcept {
if(!regfile)
regfile = std::make_unique<const RegisterFile>();
return *regfile;
}
}
| 30.333333 | 79 | 0.675039 | C6H5-NO2 |
c0c82851489233e5d903c38dafc04e8a1aa7ca29 | 1,167 | cpp | C++ | 901-1000/909. Snakes and Ladders.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 901-1000/909. Snakes and Ladders.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 901-1000/909. Snakes and Ladders.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | class Solution
{
public:
int snakesAndLadders(vector<vector<int>> &board)
{
int N = board.size();
vector<int> f(N * N, INT_MAX);
vector<int> newBoard(N * N);
bool flag = true;
for (int i = N - 1, idx = 0; i >= 0; --i)
{
if (flag)
{
for (int j = 0; j < N; ++j)
{
newBoard[idx++] = board[i][j];
}
}
else
{
for (int j = N - 1; j >= 0; --j)
{
newBoard[idx++] = board[i][j];
}
}
flag = !flag;
}
f[0] = 0;
deque<int> dq;
dq.push_back(0);
vector<bool> visited(N * N, false);
visited[0] = true;
while (!dq.empty())
{
auto i = dq.front();
dq.pop_front();
for (int d = 1; d <= 6 && i + d < N * N; ++d)
{
int dest = newBoard[i + d] == -1 ? i + d : newBoard[i + d] - 1;
f[dest] = f[dest] == -1 ? f[i] + 1 : min(f[dest], f[i] + 1);
if (!visited[dest])
{
if (dest == N * N - 1)
break;
visited[dest] = true;
dq.push_back(dest);
}
}
}
return f[N * N - 1] == INT_MAX ? -1 : f[N * N - 1];
}
}; | 22.442308 | 71 | 0.394173 | erichuang1994 |
c0c856faa76e7349d27b8bedd53061330e06eec6 | 807 | hh | C++ | src/GSPH/computeSPHVolume.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/GSPH/computeSPHVolume.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 17 | 2020-01-05T08:41:46.000Z | 2020-09-18T00:08:32.000Z | src/GSPH/computeSPHVolume.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// Compute the volume from m/rho
//----------------------------------------------------------------------------//
#ifndef __Spheral__computeSPHVolume__
#define __Spheral__computeSPHVolume__
#include <vector>
namespace Spheral {
// Forward declarations.
template<typename Dimension> class ConnectivityMap;
template<typename Dimension> class TableKernel;
template<typename Dimension, typename DataType> class FieldList;
template<typename Dimension>
void
computeSPHVolume(const FieldList<Dimension, typename Dimension::Scalar>& mass,
const FieldList<Dimension, typename Dimension::Scalar>& massDensity,
FieldList<Dimension, typename Dimension::Scalar>& volume);
}
#endif | 29.888889 | 85 | 0.612144 | jmikeowen |
c0c85bcfa6119b430f880454108b4ea9b1a2c31d | 10,954 | cpp | C++ | engine/test/qlcphysical/qlcphysical_test.cpp | bgnt44/qlcplus2020 | f0906ca725e0bae5b012a30188658e4f406355e1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | engine/test/qlcphysical/qlcphysical_test.cpp | bgnt44/qlcplus2020 | f0906ca725e0bae5b012a30188658e4f406355e1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | engine/test/qlcphysical/qlcphysical_test.cpp | bgnt44/qlcplus2020 | f0906ca725e0bae5b012a30188658e4f406355e1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Q Light Controller Plus - Unit tests
qlcphysical_test.cpp
Copyright (C) Heikki Junnila
Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QtTest>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "qlcphysical_test.h"
#include "qlcphysical.h"
void QLCPhysical_Test::bulbType()
{
QVERIFY(p.bulbType().isEmpty());
p.setBulbType("BulbType");
QVERIFY(p.bulbType() == "BulbType");
}
void QLCPhysical_Test::bulbLumens()
{
QVERIFY(p.bulbLumens() == 0);
p.setBulbLumens(10000);
QVERIFY(p.bulbLumens() == 10000);
}
void QLCPhysical_Test::bulbColourTemp()
{
QVERIFY(p.bulbColourTemperature() == 0);
p.setBulbColourTemperature(3200);
QVERIFY(p.bulbColourTemperature() == 3200);
}
void QLCPhysical_Test::weight()
{
QVERIFY(p.weight() == 0);
p.setWeight(7);
QVERIFY(p.weight() == 7);
p.setWeight(5.02837);
QCOMPARE(p.weight(), 5.02837);
}
void QLCPhysical_Test::width()
{
QVERIFY(p.width() == 0);
p.setWidth(600);
QVERIFY(p.width() == 600);
}
void QLCPhysical_Test::height()
{
QVERIFY(p.height() == 0);
p.setHeight(1200);
QVERIFY(p.height() == 1200);
}
void QLCPhysical_Test::depth()
{
QVERIFY(p.depth() == 0);
p.setDepth(250);
QVERIFY(p.depth() == 250);
}
void QLCPhysical_Test::lensName()
{
QVERIFY(p.lensName() == "Other");
p.setLensName("Fresnel");
QVERIFY(p.lensName() == "Fresnel");
}
void QLCPhysical_Test::lensDegreesMin()
{
QVERIFY(p.lensDegreesMin() == 0);
p.setLensDegreesMin(9.4);
QVERIFY(p.lensDegreesMin() == 9.4);
}
void QLCPhysical_Test::lensDegreesMax()
{
QVERIFY(p.lensDegreesMax() == 0);
p.setLensDegreesMax(40.5);
QVERIFY(p.lensDegreesMax() == 40.5);
}
void QLCPhysical_Test::focusType()
{
QVERIFY(p.focusType() == "Fixed");
p.setFocusType("Head");
QVERIFY(p.focusType() == "Head");
}
void QLCPhysical_Test::focusPanMax()
{
QVERIFY(p.focusPanMax() == 0);
p.setFocusPanMax(540);
QVERIFY(p.focusPanMax() == 540);
}
void QLCPhysical_Test::focusTiltMax()
{
QVERIFY(p.focusTiltMax() == 0);
p.setFocusTiltMax(270);
QVERIFY(p.focusTiltMax() == 270);
}
void QLCPhysical_Test::layoutSize()
{
QVERIFY(p.layoutSize() == QSize(1, 1));
p.setLayoutSize(QSize(6, 3));
QVERIFY(p.layoutSize() == QSize(6, 3));
}
void QLCPhysical_Test::powerConsumption()
{
QVERIFY(p.powerConsumption() == 0);
p.setPowerConsumption(24000);
QVERIFY(p.powerConsumption() == 24000);
}
void QLCPhysical_Test::dmxConnector()
{
QVERIFY(p.dmxConnector() == "5-pin");
p.setDmxConnector("3-pin");
QVERIFY(p.dmxConnector() == "3-pin");
}
void QLCPhysical_Test::copy()
{
QLCPhysical c = p;
QVERIFY(c.bulbType() == p.bulbType());
QVERIFY(c.bulbLumens() == p.bulbLumens());
QVERIFY(c.bulbColourTemperature() == p.bulbColourTemperature());
QVERIFY(c.weight() == p.weight());
QVERIFY(c.width() == p.width());
QVERIFY(c.height() == p.height());
QVERIFY(c.depth() == p.depth());
QVERIFY(c.lensName() == p.lensName());
QVERIFY(c.lensDegreesMin() == p.lensDegreesMin());
QVERIFY(c.lensDegreesMax() == p.lensDegreesMax());
QVERIFY(c.focusType() == p.focusType());
QVERIFY(c.focusPanMax() == p.focusPanMax());
QVERIFY(c.focusTiltMax() == p.focusTiltMax());
QVERIFY(c.powerConsumption() == p.powerConsumption());
QVERIFY(c.dmxConnector() == p.dmxConnector());
}
void QLCPhysical_Test::load()
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
xmlWriter.writeStartElement("Physical");
/* Bulb */
xmlWriter.writeStartElement("Bulb");
xmlWriter.writeAttribute("Type", "LED");
xmlWriter.writeAttribute("Lumens", "18000");
xmlWriter.writeAttribute("ColourTemperature", "6500");
xmlWriter.writeEndElement();
/* Dimensions */
xmlWriter.writeStartElement("Dimensions");
xmlWriter.writeAttribute("Weight", QString::number(39.4));
xmlWriter.writeAttribute("Width", "530");
xmlWriter.writeAttribute("Height", "320");
xmlWriter.writeAttribute("Depth", "260");
xmlWriter.writeEndElement();
/* Lens */
xmlWriter.writeStartElement("Lens");
xmlWriter.writeAttribute("Name", "Fresnel");
xmlWriter.writeAttribute("DegreesMin", "8");
xmlWriter.writeAttribute("DegreesMax", "38");
xmlWriter.writeEndElement();
/* Focus */
xmlWriter.writeStartElement("Focus");
xmlWriter.writeAttribute("Type", "Head");
xmlWriter.writeAttribute("PanMax", "520");
xmlWriter.writeAttribute("TiltMax", "270");
xmlWriter.writeEndElement();
/* Technical */
xmlWriter.writeStartElement("Technical");
xmlWriter.writeAttribute("PowerConsumption", "250");
xmlWriter.writeAttribute("DmxConnector", "5-pin");
xmlWriter.writeEndElement();
/* Unrecognized tag */
xmlWriter.writeStartElement("HomerSimpson");
xmlWriter.writeAttribute("BeerConsumption", "25000");
xmlWriter.writeAttribute("PreferredBrand", "Duff");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.setDevice(NULL);
buffer.close();
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlStreamReader xmlReader(&buffer);
xmlReader.readNextStartElement();
QVERIFY(p.loadXML(xmlReader) == true);
QVERIFY(p.bulbType() == "LED");
QVERIFY(p.bulbLumens() == 18000);
QVERIFY(p.bulbColourTemperature() == 6500);
QVERIFY(p.weight() == 39.4);
QVERIFY(p.width() == 530);
QVERIFY(p.height() == 320);
QVERIFY(p.depth() == 260);
QVERIFY(p.lensName() == "Fresnel");
QVERIFY(p.lensDegreesMin() == 8);
QVERIFY(p.lensDegreesMax() == 38);
QVERIFY(p.focusType() == "Head");
QVERIFY(p.focusPanMax() == 520);
QVERIFY(p.focusTiltMax() == 270);
QVERIFY(p.powerConsumption() == 250);
QVERIFY(p.dmxConnector() == "5-pin");
}
void QLCPhysical_Test::loadWrongRoot()
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
xmlWriter.writeStartElement("Foosical");
/* Bulb */
xmlWriter.writeStartElement("Bulb");
xmlWriter.writeAttribute("Type", "LED");
xmlWriter.writeAttribute("Lumens", "18000");
xmlWriter.writeAttribute("ColourTemperature", "6500");
xmlWriter.writeEndElement();
/* Dimensions */
xmlWriter.writeStartElement("Dimensions");
xmlWriter.writeAttribute("Weight", QString::number(39.4));
xmlWriter.writeAttribute("Width", "530");
xmlWriter.writeAttribute("Height", "320");
xmlWriter.writeAttribute("Depth", "260");
xmlWriter.writeEndElement();
/* Lens */
xmlWriter.writeStartElement("Lens");
xmlWriter.writeAttribute("Name", "Fresnel");
xmlWriter.writeAttribute("DegreesMin", "8");
xmlWriter.writeAttribute("DegreesMax", "38");
xmlWriter.writeEndElement();
/* Focus */
xmlWriter.writeStartElement("Focus");
xmlWriter.writeAttribute("Type", "Head");
xmlWriter.writeAttribute("PanMax", "520");
xmlWriter.writeAttribute("TiltMax", "270");
xmlWriter.writeEndElement();
/* Technical */
xmlWriter.writeStartElement("Technical");
xmlWriter.writeAttribute("PowerConsumption", "250");
xmlWriter.writeAttribute("DmxConnector", "5-pin");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
xmlWriter.setDevice(NULL);
buffer.close();
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlStreamReader xmlReader(&buffer);
xmlReader.readNextStartElement();
QVERIFY(p.loadXML(xmlReader) == false);
}
void QLCPhysical_Test::save()
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly | QIODevice::Text);
QXmlStreamWriter xmlWriter(&buffer);
bool bulb = false, dim = false, lens = false, focus = false, layout = false, technical = false;
QVERIFY(p.saveXML(&xmlWriter) == true);
qDebug() << buffer.buffer();
xmlWriter.setDevice(NULL);
buffer.close();
buffer.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlStreamReader xmlReader(&buffer);
xmlReader.readNextStartElement();
QVERIFY(xmlReader.name() == "Physical");
while (xmlReader.readNextStartElement())
{
if (xmlReader.name() == "Bulb")
{
bulb = true;
QVERIFY(xmlReader.attributes().value("Type") == "LED");
QVERIFY(xmlReader.attributes().value("Lumens") == "18000");
QVERIFY(xmlReader.attributes().value("ColourTemperature") == "6500");
}
else if (xmlReader.name() == "Dimensions")
{
dim = true;
QVERIFY(xmlReader.attributes().value("Width") == "530");
QVERIFY(xmlReader.attributes().value("Depth") == "260");
QVERIFY(xmlReader.attributes().value("Height") == "320");
QCOMPARE(xmlReader.attributes().value("Weight").toString().toDouble(), 39.4);
}
else if (xmlReader.name() == "Lens")
{
lens = true;
QVERIFY(xmlReader.attributes().value("Name") == "Fresnel");
QVERIFY(xmlReader.attributes().value("DegreesMin") == "8");
QVERIFY(xmlReader.attributes().value("DegreesMax") == "38");
}
else if (xmlReader.name() == "Focus")
{
focus = true;
QVERIFY(xmlReader.attributes().value("Type") == "Head");
QVERIFY(xmlReader.attributes().value("PanMax") == "520");
QVERIFY(xmlReader.attributes().value("TiltMax") == "270");
}
else if (xmlReader.name() == "Layout")
{
layout = true;
QVERIFY(xmlReader.attributes().value("Width") == "6");
QVERIFY(xmlReader.attributes().value("Height") == "3");
}
else if (xmlReader.name() == "Technical")
{
technical = true;
QVERIFY(xmlReader.attributes().value("PowerConsumption") == "250");
QVERIFY(xmlReader.attributes().value("DmxConnector") == "5-pin");
}
else
{
QFAIL(QString("Unexpected tag: %1").arg(xmlReader.name().toString())
.toLatin1());
}
xmlReader.skipCurrentElement();
}
QVERIFY(bulb == true);
QVERIFY(dim == true);
QVERIFY(lens == true);
QVERIFY(focus == true);
QVERIFY(layout == true);
QVERIFY(technical == true);
}
QTEST_MAIN(QLCPhysical_Test)
| 29.605405 | 99 | 0.638853 | bgnt44 |
c0c9ce9a061f87433336e6993ecdaacb2c09de84 | 2,325 | cpp | C++ | central_control_ui/src/ClientGroupWidget.cpp | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | central_control_ui/src/ClientGroupWidget.cpp | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | central_control_ui/src/ClientGroupWidget.cpp | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2016 James T. Kuczynski
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "../include/central_control_ui/ClientGroupWidget.h"
ClientGroupWidget::ClientGroupWidget(cct::Group group, QWidget* parent) : QWidget(parent)
{
groupLblPtr = new QLabel("test");
groupLstWidPtr = new QListWidget();
vec = new QVector<QListWidgetItem*>();
//-----------------test-----------
for(size_t i = 0; i < 1; i++)
{
if(group == cct::OPERATOR)
{
vec->push_back(new QListWidgetItem(QIcon("src/usar_teleop/central_control_ui/res/operator.png"), "James Kuczynski") );
}
else
{
vec->push_back(new QListWidgetItem(QIcon("src/usar_teleop/central_control_ui/res/observer.png"), "Justin Wood") );
}
groupLstWidPtr->addItem(vec->at(i) );
}
//--------------------------------
outerLayout = new QGridLayout();
switch(group)
{
case cct::OPERATOR:
groupLblPtr->setText("Agent");
break;
case cct::OBSERVER:
groupLblPtr->setText("Observer");
break;
default:
cerr << "ERROR @ ClientGroupWidget::ClientGroupWidget\nInvalid case in switch statement" << endl;
}
outerLayout->addWidget(groupLblPtr, 0, 0);
outerLayout->addWidget(groupLstWidPtr, 1, 0);
this->setLayout(outerLayout);
}
QListWidget* ClientGroupWidget::getGroup() const
{
return groupLstWidPtr;
}
int ClientGroupWidget::getSelected()
{
for(size_t i = 0; i < vec->size(); i++)
{
if(vec->at(i)->isSelected() )
{
return i;
}
}
return 0;
}
void ClientGroupWidget::focus(int index)
{
/*groupLstWidPtr->setStyleSheet(
"QListWidget::item {"
"border-style: solid;"
"border-width:1px;"
"border-color:black;"
"background-color: green;"
"}"
"QListWidget::item:selected {"
"background-color: red;"
"}");*/
groupLstWidPtr->item(index)->setSelected(true);
//groupLstWidPtr->item(index)->setBackground(Qt::blue);
}
ClientGroupWidget::~ClientGroupWidget()
{
;
}
| 25.549451 | 130 | 0.568172 | DeepBlue14 |
c0ca8a723454a2a120856cba148969f629c09a8a | 3,332 | hxx | C++ | opencascade/IGESSolid_SolidOfRevolution.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IGESSolid_SolidOfRevolution.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IGESSolid_SolidOfRevolution.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( SIVA )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSolid_SolidOfRevolution_HeaderFile
#define _IGESSolid_SolidOfRevolution_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Real.hxx>
#include <gp_XYZ.hxx>
#include <IGESData_IGESEntity.hxx>
#include <Standard_Boolean.hxx>
class gp_Pnt;
class gp_Dir;
class IGESSolid_SolidOfRevolution;
DEFINE_STANDARD_HANDLE(IGESSolid_SolidOfRevolution, IGESData_IGESEntity)
//! defines SolidOfRevolution, Type <162> Form Number <0,1>
//! in package IGESSolid
//! This entity is defined by revolving the area determined
//! by a planar curve about a specified axis through a given
//! fraction of full rotation.
class IGESSolid_SolidOfRevolution : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESSolid_SolidOfRevolution();
//! This method is used to set the fields of the class
//! SolidOfRevolution
//! - aCurve : the curve entity that is to be revolved
//! - aFract : the fraction of full rotation (default 1.0)
//! - aAxisPnt : the point on the axis
//! - aDirection : the direction of the axis
Standard_EXPORT void Init (const Handle(IGESData_IGESEntity)& aCurve, const Standard_Real aFract, const gp_XYZ& aAxisPnt, const gp_XYZ& aDirection);
//! Sets the Curve to be by default, Closed to Axis (Form 0)
//! if <mode> is True, Closed to Itself (Form 1) else
Standard_EXPORT void SetClosedToAxis (const Standard_Boolean mode);
//! Returns True if Form Number = 0
//! if Form no is 0, then the curve is closed to axis
//! if 1, the curve is closed to itself.
Standard_EXPORT Standard_Boolean IsClosedToAxis() const;
//! returns the curve entity that is to be revolved
Standard_EXPORT Handle(IGESData_IGESEntity) Curve() const;
//! returns the fraction of full rotation that the curve is to
//! be rotated
Standard_EXPORT Standard_Real Fraction() const;
//! returns the point on the axis
Standard_EXPORT gp_Pnt AxisPoint() const;
//! returns the point on the axis after applying Trans.Matrix
Standard_EXPORT gp_Pnt TransformedAxisPoint() const;
//! returns the direction of the axis
Standard_EXPORT gp_Dir Axis() const;
//! returns the direction of the axis after applying
//! TransformationMatrix
Standard_EXPORT gp_Dir TransformedAxis() const;
DEFINE_STANDARD_RTTIEXT(IGESSolid_SolidOfRevolution,IGESData_IGESEntity)
protected:
private:
Handle(IGESData_IGESEntity) theCurve;
Standard_Real theFraction;
gp_XYZ theAxisPoint;
gp_XYZ theAxis;
};
#endif // _IGESSolid_SolidOfRevolution_HeaderFile
| 29.75 | 150 | 0.756002 | mgreminger |
c0cd632e3f84ba880c6ef9dfa0cea6c444c0f5a7 | 4,044 | cpp | C++ | parser.cpp | kwQt/dummyscope | 160010342e87fb1578f707b97812af9d34814d76 | [
"MIT"
] | 1 | 2020-07-17T05:17:07.000Z | 2020-07-17T05:17:07.000Z | parser.cpp | kwQt/dummyscope | 160010342e87fb1578f707b97812af9d34814d76 | [
"MIT"
] | null | null | null | parser.cpp | kwQt/dummyscope | 160010342e87fb1578f707b97812af9d34814d76 | [
"MIT"
] | null | null | null | #include "parser.hpp"
Parser::Parser(std::string filename) {
lexer = std::make_unique<Lexer>(filename);
lexer->lexicalAnalysis();
curToken = lexer->getCurToken();
peekToken = lexer->getNextToken();
TU = std::make_unique<TranslationUnitAST>();
}
void Parser::nextToken() {
curToken = peekToken;
peekToken = lexer->getNextToken();
}
bool Parser::parse() { return parseTransitionUnit(); }
bool Parser::parseTransitionUnit() {
while (curToken->getTokenType() != TOK_EOF) {
auto func = parseFunctionDefinition();
if (func) {
TU->addFunction(std::move(func));
} else {
return false;
}
}
return true;
}
std::unique_ptr<ExprAST> Parser::parseBinaryOpExpr(Precedence prev_prec, std::unique_ptr<ExprAST> LHS) {
if (curToken->getTokenType() == TOK_EOF) return LHS;
while (true) {
Precedence cur_prec = curPrecedence();
if (cur_prec <= prev_prec) return LHS;
OpType op = getOpType(curToken->getTokenType());
if (op == UNDEFINED) return nullptr;
nextToken();
auto RHS = parsePrimary();
if (!RHS) return nullptr;
RHS = parseBinaryOpExpr(cur_prec, std::move(RHS));
if (!RHS) return nullptr;
LHS = std::make_unique<BinaryExprAST>(op, std::move(LHS), std::move(RHS));
}
}
std::unique_ptr<ExprAST> Parser::parseExpression() {
auto LHS = parsePrimary();
if (!LHS) return nullptr;
return parseBinaryOpExpr(LOWEST, std::move(LHS));
}
std::unique_ptr<ExprAST> Parser::parsePrimary() {
switch (curToken->getTokenType()) {
case TOK_IDENTIFIER:
return parseIdentifierExpr();
case TOK_NUMBER:
return parseNumberExpr();
case TOK_LPAREN:
return parseParenExpr();
default:
return nullptr;
}
}
std::unique_ptr<ExprAST> Parser::parseNumberExpr() {
double num = curToken->getTokenNum();
nextToken();
return std::make_unique<NumberAST>(num);
}
std::unique_ptr<ExprAST> Parser::parseIdentifierExpr() {
std::string name = curToken->getTokenString();
nextToken();
if (curToken->getTokenType() != TOK_LPAREN) return std::make_unique<VariableAST>(name);
// Call
auto call = parseCallExpr(name);
if (!call) return nullptr;
return call;
}
std::unique_ptr<ExprAST> Parser::parseParenExpr() {
// eat (
nextToken();
auto expr = parseExpression();
if (curToken->getTokenType() != TOK_RPAREN) return nullptr;
// eat )
nextToken();
return expr;
}
std::unique_ptr<CallExprAST> Parser::parseCallExpr(const std::string& callee_name) {
if (curToken->getTokenType() != TOK_LPAREN) return nullptr;
// eat (
nextToken();
std::vector<std::unique_ptr<ExprAST>> args;
auto arg = parseExpression();
while (arg) {
args.push_back(std::move(arg));
if (curToken->getTokenType() == TOK_RPAREN) break;
if (curToken->getTokenType() != TOK_COMMA) return nullptr;
// eat ,
nextToken();
arg = parseExpression();
}
// eat )
nextToken();
return std::make_unique<CallExprAST>(callee_name, std::move(args));
}
std::unique_ptr<PrototypeAST> Parser::parsePrototype() {
if (curToken->getTokenType() != TOK_IDENTIFIER) return nullptr;
std::string fn_name = curToken->getTokenString();
nextToken();
if (curToken->getTokenType() != TOK_LPAREN) return nullptr;
// eat (
nextToken();
std::vector<std::string> args;
while (curToken->getTokenType() == TOK_IDENTIFIER) {
args.push_back(curToken->getTokenString());
nextToken();
}
if (curToken->getTokenType() != TOK_RPAREN) return nullptr;
// eat )
nextToken();
return std::make_unique<PrototypeAST>(fn_name, std::move(args));
}
std::unique_ptr<FunctionAST> Parser::parseFunctionDefinition() {
if (curToken->getTokenType() != TOK_DEF) return nullptr;
// eat def
nextToken();
auto proto = parsePrototype();
if (!proto) return nullptr;
auto body = parseExpression();
if (!body) return nullptr;
return std::make_unique<FunctionAST>(std::move(proto), std::move(body));
}
Precedence Parser::curPrecedence() { return getPrecedence(curToken->getTokenType()); }
| 22.977273 | 104 | 0.675321 | kwQt |
c0ced3675f78580ef8591e1eb19ad0d01bcdf97d | 19,511 | cxx | C++ | Source/igtlPolyDataMessage.cxx | leochan2009/OpenIGTLinkPointCloud | 5243294af41d06d26008bdce5e34934a364b49e1 | [
"BSD-3-Clause"
] | null | null | null | Source/igtlPolyDataMessage.cxx | leochan2009/OpenIGTLinkPointCloud | 5243294af41d06d26008bdce5e34934a364b49e1 | [
"BSD-3-Clause"
] | null | null | null | Source/igtlPolyDataMessage.cxx | leochan2009/OpenIGTLinkPointCloud | 5243294af41d06d26008bdce5e34934a364b49e1 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: The OpenIGTLink Library
Language: C++
Web page: http://openigtlink.org/
Copyright (c) Insight Software Consortium. All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "igtlPolyDataMessage.h"
#include "igtlTypes.h"
#include "igtl_header.h"
#include "igtl_polydata.h"
// Disable warning C4996 (strncpy() may be unsafe) in Windows.
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdlib.h>
namespace igtl {
// Description:
// PolyDataPointArray class
PolyDataPointArray::PolyDataPointArray()
: Object()
{
Clear();
}
PolyDataPointArray::~PolyDataPointArray()
{
}
void PolyDataPointArray::Clear()
{
this->m_Data.clear();
}
void PolyDataPointArray::SetNumberOfPoints(int n)
{
this->m_Data.resize(n);
std::vector< Point >::iterator iter;
for (iter = this->m_Data.begin(); iter != this->m_Data.end(); iter ++)
{
iter->resize(3);
}
}
int PolyDataPointArray::GetNumberOfPoints()
{
return this->m_Data.size();
}
int PolyDataPointArray::SetPoint(unsigned int id, igtlFloat32 * point)
{
if (id >= this->m_Data.size())
{
return 0;
}
Point & dst = this->m_Data[id];
dst[0] = point[0];
dst[1] = point[1];
dst[2] = point[2];
return 1;
}
int PolyDataPointArray::SetPoint(unsigned int id, igtlFloat32 x, igtlFloat32 y, igtlFloat32 z)
{
if (id >= this->m_Data.size())
{
return 0;
}
Point & dst = this->m_Data[id];
dst[0] = x;
dst[1] = y;
dst[2] = z;
return 1;
}
int PolyDataPointArray::AddPoint(igtlFloat32 * point)
{
Point newPoint;
newPoint.resize(3);
newPoint[0] = point[0];
newPoint[1] = point[1];
newPoint[2] = point[2];
this->m_Data.push_back(newPoint);
return 1;
}
int PolyDataPointArray::AddPoint(igtlFloat32 x, igtlFloat32 y, igtlFloat32 z)
{
Point newPoint;
newPoint.resize(3);
newPoint[0] = x;
newPoint[1] = y;
newPoint[2] = z;
this->m_Data.push_back(newPoint);
return 1;
}
int PolyDataPointArray::GetPoint(unsigned int id, igtlFloat32 & x, igtlFloat32 & y, igtlFloat32 & z)
{
if (id >= this->m_Data.size())
{
return 0;
}
Point & dst = this->m_Data[id];
x = dst[0];
y = dst[1];
z = dst[2];
return 1;
}
int PolyDataPointArray::GetPoint(unsigned int id, igtlFloat32 * point)
{
if (id >= this->m_Data.size())
{
return 0;
}
Point & dst = this->m_Data[id];
point[0] = dst[0];
point[1] = dst[1];
point[2] = dst[2];
return 1;
}
// Description:
// PolyDataCellArray class to pass vertices, lines, polygons, and triangle strips
PolyDataCellArray::PolyDataCellArray()
: Object()
{
Clear();
}
PolyDataCellArray::~PolyDataCellArray()
{}
void PolyDataCellArray::Clear()
{
this->m_Data.clear();
}
igtlUint32 PolyDataCellArray::GetNumberOfCells()
{
return this->m_Data.size();
}
void PolyDataCellArray::AddCell(int n, igtlUint32 * cell)
{
std::list<igtlUint32> newCell;
for (int i = 0; i < n; i ++)
{
newCell.push_back(cell[i]);
}
if (n > 0)
{
this->m_Data.push_back(newCell);
}
}
void PolyDataCellArray::AddCell(std::list<igtlUint32> cell)
{
this->m_Data.push_back(cell);
}
igtlUint32 PolyDataCellArray::GetCellSize(unsigned int id)
{
if (id >= this->m_Data.size())
{
return 0;
}
return this->m_Data[id].size();
}
igtlUint32 PolyDataCellArray::GetTotalSize()
{
igtlUint32 size;
size = 0;
std::vector< std::list<igtlUint32> >::iterator iter;
for (iter = this->m_Data.begin(); iter != this->m_Data.end(); iter ++)
{
size += ((*iter).size() + 1);
}
return size * sizeof(igtlUint32);
}
int PolyDataCellArray::GetCell(unsigned int id, igtlUint32 * cell)
{
if (id >= this->m_Data.size())
{
return 0;
}
std::list<igtlUint32> & src = this->m_Data[id];
std::list<igtlUint32>::iterator iter;
for (iter = src.begin(); iter != src.end(); iter ++)
{
*cell = *iter;
cell ++;
}
return 1;
}
int PolyDataCellArray::GetCell(unsigned int id, std::list<igtlUint32>& cell)
{
if (id >= this->m_Data.size())
{
return 0;
}
std::list<igtlUint32> & src = this->m_Data[id];
cell.resize(src.size());
std::list<igtlUint32>::iterator srcIter;
std::list<igtlUint32>::iterator dstIter = cell.begin();
for (srcIter = src.begin(); srcIter != src.end(); srcIter ++)
{
*dstIter = *srcIter;
dstIter ++;
}
return 1;
}
// Description:
// Attribute class used for passing attribute data
PolyDataAttribute::PolyDataAttribute()
: Object()
{
Clear();
}
PolyDataAttribute::~PolyDataAttribute()
{
}
void PolyDataAttribute::Clear()
{
this->m_Type = POINT_SCALAR;
this->m_NComponents = 1;
this->m_Name = "";
this->m_Data.clear();
this->m_Size = 0;
}
int PolyDataAttribute::SetType(int t, int n)
{
int valid = 0;
switch(t)
{
case POINT_SCALAR:
case CELL_SCALAR:
if (n > 0 && n < 128)
{
valid = 1;
this->m_NComponents = n;
}
break;
case POINT_VECTOR:
case CELL_VECTOR:
valid = 1;
this->m_NComponents = 3;
break;
case POINT_NORMAL:
case CELL_NORMAL:
valid = 1;
this->m_NComponents = 3;
break;
case POINT_TENSOR:
case CELL_TENSOR:
valid = 1;
this->m_NComponents = 9;
break;
case POINT_RGBA:
case CELL_RGBA:
valid = 1;
this->m_NComponents = 4;
break;
default:
break;
}
if (valid)
{
this->m_Type = t;
unsigned int n = this->m_Size * this->m_NComponents;
if (n != this->m_Data.size())
{
// TODO: this may cause unnecesasry memory allocation,
// unless m_Size == 0.
// Memory should be reallocate just before use.
this->m_Data.resize(n);
}
return t;
}
else
{
return -1;
}
}
igtlUint32 PolyDataAttribute::GetNumberOfComponents()
{
return this->m_NComponents;
}
igtlUint32 PolyDataAttribute::SetSize(igtlUint32 size)
{
this->m_Size = size;
unsigned int n = this->m_Size * this->m_NComponents;
if (n != this->m_Data.size())
{
// TODO: this may cause unnecesasry memory allocation.
// Memory should be reallocate just before use.
this->m_Data.resize(n);
}
this->m_Data.resize(size*this->m_NComponents);
return this->m_Size;
}
igtlUint32 PolyDataAttribute::GetSize()
{
return this->m_Size;
}
void PolyDataAttribute::SetName(const char * name)
{
this->m_Name = name;
}
int PolyDataAttribute::SetData(igtlFloat32 * data)
{
if (!data)
{
return 0;
}
std::vector<igtlFloat32>::iterator iter;
for (iter = this->m_Data.begin(); iter != this->m_Data.end(); iter ++)
{
*iter = *data;
data ++;
}
return 1;
}
int PolyDataAttribute::GetData(igtlFloat32 * data)
{
if (!data)
{
return 0;
}
std::vector<igtlFloat32>::iterator iter;
for (iter = this->m_Data.begin(); iter != this->m_Data.end(); iter ++)
{
*data = *iter;
data ++;
}
return 1;
}
int PolyDataAttribute::SetNthData(unsigned int n, igtlFloat32 * data)
{
if (n >= this->m_Size)
{
return 0;
}
std::vector<igtlFloat32>::iterator iter;
iter = this->m_Data.begin() + n*this->m_NComponents;
for (unsigned int i = 0; i < this->m_NComponents; i ++)
{
*iter = *data;
iter ++;
data ++;
}
return 1;
}
int PolyDataAttribute::GetNthData(unsigned int n, igtlFloat32 * data)
{
if (n >= this->m_Size)
{
return 0;
}
std::vector<igtlFloat32>::iterator iter;
iter = this->m_Data.begin() + n*this->m_NComponents;
for (unsigned int i = 0; i < this->m_NComponents; i ++)
{
*data = *iter;
iter ++;
data ++;
}
return 1;
}
// Description:
// PolyDataMessage class implementation
PolyDataMessage::PolyDataMessage()
{
this->m_DefaultBodyType = "POLYDATA";
Clear();
}
PolyDataMessage::~PolyDataMessage()
{
}
void IGTLCommon_EXPORT SetPolyDataInfo(igtl_polydata_info * info, PolyDataMessage * pdm)
{
igtl_polydata_init_info(info);
if (pdm->GetPoints())
{
info->header.npoints = pdm->GetPoints()->GetNumberOfPoints();
}
else
{
info->header.npoints = 0;
}
if (pdm->GetVertices())
{
info->header.nvertices = pdm->GetVertices()->GetNumberOfCells();
info->header.size_vertices = pdm->GetVertices()->GetTotalSize();
}
else
{
info->header.nvertices = 0;
info->header.size_vertices = 0;
}
if (pdm->GetLines())
{
info->header.nlines = pdm->GetLines()->GetNumberOfCells();
info->header.size_lines = pdm->GetLines()->GetTotalSize();
}
else
{
info->header.nlines = 0;
info->header.size_lines = 0;
}
if (pdm->GetPolygons())
{
info->header.npolygons = pdm->GetPolygons()->GetNumberOfCells();
info->header.size_polygons = pdm->GetPolygons()->GetTotalSize();
}
else
{
info->header.npolygons = 0;
info->header.size_polygons = 0;
}
if (pdm->GetTriangleStrips())
{
info->header.ntriangle_strips = pdm->GetTriangleStrips()->GetNumberOfCells();
info->header.size_triangle_strips = pdm->GetTriangleStrips()->GetTotalSize();
}
else
{
info->header.ntriangle_strips = 0;
info->header.size_triangle_strips = 0;
}
info->header.nattributes = pdm->GetNumberOfAttributes();
info->header.nPointsRGB = pdm->GetNumberOfPointsRGB();
}
void IGTLCommon_EXPORT SetPolyDataInfoAttribute(igtl_polydata_info * info, PolyDataMessage * pdm)
{
igtl_polydata_attribute * attr = info->attributes;
for (unsigned int i = 0; i < info->header.nattributes; i ++)
{
PolyDataAttribute * src = pdm->GetAttribute(i);
if (src)
{
attr->type = src->GetType();
attr->ncomponents = src->GetNumberOfComponents();
attr->n = src->GetSize();
//attr->name = const_cast<char*>(src->GetName());
// TODO: aloways allocating memory isn't a good approach...
if (attr->name)
{
free(attr->name);
}
attr->name = (char *) malloc(strlen(src->GetName())+1);
if (attr->name)
{
strcpy(attr->name, src->GetName());
}
if (attr->data)
{
free(attr->data);
}
igtlUint32 size = attr->ncomponents * attr->n;
attr->data = (igtlFloat32*)malloc((size_t)size*sizeof(igtlFloat32));
if (attr->data)
{
src->GetData(attr->data);
}
attr ++;
}
}
}
void IGTLCommon_EXPORT UnSetPolyDataInfoAttribute(igtl_polydata_info * info)
{
igtl_polydata_attribute * attr = info->attributes;
for (unsigned int i = 0; i < info->header.nattributes; i ++)
{
attr->type = 0;
attr->ncomponents = 0;
attr->n = 0;
if (attr->name)
{
free(attr->name);
attr->name = NULL;
}
if (attr->data)
{
free(attr->data);
attr->data = NULL;
}
attr ++;
}
}
int PolyDataMessage::GetBodyPackSize()
{
// TODO: The current implementation of GetBodyPackSize() allocates
// igtl_polydata_info and the array of igtl_polydata_attribute to calculate
// the size of pack. However, this approach is not efficent because
// it causes unnecessary memory allocation.
int dataSize;
igtl_polydata_info info;
SetPolyDataInfo(&info, this);
// Instead of calling igtl_polydata_alloc_info(), we only allocate
// memory for the attribute array, since igtl_polydata_alloc_info()
// allocates also allocates the memory area for actual points and
// cell data, which is not neccessary to calculate polydata size.
info.attributes = new igtl_polydata_attribute[info.header.nattributes];
if (!info.attributes)
{
//ERROR
return 0;
}
// init attributes
igtl_polydata_attribute * attr = info.attributes;
for (unsigned int i = 0; i < info.header.nattributes; i ++)
{
attr->type = 0;
attr->ncomponents = 0;
attr->n = 0;
attr->name = NULL;
attr->data = NULL;
attr ++;
}
SetPolyDataInfoAttribute(&info, this);
dataSize = igtl_polydata_get_size(&info, IGTL_TYPE_PREFIX_NONE);
UnSetPolyDataInfoAttribute(&info);
//delete [] (info.attributes);
delete [] info.attributes;
return dataSize;
}
int PolyDataMessage::PackBody()
{
// Allocate pack
AllocatePack();
igtl_polydata_info info;
SetPolyDataInfo(&info, this);
if (igtl_polydata_alloc_info(&info) == 0)
{
return 0;
}
//SetPolyDataInfoAttribute(&info, this);
// Points
if (info.points)
{
igtlFloat32 * ptr_f = info.points;
for (int i = 0; i < this->m_Points->GetNumberOfPoints(); i ++)
{
igtlFloat32 points[3];
this->m_Points->GetPoint(i, points);
*(ptr_f++) = points[0];
*(ptr_f++) = points[1];
*(ptr_f++) = points[2];
}
}
//Vertices
if (info.vertices)
{
igtlUint32 * ptr_i = info.vertices;
for (unsigned int i = 0; i < this->m_Vertices->GetNumberOfCells(); i ++)
{
*ptr_i = this->m_Vertices->GetCellSize(i);
ptr_i ++;
this->m_Vertices->GetCell(i, ptr_i);
ptr_i += this->m_Vertices->GetCellSize(i);
}
}
//Lines
if (info.lines)
{
igtlUint32 * ptr_i = info.lines;
for (unsigned int i = 0; i < this->m_Lines->GetNumberOfCells(); i ++)
{
*ptr_i = this->m_Lines->GetCellSize(i);
ptr_i ++;
this->m_Lines->GetCell(i, ptr_i);
ptr_i += this->m_Lines->GetCellSize(i);
}
}
//Polygons
if (info.polygons)
{
igtlUint32 * ptr_i = info.polygons;
for (unsigned int i = 0; i < this->m_Polygons->GetNumberOfCells(); i ++)
{
*ptr_i = this->m_Polygons->GetCellSize(i);
ptr_i ++;
this->m_Polygons->GetCell(i, ptr_i);
ptr_i += this->m_Polygons->GetCellSize(i);
}
}
//TriangleStrips
if (info.triangle_strips)
{
igtlUint32 * ptr_i = info.triangle_strips;
for (unsigned int i = 0; i < this->m_TriangleStrips->GetNumberOfCells(); i ++)
{
*ptr_i = this->m_TriangleStrips->GetCellSize(i);
ptr_i ++;
this->m_TriangleStrips->GetCell(i, ptr_i);
ptr_i += this->m_TriangleStrips->GetCellSize(i);
}
}
SetPolyDataInfoAttribute(&info, this);
//TriangleStrips
if (info.pointsRGB)
{
igtlUint8 * ptr_i = info.pointsRGB;
for (unsigned int i = 0; i < this->m_PointsRGB.size(); i++)
{
*ptr_i = this->m_PointsRGB[i];
ptr_i++;
}
}
igtl_polydata_pack(&info, this->m_Body, IGTL_TYPE_PREFIX_NONE);
igtl_polydata_free_info(&info);
return 1;
}
int PolyDataMessage::UnpackBody()
{
igtl_polydata_info info;
igtl_polydata_init_info(&info);
if (igtl_polydata_unpack(IGTL_TYPE_PREFIX_NONE, (void*)this->m_Body, &info, this->GetPackBodySize()) == 0)
{
return 0;
}
// Points
if (this->m_Points.IsNull())
{
this->m_Points = igtl::PolyDataPointArray::New();
}
this->m_Points->Clear();
if (info.header.npoints > 0)
{
this->m_Points->SetNumberOfPoints(info.header.npoints);
for (unsigned int i = 0; i < info.header.npoints; i ++)
{
this->m_Points->SetPoint(i, &(info.points[i*3]));
}
}
igtlUint32 * ptr;
// Vertices
if (this->m_Vertices.IsNull())
{
this->m_Vertices = igtl::PolyDataCellArray::New();
}
this->m_Vertices->Clear();
ptr = info.vertices;
for (unsigned int i = 0; i < info.header.nvertices; i ++)
{
unsigned int n = *ptr;
ptr ++;
this->m_Vertices->AddCell(n, ptr);
ptr += n;
}
// Lines
if (this->m_Lines.IsNull())
{
this->m_Lines = igtl::PolyDataCellArray::New();
}
this->m_Lines->Clear();
ptr = info.lines;
for (unsigned int i = 0; i < info.header.nlines; i ++)
{
unsigned int n = *ptr;
ptr ++;
this->m_Lines->AddCell(n, ptr);
ptr += n;
}
// Polygons
if (this->m_Polygons.IsNull())
{
this->m_Polygons = igtl::PolyDataCellArray::New();
}
this->m_Polygons->Clear();
ptr = info.polygons;
for (unsigned int i = 0; i < info.header.npolygons; i ++)
{
unsigned int n = *ptr;
ptr ++;
this->m_Polygons->AddCell(n, ptr);
ptr += n;
}
// TriangleStrips
if (this->m_TriangleStrips.IsNull())
{
this->m_TriangleStrips = igtl::PolyDataCellArray::New();
}
this->m_TriangleStrips->Clear();
ptr = info.triangle_strips;
for (unsigned int i = 0; i < info.header.ntriangle_strips; i ++)
{
unsigned int n = *ptr;
ptr ++;
this->m_TriangleStrips->AddCell(n, ptr);
ptr += n;
}
// Attributes
this->m_Attributes.clear();
igtl_polydata_attribute * attr = info.attributes;
for (unsigned int i = 0; i < info.header.nattributes; i ++)
{
PolyDataAttribute::Pointer pda = PolyDataAttribute::New();
if (pda.IsNotNull())
{
pda->Clear();
pda->SetType(attr->type, attr->ncomponents);
pda->SetSize(attr->n);
pda->SetName(attr->name);
pda->SetData(attr->data);
attr ++;
this->m_Attributes.push_back(pda);
}
}
// Points RGB
this->m_PointsRGB.clear();
if (info.header.nPointsRGB > 0)
{
for (unsigned int i = 0; i < info.header.nPointsRGB; i++)
{
this->m_PointsRGB.push_back(*info.pointsRGB);
info.pointsRGB++;
this->m_PointsRGB.push_back(*info.pointsRGB);
info.pointsRGB++;
this->m_PointsRGB.push_back(*info.pointsRGB);
info.pointsRGB++;
}
}
return 1;
}
void PolyDataMessage::Clear()
{
if (this->m_Points.IsNotNull())
{
//this->m_Points->Delete();
this->m_Points = NULL;
}
if (this->m_Vertices.IsNotNull())
{
//this->m_Vertices->Delete();
this->m_Vertices = NULL;
}
if(this->m_Lines.IsNotNull())
{
//this->m_Lines->Delete();
this->m_Lines = NULL;
}
if (this->m_Polygons.IsNotNull())
{
//this->m_Polygons->Delete();
this->m_Polygons = NULL;
}
if (this->m_TriangleStrips.IsNotNull())
{
//this->m_TriangleStrips->Delete();
this->m_TriangleStrips = NULL;
}
// TODO: is this OK?
this->m_Attributes.clear();
this->m_PointsRGB.clear();
}
void PolyDataMessage::ClearAttributes()
{
std::vector<PolyDataAttribute::Pointer>::iterator iter;
for (iter = this->m_Attributes.begin(); iter != this->m_Attributes.end(); iter ++)
{
*iter = NULL;
}
this->m_Attributes.clear();
}
void PolyDataMessage::AddAttribute(PolyDataAttribute * att)
{
this->m_Attributes.push_back(att);
}
void PolyDataMessage::SetPointsRGB(std::vector<igtlUint8> pointsRGB)
{
this->m_PointsRGB.swap(pointsRGB);
}
std::vector<igtlUint8> PolyDataMessage::GetPointsRGB()
{
return this->m_PointsRGB;
}
int PolyDataMessage::GetNumberOfPointsRGB()
{
return this->m_PointsRGB.size()/3;
}
int PolyDataMessage::GetNumberOfAttributes()
{
return this->m_Attributes.size();
}
PolyDataAttribute * PolyDataMessage::GetAttribute(unsigned int id)
{
if (id >= this->m_Attributes.size())
{
return NULL;
}
return this->m_Attributes[id];
}
GetPolyDataMessage::GetPolyDataMessage()
{
this->m_DefaultBodyType = "GET_POLYDATA";
}
StopPolyDataMessage::StopPolyDataMessage()
{
this->m_DefaultBodyType = "STOP_POLYDATA";
}
} // namespace igtl
| 20.934549 | 110 | 0.61268 | leochan2009 |
c0cee2c0c3699106de34766243016051f832b6d7 | 1,077 | cpp | C++ | docs/MainScreen/ProductControlGUI/mainwindow.cpp | Chesterdelang/I-OSM-Project-19-20-S1-Groep4 | d8c0a4582074243f93220b356b7000fb6ebf1df5 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | docs/MainScreen/ProductControlGUI/mainwindow.cpp | Chesterdelang/I-OSM-Project-19-20-S1-Groep4 | d8c0a4582074243f93220b356b7000fb6ebf1df5 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | docs/MainScreen/ProductControlGUI/mainwindow.cpp | Chesterdelang/I-OSM-Project-19-20-S1-Groep4 | d8c0a4582074243f93220b356b7000fb6ebf1df5 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | #include "mainwindow.hpp"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionLoad_triggered()
{
// QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
// QFile file(fileName);
// currentFile = fileName;
// if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
// {
// QMessageBox::warning(this, "Warning", "Cannot open file : " + file.errorString());
// }
// setWindowTitle(fileName);
// QTextStream in(&file);
// QString jsonFileText = in.readAll();
// //ui->textEdit->setPlainText(text);
// QString val = file.readAll();
// file.close();
}
void MainWindow::on_actionExit_triggered()
{
QApplication::quit();
}
void MainWindow::on_actionSave_triggered()
{
}
void MainWindow::on_actionStart_triggered()
{
}
void MainWindow::on_actionStop_triggered()
{
}
void MainWindow::on_actionPause_triggered()
{
}
| 17.370968 | 92 | 0.651811 | Chesterdelang |
c0d07de53c382a09dfa747d97b9d1107ef530185 | 7,804 | cpp | C++ | sdl2/BattleCitySDL/src/GameTimer.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/BattleCitySDL/src/GameTimer.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/BattleCitySDL/src/GameTimer.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include "GameTimer.h"
#include "Game.h"
using namespace std;
void GameTimer::Init() {
enemySpawnTime = 3;
currentEnemyTime = 2.5;
playerSpawnTime = 1;
currentPlayerTime = 0;
nextmapChangeTime = 3;
currentNextmapTime = 0;
currentLevelProtectTime = 0;
levelProtectTime = 15.0;
currentPlayerOneRssurectionTime = 0;
currentPlayerTwoRssurectionTime = 0;
currentGameLostTime = 0;
gameLostTime = 6.0;
levelProtectState = false;
maxEnemiesInScreen = 4;
playerRessurectionTime = 0.5;
}
void GameTimer::SetLevelProtect(bool protect) {
levelProtectState = true;
BrickType field;
if (protect)
field = BT_WHITE;
else
field = BT_BRICK;
Game::instance().GetLevel()->SetMapBrick(11, 0, field);
Game::instance().GetLevel()->SetMapBrick(11, 1, field);
Game::instance().GetLevel()->SetMapBrick(11, 2, field);
Game::instance().GetLevel()->SetMapBrick(12, 2, field);
Game::instance().GetLevel()->SetMapBrick(13, 2, field);
Game::instance().GetLevel()->SetMapBrick(14, 0, field);
Game::instance().GetLevel()->SetMapBrick(14, 1, field);
Game::instance().GetLevel()->SetMapBrick(14, 2, field);
}
void GameTimer::DrawStageSelect() {
Game::instance().GetUI()->RenderText("STAGE " + to_string(showedLevel), 230, 230, COLOR_BLACK);
}
void GameTimer::ProcessEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
Game::instance().StopGame();
}
else if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_ESCAPE) {
Game::instance().SetGameState(GS_MENU);
}
else if (Game::instance().GetLevel()->LevelNum() == 0) {
if (event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_RIGHT) {
int i = selectedLevel + 1;
if (i > Game::instance().GetLevel()->NumOfMaps())
i = Game::instance().GetLevel()->NumOfMaps();
selectedLevel = showedLevel = i;
}
else if (event.key.keysym.sym == SDLK_DOWN || event.key.keysym.sym == SDLK_LEFT) {
int i = selectedLevel - 1;
if (i < 0)
i = 0;
selectedLevel = showedLevel = i;
}
else if (event.key.keysym.sym == SDLK_RETURN) {
ChooseLevel();
}
}
}
}
}
void GameTimer::ChooseLevel() {
if (selectedLevel > Game::instance().GetLevel()->NumOfMaps())
selectedLevel = 1;
string level = "data/map/" + to_string(selectedLevel);
if (selectedLevel == 0) {
level = "data/map/temp";
}
if (Game::instance().GetLevel()->LoadMap(level) == false) {
Game::instance().SetGameState(GS_MENU);
return;
}
Game::instance().GetAudio()->PlayChunk(SOUND_GAMESTART);
Game::instance().GetBullets()->DestroyAllBullets();
Game::instance().GetAnimation()->DestroyAllAnimation();
Game::instance().GetEnemies()->DestroyAllEnemies();
Game::instance().GetEnemies()->UnPause();
Game::instance().GetPlayer()->Born();
if (Game::instance().GetPlayerTwo() != NULL) {
Game::instance().GetPlayerTwo()->Born();
}
Game::instance().GetItems()->DestroyItem();
Game::instance().StartGameplay();
Game::instance().SetGameState(GS_GAMEPLAY);
Init();
}
void GameTimer::Update(double dt) {
static int TailSize = Game::instance().TailSize();
if (Game::instance().GameState() == GS_GAMEPLAY) {
// try to add enemy
if (Game::instance().GetEnemies()->AliveEnemies() < maxEnemiesInScreen && Game::instance().GetEnemies()->NumOfEnemies() < 20) {
currentEnemyTime += dt;
if (currentEnemyTime >= enemySpawnTime) {
Game::instance().GetEnemies()->CreateEnemy();
currentEnemyTime = 0;
enemySpawnAnimation = false;
}
else if (currentEnemyTime >= enemySpawnTime - 0.5 && enemySpawnAnimation == false) {
int x = Game::instance().GetEnemies()->NextSpawnX();
Game::instance().GetAnimation()->CreateAnimation(TailSize * x, TailSize * 24, ANIMATION_SPAWN);
enemySpawnAnimation = true;
}
}
else if (Game::instance().GetEnemies()->NumOfEnemies() == 20 && Game::instance().GetEnemies()->AliveEnemies() == 0 && Game::instance().GameLost() == false) {
currentNextmapTime += dt;
if (currentNextmapTime >= nextmapChangeTime) {
// change game state
Game::instance().SetGameState(GS_STAGESELECT);
++selectedLevel;
++showedLevel;
currentNextmapTime = 0.0;
}
}
if (Game::instance().GetPlayer()->Lifes() < 0 && (Game::instance().GetPlayerTwo() == NULL || Game::instance().GetPlayerTwo()->Lifes() < 0)) {
Game::instance().SetGameLost(true);
}
if (Game::instance().GameLost()) {
if (currentGameLostTime == 0.0)
Game::instance().GetAudio()->PlayChunk(SOUND_GAMEOVER);
currentGameLostTime += dt;
if (currentGameLostTime >= gameLostTime) {
Game::instance().SetGameState(GS_MENU);
currentGameLostTime = 0.0;
}
}
// player rebirth
if (Game::instance().GetPlayer()->Alive() == false && Game::instance().GetPlayer()->Lifes() >= 0) {
if (currentPlayerOneRssurectionTime == 0.0)
Game::instance().GetAnimation()->CreateAnimation(TailSize * 8, 0, ANIMATION_SPAWN);
currentPlayerOneRssurectionTime += dt;
if (currentPlayerOneRssurectionTime >= playerRessurectionTime) {
Game::instance().GetPlayer()->Born();
currentPlayerOneRssurectionTime = 0;
}
}
if (Game::instance().GetPlayerTwo() != NULL) {
if (Game::instance().GetPlayerTwo()->Alive() == false && Game::instance().GetPlayerTwo()->Lifes() >= 0) {
if (currentPlayerTwoRssurectionTime == 0.0)
Game::instance().GetAnimation()->CreateAnimation(TailSize * 16, 0, ANIMATION_SPAWN);
currentPlayerTwoRssurectionTime += dt;
if (currentPlayerTwoRssurectionTime >= playerRessurectionTime) {
Game::instance().GetPlayerTwo()->Born();
currentPlayerTwoRssurectionTime = 0;
}
}
}
// protection state
if (levelProtectState == true) {
currentLevelProtectTime += dt;
if (currentLevelProtectTime >= levelProtectTime) {
levelProtectState = false;
SetLevelProtect(false);
currentLevelProtectTime = 0.0;
}
if (currentLevelProtectTime >= levelProtectTime - 0.5)
SetLevelProtect(true);
else if (currentLevelProtectTime >= levelProtectTime - 1)
SetLevelProtect(false);
else if (currentLevelProtectTime >= levelProtectTime - 1.5)
SetLevelProtect(true);
else if (currentLevelProtectTime >= levelProtectTime - 2)
SetLevelProtect(false);
}
}
else if (Game::instance().GameState() == GS_STAGESELECT) {
if (Game::instance().GetLevel()->LevelNum() != 0) {
currentNextmapTime += dt;
if (currentNextmapTime >= nextmapChangeTime) {
currentNextmapTime = 0.0;
ChooseLevel();
}
}
}
}
| 37.161905 | 165 | 0.561379 | pdpdds |
c0d0edbfa879bce4ad26fc4cd0a7ed65deb6b63f | 2,343 | cpp | C++ | src/smtrat-mcsat/assignments/arithmetic/AssignmentFinder.cpp | modass/smtrat | 2e6909bb764cf30d6afc231a2d447dfc13f3fa40 | [
"MIT"
] | null | null | null | src/smtrat-mcsat/assignments/arithmetic/AssignmentFinder.cpp | modass/smtrat | 2e6909bb764cf30d6afc231a2d447dfc13f3fa40 | [
"MIT"
] | null | null | null | src/smtrat-mcsat/assignments/arithmetic/AssignmentFinder.cpp | modass/smtrat | 2e6909bb764cf30d6afc231a2d447dfc13f3fa40 | [
"MIT"
] | null | null | null | #include "AssignmentFinder.h"
#include "AssignmentFinder_arithmetic.h"
namespace smtrat {
namespace mcsat {
namespace arithmetic {
boost::optional<AssignmentOrConflict> AssignmentFinder::operator()(const mcsat::Bookkeeping& data, carl::Variable var) const {
SMTRAT_LOG_DEBUG("smtrat.mcsat.arithmetic", "Looking for an assignment for " << var);
AssignmentFinder_detail af(var, data.model());
FormulasT conflict;
for (const auto& c: data.constraints()) {
if (!active(data, c)) {
SMTRAT_LOG_TRACE("smtrat.mcsat.arithmetic", "Skipping inactive Constraint " << c);
continue;
}
assert(c.getType() == carl::FormulaType::CONSTRAINT);
SMTRAT_LOG_TRACE("smtrat.mcsat.arithmetic", "Adding Constraint " << c);
if(!af.addConstraint(c)){
conflict.push_back(c);
SMTRAT_LOG_DEBUG("smtrat.mcsat.arithmetic", "No Assignment, built conflicting core " << conflict << " under model " << data.model());
return AssignmentOrConflict(conflict);
}
}
for (const auto& b: data.mvBounds()) {
if (!active(data, b)) {
SMTRAT_LOG_TRACE("smtrat.mcsat.arithmetic", "Skipping inactive MVBound " << b);
continue;
}
SMTRAT_LOG_TRACE("smtrat.mcsat.arithmetic", "Adding MVBound " << b);
if (!af.addMVBound(b)) {
conflict.push_back(b);
SMTRAT_LOG_DEBUG("smtrat.mcsat.arithmetic", "No Assignment, built conflicting core " << conflict << " under model " << data.model());
return AssignmentOrConflict(conflict);
}
}
SMTRAT_LOG_DEBUG("smtrat.mcsat.arithmetic", "Calling AssignmentFinder...");
return af.findAssignment();
}
bool AssignmentFinder::active(const mcsat::Bookkeeping& data, const FormulaT& f) const {
if(f.getType() != carl::FormulaType::VARCOMPARE)
return true;
const auto& val = f.variableComparison().value();
if (std::holds_alternative<VariableComparisonT::RAN>(val)) {
return true;
} else {
if (data.model().find(f.variableComparison().var()) == data.model().end()) {
return true;
} else {
const auto& mvroot = std::get<MultivariateRootT>(val);
auto vars = mvroot.poly().gatherVariables();
vars.erase(mvroot.var());
for (auto iter = data.assignedVariables().begin(); iter != data.assignedVariables().end(); iter++) {
if (*iter == f.variableComparison().var()) {
break;
}
vars.erase(*iter);
}
return vars.size() == 0;
}
}
}
}
}
}
| 33.471429 | 136 | 0.682885 | modass |
c0d0f8c9ac7cd461fb20f71d4e338a3622a08df0 | 78 | cpp | C++ | src/Duration.cpp | DarkBlackJPG/Virtual-Piano | 08d9989113af8c2c1084a0840301dd0d34c5cb02 | [
"MIT"
] | null | null | null | src/Duration.cpp | DarkBlackJPG/Virtual-Piano | 08d9989113af8c2c1084a0840301dd0d34c5cb02 | [
"MIT"
] | null | null | null | src/Duration.cpp | DarkBlackJPG/Virtual-Piano | 08d9989113af8c2c1084a0840301dd0d34c5cb02 | [
"MIT"
] | null | null | null | #include "Duration.h"
Duration::Duration()
{
}
Duration::~Duration()
{
}
| 6 | 21 | 0.615385 | DarkBlackJPG |
c0d1259116af35538d274f525bfc8b8e4119dbf3 | 33,507 | cpp | C++ | rev/asset_manager/dds_loader.cpp | Roman-Skabin/REV | adfa0a742525784d66f98ff5b0d157343e5f1cf4 | [
"BSD-4-Clause"
] | 2 | 2020-12-12T20:37:32.000Z | 2022-01-06T22:20:30.000Z | rev/asset_manager/dds_loader.cpp | Roman-Skabin/REV | adfa0a742525784d66f98ff5b0d157343e5f1cf4 | [
"BSD-4-Clause"
] | null | null | null | rev/asset_manager/dds_loader.cpp | Roman-Skabin/REV | adfa0a742525784d66f98ff5b0d157343e5f1cf4 | [
"BSD-4-Clause"
] | null | null | null | // Copyright (c) 2020-2021, Roman-Skabin
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE.md file in the root directory of this source tree.
#include "core/pch.h"
#include "asset_manager/asset_manager.h"
#include "graphics/graphics_api.h"
#include "core/settings.h"
#include "memory/memory.h"
#include "math/math.h"
// @TODO(Roman): #CrossPlatform
#include "platform/d3d12/d3d12_memory_manager.h"
#include <dxgiformat.h>
#include <d3d12.h>
#pragma pack(push, 1)
namespace REV
{
enum DDS_FLAG : u32
{
DDS_FLAG_CAPS = 0x00000001,
DDS_FLAG_HEIGHT = 0x00000002,
DDS_FLAG_WIDTH = 0x00000004,
DDS_FLAG_PITCH = 0x00000008,
DDS_FLAG_BACKBUFFERCOUNT = 0x00000020,
DDS_FLAG_ZBUFFERBITDEPTH = 0x00000040,
DDS_FLAG_ALPHABITDEPTH = 0x00000080,
DDS_FLAG_LPSURFACE = 0x00000800,
DDS_FLAG_PIXELFORMAT = 0x00001000,
DDS_FLAG_CKDESTOVERLAY = 0x00002000,
DDS_FLAG_CKDESTBLT = 0x00004000,
DDS_FLAG_CKSRCOVERLAY = 0x00008000,
DDS_FLAG_CKSRCBLT = 0x00010000,
DDS_FLAG_MIPMAPCOUNT = 0x00020000,
DDS_FLAG_REFRESHRATE = 0x00040000,
DDS_FLAG_LINEARSIZE = 0x00080000,
DDS_FLAG_TEXTURESTAGE = 0x00100000,
DDS_FLAG_FVF = 0x00200000,
DDS_FLAG_SRCVBHANDLE = 0x00400000,
DDS_FLAG_DEPTH = 0x00800000,
DDS_FLAG_ALL = 0x00FFF9EE
};
REV_ENUM_OPERATORS(DDS_FLAG);
static_assert(sizeof(DDS_FLAG) == 4);
enum PIXEL_FORMAT_FLAG : u32
{
PIXEL_FORMAT_FLAG_ALPHAPIXELS = 0x00000001,
PIXEL_FORMAT_FLAG_ALPHA = 0x00000002,
PIXEL_FORMAT_FLAG_FOURCC = 0x00000004,
PIXEL_FORMAT_FLAG_PALETTEINDEXED4 = 0x00000008,
PIXEL_FORMAT_FLAG_PALETTEINDEXEDTO8 = 0x00000010,
PIXEL_FORMAT_FLAG_PALETTEINDEXED8 = 0x00000020,
PIXEL_FORMAT_FLAG_RGB = 0x00000040,
PIXEL_FORMAT_FLAG_COMPRESSED = 0x00000080,
PIXEL_FORMAT_FLAG_RGBTOYUV = 0x00000100,
PIXEL_FORMAT_FLAG_YUV = 0x00000200,
PIXEL_FORMAT_FLAG_ZBUFFER = 0x00000400,
PIXEL_FORMAT_FLAG_PALETTEINDEXED1 = 0x00000800,
PIXEL_FORMAT_FLAG_PALETTEINDEXED2 = 0x00001000,
PIXEL_FORMAT_FLAG_ZPIXELS = 0x00002000,
PIXEL_FORMAT_FLAG_STENCILBUFFER = 0x00004000,
PIXEL_FORMAT_FLAG_ALPHAPREMULT = 0x00008000,
PIXEL_FORMAT_FLAG_LUMINANCE = 0x00020000,
PIXEL_FORMAT_FLAG_BUMPLUMINANCE = 0x00040000,
PIXEL_FORMAT_FLAG_BUMPDUDV = 0x00080000,
};
REV_ENUM_OPERATORS(PIXEL_FORMAT_FLAG);
static_assert(sizeof(PIXEL_FORMAT_FLAG) == 4);
enum CAPS1 : u32
{
CAPS1_RESERVED1 = 0x00000001,
CAPS1_ALPHA = 0x00000002,
CAPS1_BACKBUFFER = 0x00000004,
CAPS1_COMPLEX = 0x00000008,
CAPS1_FLIP = 0x00000010,
CAPS1_FRONTBUFFER = 0x00000020,
CAPS1_OFFSCREENPLAIN = 0x00000040,
CAPS1_OVERLAY = 0x00000080,
CAPS1_PALETTE = 0x00000100,
CAPS1_PRIMARYSURFACE = 0x00000200,
CAPS1_RESERVED3 = 0x00000400,
CAPS1_PRIMARYSURFACELEFT = 0x00000000,
CAPS1_SYSTEMMEMORY = 0x00000800,
CAPS1_TEXTURE = 0x00001000,
CAPS1_3DDEVICE = 0x00002000,
CAPS1_VIDEOMEMORY = 0x00004000,
CAPS1_VISIBLE = 0x00008000,
CAPS1_WRITEONLY = 0x00010000,
CAPS1_ZBUFFER = 0x00020000,
CAPS1_OWNDC = 0x00040000,
CAPS1_LIVEVIDEO = 0x00080000,
CAPS1_HWCODEC = 0x00100000,
CAPS1_MODEX = 0x00200000,
CAPS1_MIPMAP = 0x00400000,
CAPS1_RESERVED2 = 0x00800000,
CAPS1_ALLOCONLOAD = 0x04000000,
CAPS1_VIDEOPORT = 0x08000000,
CAPS1_LOCALVIDMEM = 0x10000000,
CAPS1_NONLOCALVIDMEM = 0x20000000,
CAPS1_STANDARDVGAMODE = 0x40000000,
CAPS1_OPTIMIZED = 0x80000000,
};
REV_ENUM_OPERATORS(CAPS1);
static_assert(sizeof(CAPS1) == 4);
enum CAPS2 : u32
{
CAPS2_RESERVED4 = 0x00000002,
CAPS2_HARDWAREDEINTERLACE = 0x00000000,
CAPS2_HINTDYNAMIC = 0x00000004,
CAPS2_HINTSTATIC = 0x00000008,
CAPS2_TEXTUREMANAGE = 0x00000010,
CAPS2_RESERVED1 = 0x00000020,
CAPS2_RESERVED2 = 0x00000040,
CAPS2_OPAQUE = 0x00000080,
CAPS2_HINTANTIALIASING = 0x00000100,
CAPS2_CUBEMAP = 0x00000200,
CAPS2_CUBEMAP_POSITIVEX = 0x00000400,
CAPS2_CUBEMAP_NEGATIVEX = 0x00000800,
CAPS2_CUBEMAP_POSITIVEY = 0x00001000,
CAPS2_CUBEMAP_NEGATIVEY = 0x00002000,
CAPS2_CUBEMAP_POSITIVEZ = 0x00004000,
CAPS2_CUBEMAP_NEGATIVEZ = 0x00008000,
CAPS2_CUBEMAP_ALLFACES = CAPS2_CUBEMAP_POSITIVEX
| CAPS2_CUBEMAP_NEGATIVEX
| CAPS2_CUBEMAP_POSITIVEY
| CAPS2_CUBEMAP_NEGATIVEY
| CAPS2_CUBEMAP_POSITIVEZ
| CAPS2_CUBEMAP_NEGATIVEZ,
CAPS2_MIPMAPSUBLEVEL = 0x00010000,
CAPS2_D3DTEXTUREMANAGE = 0x00020000,
CAPS2_DONOTPERSIST = 0x00040000,
CAPS2_STEREOSURFACELEFT = 0x00080000,
CAPS2_VOLUME = 0x00200000,
CAPS2_NOTUSERLOCKABLE = 0x00400000,
CAPS2_POINTS = 0x00800000,
CAPS2_RTPATCHES = 0x01000000,
CAPS2_NPATCHES = 0x02000000,
CAPS2_RESERVED3 = 0x04000000,
CAPS2_DISCARDBACKBUFFER = 0x10000000,
CAPS2_ENABLEALPHACHANNEL = 0x20000000,
CAPS2_EXTENDEDFORMATPRIMARY = 0x40000000,
CAPS2_ADDITIONALPRIMARY = 0x80000000,
};
REV_ENUM_OPERATORS(CAPS2);
static_assert(sizeof(CAPS2) == 4);
enum CAPS3 : u32
{
CAPS3_MULTISAMPLE_MASK = 0x0000001F,
CAPS3_MULTISAMPLE_QUALITY_MASK = 0x000000E0,
CAPS3_MULTISAMPLE_QUALITY_SHIFT = 5,
CAPS3_RESERVED1 = 0x00000100,
CAPS3_RESERVED2 = 0x00000200,
CAPS3_LIGHTWEIGHTMIPMAP = 0x00000400,
CAPS3_AUTOGENMIPMAP = 0x00000800,
CAPS3_DMAP = 0x00001000,
CAPS3_CREATESHAREDRESOURCE = 0x00002000,
CAPS3_READONLYRESOURCE = 0x00004000,
CAPS3_OPENSHAREDRESOURCE = 0x00008000,
};
REV_ENUM_OPERATORS(CAPS3);
static_assert(sizeof(CAPS3) == 4);
#define REV_MAKE_FOURCC(str) ((str[3] << 24) | (str[2] << 16) | (str[1] << 8) | str[0])
enum FOURCC : u32
{
FOURCC_DXT1 = REV_MAKE_FOURCC("DXT1"),
FOURCC_DXT2 = REV_MAKE_FOURCC("DXT2"),
FOURCC_DXT3 = REV_MAKE_FOURCC("DXT3"),
FOURCC_DXT4 = REV_MAKE_FOURCC("DXT4"),
FOURCC_DXT5 = REV_MAKE_FOURCC("DXT5"),
FOURCC_DX10 = REV_MAKE_FOURCC("DX10"),
};
static_assert(sizeof(FOURCC) == 4);
enum : u32
{
DDS_MAGIC = REV_MAKE_FOURCC("DDS "),
};
enum MISC_FLAG : u32
{
MISC_FLAG_GENERATE_MIPS = 0x00001,
MISC_FLAG_SHARED = 0x00002,
MISC_FLAG_TEXTURECUBE = 0x00004,
MISC_FLAG_DRAWINDIRECT_ARGS = 0x00010,
MISC_FLAG_BUFFER_ALLOW_RAW_VIEWS = 0x00020,
MISC_FLAG_BUFFER_STRUCTURED = 0x00040,
MISC_FLAG_RESOURCE_CLAMP = 0x00080,
MISC_FLAG_SHARED_KEYEDMUTEX = 0x00100,
MISC_FLAG_GDI_COMPATIBLE = 0x00200,
MISC_FLAG_SHARED_NTHANDLE = 0x00800,
MISC_FLAG_RESTRICTED_CONTENT = 0x01000,
MISC_FLAG_RESTRICT_SHARED_RESOURCE = 0x02000,
MISC_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = 0x04000,
MISC_FLAG_GUARDED = 0x08000,
MISC_FLAG_TILE_POOL = 0x20000,
MISC_FLAG_TILED = 0x40000,
MISC_FLAG_HW_PROTECTED = 0x80000,
};
REV_ENUM_OPERATORS(MISC_FLAG);
static_assert(sizeof(MISC_FLAG) == 4);
enum MISC_FLAG2 : u32
{
MISC_FLAG2_ALPHA_MODE_MASK = 0x7,
};
REV_ENUM_OPERATORS(MISC_FLAG2);
static_assert(sizeof(MISC_FLAG2) == 4);
struct PixelFormat
{
u32 self_size;
PIXEL_FORMAT_FLAG flags;
union
{
char str[4];
FOURCC _enum;
} fourcc;
union
{
u32 rgb_bit_count;
u32 yuv_bit_count;
u32 zbuffer_bit_depth;
u32 alpha_bit_depth;
u32 luminance_bit_count;
u32 bump_bit_count;
u32 private_format_bit_count;
};
union
{
u32 r_bit_mask;
u32 y_bit_mask;
u32 stencil_bit_depth;
u32 luminance_bit_mask;
u32 bump_du_bit_mask;
u32 operations;
};
union
{
u32 g_bit_mask;
u32 u_bit_mask;
u32 z_bit_mask;
u32 bump_dv_bit_mask;
struct
{
u16 flip_ms_types;
u16 blt_ms_types;
} multisample_caps;
};
union
{
u32 b_bit_mask;
u32 v_bit_mask;
u32 stencil_bit_mask;
u32 bump_luminance_bit_mask;
};
union
{
u32 a_bit_mask;
u32 z_bit_mask;
};
};
struct Caps2
{
CAPS1 caps1;
CAPS2 caps2;
CAPS3 caps3;
union
{
u32 caps4;
u32 volume_depth;
};
};
struct ColorKey
{
u32 color_space_low_value;
u32 color_space_high_value;
};
struct DDSHeader
{
u32 self_size;
DDS_FLAG flags;
u32 height;
u32 width;
union
{
s32 pitch;
u32 linear_size;
};
union
{
u32 back_buffer_count;
u32 depth;
};
union
{
u32 mipmap_count;
u32 refresh_rate;
u32 src_vb_handle;
};
u32 alpha_bit_depth;
u32 reserved;
intptr32 surface;
union
{
ColorKey ck_dest_overlay;
u32 empty_face_color;
};
ColorKey ck_dest_blt;
ColorKey ck_src_overlay;
ColorKey ck_src_blt;
union
{
PixelFormat pixel_format;
u32 vertex_format; // @NOTE(Roman): for vertex buffers only
};
Caps2 caps;
u32 texture_stage;
};
struct DX10Header
{
DXGI_FORMAT format;
D3D12_RESOURCE_DIMENSION dimension;
MISC_FLAG misc_flags;
u32 array_size;
MISC_FLAG2 misc_flags2;
};
REV_INTERNAL u64 BitsPerPixel(GPU::TEXTURE_FORMAT format)
{
if (cast(bool, format & GPU::TEXTURE_FORMAT::_DDS_DX10))
{
switch (cast(u32, format & ~GPU::TEXTURE_FORMAT::_DDS_DX10))
{
/* 1 */ case DXGI_FORMAT_R32G32B32A32_TYPELESS: return 128;
/* 2 */ case DXGI_FORMAT_R32G32B32A32_FLOAT: return 128;
/* 3 */ case DXGI_FORMAT_R32G32B32A32_UINT: return 128;
/* 4 */ case DXGI_FORMAT_R32G32B32A32_SINT: return 128;
/* 5 */ case DXGI_FORMAT_R32G32B32_TYPELESS: return 96;
/* 6 */ case DXGI_FORMAT_R32G32B32_FLOAT: return 96;
/* 7 */ case DXGI_FORMAT_R32G32B32_UINT: return 96;
/* 8 */ case DXGI_FORMAT_R32G32B32_SINT: return 96;
/* 9 */ case DXGI_FORMAT_R16G16B16A16_TYPELESS: return 64;
/* 10 */ case DXGI_FORMAT_R16G16B16A16_FLOAT: return 64;
/* 11 */ case DXGI_FORMAT_R16G16B16A16_UNORM: return 64;
/* 12 */ case DXGI_FORMAT_R16G16B16A16_UINT: return 64;
/* 13 */ case DXGI_FORMAT_R16G16B16A16_SNORM: return 64;
/* 14 */ case DXGI_FORMAT_R16G16B16A16_SINT: return 64;
/* 15 */ case DXGI_FORMAT_R32G32_TYPELESS: return 64;
/* 16 */ case DXGI_FORMAT_R32G32_FLOAT: return 64;
/* 17 */ case DXGI_FORMAT_R32G32_UINT: return 64;
/* 18 */ case DXGI_FORMAT_R32G32_SINT: return 64;
/* 19 */ case DXGI_FORMAT_R32G8X24_TYPELESS: return 64;
/* 20 */ case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return 64;
/* 21 */ case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return 64;
/* 22 */ case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return 64;
/* 23 */ case DXGI_FORMAT_R10G10B10A2_TYPELESS: return 32;
/* 24 */ case DXGI_FORMAT_R10G10B10A2_UNORM: return 32;
/* 25 */ case DXGI_FORMAT_R10G10B10A2_UINT: return 32;
/* 26 */ case DXGI_FORMAT_R11G11B10_FLOAT: return 32;
/* 27 */ case DXGI_FORMAT_R8G8B8A8_TYPELESS: return 32;
/* 28 */ case DXGI_FORMAT_R8G8B8A8_UNORM: return 32;
/* 29 */ case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return 32;
/* 30 */ case DXGI_FORMAT_R8G8B8A8_UINT: return 32;
/* 31 */ case DXGI_FORMAT_R8G8B8A8_SNORM: return 32;
/* 32 */ case DXGI_FORMAT_R8G8B8A8_SINT: return 32;
/* 33 */ case DXGI_FORMAT_R16G16_TYPELESS: return 32;
/* 34 */ case DXGI_FORMAT_R16G16_FLOAT: return 32;
/* 35 */ case DXGI_FORMAT_R16G16_UNORM: return 32;
/* 36 */ case DXGI_FORMAT_R16G16_UINT: return 32;
/* 37 */ case DXGI_FORMAT_R16G16_SNORM: return 32;
/* 38 */ case DXGI_FORMAT_R16G16_SINT: return 32;
/* 39 */ case DXGI_FORMAT_R32_TYPELESS: return 32;
/* 40 */ case DXGI_FORMAT_D32_FLOAT: return 32;
/* 41 */ case DXGI_FORMAT_R32_FLOAT: return 32;
/* 42 */ case DXGI_FORMAT_R32_UINT: return 32;
/* 43 */ case DXGI_FORMAT_R32_SINT: return 32;
/* 44 */ case DXGI_FORMAT_R24G8_TYPELESS: return 32;
/* 45 */ case DXGI_FORMAT_D24_UNORM_S8_UINT: return 32;
/* 46 */ case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return 32;
/* 47 */ case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return 32;
/* 48 */ case DXGI_FORMAT_R8G8_TYPELESS: return 16;
/* 49 */ case DXGI_FORMAT_R8G8_UNORM: return 16;
/* 50 */ case DXGI_FORMAT_R8G8_UINT: return 16;
/* 51 */ case DXGI_FORMAT_R8G8_SNORM: return 16;
/* 52 */ case DXGI_FORMAT_R8G8_SINT: return 16;
/* 53 */ case DXGI_FORMAT_R16_TYPELESS: return 16;
/* 54 */ case DXGI_FORMAT_R16_FLOAT: return 16;
/* 55 */ case DXGI_FORMAT_D16_UNORM: return 16;
/* 56 */ case DXGI_FORMAT_R16_UNORM: return 16;
/* 57 */ case DXGI_FORMAT_R16_UINT: return 16;
/* 58 */ case DXGI_FORMAT_R16_SNORM: return 16;
/* 59 */ case DXGI_FORMAT_R16_SINT: return 16;
/* 60 */ case DXGI_FORMAT_R8_TYPELESS: return 8;
/* 61 */ case DXGI_FORMAT_R8_UNORM: return 8;
/* 62 */ case DXGI_FORMAT_R8_UINT: return 8;
/* 63 */ case DXGI_FORMAT_R8_SNORM: return 8;
/* 64 */ case DXGI_FORMAT_R8_SINT: return 8;
/* 65 */ case DXGI_FORMAT_A8_UNORM: return 8;
/* 66 */ case DXGI_FORMAT_R1_UNORM: return 1;
/* 67 */ case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return 32;
/* 68 */ case DXGI_FORMAT_R8G8_B8G8_UNORM: return 32;
/* 69 */ case DXGI_FORMAT_G8R8_G8B8_UNORM: return 32;
/* 70 */ case DXGI_FORMAT_BC1_TYPELESS: return 4;
/* 71 */ case DXGI_FORMAT_BC1_UNORM: return 4;
/* 72 */ case DXGI_FORMAT_BC1_UNORM_SRGB: return 4;
/* 73 */ case DXGI_FORMAT_BC2_TYPELESS: return 8;
/* 74 */ case DXGI_FORMAT_BC2_UNORM: return 8;
/* 75 */ case DXGI_FORMAT_BC2_UNORM_SRGB: return 8;
/* 76 */ case DXGI_FORMAT_BC3_TYPELESS: return 8;
/* 77 */ case DXGI_FORMAT_BC3_UNORM: return 8;
/* 78 */ case DXGI_FORMAT_BC3_UNORM_SRGB: return 8;
/* 79 */ case DXGI_FORMAT_BC4_TYPELESS: return 4;
/* 80 */ case DXGI_FORMAT_BC4_UNORM: return 4;
/* 81 */ case DXGI_FORMAT_BC4_SNORM: return 4;
/* 82 */ case DXGI_FORMAT_BC5_TYPELESS: return 8;
/* 83 */ case DXGI_FORMAT_BC5_UNORM: return 8;
/* 84 */ case DXGI_FORMAT_BC5_SNORM: return 8;
/* 85 */ case DXGI_FORMAT_B5G6R5_UNORM: return 16;
/* 86 */ case DXGI_FORMAT_B5G5R5A1_UNORM: return 16;
/* 87 */ case DXGI_FORMAT_B8G8R8A8_UNORM: return 32;
/* 88 */ case DXGI_FORMAT_B8G8R8X8_UNORM: return 32;
/* 89 */ case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return 32;
/* 90 */ case DXGI_FORMAT_B8G8R8A8_TYPELESS: return 32;
/* 91 */ case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return 32;
/* 92 */ case DXGI_FORMAT_B8G8R8X8_TYPELESS: return 32;
/* 93 */ case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return 32;
/* 94 */ case DXGI_FORMAT_BC6H_TYPELESS: return 8;
/* 95 */ case DXGI_FORMAT_BC6H_UF16: return 8;
/* 96 */ case DXGI_FORMAT_BC6H_SF16: return 8;
/* 97 */ case DXGI_FORMAT_BC7_TYPELESS: return 8;
/* 98 */ case DXGI_FORMAT_BC7_UNORM: return 8;
/* 99 */ case DXGI_FORMAT_BC7_UNORM_SRGB: return 8;
/* 100 */ case DXGI_FORMAT_AYUV: return 32;
/* 101 */ case DXGI_FORMAT_Y410: return 32;
/* 102 */ case DXGI_FORMAT_Y416: return 64;
/* 103 */ case DXGI_FORMAT_NV12: return 12;
/* 104 */ case DXGI_FORMAT_P010: return 24;
/* 105 */ case DXGI_FORMAT_P016: return 24;
/* 106 */ case DXGI_FORMAT_420_OPAQUE: return 12;
/* 107 */ case DXGI_FORMAT_YUY2: return 32;
/* 108 */ case DXGI_FORMAT_Y210: return 64;
/* 109 */ case DXGI_FORMAT_Y216: return 64;
/* 110 */ case DXGI_FORMAT_NV11: return 12;
/* 111 */ case DXGI_FORMAT_AI44: return 8;
/* 112 */ case DXGI_FORMAT_IA44: return 8;
/* 113 */ case DXGI_FORMAT_P8: return 8;
/* 114 */ case DXGI_FORMAT_A8P8: return 16;
/* 115 */ case DXGI_FORMAT_B4G4R4A4_UNORM: return 16;
/* 130 */ case DXGI_FORMAT_P208: return 16;
/* 131 */ case DXGI_FORMAT_V208: return 16;
/* 132 */ case DXGI_FORMAT_V408: return 24;
default: return 0;
}
}
else
{
switch (format)
{
/* 1 */ case GPU::TEXTURE_FORMAT::RGBA8: return 32;
/* 2 */ case GPU::TEXTURE_FORMAT::BGRA8: return 32;
/* 3 */ case GPU::TEXTURE_FORMAT::DXT1: return 4;
/* 4 */ case GPU::TEXTURE_FORMAT::DXT2: return 8;
/* 5 */ case GPU::TEXTURE_FORMAT::DXT3: return 8;
/* 6 */ case GPU::TEXTURE_FORMAT::DXT4: return 4;
/* 7 */ case GPU::TEXTURE_FORMAT::DXT5: return 8;
default: return 0;
}
}
}
void AssetManager::LoadDDSTexture(Asset *asset, const ConstArray<byte>& data, const ConstString& name, bool _static)
{
GPU::MemoryManager *memory_manager = GraphicsAPI::GetMemoryManager();
u32 magic = *cast(u32 *, data.Data());
REV_CHECK_M(magic == DDS_MAGIC, "This is not a DDS file");
DDSHeader *dds_header = cast(DDSHeader *, data.Data() + sizeof(u32));
REV_CHECK_M(dds_header->self_size == sizeof(DDSHeader) && dds_header->pixel_format.self_size == sizeof(PixelFormat), "Invalid DDS file layout");
DX10Header *dx10_header = null;
u32 data_offset = sizeof(u32) + sizeof(DDSHeader);
GPU::TEXTURE_FORMAT texture_format = GPU::TEXTURE_FORMAT::UNKNOWN;
u32 compression_ratio = 1;
bool block_compression = false;
bool packed = false; // @TODO(Roman): #OtherFormats
bool planar = false; // @TODO(Roman): #OtherFormats
if (dds_header->pixel_format.flags & PIXEL_FORMAT_FLAG_FOURCC)
{
switch (dds_header->pixel_format.fourcc._enum)
{
case FOURCC_DXT1:
{
texture_format = GPU::TEXTURE_FORMAT::DXT1;
compression_ratio = 8;
block_compression = true;
} break;
case FOURCC_DXT2:
{
texture_format = GPU::TEXTURE_FORMAT::DXT2;
compression_ratio = 16;
block_compression = true;
} break;
case FOURCC_DXT3:
{
texture_format = GPU::TEXTURE_FORMAT::DXT3;
compression_ratio = 16;
block_compression = true;
} break;
case FOURCC_DXT4:
{
texture_format = GPU::TEXTURE_FORMAT::DXT4;
compression_ratio = 16;
block_compression = true;
} break;
case FOURCC_DXT5:
{
texture_format = GPU::TEXTURE_FORMAT::DXT5;
compression_ratio = 16;
block_compression = true;
} break;
case FOURCC_DX10:
{
dx10_header = cast(DX10Header *, data.Data() + sizeof(u32) + sizeof(DDSHeader));
data_offset += sizeof(DX10Header);
texture_format = cast(GPU::TEXTURE_FORMAT, dx10_header->format) | GPU::TEXTURE_FORMAT::_DDS_DX10;
} break;
default:
{
// @TODO(Roman): #OtherFormats
REV_ERROR_M("Unhandled DDS texture format: %.4s", dds_header->pixel_format.fourcc.str);
} break;
};
}
else
{
// @TODO(Roman): #OtherFormats: BC4, BC5, Uncompressed RGB(A), YCrCb
REV_ERROR_M("Unhandled DDS texture format");
}
if (dx10_header)
{
if (dx10_header->dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D)
{
REV_CHECK(dds_header->caps.caps2 & CAPS2_VOLUME);
REV_CHECK(dx10_header->array_size == 1);
asset->texture.resource = memory_manager->AllocateTexture3D(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->depth),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
else if (dx10_header->dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D)
{
if (dx10_header->array_size > 1)
{
if (dds_header->caps.caps2 & CAPS2_CUBEMAP)
{
REV_CHECK(dx10_header->misc_flags & MISC_FLAG_TEXTURECUBE);
REV_CHECK_M(dds_header->caps.caps2 & CAPS2_CUBEMAP_ALLFACES, "Currently only DDS cube textures with ALL faces are allowed");
asset->texture.resource = memory_manager->AllocateTextureCubeArray(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dx10_header->array_size),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
else
{
asset->texture.resource = memory_manager->AllocateTexture2DArray(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dx10_header->array_size),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
}
else
{
if (dds_header->caps.caps2 & CAPS2_CUBEMAP)
{
REV_CHECK(dx10_header->misc_flags & MISC_FLAG_TEXTURECUBE);
REV_CHECK_M(dds_header->caps.caps2 & CAPS2_CUBEMAP_ALLFACES, "Currently only DDS cube textures with ALL faces are allowed");
asset->texture.resource = memory_manager->AllocateTextureCube(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
else
{
asset->texture.resource = memory_manager->AllocateTexture2D(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
}
}
else if (dx10_header->dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D)
{
asset->texture.resource = memory_manager->AllocateTexture1D(cast(u16, dds_header->width),
texture_format,
name,
_static);
}
else
{
REV_ERROR_M("Incorrect dimension");
}
}
else
{
if (dds_header->flags & DDS_FLAG_DEPTH)
{
REV_CHECK(dds_header->caps.caps2 & CAPS2_VOLUME);
asset->texture.resource = memory_manager->AllocateTexture3D(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->depth),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
else if (dds_header->caps.caps2 & CAPS2_CUBEMAP)
{
REV_CHECK_M(dds_header->caps.caps2 & CAPS2_CUBEMAP_ALLFACES, "Currently only DDS cube textures with ALL faces are allowed");
asset->texture.resource = memory_manager->AllocateTextureCube(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
else
{
REV_CHECK(dds_header->width && dds_header->height);
asset->texture.resource = memory_manager->AllocateTexture2D(cast(u16, dds_header->width),
cast(u16, dds_header->height),
cast(u16, dds_header->mipmap_count),
texture_format,
name,
_static);
}
}
GPU::TextureDesc *texture_desc = null;
// @NOTE(Roman): compressed: DDS_FLAG_LINEARSIZE, linear_size = number of bytes for the main image.
// uncompressed: DDS_FLAG_PITCH, pitch = number of bytes per row.
if (dds_header->flags & DDS_FLAG_LINEARSIZE)
{
u64 alloc_size = sizeof(GPU::TextureDesc) + sizeof(GPU::SubTextureDesc) * dds_header->mipmap_count;
texture_desc = cast(GPU::TextureDesc *, Memory::Get()->PushToFrameArena(alloc_size));
texture_desc->subtextures_count = dds_header->mipmap_count;
const byte *mipmap_level_data = data.Data() + data_offset;
u64 width = dds_header->width;
u64 height = dds_header->height;
for (u64 i = 0; i < dds_header->mipmap_count; ++i)
{
s64 row_bytes = 0;
s64 slice_bytes = 0;
if (block_compression)
{
row_bytes = Math::max(1ui64, (width + 3) / 4) * compression_ratio;
slice_bytes = Math::max(1ui64, (height + 3) / 4) * row_bytes;
}
else if (packed)
{
row_bytes = ((width + 1) >> 1) * compression_ratio;
slice_bytes = row_bytes * height;
}
else if (planar)
{
row_bytes = ((width + 1) >> 1) * compression_ratio;
slice_bytes = (3 * row_bytes * height + 1) >> 1;
}
else
{
row_bytes = (width * BitsPerPixel(texture_format) + 7) / 8;
slice_bytes = row_bytes * height;
}
GPU::SubTextureDesc *sub_texture = texture_desc->subtexture_desc + i;
sub_texture->data = cast(byte *, mipmap_level_data);
sub_texture->bytes_per_row = row_bytes;
sub_texture->bytes_per_tex2d = slice_bytes;
mipmap_level_data += slice_bytes;
width >>= 1;
height >>= 1;
}
}
else if (dds_header->flags & DDS_FLAG_PITCH)
{
REV_ERROR_M("Only BC1-BC5 foramts are supported. Any format supported only with DDS_HEADER_DXT10.");
}
memory_manager->SetTextureData(asset->texture.resource, texture_desc);
}
}
#pragma pack(pop)
| 45.27973 | 148 | 0.493091 | Roman-Skabin |
c0d1f511d6322037a1efebf0e88c27bda31791f3 | 1,256 | cpp | C++ | Question 0160 Intersection Of Two Linked Lists/main.cpp | toby0622/Leetcode-Practicing | dd2b3fd2e1aba601abf2c7a308c4d1d1b5f9015e | [
"MIT"
] | null | null | null | Question 0160 Intersection Of Two Linked Lists/main.cpp | toby0622/Leetcode-Practicing | dd2b3fd2e1aba601abf2c7a308c4d1d1b5f9015e | [
"MIT"
] | null | null | null | Question 0160 Intersection Of Two Linked Lists/main.cpp | toby0622/Leetcode-Practicing | dd2b3fd2e1aba601abf2c7a308c4d1d1b5f9015e | [
"MIT"
] | null | null | null | // LeetCode Solution Class
// 解題思路:考量如果兩條 linked list 長度相同,對應的一個一個比下去便能找到相交點
// ,所以要做的就是把比較長的 linked list 縮短即可。分別遍歷兩個 linked list,得
// 到分別對應的長度,然後求兩長度的差值,並且把長 linked list 向後移動這個差值得個
// 數,再次一一進行比較即可求解。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) {
return NULL;
}
int lengthA = getLength(headA);
int lengthB = getLength(headB);
if (lengthA < lengthB) {
for (int i = 0; i < lengthB - lengthA; ++i) {
headB = headB -> next;
}
} else {
for (int i = 0; i < lengthA - lengthB; ++i) {
headA = headA -> next;
}
}
while (headA && headB && headA != headB) {
headA = headA -> next;
headB = headB -> next;
}
return (headA && headB) ? headA : NULL;
}
int getLength(ListNode* Node) {
int count = 0;
while (Node) {
++count;
Node = Node -> next;
}
return count;
}
};
| 22.428571 | 69 | 0.501592 | toby0622 |
c0d5fc580f330b57417f62b4ee59c8beb5b13c36 | 2,084 | hh | C++ | src/Finalizer/GCC/ELFExecutable.hh | pjaaskel/phsa-runtime | b37cd9bd8085632e89b02861da193bbd0fa25c5b | [
"MIT"
] | 7 | 2016-04-17T20:38:36.000Z | 2017-12-28T17:46:21.000Z | src/Finalizer/GCC/ELFExecutable.hh | pjaaskel/phsa-runtime | b37cd9bd8085632e89b02861da193bbd0fa25c5b | [
"MIT"
] | 6 | 2016-03-11T15:54:28.000Z | 2016-11-22T13:20:11.000Z | src/Finalizer/GCC/ELFExecutable.hh | pjaaskel/phsa-runtime | b37cd9bd8085632e89b02861da193bbd0fa25c5b | [
"MIT"
] | 4 | 2016-03-10T14:27:53.000Z | 2020-05-03T22:16:51.000Z | /*
Copyright (c) 2016 General Processor Tech.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/**
* @author tomi.aijo@parmance.com for General Processor Tech.
*/
#ifndef HSA_RUNTIME_ELFEXECUTABLE_HH
#define HSA_RUNTIME_ELFEXECUTABLE_HH
#include <cstring>
#include <libelf.h>
#include <iostream>
#include "Executable.hh"
#include "common/Logging.hh"
#include "gcc-phsa.h"
#define MIN_ALIGNMENT 16u
namespace phsa {
// Handles ELFs produced by the GCC BRIG frontend.
class ELFExecutable : public Executable {
public:
ELFExecutable(hsa_profile_t Profile, bool IsFrozen)
: Executable(IsFrozen), Profile(Profile) {}
virtual ~ELFExecutable() {}
virtual hsa_profile_t getProfile() const override { return Profile; }
virtual HSAReturnValue<> LoadCodeObject(phsa::Agent *Agent,
const hsa_code_object_t CodeObject,
const char *Options) override;
private:
hsa_profile_t Profile;
};
} // namespace phsa
#endif // HSA_RUNTIME_ELFEXECUTABLE_HH
| 35.322034 | 80 | 0.729367 | pjaaskel |
c0d714ff3f82511a07c7e1c687b646ed4a355cb1 | 1,222 | cpp | C++ | Common/Loader/ssloader_ssee.cpp | Naruto/SpriteStudio6-SDK | 0966fed33800f7b0194ac4a40ac6d1737b56e645 | [
"BSD-3-Clause"
] | 2 | 2021-04-28T23:26:18.000Z | 2021-11-08T08:56:25.000Z | Common/Loader/ssloader_ssee.cpp | Naruto/SpriteStudio6-SDK | 0966fed33800f7b0194ac4a40ac6d1737b56e645 | [
"BSD-3-Clause"
] | 2 | 2018-10-17T14:14:42.000Z | 2019-11-19T09:16:34.000Z | Common/Loader/ssloader_ssee.cpp | Naruto/SpriteStudio6-SDK | 0966fed33800f7b0194ac4a40ac6d1737b56e645 | [
"BSD-3-Clause"
] | null | null | null | #include "ssloader_sspj.h"
#include "ssloader_ssae.h"
#include "ssloader_ssce.h"
#include "ssloader_ssee.h"
#include "ssstring_uty.h"
#include "../Helper/DebugPrint.h"
SsEffectFile* ssloader_ssee::Load(const std::string& filename )
{
SsString _basepath = "";
SsEffectFile* effectFile = new SsEffectFile();
XMLDocument xml;
if ( XML_SUCCESS == xml.LoadFile( filename.c_str() ) )
{
SsXmlIArchiver ar( xml.GetDocument() , "SpriteStudioEffect" );
effectFile->__Serialize( &ar );
}else{
delete effectFile;
effectFile = 0;
}
return effectFile;
}
void ssloader_ssee::loadPostProcessing( SsEffectFile* file , SsProject* pj )
{
for ( size_t i = 0 ; i < file->effectData.nodeList.size(); i++)
{
SsEffectBehavior* beh = &file->effectData.nodeList[i]->behavior;
beh->refCell = 0;
if ( beh->CellMapName == "" )continue;
SsCellMap* map =pj->findCellMap( beh->CellMapName );
if ( map )
{
for ( size_t n = 0 ; n < map->cells.size() ; n++ )
{
if ( map->cells[n]->name == beh->CellName )
{
beh->refCell = map->cells[n];
}
}
if ( beh->refCell == 0 )
{
DEBUG_PRINTF("not fount cell : %s , %s", beh->CellMapName.c_str(), beh->CellName.c_str());
}
}
}
}
| 19.709677 | 94 | 0.635025 | Naruto |
c0da04ed1901cfff33bf25fcf5824c407fb7d02f | 51,873 | cpp | C++ | datanet_openresty_1.9.7.3_0.1.1/datanet_engine/ooo_replay.cpp | phaynes/datanet | ac448c2886becce253b247b9fa480b7a783810e6 | [
"BSD-2-Clause"
] | 16 | 2017-12-14T03:57:28.000Z | 2021-02-28T23:50:29.000Z | datanet_openresty_1.9.7.3_0.1.1/datanet_engine/ooo_replay.cpp | phaynes/datanet | ac448c2886becce253b247b9fa480b7a783810e6 | [
"BSD-2-Clause"
] | null | null | null | datanet_openresty_1.9.7.3_0.1.1/datanet_engine/ooo_replay.cpp | phaynes/datanet | ac448c2886becce253b247b9fa480b7a783810e6 | [
"BSD-2-Clause"
] | 4 | 2018-11-05T10:42:46.000Z | 2019-10-28T21:08:07.000Z |
#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>
#include <iostream>
extern "C" {
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
}
#include "json/json.h"
#include "easylogging++.h"
#include "helper.h"
#include "external_hooks.h"
#include "shared.h"
#include "merge.h"
#include "deltas.h"
#include "subscriber_delta.h"
#include "ooo_replay.h"
#include "apply_delta.h"
#include "activesync.h"
#include "gc.h"
#include "agent_daemon.h"
#include "datastore.h"
#include "trace.h"
#include "storage.h"
using namespace std;
extern Int64 MyUUID;
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// DEBUG OVERRIDES -----------------------------------------------------------
//#define DISABLE_LT
#ifdef DISABLE_LT
#undef LT
#define LT(text) /* text */
#endif
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// DEBUG ---------------------------------------------------------------------
static string debug_dentries_agent_versions(jv *rdentries) {
string ret;
for (uint i = 0; i < rdentries->size(); i++) {
jv *jdentry = &((*rdentries)[i]);
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
string avrsn = (*jauthor)["agent_version"].asString();
if (ret.size()) ret += ", ";
ret += avrsn;
}
return ret;
}
static void debug_replay_merge_dentries(string &kqk, jv *rdentries) {
if (!rdentries->size()) {
LE("ZOOR.replay_local_deltas: K: " << kqk << " ZERO DENTRIES");
} else {
LE("ZOOR.replay_local_deltas: K: " << kqk << " rdentries[AV]: [" <<
debug_dentries_agent_versions(rdentries) << "]");
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// HELPERS -------------------------------------------------------------------
static bool DebugCmpDeltaAgentVersion = false;
static bool cmp_delta_agent_version(jv *javrsn1, jv *javrsn2) {
string avrsn1 = javrsn1->asString();
vector<string> res1 = split(avrsn1, '|');
UInt64 auuid1 = strtoul(res1[0].c_str(), NULL, 10);
UInt64 avnum1 = strtoul(res1[1].c_str(), NULL, 10);
string avrsn2 = javrsn2->asString();
vector<string> res2 = split(avrsn2, '|');
UInt64 auuid2 = strtoul(res2[0].c_str(), NULL, 10);
UInt64 avnum2 = strtoul(res2[1].c_str(), NULL, 10);
if (DebugCmpDeltaAgentVersion && (auuid1 == auuid2) && (avnum1 == avnum2)) {
string ferr = "cmp_delta_agent_version: REPEAT AV: AV1: " + avrsn1 +
" AV2: " + avrsn2;
zh_fatal_error(ferr.c_str());
}
if (auuid1 != auuid2) return (auuid1 < auuid2);
else return (avnum1 < avnum2);
}
static jv create_reference_author(jv *jdentry) {
jv *jdmeta = &((*jdentry)["delta"]["_meta"]);
UInt64 rfauuid = (*jdmeta)["reference_uuid"].asUInt64();
string rfavrsn = (*jdmeta)["reference_version"].asString();
jv rfauthor = JOBJECT;
rfauthor["agent_uuid"] = rfauuid;
rfauthor["agent_version"] = rfavrsn;
return rfauthor;
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// GC-WAIT_INCOMPLETE --------------------------------------------------------
sqlres zoor_set_gc_wait_incomplete(string &kqk) {
LD("START: GC-WAIT_INCOMPLETE: K: " << kqk);
return persist_agent_key_gc_wait_incomplete(kqk);
}
sqlres zoor_end_gc_wait_incomplete(string &kqk) {
LD("END: GC-WAIT_INCOMPLETE: K: " << kqk);
return remove_agent_key_gc_wait_incomplete(kqk);
}
sqlres zoor_agent_in_gc_wait(string &kqk) {
sqlres sr = fetch_all_agent_key_gcv_needs_reorder(kqk);
RETURN_SQL_ERROR(sr)
jv *jgavrsns = &(sr.jres);
bool empty = (zjn(jgavrsns) || jgavrsns->size() == 0);
bool gwait = !empty;
if (gwait) RETURN_SQL_RESULT_UINT(1)
sr = fetch_agent_key_gc_wait_incomplete(kqk);
RETURN_SQL_ERROR(sr)
bool gcwi = sr.ures ? true : false;
LD("REO: (GC-WAIT) K: " << kqk << " GCW(INCOMPLETE): " << gcwi);
if (gcwi) RETURN_SQL_RESULT_UINT(1) // POSSIBLE END-GC-WAIT-INCOMPLETE
else RETURN_EMPTY_SQLRES
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// GET/SET/DECREMENT KEY-GCV-NREO --------------------------------------------
static sqlres get_num_agent_key_gcv_needs_reorder(string &kqk, UInt64 gcv) {
sqlres sr = fetch_agent_key_gcv_needs_reorder(kqk, gcv);
RETURN_SQL_ERROR(sr)
jv *javrsns = &(sr.jres);
UInt64 nreo = javrsns->size();
RETURN_SQL_RESULT_UINT(nreo);
}
static sqlres do_remove_agent_key_gcv_needs_reorder(string &kqk, UInt64 gcv) {
LD("REMOVE-KEY-GCV-NREO: (GC-WAIT): K: " << kqk << " GCV: " << gcv);
sqlres sr = fetch_all_agent_key_gcv_needs_reorder(kqk);
RETURN_SQL_ERROR(sr)
jv *jgavrsns = &(sr.jres);
jgavrsns->removeMember("_id");
bool empty = true;
vector<string> mbrs = zh_jv_get_member_names(jgavrsns);
for (uint i = 0; i < mbrs.size(); i++) {
string sgcv = mbrs[i];
jv *javrsns = &((*jgavrsns)[sgcv]);
UInt64 nreo = javrsns->size();
if (nreo > 0) {
empty = false;
break;
}
}
LD("do_remove_agent_key_gcv_needs_reorder: empty: " << empty);
if (empty) return remove_all_agent_key_gcv_needs_reorder(kqk);
else return remove_agent_key_gcv_needs_reorder(kqk, gcv);
}
static void debug_remove_agent_version_agent_key_gcv_nreo(string avrsn,
jv *javrsns,
UInt64 nreo) {
LD("REMOVE-AV-KGNREO: AV: " << avrsn << " NREO: " << nreo <<
" AVS[]; " << *javrsns);
}
static sqlres remove_agent_version_agent_key_gcv_needs_reorder(string &kqk,
UInt64 gcv,
string avrsn) {
sqlres sr = fetch_agent_key_gcv_needs_reorder(kqk, gcv);
RETURN_SQL_ERROR(sr)
jv *javrsns = &(sr.jres);
javrsns->removeMember(avrsn); // REMOVE SINGLE AGENT-VERSION
UInt64 nreo = javrsns->size();
debug_remove_agent_version_agent_key_gcv_nreo(avrsn, javrsns, nreo);
sr = persist_agent_key_gcv_needs_reorder(kqk, gcv, javrsns);
RETURN_SQL_ERROR(sr)
sr = remove_agent_delta_gcv_needs_reorder(kqk, avrsn);
RETURN_SQL_ERROR(sr)
RETURN_SQL_RESULT_UINT(nreo)
}
static sqlres decrement_agent_key_gcv_needs_reorder(string &kqk, UInt64 gcv,
string avrsn) {
LD("decrement_agent_key_gcv_needs_reorder: K: " << kqk << " GCV: " << gcv);
sqlres sr = get_num_agent_key_gcv_needs_reorder(kqk, gcv);
RETURN_SQL_ERROR(sr)
UInt64 nreo = sr.ures;
LD("REO: (GC-WAIT) GET-KEY-GCV-NREO: K: " << kqk << " GCV: " << gcv <<
" N: " << nreo);
if (!nreo) RETURN_EMPTY_SQLRES // RETURN FALSE
else {
string sgcv = to_string(gcv);
sqlres sr = remove_agent_version_agent_key_gcv_needs_reorder(kqk, gcv,
avrsn);
RETURN_SQL_ERROR(sr)
UInt64 nnreo = sr.ures;
LD("DECREMENT-KEY-GCV-NREO: (GC-WAIT) K: " << kqk << " GCV: " << gcv <<
" (N)NREO: " << nnreo);
if (nnreo) RETURN_EMPTY_SQLRES // RETURN FALSE
else {
sqlres sr = do_remove_agent_key_gcv_needs_reorder(kqk, gcv);
RETURN_SQL_ERROR(sr)
RETURN_SQL_RESULT_UINT(1) // RETURN TRUE
}
}
}
static jv get_per_gcv_number_key_gcv_needs_reorder(string &kqk, UInt64 xgcv,
jv *jdentries) {
jv gavrsns = JOBJECT;
for (uint i = 0; i < jdentries->size(); i++) {
jv *jdentry = &((*jdentries)[i]);
UInt64 dgcv = zh_get_dentry_gcversion(jdentry);
jv *jdmeta = &((*jdentry)["delta"]["_meta"]);
string avrsn = (*jdmeta)["author"]["agent_version"].asString();
bool fcentral = zh_get_bool_member(jdmeta, "from_central");
bool gmismatch = (xgcv != dgcv);
bool do_ignore = zh_get_bool_member(jdmeta, "DO_IGNORE");
// (AGENT-DELTA) AND (DELTA(GCV) mismatch XCRDT) AND (NOT AN IGNORE)
if (!fcentral && gmismatch && !do_ignore) {
UInt64 gc_gcv = dgcv + 1; // NEXT GC_version will be GC-WAIT
string sgc_gcv = to_string(gc_gcv);
if (!zh_jv_is_member(&gavrsns, sgc_gcv)) gavrsns[sgc_gcv] = JOBJECT;
gavrsns[sgc_gcv][avrsn] = true;
}
}
return gavrsns;
}
static UInt64 get_total_number_key_gcv_needs_reorder(string &kqk, UInt64 xgcv,
jv *jdentries) {
jv gavrsns = get_per_gcv_number_key_gcv_needs_reorder(kqk, xgcv,
jdentries);
UInt64 tot = 0;
vector<string> mbrs = zh_jv_get_member_names(&gavrsns);
for (uint i = 0; i < mbrs.size(); i++) {
string sgcv = mbrs[i];
jv *javrsns = &(gavrsns[sgcv]);
UInt64 nreo = javrsns->size();
tot += nreo;
}
return tot;
}
static sqlres set_delta_gcv_needs_reorder(string &kqk, jv *javrsns) {
vector<string> mbrs = zh_jv_get_member_names(javrsns);
for (uint i = 0; i < mbrs.size(); i++) {
string avrsn = mbrs[i];
sqlres sr = persist_agent_delta_gcv_needs_reorder(kqk, avrsn);
RETURN_SQL_ERROR(sr)
}
RETURN_EMPTY_SQLRES
}
static void debug_set_per_gcv_key_gcv_needs_reorder(string &kqk, UInt64 gcv,
jv *javrsns, UInt64 nreo) {
LE("(GC-WAIT) SET-KEY-GCV-NREO: K: " << kqk << " GCV: " << gcv <<
" N: " << nreo);
LD("(GC-WAIT) SET-KEY-GCV-NREO: K: " << kqk << " AVS[]: " << *javrsns);
}
static sqlres set_key_gcv_needs_reorder(string &kqk, UInt64 xgcv,
jv *jdentries) {
jv gavrsns = get_per_gcv_number_key_gcv_needs_reorder(kqk, xgcv, jdentries);
vector<string> mbrs = zh_jv_get_member_names(&gavrsns);
for (uint i = 0; i < mbrs.size(); i++) {
string sgcv = mbrs[i];
UInt64 gcv = strtoul(sgcv.c_str(), NULL, 10);
jv *javrsns = &(gavrsns[sgcv]);
UInt64 nreo = javrsns->size();
debug_set_per_gcv_key_gcv_needs_reorder(kqk, gcv, javrsns, nreo);
sqlres sr = persist_agent_key_gcv_needs_reorder(kqk, gcv, javrsns);
RETURN_SQL_ERROR(sr)
sr = set_delta_gcv_needs_reorder(kqk, javrsns);
RETURN_SQL_ERROR(sr)
}
RETURN_EMPTY_SQLRES
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ANALYZE KEY-GCV-NREO ------------------------------------------------------
static bool analyze_pending_deltas_on_do_gc(UInt64 cgcv, jv *jdentries) {
vector<int> tor;
for (uint i = 0; i < jdentries->size(); i++) {
jv *jdentry = &((*jdentries)[i]);
UInt64 dgcv = zh_get_dentry_gcversion(jdentry);
if (dgcv < cgcv) {
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
string avrsn = (*jauthor)["agent_version"].asString();
LD("analyze_pending_deltas_on_do_gc: IGNORE: AV: " << avrsn <<
" CGCV: " << cgcv << " DGCV: " << dgcv);
tor.push_back(i);
}
}
for (int i = (int)(tor.size() - 1); i >= 0; i--) {
zh_jv_splice(jdentries, tor[i]);
}
bool ok = (jdentries->size() == 0); // IGNORE ALL DELTAS -> DO RUN-GC
LD("analyze_pending_deltas_on_do_gc: OK: " << ok);
return ok;
}
sqlres zoor_analyze_key_gcv_needs_reorder_range(jv *jks, UInt64 cgcv,
jv *jdiffs) {
LD("ZOOR.AnalyzeKeyGCVNeedsReorderRange: (C)GCV: " << cgcv <<
" DIFFS: " << *jdiffs);
string kqk = (*jks)["kqk"].asString();
UInt64 xgcv = -1; // NOTE: JERRY-RIG to IGNORE gmismatch check
jv authors = JARRAY;
vector<string> mbrs = zh_jv_get_member_names(jdiffs);
for (uint i = 0; i < mbrs.size(); i++) {
string suuid = mbrs[i];
UInt64 isuuid = strtoul(suuid.c_str(), NULL, 10);
jv *jdiff = &((*jdiffs)[suuid]);
string mavrsn = (*jdiff)["mavrsn"].asString();
string davrsn = (*jdiff)["davrsn"].asString();
UInt64 mavnum = zh_get_avnum(mavrsn);
UInt64 davnum = zh_get_avnum(davrsn);
// DAVNUM is OK(SKIP), MAVNUM NEEDS REORDER(INCLUDE)
for (uint avnum = (davnum + 1); avnum <= mavnum; avnum++) {
string avrsn = zh_create_avrsn(isuuid, avnum);
jv author = JOBJECT;
author["agent_uuid"] = isuuid;
author["agent_version"] = avrsn;
zh_jv_append(&authors, &author);
}
}
jv mdentries = JARRAY;
for (uint i = 0; i < authors.size(); i++) {
jv *author = &(authors[i]);
sqlres sr = zsd_fetch_subscriber_delta(kqk, author);
RETURN_SQL_ERROR(sr)
jv *jdentry = &(sr.jres);
if (zjd(jdentry)) zh_jv_append(&mdentries, jdentry);
}
bool ok = analyze_pending_deltas_on_do_gc(cgcv, &mdentries);
if (ok) RETURN_SQL_RESULT_UINT(1) // OK -> DO RUN-GC
else {
sqlres sr = set_key_gcv_needs_reorder(kqk, xgcv, &mdentries);
RETURN_SQL_ERROR(sr)
RETURN_EMPTY_SQLRES // NOT OK -> DO NOT RUN-GC -> GC-WAIT
}
}
sqlres get_max_zero_level_needs_reorder(string &kqk, UInt64 gcv, UInt64 rogcv) {
LD("get_max_zero_level_needs_reorder: K: " << kqk << " GCV: " << gcv <<
" ROGCV: " << rogcv);
sqlres sr = get_num_agent_key_gcv_needs_reorder(kqk, gcv);
RETURN_SQL_ERROR(sr)
UInt64 nreo = sr.ures;
LD("GET_ZERO_LEVEL: (GC-WAIT) GET-KEY-GCV-NREO: K: " << kqk <<
" GCV: " << gcv << " N: " << nreo);
if (nreo) { // NOT ZERO LEVEL, RETURN PREVIOUS GCV
RETURN_SQL_RESULT_UINT((gcv - 1))
} else {
if (gcv == rogcv) { // MAX POSSIBLE GCV
RETURN_SQL_RESULT_UINT(gcv);
} else {
gcv = gcv + 1; // CHECK NEXT GCV
return get_max_zero_level_needs_reorder(kqk, gcv, rogcv);
}
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// REORDER SUBSCRIBER DELTA --------------------------------------------------
static sqlres do_process_reorder_delta(jv *pc, bool is_sub) {
jv *jks = &((*pc)["ks"]);
jv *jdentry = &((*pc)["dentry"]);
jv *md = &((*pc)["extra_data"]["md"]);
string kqk = (*jks)["kqk"].asString();
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
string avrsn = (*jauthor)["agent_version"].asString();
LE("ZOOR.REORDER: APPLY: K: " << kqk << " (R)AV: " << avrsn);
sqlres sr = zsd_internal_handle_subscriber_delta(jks, jdentry, md);
RETURN_SQL_ERROR(sr)
bool ok = sr.ures ? true : false;
jv *jncrdt = &(sr.jres);
LD("ZOOR.do_process_reorder_delta: OK: " << ok);
if (!ok) RETURN_EMPTY_SQLRES // INTERNAL NO-OP
else { // SUCCESFFULY APPLIED -> NO LONGER OOO
if (zjd(jncrdt)) zh_set_new_crdt(pc, md, jncrdt, false);
sqlres sr = zoor_unset_ooo_gcv_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
return zoor_do_remove_ooo_delta(kqk, jauthor);
}
}
static sqlres process_reorder_delta(jv *pc, jv *rdentry, bool is_sub) {
LT("process_reorder_delta");
jv rodentry = (*pc)["dentry"]; // FROM SUBSCRIBER-DELTA
jv rrdentry = zmerge_add_reorder_to_reference(&rodentry, rdentry);
(*pc)["dentry"] = rrdentry; // [REORDER + REFERENCE] DELTA
sqlres sr = do_process_reorder_delta(pc, is_sub);
RETURN_SQL_ERROR(sr)
sr = zoor_check_replay_ooo_deltas(pc, true, is_sub);
RETURN_SQL_ERROR(sr)
(*pc)["dentry"] = rodentry; // FROM SUBSCRIBER-DELTA
RETURN_EMPTY_SQLRES
}
static void debug_post_check_agent_gc_wait(bool fgcw, bool gcwi, bool zreo,
UInt64 rfgcv, UInt64 ogcv) {
LD("post_check_agent_gc_wait: (GC-WAIT): FIN-GCW: " << fgcw <<
" GCWI: " << gcwi << " ZREO: " << zreo <<
" RFGCV: " << rfgcv << " OGCV: " << ogcv);
}
static sqlres post_check_agent_gc_wait(jv *pc, bool zreo) {
jv *jks = &((*pc)["ks"]);
jv *rodentry = &((*pc)["dentry"]);
jv *md = &((*pc)["extra_data"]["md"]);
string kqk = (*jks)["kqk"].asString();
jv *rometa = &((*rodentry)["delta"]["_meta"]);
UInt64 ogcv = (*md)["ogcv"].asUInt64();
UInt64 rogcv = zh_get_dentry_gcversion(rodentry);
UInt64 rfgcv = (*rometa)["reference_GC_version"].asUInt64();
sqlres sr = fetch_agent_key_gc_wait_incomplete(kqk);
RETURN_SQL_ERROR(sr)
bool gcwi = sr.ures ? true : false;
bool fgcw = gcwi || (zreo && (rfgcv == ogcv)); // OGCV governs FIN-GCW
debug_post_check_agent_gc_wait(fgcw, gcwi, zreo, rfgcv, ogcv);
if (!fgcw) RETURN_EMPTY_SQLRES
else {
UInt64 bgcv;
if (gcwi) bgcv = ogcv + 1; // OGCV already applied
else bgcv = rfgcv + 1; // REFERENCE-DELTA-GCV already applied
if (!zh_jv_is_member(pc, "ncrdt")) {
zh_set_new_crdt(pc, md, &((*md)["ocrdt"]), false);
}
sqlres sr = get_max_zero_level_needs_reorder(kqk, bgcv, rogcv);
RETURN_SQL_ERROR(sr)
UInt64 egcv = sr.ures;
if (egcv >= bgcv) return zgc_finish_agent_gc_wait(pc, bgcv, egcv);
else {
LE("FINISH-AGENT-GC-WAIT: NON-MINIMUM-GCV: BGCV: " << bgcv <<
" EGCV: " << egcv << "-> NO-OP");
RETURN_EMPTY_SQLRES
}
}
}
sqlres zoor_decrement_reorder_delta(jv *pc) {
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
jv *rodentry = &((*pc)["dentry"]);
jv *rometa = &((*rodentry)["delta"]["_meta"]);
string rfavrsn = (*rometa)["reference_version"].asString();
UInt64 rfgcv = (*rometa)["reference_GC_version"].asUInt64();
UInt64 gc_gcv = rfgcv + 1; // NEXT GC_version will be GC-WAIT
LD("ZOOR.DecrementReorderDelta: K: " << kqk << " GCV: " << gc_gcv);
sqlres sr = decrement_agent_key_gcv_needs_reorder(kqk, gc_gcv, rfavrsn);
RETURN_SQL_ERROR(sr)
bool zreo = sr.ures ? true : false;
return post_check_agent_gc_wait(pc, zreo);
}
static sqlres agent_post_reorder_delta(jv *pc) {
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
LD("agent_post_reorder_delta: K: " << kqk);
return zoor_decrement_reorder_delta(pc);
}
static sqlres set_wait_on_reference_delta(jv *pc, jv *roauthor, jv *rfauthor) {
LE("set_wait_on_reference_delta: REFERENCE-DELTA NOT YET ARRIVED");
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
// PERSIST BOTH NEED_REFERENCE & NEED_REORDER
sqlres sr = persist_delta_need_reference(kqk, roauthor, rfauthor);
RETURN_SQL_ERROR(sr)
return persist_delta_need_reorder(kqk, rfauthor, roauthor);
}
static sqlres get_need_apply_reorder_delta(string &kqk, jv *rfauthor,
bool is_sub) {
UInt64 rauuid = (*rfauthor)["agent_uuid"].asUInt64();
string ravrsn = (*rfauthor)["agent_version"].asString();
bool rselfie = ((int)rauuid == MyUUID);
if (rselfie) {
LD("get_need_apply_reorder_delta: RSELFIE: NEED: true");
RETURN_SQL_RESULT_UINT(1) // RETURN TRUE
}
sqlres sr = zdelt_get_key_subscriber_versions(kqk);
RETURN_SQL_ERROR(sr)
jv *mavrsns = &(sr.jres);
if (zjn(mavrsns)) {
LD("get_need_apply_reorder_delta: NO SAVRSNS[]: NEED: false");
RETURN_EMPTY_SQLRES // RETURN FALSE
} else {
string srauuid = to_string(rauuid);
string mavrsn = (*mavrsns)[srauuid].asString();
UInt64 mavnum = zh_get_avnum(mavrsn);
UInt64 ravnum = zh_get_avnum(ravrsn);
bool need = (mavnum && mavnum < ravnum);
LD("get_need_apply_reorder_delta: RUUID: " << rauuid <<
" SAVRSN: " << mavrsn << " RAVRSN: " << ravrsn << " NEED: " << need);
uint uneed = need ? 1 : 0;
RETURN_SQL_RESULT_UINT(uneed)
}
}
static sqlres persist_set_wait_on_reference_delta(jv *pc, jv *rodentry,
jv *rfauthor) {
LE("FINISH-GC-WAIT-WAIT-ON-REFERENCE");
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
sqlres sr = zsd_conditional_persist_subscriber_delta(kqk, rodentry);
RETURN_SQL_ERROR(sr)
jv *rometa = &((*rodentry)["delta"]["_meta"]);
jv *roauthor = &((*rometa)["author"]);
return set_wait_on_reference_delta(pc, roauthor, rfauthor);
}
static sqlres do_finish_gc_wait_apply_reorder_delta(jv *pc, jv *rodentry,
jv *rfdentry) {
bool is_sub = true;
jv odentry = (*pc)["dentry"]; // ORIGINAL DENTRY that CAUSED ForwardGCV
(*pc)["dentry"] = *rodentry;
LE("FINISH-GC-WAIT-APPLY-REORDER-DELTA");
// NOTE: APPLY [RODENTRY & RFDENTRY] to CRDT
sqlres sr = process_reorder_delta(pc, rfdentry, is_sub);
RETURN_SQL_ERROR(sr)
(*pc)["dentry"] = odentry; // REPLACE WITH ORIGINAL DENTRY
RETURN_EMPTY_SQLRES
}
sqlres zoor_forward_crdt_gc_version_apply_reference_delta(jv *pc,
jv *rodentry) {
LT("zoor_forward_crdt_gc_version_apply_reference_delta");
bool is_sub = true;
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
jv rfauthor = create_reference_author(rodentry);
sqlres sr = get_need_apply_reorder_delta(kqk, &rfauthor, is_sub);
RETURN_SQL_ERROR(sr)
bool need = sr.ures ? true : false;
if (!need) RETURN_EMPTY_SQLRES
else {
sqlres sr = zsd_fetch_subscriber_delta(kqk, &rfauthor);
RETURN_SQL_ERROR(sr)
jv *rfdentry = &(sr.jres);
if (zjd(rfdentry)) {
return do_finish_gc_wait_apply_reorder_delta(pc, rodentry, rfdentry);
} else {
return persist_set_wait_on_reference_delta(pc, rodentry, &rfauthor);
}
}
}
static sqlres apply_reference_delta(jv *pc, jv *rfdentry, bool is_sub) {
if (zjd(rfdentry)) { // NORMAL REORDER DELTA PROCESSING
return process_reorder_delta(pc, rfdentry, is_sub);
} else { // REFERENCE-DENTRY NOT YET ARRIVED ->
jv *rodentry = &((*pc)["dentry"]);
jv *rometa = &((*rodentry)["delta"]["_meta"]);
jv *roauthor = &((*rometa)["author"]);
jv rfauthor = create_reference_author(rodentry);
return set_wait_on_reference_delta(pc, roauthor, &rfauthor);
}
}
static sqlres do_apply_reorder_delta(jv *pc, bool is_sub) {
LT("do_apply_reorder_delta");
jv *jks = &((*pc)["ks"]);
jv *rodentry = &((*pc)["dentry"]);
string kqk = (*jks)["kqk"].asString();
jv *rometa = &((*rodentry)["delta"]["_meta"]);
jv rfauthor = create_reference_author(rodentry);
sqlres sr = get_need_apply_reorder_delta(kqk, &rfauthor, is_sub);
RETURN_SQL_ERROR(sr)
bool need = sr.ures ? true : false;
if (!need) { // APPLY REORDER[] but NOT REFERENCE_DELT
bool rignore = zh_get_bool_member(rometa, "reference_ignore");
if (rignore) { // Used in ZAD.do_apply_delta()
(*rometa)["DO_IGNORE"] = true;
} else { // Used in ZAD.do_apply_delta()
(*rometa)["REORDERED"] = true;
}
return zad_apply_subscriber_delta(pc);
} else {
sqlres sr = zsd_fetch_subscriber_delta(kqk, &rfauthor);
RETURN_SQL_ERROR(sr)
jv *rfdentry = &(sr.jres);
return apply_reference_delta(pc, rfdentry, is_sub);
}
}
static sqlres normal_agent_apply_reorder_delta(jv *pc) {
bool is_sub = true;
jv *jks = &((*pc)["ks"]);
jv *rodentry = &((*pc)["dentry"]);
string kqk = (*jks)["kqk"].asString();
jv *reorder = &((*rodentry)["delta"]["reorder"]);
LD("normal_agent_apply_reorder_delta: K: " << kqk);
sqlres sr = zgc_add_reorder_to_gc_summaries(kqk, reorder);
RETURN_SQL_ERROR(sr)
sr = do_apply_reorder_delta(pc, is_sub);
RETURN_SQL_ERROR(sr)
return agent_post_reorder_delta(pc);
}
static sqlres gc_wait_agent_apply_reorder_delta(jv *pc) {
jv *jks = &((*pc)["ks"]);
jv *rodentry = &((*pc)["dentry"]);
string kqk = (*jks)["kqk"].asString();
UInt64 rogcv = zh_get_dentry_gcversion(rodentry);
jv *rometa = &((*rodentry)["delta"]["_meta"]);
jv *reorder = &((*rodentry)["delta"]["reorder"]);
LE("DO_REORDER: OOOGCW: K: " << kqk << " DURING AGENT-GC-WAIT");
sqlres sr = zgc_add_reorder_to_gc_summaries(kqk, reorder);
RETURN_SQL_ERROR(sr)
sr = zgc_add_ooogcw_to_gc_summary(pc, rogcv, rometa, reorder);
RETURN_SQL_ERROR(sr)
return agent_post_reorder_delta(pc);
}
static sqlres agent_apply_reorder_delta(jv *pc) {
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
sqlres sr = zoor_agent_in_gc_wait(kqk);
RETURN_SQL_ERROR(sr)
bool gwait = sr.ures;
LD("REO: (GC-WAIT) GET-KEY-GCV-NREO: K: " << kqk << " GW: " << gwait);
if (!gwait) return normal_agent_apply_reorder_delta (pc);
else return gc_wait_agent_apply_reorder_delta(pc);
}
// NOTE: returns CRDT
sqlres zoor_apply_reorder_delta(jv *pc, bool is_sub) {
LT("zoor_apply_reorder_delta");
ztrace_start("ZOOR.agent_apply_reorder_delta");
sqlres sr = agent_apply_reorder_delta(pc);
ztrace_finish("ZOOR.agent_apply_reorder_delta");
return sr;
}
// RETURNS CRDT
static sqlres internal_apply_reorder_delta(jv *jks, jv *jdentry, jv *md,
bool is_sub) {
string kqk = (*jks)["kqk"].asString();
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
string avrsn = (*jauthor)["agent_version"].asString();
LD("START: internal_apply_reorder_delta: K: " << kqk << " AV: " << avrsn);
sqlres sr = zsd_create_sd_pc(jks, jdentry, md);
RETURN_SQL_ERROR(sr)
jv pc = sr.jres;
sr = zoor_apply_reorder_delta(&pc, is_sub);
RETURN_SQL_ERROR(sr)
LD("END: internal_apply_reorder_delta: K: " << kqk << " AV: " << avrsn);
zh_override_pc_ncrdt_with_md_gcv(&pc); // GCV used in save_new_crdt()
RETURN_SQL_RESULT_JSON(pc["ncrdt"])
}
static sqlres save_ooo_gcv_delta(jv *jks, jv *jdentry, bool is_sub) {
string kqk = (*jks)["kqk"].asString();
jv *jdmeta = &((*jdentry)["delta"]["_meta"]);
jv *jauthor = &((*jdmeta)["author"]);
UInt64 auuid = (*jauthor)["agent_uuid"].asUInt64();
sqlres sr = persist_agent_key_ooo_gcv(kqk, auuid);
RETURN_SQL_ERROR(sr)
jv einfo = JOBJECT;
einfo["is_sub"] = is_sub;
einfo["kosync"] = false;
einfo["knreo"] = true;
einfo["central"] = zh_get_bool_member(jdmeta, "from_central");
return zoor_persist_ooo_delta(jks, jdentry, &einfo);
}
// RETURNS CRDT
sqlres zoor_handle_ooo_gcv_delta(jv *jks, jv *jdentry, jv *md, bool is_sub) {
string kqk = (*jks)["kqk"].asString();
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
LD("ZOOR.HandleOOOGCVDelta: K: " << kqk);
sqlres sr = save_ooo_gcv_delta(jks, jdentry, is_sub);
RETURN_SQL_ERROR(sr)
sr = fetch_delta_need_reorder(kqk, jauthor);
RETURN_SQL_ERROR(sr)
jv *roauthor = &(sr.jres);
if (zjn(roauthor)) RETURN_EMPTY_SQLRES
else {
LE("ZOOR.HandleOOOGCVDelta: REFERENCE FOUND: K: " << kqk <<
" REO-AUTHOR: " << *roauthor);
sqlres sr = zsd_fetch_subscriber_delta(kqk, roauthor);
RETURN_SQL_ERROR(sr)
jv *rodentry = &(sr.jres);
return internal_apply_reorder_delta(jks, rodentry, md, is_sub);
}
}
sqlres zoor_unset_ooo_gcv_delta(string &kqk, jv *jauthor) {
UInt64 auuid = (*jauthor)["agent_uuid"].asUInt64();
string avrsn = (*jauthor)["agent_version"].asString();
LD("ZOOR.UnsetOOOGCVDelta: K: " << kqk << " AV: " << avrsn);
sqlres sr = remove_agent_key_ooo_gcv(kqk, auuid);
RETURN_SQL_ERROR(sr)
sr = fetch_delta_need_reorder(kqk, jauthor);
RETURN_SQL_ERROR(sr)
jv *roauthor = &(sr.jres);
if (zjn(roauthor)) RETURN_EMPTY_SQLRES
else { // REMOVE BOTH NEED_REFERENCE & NEED_REORDER
sqlres sr = remove_delta_need_reference(kqk, roauthor);
RETURN_SQL_ERROR(sr)
return remove_delta_need_reorder(kqk, jauthor);
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// STORE OOO SUBSCRIBER DELTAS -----------------------------------------------
#define THRESHOLD_UNEXPECTED_DELTA_TIMEOUT 5000 /* 5 seconds */
#define UNEXPECTED_DELTA_TIMEOUT 2000 /* 2 seconds */
jv UnexpectedDeltaPerAgent = JOBJECT; // PER [KQK,AUUID}
sqlres zoor_handle_unexpected_subscriber_delta(const char *ckqk,
const char *sectok,
UInt64 auuid) {
string kqk(ckqk);
bool fire = zh_jv_is_member(&UnexpectedDeltaPerAgent, kqk);
LE("zoor_handle_unexpected_subscriber_delta: (UNEXSD) K: " << kqk <<
" AU: " << auuid << " -> FIRE: " << fire);
if (!fire) RETURN_EMPTY_SQLRES
else {
jv jks = zh_create_ks(kqk, sectok);
jv einfo = JOBJECT; // NOTE: not used
zsd_handle_unexpected_ooo_delta(&jks, &einfo);
UnexpectedDeltaPerAgent.removeMember(kqk);
RETURN_EMPTY_SQLRES
}
}
static sqlres set_timer_unexpected_subscriber_delta(jv *jks, UInt64 auuid,
UInt64 now) {
string kqk = (*jks)["kqk"].asString();
string sectok = (*jks)["security_token"].asString();
LE("UNEXPECTED OOO-SD K: " << kqk << " -> SET-TIMER: (UNEXSD)");
UInt64 to = UNEXPECTED_DELTA_TIMEOUT;
if (!zexh_set_timer_unexpected_subscriber_delta(kqk, sectok, auuid, to)) {
RETURN_SQL_RESULT_ERROR("zexh_set_timer_unexpected_subscriber_delta");
} else {
if (!zh_jv_is_member(&UnexpectedDeltaPerAgent, kqk)) {
UnexpectedDeltaPerAgent[kqk] = JOBJECT;
}
string sauuid = to_string(auuid);
UnexpectedDeltaPerAgent[kqk][sauuid] = now;
RETURN_EMPTY_SQLRES
}
}
UInt64 get_lowest_timestamp_unexpected_subscriber_delta(string &kqk) {
if (!zh_jv_is_member(&UnexpectedDeltaPerAgent, kqk)) return 0;
else {
UInt64 mts = ULLONG_MAX;
jv *a_ts = &(UnexpectedDeltaPerAgent[kqk]);
vector<string> mbrs = zh_jv_get_member_names(a_ts);
for (uint i = 0; i < mbrs.size(); i++) {
string auuid = mbrs[i];
jv jts = (*a_ts)[auuid];
UInt64 ts = jts.asUInt64();
if (ts < mts) mts = ts;
}
return mts;
}
}
static sqlres action_ooo_delta(jv *jks, jv *einfo, UInt64 auuid) {
string kqk = (*jks)["kqk"].asString();
bool ok = (*einfo)["kosync"].asBool();
if (!ok) ok = ((*einfo)["ooodep"].asBool() && !(*einfo)["oooav"].asBool());
if (!ok) ok = ((*einfo)["knreo"].asBool() && !(*einfo)["central"].asBool());
LE("action_ooo_delta: K: " << kqk << " EINFO: " << *einfo << " OK: " << ok);
if (ok) RETURN_EMPTY_SQLRES
else{
UInt64 now = zh_get_ms_time();
UInt64 ts = get_lowest_timestamp_unexpected_subscriber_delta(kqk);
Int64 diff = (now - ts);
bool sane = (diff > 0);
LE("action_ooo_delta: TS: " << ts << " NOW: " << now << " DIFF: " << diff);
if (ts && sane && (diff < THRESHOLD_UNEXPECTED_DELTA_TIMEOUT)) {
LE("UNEXPECTED OOO-SD K: " << kqk << " (TIMER-SET) -> NO-OP (UNEXSD)");
RETURN_EMPTY_SQLRES
} else {
return set_timer_unexpected_subscriber_delta(jks, auuid, now);
}
}
}
static sqlres do_persist_ooo_delta(jv *jks, jv *jdentry, jv *einfo) {
string kqk = (*jks)["kqk"].asString();
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
UInt64 auuid = (*jauthor)["agent_uuid"].asUInt64();
string avrsn = (*jauthor)["agent_version"].asString();
LD("ZOOR.PersistOOODelta: K: " << kqk << " AV: " << avrsn);
sqlres sr = increment_ooo_key(kqk, 1);
RETURN_SQL_ERROR(sr)
sr = persist_ooo_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
sr = persist_ooo_key_delta_version(kqk, avrsn);
RETURN_SQL_ERROR(sr)
sr = zsd_conditional_persist_subscriber_delta(kqk, jdentry);
RETURN_SQL_ERROR(sr)
return action_ooo_delta(jks, einfo, auuid);
}
sqlres zoor_persist_ooo_delta(jv *jks, jv *jdentry, jv *einfo) {
LT("zoor_persist_ooo_delta");
string kqk = (*jks)["kqk"].asString();
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
sqlres sr = fetch_ooo_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
bool oooav = sr.ures ? true : false;
if (!oooav) return do_persist_ooo_delta(jks, jdentry, einfo);
else {
string avrsn = (*jauthor)["agent_version"].asString();
LE("ZOOR.PersistOOODelta: K: " << kqk <<
" AV: " << avrsn << " DELTA ALREADY PERSISTED -> NO-OP");
RETURN_EMPTY_SQLRES
}
}
static sqlres do_remove_ooo_delta_metadata(string &kqk) {
return remove_ooo_key(kqk);
//NOTE: ooo_key_delta_version[] has already been fully removed
}
sqlres zoor_do_remove_ooo_delta(string &kqk, jv *jauthor) {
LT("zoor_do_remove_ooo_delta");
sqlres sr = fetch_ooo_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
bool oooav = sr.ures ? true : false;
if (!oooav) RETURN_EMPTY_SQLRES
else {
string avrsn = (*jauthor)["agent_version"].asString();
LD("ZOOR.DoRemoveOOODelta: K: " << kqk << " AV: " << avrsn);
sr = remove_ooo_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
sr = remove_ooo_key_delta_version(kqk, avrsn);
RETURN_SQL_ERROR(sr)
sr = increment_ooo_key(kqk, -1);
RETURN_SQL_ERROR(sr)
UInt64 noooav = sr.ures;
if (noooav) RETURN_EMPTY_SQLRES
else return do_remove_ooo_delta_metadata(kqk);
}
}
sqlres zoor_remove_subscriber_delta(string &kqk, jv *jauthor) {
LT("zoor_remove_subscriber_delta");
sqlres sr = zds_remove_subscriber_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
return zoor_do_remove_ooo_delta(kqk, jauthor);
};
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// IRRELEVANT DELTAS (ON MERGE) ----------------------------------------------
static sqlres remove_irrelevant_deltas(jv *jks, jv *authors) {
LT("remove_irrelevant_deltas");
for (uint i = 0; i < authors->size(); i++) {
jv *jauthor = &((*authors)[i]);
sqlres sr = zas_do_commit_delta(jks, jauthor);
RETURN_SQL_ERROR(sr)
}
RETURN_EMPTY_SQLRES
}
static void add_irrelevant_agent_version(jv *authors, jv *jcavrsns,
jv *javrsns) {
LT("add_irrelevant_agent_version");
if (zjn(javrsns)) return;
for (uint i = 0; i < javrsns->size(); i++) {
string avrsn = (*javrsns)[i].asString();
vector<string> res = split(avrsn, '|');
string sauuid = res[0];
string savnum = res[1];
UInt64 avnum = strtoul(savnum.c_str(), NULL, 10);
UInt64 auuid = strtoul(sauuid.c_str(), NULL, 10);
UInt64 cavnum = 0;
if (zh_jv_is_member(jcavrsns, sauuid)) { // NOTE: STRING (sauuid) is correct
string cavrsn = (*jcavrsns)[sauuid].asString();
cavnum = zh_get_avnum(cavrsn);
}
if (avnum <= cavnum) {
jv author;
author["agent_uuid"] = auuid;
author["agent_version"] = avrsn;
zh_jv_append(authors, &author);
}
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// SORT OOO DELTAS (DEPENDENCIES) --------------------------------------------
static void add_contiguous_agent_version(jv *authors, jv *jcavrsns,
jv *javrsns) {
LT("add_contiguous_agent_version");
if (zjn(javrsns)) return;
for (uint i = 0; i < javrsns->size(); i++) {
string avrsn = (*javrsns)[i].asString();
vector<string> res = split(avrsn, '|');
string sauuid = res[0];
string savnum = res[1];
UInt64 avnum = strtoul(savnum.c_str(), NULL, 10);
UInt64 auuid = strtoul(sauuid.c_str(), NULL, 10);
UInt64 cavnum = 0;
if (zh_jv_is_member(jcavrsns, sauuid)) { // NOTE: STRING (sauuid) is correct
string cavrsn = (*jcavrsns)[sauuid].asString();
cavnum = zh_get_avnum(cavrsn);
}
UInt64 eavnum = cavnum + 1;
if (avnum == eavnum) {
(*jcavrsns)[sauuid] = avrsn; // NOTE: modifies cavrsns[]
jv author;
author["agent_uuid"] = auuid;
author["agent_version"] = avrsn;
zh_jv_append(authors, &author);
}
}
}
static sqlres fetch_author_deltas(string &kqk, bool is_sub, jv *authors,
jv *adentries) {
LT("fetch_author_deltas");
UInt64 nd = 0;
for (uint i = 0; i < authors->size(); i++) {
jv *jauthor = &((*authors)[i]);
string sauuid = (*jauthor)["agent_uuid"].asString();
sqlres sr = zsd_fetch_subscriber_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
jv *odentry = &(sr.jres);
if (zjn(odentry)) { //NOTE: odentry missing on RECURSIVE CORNER CASES
LD("fetch_author_deltas: MISSING DELTA: AUTHOR: " << *jauthor);
} else {
if (!zh_jv_is_member(adentries, sauuid)) (*adentries)[sauuid] = JARRAY;
zh_jv_append(&((*adentries)[sauuid]), odentry);
}
nd += 1;
}
LD("fetch_author_deltas: #D: " << nd);
RETURN_EMPTY_SQLRES
}
static bool cmp_dependency(jv *jdentry1, jv *jdentry2) {
//LT("cmp_dependency");
bool ret = 0;
jv *jdmeta1 = &((*jdentry1)["delta"]["_meta"]);
string sauuid1 = (*jdmeta1)["author"]["agent_uuid"].asString();
string avrsn1 = (*jdmeta1)["author"]["agent_version"].asString();
jv *jdeps1 = &((*jdmeta1)["dependencies"]);
jv *jdmeta2 = &((*jdentry2)["delta"]["_meta"]);
string sauuid2 = (*jdmeta2)["author"]["agent_uuid"].asString();
string avrsn2 = (*jdmeta2)["author"]["agent_version"].asString();
jv *jdeps2 = &((*jdmeta2)["dependencies"]);
string rdep, ldep;
if (zjd(jdeps2) && zh_jv_is_member(jdeps2, sauuid1)) {
rdep = (*jdeps2)[sauuid1].asString();
}
if (zjd(jdeps1) && zh_jv_is_member(jdeps1, sauuid2)) {
ldep = (*jdeps1)[sauuid2].asString();
}
if (!rdep.size() && !ldep.size()) {
ret = 0;
} else if (rdep.size()) {
UInt64 avnum1 = zh_get_avnum(avrsn1);
UInt64 ravnum = zh_get_avnum(rdep);
ret = (avnum1 == ravnum) ? 0 : (avnum1 > ravnum);
} else { // LDEP
UInt64 avnum2 = zh_get_avnum(avrsn2);
UInt64 lavnum = zh_get_avnum(ldep);
ret = (avnum2 == lavnum) ? 0 : (avnum2 < lavnum);
}
return ret;
}
static jv init_dependency_sort_authors(jv *adentries) {
LT("init_dependency_sort_authors");
jv fdentries = JARRAY;
vector<string> mbrs = zh_jv_get_member_names(adentries);
for (uint i = 0; i < mbrs.size(); i++) {
string sauuid = mbrs[i];
jv *jdentries = &((*adentries)[sauuid]);
jv dentry = zh_jv_shift(jdentries); // TAKE FIRST FROM EACH AUUID
zh_jv_append(&fdentries, &dentry);
}
return fdentries;
}
static jv get_next_agent_dentry(jv *adentries, string &sauuid) {
if (!zh_jv_is_member(adentries, sauuid)) return JNULL;
jv *jdentries = &((*adentries)[sauuid]);
jv dentry = zh_jv_shift(jdentries);
return dentry;
}
static void do_dependency_sort_authors(string &kqk, jv *adentries,
jv *rdentries) {
LT("do_dependency_sort_authors");
jv fdentries = init_dependency_sort_authors(adentries);
while (fdentries.size()) {
zh_jv_sort(&fdentries, cmp_dependency);
jv rdentry = zh_jv_shift(&fdentries);
zh_jv_append(rdentries, &rdentry);
jv *jmeta = &(rdentry["delta"]["_meta"]);
string sauuid = (*jmeta)["author"]["agent_uuid"].asString();
jv fdentry = get_next_agent_dentry(adentries, sauuid);
if (zjd(&fdentry)) zh_jv_append(&fdentries, &fdentry);
}
LD("END: do_dependency_sort_authors: #RD: " << rdentries->size());
}
sqlres zoor_dependencies_sort_authors(string &kqk, bool is_sub, jv *jauthors) {
LT("zoor_dependencies_sort_authors");
jv cauthors = *jauthors; // NOTE: gets modified
jv adentries = JOBJECT;
sqlres sr = fetch_author_deltas(kqk, is_sub, &cauthors, &adentries);
RETURN_SQL_ERROR(sr)
jv rdentries = JARRAY;
do_dependency_sort_authors(kqk, &adentries, &rdentries);
RETURN_SQL_RESULT_JSON(rdentries)
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// REPLAY APPLY DELTAS -------------------------------------------------------
static sqlres replay_delta_versions(jv *pc, jv *jxcrdt,
jv *jdentries, bool is_sub) {
LD("replay_delta_versions: #D: " << jdentries->size());
jv *jks = &((*pc)["ks"]);
jv *md = &((*pc)["extra_data"]["md"]);
string kqk = (*jks)["kqk"].asString();
(*md)["ocrdt"] = *jxcrdt; // zsd_internal_handle_subscriber_delta on THIS CRDT
for (uint i = 0; i < jdentries->size(); i++) {
jv *jdentry = &((*jdentries)[i]);
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
sqlres sr = zsd_internal_handle_subscriber_delta(jks, jdentry, md);
RETURN_SQL_ERROR(sr)
bool ok = sr.ures ? true : false;
jv *jncrdt = &(sr.jres);
LD("ZOOR.replay_delta_versions: OK: " << ok);
if (!ok) continue; // INTERNAL NO-OP
else { // SUCCESFFULY APPLIED -> NO LONGER OOO
if (zjd(jncrdt)) zh_set_new_crdt(pc, md, jncrdt, false);
sqlres sr = zoor_do_remove_ooo_delta(kqk, jauthor);
RETURN_SQL_ERROR(sr)
}
}
RETURN_EMPTY_SQLRES
}
static sqlres get_merge_replay_deltas(jv *jks, bool is_sub, jv *jcavrsns) {
LT("get_merge_replay_deltas");
string kqk = (*jks)["kqk"].asString();
jv ccavrsns = *jcavrsns; // NOTE: gets modified
sqlres sr = fetch_subscriber_delta_aversions(kqk);
RETURN_SQL_ERROR(sr)
jv javrsns = sr.jres;
sr = fetch_ooo_key_delta_versions(kqk);
RETURN_SQL_ERROR(sr)
jv joooavrsns = sr.jres;
jv iauthors = JARRAY;
jv authors = JARRAY;
if (joooavrsns.size()) {
for (uint i = 0; i < joooavrsns.size(); i++) {
zh_jv_append(&javrsns, &(joooavrsns[i])); // APPEND OOOAVRSNS[] TO AVRNS[]
}
}
zh_jv_sort(&javrsns, cmp_delta_agent_version);
add_irrelevant_agent_version(&iauthors, jcavrsns, &javrsns);
add_contiguous_agent_version(&authors, &ccavrsns, &javrsns);
sr = remove_irrelevant_deltas(jks, &iauthors);
RETURN_SQL_ERROR(sr)
return zoor_dependencies_sort_authors(kqk, is_sub, &authors);
}
static void adjust_replay_deltas_to_gc_summaries(string &kqk, jv *jdentries,
UInt64 min_gcv) {
UInt64 dmin_gcv = min_gcv ? (min_gcv - 1) : 0; // PREVIOUS GCV DELTAS ARE OK
LD("adjust_replay_deltas_to_gc_summaries: (D)MIN-GCV: " << dmin_gcv);
for (uint i = 0; i < jdentries->size(); i++) {
jv *jdentry = &((*jdentries)[i]);
UInt64 dgcv = zh_get_dentry_gcversion(jdentry);
if (dgcv < dmin_gcv) {
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
string avrsn = (*jauthor)["agent_version"].asString();
LE("SET DO_IGNORE: K: " << kqk << " AV: " << avrsn);
(*jdentry)["delta"]["_meta"]["DO_IGNORE"] = true;
}
}
}
static void adjust_gc_summaries_to_replay_deltas(jv *jgcsumms, jv *jdentries) {
UInt64 min_gcv = ULLONG_MAX;
for (uint i = 0; i < jdentries->size(); i++) {
jv *jdentry = &((*jdentries)[i]);
jv *jdmeta = &((*jdentry)["delta"]["_meta"]);
bool ignore = zh_get_bool_member(jdmeta, "DO_IGNORE");
if (!ignore) {
UInt64 dgcv = zh_get_dentry_gcversion(jdentry);
if (dgcv < min_gcv) min_gcv = dgcv;
}
}
LD("adjust_gc_summaries_to_replay_deltas: MIN-GCV: " << min_gcv);
vector<string> mbrs = zh_jv_get_member_names(jgcsumms);
for (uint i = 0; i < mbrs.size(); i++) {
string sgcv = mbrs[i];
UInt64 gcv = strtoul(sgcv.c_str(), NULL, 10);
if (gcv <= min_gcv) { // LESS THAN OR EQUAL -> ALREADY PROCESSED MIN-GCV
LD("adjust_gc_summaries_to_replay_deltas: DELETE: GCV: " << sgcv);
jgcsumms->removeMember(sgcv);
}
}
}
// NOTE: ZSD.InternalHandleSubscriberDelta skips OOOGCV check
// |-> AUTO-DTS can incorrectly advance ncrdt.GCV
sqlres finalize_rewound_subscriber_merge(jv *pc) {
jv *md = &((*pc)["extra_data"]["md"]);
UInt64 gcv = (*md)["gcv"].asUInt64(); // NOTE: SET MD.OGCV
LD("ZOOR.replay_subscriber_merge_deltas: (F)GCV: " << gcv);
(*pc)["ncrdt"]["_meta"]["GC_version"] = gcv;
RETURN_EMPTY_SQLRES
}
sqlres zoor_replay_subscriber_merge_deltas(jv *pc, bool is_sub) {
jv *jks = &((*pc)["ks"]);
jv *md = &((*pc)["extra_data"]["md"]);
jv *jxcrdt = &((*pc)["xcrdt"]);
jv *jcavrsns = &((*pc)["extra_data"]["cavrsns"]);
jv jgcsumms = (*pc)["extra_data"]["gcsumms"]; // NOTE: GETS MODIFIED
string kqk = (*jks)["kqk"].asString();
UInt64 xgcv = (*jxcrdt)["_meta"]["GC_version"].asUInt64();
zh_set_new_crdt(pc, md, jxcrdt, true);
LD("zoor_replay_subscriber_merge_deltas: cavrsns: " << *jcavrsns);
sqlres sr = get_merge_replay_deltas(jks, is_sub, jcavrsns);
RETURN_SQL_ERROR(sr)
jv rdentries = sr.jres;
UInt64 tot = get_total_number_key_gcv_needs_reorder(kqk, xgcv,
&rdentries);
LD("zoor_replay_subscriber_merge_deltas: TOTAL(NUM): " << tot);
if (tot == 0) { // NO REWIND
if (!rdentries.size()) RETURN_EMPTY_SQLRES // NO-OP
else { // REPLAY
debug_replay_merge_dentries(kqk, &rdentries);
return replay_delta_versions(pc, &((*pc)["ncrdt"]), &rdentries, is_sub);
}
} else { // REWIND AND REPLAY
debug_replay_merge_dentries(kqk, &rdentries);
UInt64 min_gcv = zgc_get_min_gcv(&jgcsumms);
adjust_replay_deltas_to_gc_summaries(kqk, &rdentries, min_gcv);
LD("ZOOR.replay_subscriber_merge_deltas: MIN-GCV: " << min_gcv);
adjust_gc_summaries_to_replay_deltas(&jgcsumms, &rdentries);
jv jncrdt = zmerge_rewind_crdt_gc_version(kqk, jxcrdt, &jgcsumms);
zh_set_new_crdt(pc, md, &jncrdt, true);
(*md)["ogcv"] = (*md)["gcv"]; // NOTE: SET MD.OGCV
LD("ZOOR.replay_subscriber_merge_deltas: (N)GCV: " << (*md)["gcv"]);
sqlres sr = set_key_gcv_needs_reorder(kqk, xgcv, &rdentries);
RETURN_SQL_ERROR(sr)
sr = replay_delta_versions(pc, &((*pc)["ncrdt"]),
&rdentries, is_sub);
RETURN_SQL_ERROR(sr)
return finalize_rewound_subscriber_merge(pc);
}
}
sqlres zoor_prepare_local_deltas_post_subscriber_merge(jv *pc) {
bool is_sub = true;
jv *jks = &((*pc)["ks"]);
jv *jxcrdt = &((*pc)["xcrdt"]);
jv *jcavrsns = &((*pc)["extra_data"]["cavrsns"]);
string kqk = (*jks)["kqk"].asString();
UInt64 xgcv = (*jxcrdt)["_meta"]["GC_version"].asUInt64();
LD("zoor_prepare_local_deltas_post_subscriber_merge: cavrsns: " << *jcavrsns);
sqlres sr = get_merge_replay_deltas(jks, is_sub, jcavrsns);
RETURN_SQL_ERROR(sr)
jv rdentries = sr.jres;
return set_key_gcv_needs_reorder(kqk, xgcv, &rdentries);
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// HANDLE OOO SUBSCRIBER DELTAS ----------------------------------------------
static sqlres do_replay_ooo_deltas(jv *pc, bool is_sub, jv *rdentries) {
jv *jks = &((*pc)["ks"]);
jv *md = &((*pc)["extra_data"]["md"]);
string kqk = (*jks)["kqk"].asString();
jv *jocrdt = &((*md)["ocrdt"]);
LE("ZOOR.do_replay_ooo_deltas: K: " << kqk << " rdentries[AV]: [" <<
debug_dentries_agent_versions(rdentries) << "]");
return replay_delta_versions(pc, jocrdt, rdentries, is_sub);
}
static sqlres get_replay_ooo_deltas(string &kqk, bool is_sub) {
LT("get_replay_ooo_deltas");
sqlres sr = zdelt_get_key_subscriber_versions(kqk);
RETURN_SQL_ERROR(sr)
jv mavrsns = sr.jres;
sr = fetch_ooo_key_delta_versions(kqk);
RETURN_SQL_ERROR(sr)
jv joooavrsns = sr.jres;
zh_jv_sort(&joooavrsns, cmp_delta_agent_version);
jv authors = JARRAY;
add_contiguous_agent_version(&authors, &mavrsns, &joooavrsns);
LD("get_replay_ooo_deltas: authors: " << authors);
return zoor_dependencies_sort_authors(kqk, is_sub, &authors);
}
static sqlres replay_ooo_deltas(jv *pc, bool is_sub) {
LT("replay_ooo_deltas");
jv *jks = &((*pc)["ks"]);
string kqk = (*jks)["kqk"].asString();
sqlres sr = get_replay_ooo_deltas(kqk, is_sub);
RETURN_SQL_ERROR(sr)
jv *rdentries = &(sr.jres);
return do_replay_ooo_deltas(pc, is_sub, rdentries);
}
static sqlres check_finish_unexpected_delta(string &kqk, UInt64 auuid,
bool is_sub) {
string sauuid = to_string(auuid);
bool afire = zh_jv_is_member(&UnexpectedDeltaPerAgent, kqk) &&
zh_jv_is_member(&(UnexpectedDeltaPerAgent[kqk]), sauuid);
if (!afire) RETURN_EMPTY_SQLRES
else {
sqlres sr = get_replay_ooo_deltas(kqk, is_sub);
RETURN_SQL_ERROR(sr)
jv *rdentries = &(sr.jres);
LD("check_finish_unexpected_delta: (UNEXSD)");
for (uint i = 0; i < rdentries->size(); i++) {
jv *jdentry = &((*rdentries)[i]);
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
UInt64 dauuid = (*jauthor)["agent_uuid"].asUInt64();
if (auuid == dauuid) RETURN_EMPTY_SQLRES
}
UnexpectedDeltaPerAgent[kqk].removeMember(sauuid);
UInt64 n = UnexpectedDeltaPerAgent[kqk].size();
LD("NUM UNEXSD PER KQK: " << n);
if (n == 0) {
LE("FINISH-UNEXSD: K: " << kqk << " U: " << auuid);
UnexpectedDeltaPerAgent.removeMember(kqk);
}
RETURN_EMPTY_SQLRES
}
}
static sqlres conditional_replay_ooo_deltas(jv *pc, UInt64 noooav,
bool is_sub) {
if (!noooav) RETURN_EMPTY_SQLRES
else {
jv *md = &((*pc)["extra_data"]["md"]);
if (zh_jv_is_member(pc, "ncrdt") && zjd(&((*pc)["ncrdt"]))) {
(*md)["ocrdt"] = (*pc)["ncrdt"]; // replay_ooo_deltas() on THIS CRDT
}
sqlres sr = replay_ooo_deltas(pc, is_sub);
RETURN_SQL_ERROR(sr)
RETURN_EMPTY_SQLRES
}
}
sqlres zoor_check_replay_ooo_deltas(jv *pc, bool do_check, bool is_sub) {
jv *jks = &((*pc)["ks"]);
jv *jdentry = &((*pc)["dentry"]);
string kqk = (*jks)["kqk"].asString();
sqlres sr = fetch_ooo_key(kqk);
RETURN_SQL_ERROR(sr)
UInt64 noooav = sr.ures;
LD("zoor_check_replay_ooo_deltas: noooav: " << noooav);
sr = conditional_replay_ooo_deltas(pc, noooav, is_sub);
RETURN_SQL_ERROR(sr)
if (!do_check) RETURN_EMPTY_SQLRES
else {
jv *jauthor = &((*jdentry)["delta"]["_meta"]["author"]);
UInt64 auuid = (*jauthor)["agent_uuid"].asUInt64();
return check_finish_unexpected_delta(kqk, auuid, is_sub);
}
}
| 39.477169 | 80 | 0.58356 | phaynes |
c0dbe8cf34ccf3222f690cf6caa9d309340caf8c | 7,143 | cpp | C++ | franka_control/src/franka_control_node.cpp | suneelbelkhale/franka_ros2 | 1cfdc6b89acf6008f788c9e27d7acee34e66b954 | [
"Apache-2.0"
] | null | null | null | franka_control/src/franka_control_node.cpp | suneelbelkhale/franka_ros2 | 1cfdc6b89acf6008f788c9e27d7acee34e66b954 | [
"Apache-2.0"
] | 3 | 2021-08-15T19:17:03.000Z | 2021-08-16T20:16:22.000Z | franka_control/src/franka_control_node.cpp | suneelbelkhale/franka_ros2 | 1cfdc6b89acf6008f788c9e27d7acee34e66b954 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <algorithm>
#include <atomic>
#include <chrono>
#include <thread>
#include <rclcpp_action/rclcpp_action.hpp>
#include <controller_manager/controller_manager.h>
#include <franka/exception.h>
#include <franka/robot.h>
#include <franka_hw/franka_hw.h>
#include <franka_hw/services.h>
#include <franka_msgs/action/ErrorRecovery.hpp>
#include <rclcpp/rclcpp.hpp>
#include <std_srvs/srv/Trigger.hpp>
using franka_hw::ServiceContainer;
using namespace std::chrono_literals;
// action server
rclcpp_action::GoalResponse error_recovery_handle_goal(
const rclcpp_action::GoalUUID& uuid,
std::shared_ptr<const franka_msgs::action::ErrorRecovery::Goal> goal) {
(void)uuid;
if (rclcpp::ok() && connected()) {
return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
} else {
return rclcpp_action::GoalResponse::REJECT;
}
}
rclcpp_action::CancelResponse error_recovery_handle_cancel(
const std::shared_ptr<rclcpp_action::ServerGoalHandle<franka_msgs::action::ErrorRecovery>> goal_handle,
std::atomic_bool& has_error) {
RCLCPP_INFO(robot_hw_nh_->get_logger(), "Cancel is not implemented! Will accept though...")
return rclcpp_action::CancelResponse::ACCEPT;
}
void error_recovery_handle_accepted(
const std::shared_ptr<rclcpp_action::ServerGoalHandle<franka_msgs::action::ErrorRecovery>> goal_handle,
std::atomic_bool& has_error
franka_hw::FrankaHW& franka_control) {
using namespace std::placeholders;
// this needs to return quickly to avoid blocking the executor, so spin up a new thread
std::thread{&execute, goal_handle, has_error, franka_control}.detach();
}
void execute(
const std::shared_ptr<rclcpp_action::ServerGoalHandle<franka_msgs::action::ErrorRecovery>> goal_handle,
std::atomic_bool& has_error,
franka_hw::FrankaHW& franka_control) {
auto result = std::make_shared<franka_msgs::action::ErrorRecovery::Result>()
if (rclcpp::ok() && franka_control.connected()) {
try {
// acquire robot lock
std::lock_guard<std::mutex> lock(robot_mutex_);
// blocking step
robot_->automaticErrorRecovery();
// error recovered => reset controller
has_error = false;
goal_handle->succeed(result);
RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Recovered from error");
} catch (const franka::Exception& ex) {
goal_handle->abort(result);
}
} else {
goal_handle->abort(result);
}
}
/* MAIN */
int main(int argc, char** argv) {
rclcpp::init(argc, argv);
std::shared_ptr<rclcpp::Node> public_node_handle;
auto node_handle = std::make_shared<rclcpp::Node>("franka_control_node");
franka_hw::FrankaHW franka_control;
if (!franka_control.init(public_node_handle, node_handle)) {
RCLCPP_ERROR(node_handle->get_logger(), "franka_control_node: Failed to initialize FrankaHW class. Shutting down!");
return 1;
}
auto services = std::make_unique<ServiceContainer>();
rclcpp_action::Server<franka_msgs::action::ErrorRecovery>::SharedPtr
recovery_action_server;
std::atomic_bool has_error(false);
auto connect = [&]() {
franka_control.connect();
std::lock_guard<std::mutex> lock(franka_control.robotMutex());
auto& robot = franka_control.robot();
services = std::make_unique<ServiceContainer>();
franka_hw::setupServices(robot, franka_control.robotMutex(), node_handle, *services);
recovery_action_server = node_handle->create_server<franka_msgs::action::ErrorRecovery>(node_handle, "error_recovery",
std::bind(&error_recovery_handle_goal, _1, _2),
std::bind(&error_recovery_handle_cancel, _1, has_error),
std::bind(&error_recovery_handle_accepted, _1, has_error, franka_control)
);
// Initialize robot state before loading any controller
franka_control.update(robot.readOnce());
};
auto disconnect_handler = [&](const std::shared_ptr<std_srvs::srv::Trigger::Request> request,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) -> bool {
if (franka_control.controllerActive()) {
response->success = 0u;
response->message = "Controller is active. Cannot disconnect while a controller is running.";
return true;
}
services.reset();
recovery_action_server.reset();
auto result = franka_control.disconnect();
response->success = result ? 1u : 0u;
response->message = result ? "" : "Failed to disconnect robot.";
return true;
};
auto connect_handler = [&](const std::shared_ptr<std_srvs::srv::Trigger::Request> request,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) -> bool {
if (franka_control.connected()) {
response->success = 0u;
response->message = "Already connected to robot. Cannot connect twice.";
return true;
}
connect();
response->success = 1u;
response->message = "";
return true;
};
connect();
rclcpp::Server<std_srvs::srv::Trigger>::SharedPtr connect_server =
node_handle->create_service<std_srvs::srv::Trigger>(
"connect", connect_handler);
rclcpp::Server<std_srvs::srv::Trigger>::SharedPtr disconnect_server =
node_handle->create_service<std_srvs::srv::Trigger>(
"disconnect", disconnect_handler);
controller_manager::ControllerManager control_manager(&franka_control, public_node_handle);
while (rclcpp::ok()) {
rclcpp::Time last_time = rclcpp::Time::now();
// Wait until controller has been activated or error has been recovered
while (!franka_control.controllerActive() || has_error) {
if (franka_control.connected()) {
try {
std::lock_guard<std::mutex> lock(franka_control.robotMutex());
franka_control.update(franka_control.robot().readOnce());
rclcpp::Time now = rclcpp::Time::now();
control_manager.update(now, now - last_time);
franka_control.checkJointLimits();
last_time = now;
} catch (const std::logic_error& e) {
}
} else {
std::this_thread::sleep_for(1ms);
}
if (!rclcpp::ok()) {
return 0;
}
}
if (franka_control.connected()) {
try {
// Run control loop. Will exit if the controller is switched.
franka_control.control([&](const rclcpp::Time& now, const rclcpp::Duration& period) {
if (period.toSec() == 0.0) {
// Reset controllers before starting a motion
control_manager.update(now, period, true);
franka_control.checkJointLimits();
franka_control.reset();
} else {
control_manager.update(now, period);
franka_control.checkJointLimits();
franka_control.enforceLimits(period);
}
return rclcpp::ok();
});
} catch (const franka::ControlException& e) {
RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "%s", e.what());
has_error = true;
}
}
RCLCPP_INFO_THROTTLE(rclcpp::get_logger("rclcpp"), 1, "franka_control, main loop");
}
return 0;
}
| 35.014706 | 123 | 0.686126 | suneelbelkhale |
c0e1f1f0349869d4fe89d39af0ccc8ec1b347392 | 10,995 | cc | C++ | spicy/context.cc | asilha/hilti | ebfffc7dad31059b43a02eb26abcf7a25f742eb8 | [
"BSD-3-Clause"
] | 46 | 2015-01-21T13:31:25.000Z | 2020-10-27T10:18:03.000Z | spicy/context.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 29 | 2015-03-30T08:23:04.000Z | 2019-05-03T13:11:35.000Z | spicy/context.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 20 | 2015-01-27T12:59:38.000Z | 2020-10-28T21:40:47.000Z |
#include <fstream>
#include <limits.h>
#include <util/util.h>
// LLVM redefines the DEBUG macro. Sigh.
#ifdef DEBUG
#define __SAVE_DEBUG DEBUG
#undef DEBUG
#endif
#include <llvm/IR/Module.h>
#undef DEBUG
#ifdef __SAVE_DEBUG
#define DEBUG __SAVE_DEBUG
#endif
#include "context.h"
#include "expression.h"
#include "operator.h"
#include "options.h"
#include "parser/driver.h"
#include "passes/grammar-builder.h"
#include "passes/id-resolver.h"
#include "passes/normalizer.h"
#include "passes/operator-resolver.h"
#include "passes/overload-resolver.h"
#include "passes/printer.h"
#include "passes/scope-builder.h"
#include "passes/scope-printer.h"
#include "passes/unit-scope-builder.h"
#include "passes/validator.h"
#include "codegen/codegen.h"
#include "codegen/type-builder.h"
#include "hilti/context.h"
using namespace spicy;
using namespace spicy::passes;
spicy::CompilerContext::~CompilerContext()
{
}
const spicy::Options& spicy::CompilerContext::options() const
{
return *_options;
}
shared_ptr<spicy::Module> spicy::CompilerContext::load(string path, bool finalize)
{
path = util::strtolower(path);
if ( ! util::endsWith(path, ".spicy") )
path += ".spicy";
string full_path = util::findInPaths(path, options().libdirs_spicy);
if ( full_path.size() == 0 ) {
error(util::fmt("cannot find input file %s", path.c_str()));
return nullptr;
}
char buf[PATH_MAX];
full_path = realpath(full_path.c_str(), buf);
auto m = _modules.find(full_path);
if ( m != _modules.end() )
return m->second;
std::ifstream in(full_path);
if ( in.fail() ) {
error(util::fmt("cannot open input file %s", full_path.c_str()));
return nullptr;
}
auto module = parse(in, full_path);
if ( ! module )
return nullptr;
if ( finalize && ! spicy::CompilerContext::finalize(module) )
return nullptr;
_modules.insert(std::make_pair(full_path, module));
return module;
}
shared_ptr<spicy::Module> spicy::CompilerContext::parse(std::istream& in, const std::string& sname)
{
spicy_parser::Driver driver;
driver.forwardLoggingTo(this);
driver.enableDebug(options().cgDebugging("scanner"), options().cgDebugging("parser"));
_beginPass(sname, "Parser");
auto module = driver.parse(this, in, sname);
_endPass();
return module;
}
shared_ptr<spicy::Expression> spicy::CompilerContext::parseExpression(const std::string& expr)
{
spicy_parser::Driver driver;
driver.forwardLoggingTo(this);
driver.enableDebug(options().cgDebugging("scanner"), options().cgDebugging("parser"));
auto bexpr = driver.parseExpression(this, expr);
passes::Normalizer normalizer;
if ( normalizer.run(bexpr) )
return bexpr;
error(util::fmt("error normalizing expression %s", expr));
return nullptr;
}
static void _debugAST(spicy::CompilerContext* ctx, shared_ptr<spicy::Module> module,
const ast::Logger& before)
{
if ( ctx->options().cgDebugging("dump-ast") ) {
std::cerr << std::endl
<< "===" << std::endl
<< "=== AST for " << module->id()->pathAsString() << " before "
<< before.loggerName() << std::endl
<< "===" << std::endl
<< std::endl;
ctx->dump(module, std::cerr);
}
if ( ctx->options().cgDebugging("print-ast") ) {
std::cerr << std::endl
<< "===" << std::endl
<< "=== AST for " << module->id()->pathAsString() << " before "
<< before.loggerName() << std::endl
<< "===" << std::endl
<< std::endl;
ctx->print(module, std::cerr);
}
}
void spicy::CompilerContext::_beginPass(const string& module, const string& name)
{
hilti::CompilerContext::PassInfo pass;
pass.module = module;
pass.time = ::util::currentTime();
pass.name = name;
_hilti_context->passes().push_back(pass);
}
void spicy::CompilerContext::_beginPass(shared_ptr<Module> module, const string& name)
{
_debugAST(this, module, name);
_beginPass(module->id()->name(), name);
}
void spicy::CompilerContext::_beginPass(shared_ptr<Module> module, const ast::Logger& pass)
{
_beginPass(module, pass.loggerName());
}
void spicy::CompilerContext::_beginPass(const string& module, const ast::Logger& pass)
{
_beginPass(module, pass.loggerName());
}
void spicy::CompilerContext::_endPass()
{
assert(_hilti_context->passes().size());
auto pass = _hilti_context->passes().back();
auto cg_time = options().cgDebugging("time");
auto cgpasses = options().cgDebugging("passes");
if ( cg_time || cgpasses ) {
auto delta = util::currentTime() - pass.time;
auto indent = string(_hilti_context->passes().size(), ' ');
if ( cgpasses || delta >= 0.1 )
std::cerr << util::fmt("(%2.2fs) %sspicy::%s [module \"%s\"]", delta, indent, pass.name,
pass.module)
<< std::endl;
}
_hilti_context->passes().pop_back();
}
bool spicy::CompilerContext::partialFinalize(shared_ptr<Module> module)
{
return finalize(module, false);
}
bool spicy::CompilerContext::finalize(shared_ptr<Module> module)
{
// Just a double-check ...
if ( ! OperatorRegistry::globalRegistry()->byKind(operator_::Plus).size() ) {
internalError("spicy: no operators defined, did you call spicy::init()?");
}
return finalize(module, options().verify);
}
bool spicy::CompilerContext::finalize(shared_ptr<Module> node, bool verify)
{
passes::GrammarBuilder grammar_builder(std::cerr);
passes::IDResolver id_resolver;
passes::OverloadResolver overload_resolver(node);
passes::Normalizer normalizer;
passes::OperatorResolver op_resolver(node);
passes::ScopeBuilder scope_builder(this);
passes::ScopePrinter scope_printer(std::cerr);
passes::UnitScopeBuilder unit_scope_builder;
passes::Validator validator;
// TODO: This needs a reorg. Currently the op_resolver iterates until it
// hasn't changed anything anymore but that leaves the other passes out
// of that loop and we have to run them manually a few times more (and
// the number of rounds might not be constant actually). We need to pull
// that up a higher a level and iterate over all the passes until nothing
// has changed anymore.
_beginPass(node, scope_builder);
if ( ! scope_builder.run(node) )
return false;
_endPass();
if ( options().cgDebugging("scopes") )
scope_printer.run(node);
_beginPass(node, id_resolver);
if ( ! id_resolver.run(node, false) )
return false;
_endPass();
_beginPass(node, unit_scope_builder);
if ( ! unit_scope_builder.run(node) )
return false;
_endPass();
_beginPass(node, id_resolver);
if ( ! id_resolver.run(node, true) )
return false;
_endPass();
_beginPass(node, overload_resolver);
if ( ! overload_resolver.run(node) )
return false;
_endPass();
_beginPass(node, op_resolver);
if ( ! op_resolver.run(node) )
return false;
_endPass();
// The operators may have some unresolved types, too.
_beginPass(node, id_resolver);
if ( ! id_resolver.run(node, true) )
return false;
_endPass();
if ( verify ) {
_beginPass(node, validator);
if ( ! validator.run(node) )
return false;
_endPass();
}
_beginPass(node, normalizer);
if ( ! normalizer.run(node) )
return false;
_endPass();
// Normalizer might have added some new (unresolved) stuff.
_beginPass(node, id_resolver);
if ( ! id_resolver.run(node, true) )
return false;
_endPass();
_beginPass(node, overload_resolver);
if ( ! overload_resolver.run(node) )
return false;
_endPass();
_beginPass(node, op_resolver);
if ( ! op_resolver.run(node) )
return false;
_endPass();
if ( verify ) {
_beginPass(node, validator);
if ( ! validator.run(node) )
return false;
_endPass();
}
if ( options().cgDebugging("grammars") )
grammar_builder.enableDebug();
_beginPass(node, grammar_builder);
if ( ! grammar_builder.run(node) )
return false;
_endPass();
if ( verify ) {
_beginPass(node, validator);
if ( ! validator.run(node) )
return false;
_endPass();
}
return true;
}
std::unique_ptr<llvm::Module> spicy::CompilerContext::compile(
shared_ptr<Module> module, shared_ptr<hilti::Module>* hilti_module_out, bool hilti_only)
{
CodeGen codegen(this);
_beginPass(module, "CodeGen");
auto compiled = codegen.compile(module);
if ( ! compiled )
return nullptr;
if ( hilti_module_out )
*hilti_module_out = compiled;
_endPass();
if ( hilti_only )
return nullptr;
auto llvm_module = _hilti_context->compile(compiled);
if ( ! llvm_module )
return nullptr;
return llvm_module;
}
std::unique_ptr<llvm::Module> spicy::CompilerContext::compile(
const string& path, shared_ptr<hilti::Module>* hilti_module_out)
{
auto module = load(path);
if ( ! module )
return nullptr;
CodeGen codegen(this);
_beginPass(module, "CodeGen");
auto compiled = codegen.compile(module);
if ( hilti_module_out )
*hilti_module_out = compiled;
_endPass();
auto llvm_module = _hilti_context->compile(compiled);
if ( ! llvm_module )
return nullptr;
return llvm_module;
}
bool spicy::CompilerContext::print(shared_ptr<Module> module, std::ostream& out)
{
passes::Printer printer(out);
return printer.run(module);
}
bool spicy::CompilerContext::dump(shared_ptr<Node> ast, std::ostream& out)
{
ast->dump(out);
return true;
}
shared_ptr<hilti::CompilerContextJIT<spicy::JIT>> spicy::CompilerContext::hiltiContext() const
{
return _hilti_context;
}
shared_ptr<hilti::Type> spicy::CompilerContext::hiltiType(shared_ptr<spicy::Type> type,
id_list* deps)
{
codegen::TypeBuilder tb(nullptr);
return tb.hiltiType(type, deps);
}
void spicy::CompilerContext::toCacheKey(shared_ptr<Module> module,
::util::cache::FileCache::Key* key)
{
if ( module->path() != "-" )
key->files.insert(module->path());
else {
std::ostringstream s;
print(module, s);
auto hash = util::cache::hash(s.str());
key->hashes.insert(hash);
}
for ( auto d : dependencies(module) )
key->files.insert(d);
}
std::list<string> spicy::CompilerContext::dependencies(shared_ptr<Module> module)
{
// TODO: Not implementated.
return std::list<string>();
}
| 24.111842 | 100 | 0.626739 | asilha |
c0e2013d0bc26d42b7203e712ef467cd3a80b557 | 1,476 | cpp | C++ | Meeting Rooms II with Description.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | 1 | 2021-12-12T05:55:44.000Z | 2021-12-12T05:55:44.000Z | Meeting Rooms II with Description.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | null | null | null | Meeting Rooms II with Description.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | null | null | null |
// Description:
// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
// find the minimum number of conference rooms required.
// Example:
// Input: intervals = [(0,30),(5,10),(15,20)]
// Output: 2
// Explanation:
// We need two meeting rooms
// room1: (0,30)
// room2: (5,10),(15,20)
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
class Solution{
public:
/**
* @param intervals: an array of meeting time intervals
* @return: the minimum number of conference rooms required
*/
static bool custom(int &a, int &b)
{
return abs(a) < abs(b);
}
int minMeetingRooms(vector<Interval> &intervals) {
// Write your code here
vector<int> times;
for (auto &itr:intervals) {
times.push_back(itr.start);
times.push_back(-itr.end);
}
sort(times.begin(), times.end(), custom);
int res = 0;
int ans = 0;
for (int i = 0; i < times.size(); i++) {
if (times[i] >= 0) {
ans++;
} else {
ans--;
}
res = max(res, ans);
}
return res;
}
};
| 23.806452 | 110 | 0.468835 | chaitanyks |
c0e2ab8b160fa84fb03c8e0bea3996ae00fba8b7 | 1,521 | cpp | C++ | sources/Engine/Modules/Graphics/GraphicsSystem/Animation/AnimationStatesMachineVariables.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 22 | 2017-07-26T17:42:56.000Z | 2022-03-21T22:12:52.000Z | sources/Engine/Modules/Graphics/GraphicsSystem/Animation/AnimationStatesMachineVariables.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 50 | 2017-08-02T19:37:48.000Z | 2020-07-24T21:10:38.000Z | sources/Engine/Modules/Graphics/GraphicsSystem/Animation/AnimationStatesMachineVariables.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 4 | 2018-08-20T08:12:48.000Z | 2020-07-19T14:10:05.000Z | #include "precompiled.h"
#pragma hdrstop
#include "AnimationStatesMachineVariables.h"
AnimationStatesMachineVariables::AnimationStatesMachineVariables() = default;
SkeletalAnimationVariableId AnimationStatesMachineVariables::registerVariable(const std::string& name,
float initialValue)
{
SW_ASSERT(m_variablesNameIdMap.count(name) == 0);
m_variablesValues.push_back(initialValue);
m_variablesNameIdMap[name] = static_cast<SkeletalAnimationVariableId>(m_variablesValues.size()) - 1;
return static_cast<SkeletalAnimationVariableId>(m_variablesValues.size()) - 1;
}
SkeletalAnimationVariableId AnimationStatesMachineVariables::getVariableId(const std::string& name) const
{
return m_variablesNameIdMap.at(name);
}
void AnimationStatesMachineVariables::setVariableValue(const std::string& name, float value)
{
m_variablesValues[static_cast<size_t>(getVariableId(name))] = value;
}
float AnimationStatesMachineVariables::getVariableValue(const std::string& name) const
{
return m_variablesValues[static_cast<size_t>(getVariableId(name))];
}
float AnimationStatesMachineVariables::getVariableValue(SkeletalAnimationVariableId id) const
{
SW_ASSERT(id < SkeletalAnimationVariableId(m_variablesValues.size()));
return m_variablesValues[static_cast<size_t>(id)];
}
void AnimationStatesMachineVariables::setVariableValue(SkeletalAnimationVariableId id, float value)
{
SW_ASSERT(id < SkeletalAnimationVariableId(m_variablesValues.size()));
m_variablesValues[static_cast<size_t>(id)] = value;
}
| 31.6875 | 105 | 0.819198 | n-paukov |
c0e318df0544b72eff3db16d5f2e25f8acdb285e | 4,856 | cpp | C++ | source/utils/file/file.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | 5 | 2019-09-14T10:10:18.000Z | 2022-02-18T03:50:23.000Z | source/utils/file/file.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | null | null | null | source/utils/file/file.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | 1 | 2019-10-10T16:23:05.000Z | 2019-10-10T16:23:05.000Z | #include "file.h"
#include "./../../utils/hdetect/hdetect.h"
#include <unistd.h>
#include <ncurses.h>
#include <sstream>
namespace utils
{
file::file()
{
fileStream = new std::fstream();
}
file::file(const char* path)
{
this->fileStream = new std::fstream();
this->open(std::string(path));
}
file::file(const std::string& path)
{
this->fileStream = new std::fstream();
this->open(path);
}
file& file::open(const char* path)
{
return this->open(std::string(path));
}
file& file::open(const std::string& path)
{
this->path = path;
this->fileStream->open(path, std::ios::out | std::ios::binary | std::ios::in);
this->fileBuffer = fileStream->rdbuf();
this->header = utils::getFileHeaderType(*this);
if (!fileStream->is_open())
throw FailedToOpenFileException("Could not open file", path);
return *this;
}
file& file::close()
{
this->fileStream->close();
this->fileBuffer->close();
return *this;
}
std::string file::getPath()
{
return this->path;
}
std::string file::getName()
{
std::size_t found = path.find_last_of("/\\");
return path.substr(0,found);
}
std::string file::getHeader()
{
return header;
}
unsigned long long file::getFileEnd()
{
auto cursor = getCursorLocation();
moveCursor(0);
auto res = getBytesAfterCursor();
moveCursor(cursor);
return res;
}
unsigned long long file::getCursorLocation()
{
return fileStream->tellg();
}
file& file::resetCursor()
{
fileBuffer->pubseekpos(0);
fileStream->seekg(0);
fileStream->seekp(0);
return *this;
}
file& file::moveCursor(unsigned long long location)
{
fileBuffer->pubseekpos(location);
fileStream->seekg(location);
fileStream->seekp(location);
return *this;
}
file& file::incCursor()
{
auto cursor = getCursorLocation();
if (cursor < getFileEnd())
moveCursor(getCursorLocation()+1);
return *this;
}
file& file::incCursor(const unsigned long long n)
{
auto res = getCursorLocation() + n;
if (res <= getFileEnd())
moveCursor(res);
return *this;
}
file& file::decCursor()
{
auto cursor = getCursorLocation();
if (cursor != 0)
moveCursor(cursor-1);
return *this;
}
file& file::decCursor(const unsigned long long n)
{
if (n <= getCursorLocation())
moveCursor(getCursorLocation() - n);
return *this;
}
unsigned long long file::getBytesAfterCursor()
{
return fileBuffer->in_avail() - 1;
}
byte file::getCurrentByte()
{
auto res = fileBuffer->sbumpc();
fileBuffer->sungetc();
return res;
}
// byte* file::getCurrentBytesN(const int n)
file& file::insertByte(const byte newByte)
{
auto cursor = getCursorLocation();
auto end = getFileEnd();
// Place temporary new byte at file end to make room for shifting.
moveCursor(end+1);
fileBuffer->sputc(newByte);
// Shift over all bytes in front of cursor to make room for new byte.
for (unsigned long long i = end+1; i > cursor; i--) {
moveCursor(i-1);
byte current = getCurrentByte();
moveCursor(i);
fileBuffer->sputc(current);
}
// Move cursor back and finnally insert byte.
moveCursor(cursor);
replaceByte(newByte);
// Return reference to self.
return *this;
}
file& file::insertBytes(const byte* bytes, const int n)
{
auto cursor = getCursorLocation();
auto end = getFileEnd();
// Place new bytes at file end to make room for shifting over all bytes.
moveCursor(end+1);
fileBuffer->sputn(bytes, n);
// Shift over all bytes in front of cursor to make room for new byte.
for (unsigned long long i = end+n; i > cursor+n-1; i--)
{
moveCursor(i-n);
byte current = getCurrentByte();
moveCursor(i);
fileBuffer->sputc(current);
}
// Move cursor back and finnally insert byte.
moveCursor(cursor);
fileBuffer->sputn(bytes, n);
// Return reference to self.
return *this;
}
file& file::replaceByte(const byte in)
{
fileBuffer->sputc(in);
return (*this);
}
file& file::replaceBytes(const byte* in, const int n)
{
fileBuffer->sputn(in, n);
return (*this);
}
}
| 23.572816 | 86 | 0.548188 | MatthijsReyers |
c0e5c705fd12e835102bbd0834be604d6a53a470 | 1,050 | cpp | C++ | src/homework/04_iteration/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-JustinBrewer22 | 9a2c884cc4189808eb80255c94a183645b209f5f | [
"MIT"
] | null | null | null | src/homework/04_iteration/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-JustinBrewer22 | 9a2c884cc4189808eb80255c94a183645b209f5f | [
"MIT"
] | null | null | null | src/homework/04_iteration/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-JustinBrewer22 | 9a2c884cc4189808eb80255c94a183645b209f5f | [
"MIT"
] | null | null | null | //write include statements
#include "dna.h"
#include <iostream>
//write using statements
using std::cout;
using std::cin;
using std::string;
/*
Write code that prompts user to enter 1 for Get GC Content,
or 2 for Get DNA Complement. The program will prompt user for a
DNA string and call either get gc content or get dna complement
function and display the result. Program runs as long as
user enters a y or Y.
*/
int main()
{
int num = 0;
char yn = 'y';
string dna;
do
{
cout<<"Please enter (1) for Get CG Content, or (2) for Get DNA Complement\n";
cin>>num;
cout<<"Please enter DNA string: \n";
cin>>dna;
if (num == 1)
{
double content = get_gc_content(dna);
cout<<"GC Content: "<<content<<"\n";
}
else if (num == 2)
{
string complement = get_dna_complement(dna);
cout<<"DNA Complement: "<<complement<<"\n";
}
else
{
cout<<"Sorry I could not accept input given. ";
}
cout<<"Do you want to enter another DNA string? (Y/N) \n";
cin>>yn;
}
while (yn == 'y' || yn == 'Y');
return 0;
} | 20.588235 | 79 | 0.638095 | acc-cosc-1337-fall-2020 |
c0ea8a4317f52db6c8bc69b807d893d13e38b9ff | 6,912 | cpp | C++ | src/thunderbots/software/ai/hl/stp/tactic/shoot_goal_tactic.cpp | Solaris5959/Software | b34ed63f671460dcb8db62d328b776747adaf374 | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/tactic/shoot_goal_tactic.cpp | Solaris5959/Software | b34ed63f671460dcb8db62d328b776747adaf374 | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/tactic/shoot_goal_tactic.cpp | Solaris5959/Software | b34ed63f671460dcb8db62d328b776747adaf374 | [
"MIT"
] | null | null | null | #include "ai/hl/stp/tactic/shoot_goal_tactic.h"
#include "ai/hl/stp/action/move_action.h"
#include "ai/hl/stp/evaluation/calc_best_shot.h"
#include "ai/hl/stp/evaluation/intercept.h"
#include "geom/rectangle.h"
ShootGoalTactic::ShootGoalTactic(const Field &field, const Team &friendly_team,
const Team &enemy_team, const Ball &ball,
Angle min_net_open_angle,
std::optional<Point> chip_target, bool loop_forever)
: field(field),
friendly_team(friendly_team),
enemy_team(enemy_team),
ball(ball),
min_net_open_angle(min_net_open_angle),
chip_target(chip_target),
has_shot_available(false),
Tactic(loop_forever, {RobotCapabilityFlags::Kick})
{
}
std::string ShootGoalTactic::getName() const
{
return "Shoot Goal Tactic";
}
void ShootGoalTactic::updateParams(const Field &field, const Team &friendly_team,
const Team &enemy_team, const Ball &ball)
{
this->field = field;
this->friendly_team = friendly_team;
this->enemy_team = enemy_team;
this->ball = ball;
}
void ShootGoalTactic::updateParams(const Field &field, const Team &friendly_team,
const Team &enemy_team, const Ball &ball,
std::optional<Point> chip_target)
{
this->chip_target = chip_target;
updateParams(field, friendly_team, enemy_team, ball);
}
double ShootGoalTactic::calculateRobotCost(const Robot &robot, const World &world)
{
auto ball_intercept_opt =
Evaluation::findBestInterceptForBall(world.ball(), world.field(), robot);
double cost = 0;
if (ball_intercept_opt)
{
// If we can intercept the ball, use the distance to the intercept point.
// We normalize with the total field length so that robots that are within the
// field have a cost less than 1
cost = (ball_intercept_opt->first - robot.position()).len() /
world.field().totalLength();
}
else
{
// If we can't intercept the ball, just use the distance to the ball's current
// position. We normalize with the total field length so that robots that are
// within the field have a cost less than 1
cost = (world.ball().position() - robot.position()).len() /
world.field().totalLength();
}
return std::clamp<double>(cost, 0, 1);
}
bool ShootGoalTactic::hasShotAvailable() const
{
return has_shot_available;
}
bool ShootGoalTactic::isEnemyAboutToStealBall() const
{
// Our rectangle class does not have the concept of rotation, so instead
// we rotate all the robot positions about the origin so we can construct
// a rectangle that is aligned with the axis
Angle theta = -robot->orientation();
Point rotated_baller_position = robot->position().rotate(theta);
Rectangle area_in_front_of_rotated_baller(
rotated_baller_position - Vector(0, 3 * ROBOT_MAX_RADIUS_METERS),
rotated_baller_position +
Vector(5 * ROBOT_MAX_RADIUS_METERS, 3 * ROBOT_MAX_RADIUS_METERS));
for (const auto &enemy : enemy_team.getAllRobots())
{
Point rotated_enemy_position = enemy.position().rotate(theta);
if (area_in_front_of_rotated_baller.containsPoint(rotated_enemy_position))
{
return true;
}
}
return false;
}
void ShootGoalTactic::shootUntilShotBlocked(KickAction &kick_action,
ChipAction &chip_action,
IntentCoroutine::push_type &yield) const
{
auto shot_target = Evaluation::calcBestShotOnEnemyGoal(field, friendly_team,
enemy_team, ball.position());
while (shot_target)
{
if (!isEnemyAboutToStealBall())
{
yield(kick_action.updateStateAndGetNextIntent(
*robot, ball, ball.position(), shot_target->first,
BALL_MAX_SPEED_METERS_PER_SECOND - 0.5));
}
else
{
// If we are in the middle of committing to a shot but an enemy is about to
// steal the ball we chip instead to just get over the enemy. We do not adjust
// the point we are targeting since that may take more time to realign to, and
// we need to be very quick so the enemy doesn't get the ball
yield(chip_action.updateStateAndGetNextIntent(*robot, ball, ball.position(),
shot_target->first, CHIP_DIST));
}
shot_target = Evaluation::calcBestShotOnEnemyGoal(field, friendly_team,
enemy_team, ball.position());
}
}
void ShootGoalTactic::calculateNextIntent(IntentCoroutine::push_type &yield)
{
KickAction kick_action = KickAction();
ChipAction chip_action = ChipAction();
MoveAction move_action =
MoveAction(MoveAction::ROBOT_CLOSE_TO_DEST_THRESHOLD, Angle(), true);
do
{
auto shot_target = Evaluation::calcBestShotOnEnemyGoal(
field, friendly_team, enemy_team, ball.position());
if (shot_target && shot_target->second > min_net_open_angle)
{
// Once we have determined we can take a shot, continue to try shoot until the
// shot is entirely blocked
has_shot_available = true;
shootUntilShotBlocked(kick_action, chip_action, yield);
has_shot_available = false;
}
else if (isEnemyAboutToStealBall())
{
// If an enemy is about to steal the ball from us, we try chip over them to
// try recover the ball after, which is better than being stripped of the ball
// and directly losing possession that way
Point fallback_chip_target = chip_target ? *chip_target : field.enemyGoal();
yield(chip_action.updateStateAndGetNextIntent(
*robot, ball, ball.position(), fallback_chip_target, CHIP_DIST));
}
else
{
Vector behind_ball_vector = (ball.position() - field.enemyGoal());
// A point behind the ball that leaves 5cm between the ball and kicker of the
// robot
Point behind_ball =
ball.position() +
behind_ball_vector.norm(BALL_MAX_RADIUS_METERS +
DIST_TO_FRONT_OF_ROBOT_METERS + TRACK_BALL_DIST);
// The default behaviour is to move behind the ball and face the net
yield(move_action.updateStateAndGetNextIntent(
*robot, behind_ball, (-behind_ball_vector).orientation(), 0));
}
} while (!(kick_action.done() || chip_action.done()));
}
| 39.724138 | 90 | 0.619792 | Solaris5959 |
c0fc8f4da816af4e1c19d5ae0d43cc7d115f80da | 488 | cpp | C++ | tests/unit/parse/concepts/error_rule.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T17:56:23.000Z | 2019-04-30T17:56:23.000Z | tests/unit/parse/concepts/error_rule.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | null | null | null | tests/unit/parse/concepts/error_rule.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 4 | 2018-08-01T08:32:00.000Z | 2019-12-18T06:34:33.000Z | #include "parse/concepts/error_rule.hpp"
#include <catch2/catch.hpp>
using namespace Parse::Concepts;
struct FooSimpleRule {
template <class Input, class... States>
static bool match(Input& /*unused*/, States&&... /*unused*/) {return true;}
};
struct FooErrorRule : FooSimpleRule {
static constexpr auto error() { return "error_string"; }
};
TEST_CASE("Parse.Concepts.ErrorRule", "[Concepts]") {
REQUIRE(ErrorRule<FooErrorRule>);
REQUIRE_FALSE(ErrorRule<FooSimpleRule>);
}
| 24.4 | 77 | 0.721311 | qedalab |
c0fda5fb944745e31069568569beff11d91b59e9 | 77 | cpp | C++ | NayukiYq/Src/NayukiYq/Common/FSM/FSMBuilder.cpp | qiboda/NayukiYq | 4969502b3d32383cbf3d943e68b979325eb05e61 | [
"MIT"
] | null | null | null | NayukiYq/Src/NayukiYq/Common/FSM/FSMBuilder.cpp | qiboda/NayukiYq | 4969502b3d32383cbf3d943e68b979325eb05e61 | [
"MIT"
] | null | null | null | NayukiYq/Src/NayukiYq/Common/FSM/FSMBuilder.cpp | qiboda/NayukiYq | 4969502b3d32383cbf3d943e68b979325eb05e61 | [
"MIT"
] | null | null | null | #include <NayukiYq/NayukiYq.h>
#include <NayukiYq/Common/FSM/FSMBuilder.h>
| 15.4 | 43 | 0.766234 | qiboda |
8d038172c989017671b20173ca8d50dd7f61ea34 | 34,255 | cpp | C++ | Source/Storm-Graphics/include/GraphicManager.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | 3 | 2021-11-27T04:56:12.000Z | 2022-02-14T04:02:10.000Z | Source/Storm-Graphics/include/GraphicManager.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | Source/Storm-Graphics/include/GraphicManager.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | #include "GraphicManager.h"
#include "DirectXController.h"
#include "Camera.h"
#include "GeneralReadOnlyUIDisplay.h"
#include "Grid.h"
#include "GraphicCoordinateSystem.h"
#include "GraphicRigidBody.h"
#include "GraphicParticleSystem.h"
#include "GraphicParticleData.h"
#include "GraphicConstraintSystem.h"
#include "GraphicBlower.h"
#include "GraphicGravity.h"
#include "ParticleForceRenderer.h"
#include "GraphicKernelEffectArea.h"
#include "GraphicNormals.h"
#include "RenderedElementProxy.h"
#include "PushedParticleSystemData.h"
#include "GraphicPipe.h"
#include "SceneBlowerConfig.h"
#include "SceneGraphicConfig.h"
#include "SceneSimulationConfig.h"
#include "SingletonHolder.h"
#include "IWindowsManager.h"
#include "ITimeManager.h"
#include "IInputManager.h"
#include "IConfigManager.h"
#include "IThreadManager.h"
#include "ThreadHelper.h"
#include "ThreadEnumeration.h"
#include "ThreadFlaggerObject.h"
#include "ThreadingSafety.h"
#include "SpecialKey.h"
#include "GraphicCutMode.h"
#include "UIFieldBase.h"
#include "UIField.h"
#include "UIFieldContainer.h"
#include "FuncMovePass.h"
namespace
{
#if false
const float g_defaultColor[4] = { 0.f, 0.5f, 0.0f, 1.f };
#else
const float g_defaultColor[4] = { 0.f, 0.f, 0.f, 1.f };
#endif
}
#define STORM_WATCHED_RB_POSITION "Rb position"
Storm::GraphicManager::GraphicManager() :
_renderCounter{ 0 },
_directXController{ std::make_unique<Storm::DirectXController>() },
_selectedParticle{ std::numeric_limits<decltype(_selectedParticle.first)>::max(), 0 },
_hasUI{ false },
_dirty{ true },
_watchedRbNonOwningPtr{ nullptr },
_displayNormals{ false },
_userMovedCameraThisFrame{ true },
_rbNoNearPlaneCut{ false }
{
}
Storm::GraphicManager::~GraphicManager() = default;
bool Storm::GraphicManager::initialize_Implementation(const Storm::WithUI &)
{
LOG_COMMENT << "Starting to initialize the Graphic Manager. We would evaluate if Windows is created. If not, we will suspend initialization and come back later.";
_hasUI = true;
_pipe = std::make_unique<Storm::GraphicPipe>();
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
Storm::IWindowsManager &windowsMgr = singletonHolder.getSingleton<Storm::IWindowsManager>();
HWND hwnd = static_cast<HWND>(windowsMgr.getWindowHandle());
if (hwnd != nullptr)
{
this->initialize_Implementation(hwnd);
return true;
}
else
{
bool initRes = false;
windowsMgr.bindFinishInitializeCallback([this, res = &initRes](void* hwndOnceReady, bool calledAtBindingTime)
{
if (calledAtBindingTime)
{
// If this was called at binding time, then this is on the same thread so it is okay to still reference res (we haven't left initialize_Implementation yet).
this->initialize_Implementation(hwndOnceReady);
*res = true;
}
else
{
// It is important to call initialize here and not initialize_Implementation because it locks the initialization mutex. It prevents tocttou.
this->initialize(hwndOnceReady);
}
});
LOG_WARNING << "HWND not valid, Graphic initialization will be suspended and done asynchronously later.";
return initRes;
}
}
void Storm::GraphicManager::initialize_Implementation(const Storm::NoUI &)
{
LOG_DEBUG << "No UI requested. Graphic Manager will be left uninitialized.";
_hasUI = false;
}
void Storm::GraphicManager::initialize_Implementation(void* hwnd)
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
const Storm::IConfigManager &configMgr = singletonHolder.getSingleton<Storm::IConfigManager>();
if (!configMgr.withUI())
{
return;
}
Storm::IWindowsManager &windowsMgr = singletonHolder.getSingleton<Storm::IWindowsManager>();
_windowsResizedCallbackId = windowsMgr.bindWindowsResizedCallback([this, &singletonHolder](int newWidth, int newHeight)
{
singletonHolder.getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, newWidth, newHeight]()
{
this->notifyViewportRescaled(newWidth, newHeight);
_dirty = true;
});
});
_windowsMovedCallbackId = windowsMgr.bindWindowsMovedCallback([this, &singletonHolder](int newX, int newY)
{
singletonHolder.getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, newX, newY]()
{
_dirty = true;
});
});
LOG_COMMENT << "HWND is valid so Windows was created, we can pursue the graphic initialization.";
_fields = std::make_unique<Storm::UIFieldContainer>();
_directXController->initialize(static_cast<HWND>(hwnd));
_camera = std::make_unique<Storm::Camera>(_directXController->getViewportWidth(), _directXController->getViewportHeight());
const auto &device = _directXController->getDirectXDevice();
const Storm::SceneGraphicConfig &sceneGraphicConfig = configMgr.getSceneGraphicConfig();
_rbNoNearPlaneCut = sceneGraphicConfig._displayRbInFull;
_gridNonOwningPtr = static_cast<Storm::Grid*>(_renderedElements.emplace_back(std::make_unique<Storm::Grid>(device, sceneGraphicConfig._grid, sceneGraphicConfig._showGridFloor)).get());
_coordSystemNonOwningPtr = static_cast<Storm::GraphicCoordinateSystem*>(_renderedElements.emplace_back(std::make_unique<Storm::GraphicCoordinateSystem>(device, sceneGraphicConfig._showCoordinateAxis)).get());
_gravityNonOwningPtr = static_cast<Storm::GraphicGravity*>(_renderedElements.emplace_back(std::make_unique<Storm::GraphicGravity>(device, _directXController->getUIRenderTarget())).get());
_graphicParticlesSystem = std::make_unique<Storm::GraphicParticleSystem>(device);
_graphicConstraintsSystem = std::make_unique<Storm::GraphicConstraintSystem>(device);
_forceRenderer = std::make_unique<Storm::ParticleForceRenderer>(device);
_kernelEffectArea = std::make_unique<Storm::GraphicKernelEffectArea>(device);
_graphicNormals = std::make_unique<Storm::GraphicNormals>(device);
for (auto &meshesPair : _meshesMap)
{
meshesPair.second->initializeRendering(device);
}
if (sceneGraphicConfig._rbWatchId != std::numeric_limits<decltype(sceneGraphicConfig._rbWatchId)>::max())
{
_watchedRbNonOwningPtr = _meshesMap.find(static_cast<unsigned int>(sceneGraphicConfig._rbWatchId))->second.get();
_fields->bindField(STORM_WATCHED_RB_POSITION, _watchedRbNonOwningPtr->getRbPosition());
}
_shouldTrackRbTranslation = sceneGraphicConfig._trackTranslation;
if (sceneGraphicConfig._displaySolidAsParticles)
{
_directXController->setAllParticleState();
}
_readOnlyFields = std::make_unique<Storm::GeneralReadOnlyUIDisplay>();
_renderThread = std::thread([this]()
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
STORM_REGISTER_THREAD(GraphicsThread);
STORM_DECLARE_THIS_THREAD_IS << Storm::ThreadFlagEnum::GraphicThread;
{
// I have an Azerty keyboard, so if you have a Qwerty keyboard, you'll surely need to change those.
Storm::IInputManager &inputMgr = singletonHolder.getSingleton<Storm::IInputManager>();
inputMgr.bindKey(Storm::SpecialKey::KC_UP, [this]() { _camera->positiveMoveYAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_LEFT, [this]() { _camera->positiveMoveXAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_NUMPAD8, [this]() { _camera->positiveMoveZAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_RIGHT, [this]() { _camera->negativeMoveXAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_DOWN, [this]() { _camera->negativeMoveYAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_NUMPAD2, [this]() { _camera->negativeMoveZAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_S, [this]() { _camera->positiveRotateXAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_D, [this]() { _camera->positiveRotateYAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_W, [this]() { _camera->negativeRotateXAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_A, [this]() { _camera->negativeRotateYAxis(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_NUMPAD0, [this]() { _camera->reset(); _dirty = true; _userMovedCameraThisFrame = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_ADD, [this]() { this->checkUserCanChangeNearPlane(); _camera->increaseNearPlane(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_SUBTRACT, [this]() { this->checkUserCanChangeNearPlane(); _camera->decreaseNearPlane(); _dirty = true;});
inputMgr.bindKey(Storm::SpecialKey::KC_MULTIPLY, [this]() { _camera->increaseFarPlane(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_DIVIDE, [this]() { _camera->decreaseFarPlane(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F2, [this]() { _coordSystemNonOwningPtr->switchShow(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F2, [this]() { _gravityNonOwningPtr->switchShow(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F3, [this]() { _directXController->setRenderSolidOnly(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F4, [this]() { _forceRenderer->tweekAlwaysOnTop(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F5, [this]() { _directXController->setWireFrameState(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F6, [this]() { _directXController->setSolidCullBackState(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F7, [this]() { _directXController->setSolidCullNoneState(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F8, [this]() { _directXController->setAllParticleState(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F9, [this]() { _directXController->setRenderNoWallParticle(); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F12, [this]() { _directXController->setUIFieldDrawEnabled(!_directXController->getUIFieldDrawEnabled()); _dirty = true; });
inputMgr.bindKey(Storm::SpecialKey::KC_F1, [this]()
{
if (this->hasSelectedParticle())
{
_kernelEffectArea->tweakEnabled();
_dirty = true;
}
});
inputMgr.bindMouseWheel([this](int axisRelativeIncrement)
{
if (axisRelativeIncrement > 0)
{
_camera->increaseCameraSpeed();
}
else if (axisRelativeIncrement < 0)
{
_camera->decreaseCameraSpeed();
}
});
}
Storm::ITimeManager &timeMgr = singletonHolder.getSingleton<Storm::ITimeManager>();
while (timeMgr.waitNextFrameOrExit())
{
this->update();
}
});
}
void Storm::GraphicManager::cleanUp_Implementation(const Storm::WithUI &)
{
LOG_COMMENT << "Starting to clean up the Graphic Manager.";
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
Storm::IWindowsManager &windowsMgr = singletonHolder.getSingleton<Storm::IWindowsManager>();
Storm::join(_renderThread);
windowsMgr.unbindWindowsResizedCallback(_windowsResizedCallbackId);
windowsMgr.unbindWindowsMovedCallback(_windowsMovedCallbackId);
_selectedParticle.first = std::numeric_limits<decltype(_selectedParticle.first)>::max();
_blowersMap.clear();
_forceRenderer.reset();
_graphicConstraintsSystem.reset();
_graphicParticlesSystem.reset();
_meshesMap.clear();
_renderedElements.clear();
_fieldsMap.clear();
_directXController->cleanUp();
}
void Storm::GraphicManager::cleanUp_Implementation(const Storm::NoUI &)
{
LOG_COMMENT << "No UI requested. Graphic Manager clean up is trivial.";
}
void Storm::GraphicManager::update()
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
singletonHolder.getSingleton<Storm::IThreadManager>().processCurrentThreadActions();
if (_renderCounter++ % 2 == 0)
{
Storm::Camera ¤tCamera = *_camera;
currentCamera.update();
if (_dirty)
{
const bool isSimulationPaused = singletonHolder.getSingleton<Storm::ITimeManager>().simulationIsPaused();
if (_watchedRbNonOwningPtr != nullptr && (_watchedRbNonOwningPtr->positionDirty() || _userMovedCameraThisFrame))
{
bool shouldTrackTranslation = _shouldTrackRbTranslation;
if (shouldTrackTranslation)
{
if (isSimulationPaused)
{
shouldTrackTranslation = false;
}
else if(_userMovedCameraThisFrame)
{
shouldTrackTranslation = true;
_userMovedCameraThisFrame = false;
}
}
currentCamera.updateWatchedRb(_watchedRbNonOwningPtr->getRbPosition(), shouldTrackTranslation);
_fields->pushField(STORM_WATCHED_RB_POSITION);
}
_directXController->clearView(g_defaultColor);
_directXController->initView();
_directXController->renderElements(currentCamera, Storm::RenderedElementProxy{
._renderedElementArrays = _renderedElements,
._rbElementArrays = _meshesMap,
._particleSystem = *_graphicParticlesSystem,
._blowersMap = _blowersMap,
._constraintSystem = *_graphicConstraintsSystem,
._selectedParticleForce = *_forceRenderer,
._kernelEffectArea = *_kernelEffectArea,
._graphicNormals = _displayNormals ? _graphicNormals.get() : nullptr,
._multiPass = _rbNoNearPlaneCut
});
_directXController->drawUI(_renderedElements, _fieldsMap);
_directXController->unbindTargetView();
_directXController->presentToDisplay();
_directXController->reportDeviceMessages();
_dirty = false;
if (!isSimulationPaused)
{
_userMovedCameraThisFrame = false;
}
}
}
}
bool Storm::GraphicManager::isActive() const noexcept
{
return _hasUI || Storm::SingletonHolder::instance().getSingleton<Storm::IConfigManager>().withUI();
}
void Storm::GraphicManager::addMesh(unsigned int meshId, const std::vector<Storm::Vector3> &vertexes, const std::vector<Storm::Vector3> &normals, const std::vector<unsigned int> &indexes)
{
if (this->isActive())
{
_meshesMap[meshId] = std::make_unique<Storm::GraphicRigidBody>(vertexes, normals, indexes);
}
}
void Storm::GraphicManager::bindParentRbToMesh(unsigned int meshId, const std::shared_ptr<Storm::IRigidBody> &parentRb) const
{
if (this->isActive())
{
if (const auto found = _meshesMap.find(meshId); found != std::end(_meshesMap))
{
found->second->setRbParent(parentRb);
}
else
{
Storm::throwException<Storm::Exception>("Cannot find rb " + std::to_string(meshId) + " inside registered graphics meshes!");
}
}
}
void Storm::GraphicManager::registerRigidbodiesParticleSystem(unsigned int rbId, const std::size_t pCount)
{
if (this->isActive())
{
assert(Storm::isSimulationThread() && "This method should be called from simulation thread!");
_pipe->registerRb(rbId, pCount);
LOG_DEBUG << "Rb particle system " << rbId << " registered to graphic pipe with " << pCount << " particles.";
}
}
void Storm::GraphicManager::loadBlower(const Storm::SceneBlowerConfig &blowerConfig, const std::vector<Storm::Vector3> &vertexes, const std::vector<unsigned int> &indexes)
{
if (this->isActive())
{
const ComPtr<ID3D11Device> ¤tDevice = _directXController->getDirectXDevice();
std::unique_ptr<Storm::GraphicBlower> graphicBlower = std::make_unique<Storm::GraphicBlower>(currentDevice, blowerConfig, vertexes, indexes);
_blowersMap[blowerConfig._blowerId] = std::move(graphicBlower);
LOG_DEBUG << "Graphic blower " << blowerConfig._blowerId << " was created.";
}
}
void Storm::GraphicManager::pushParticlesData(const Storm::PushedParticleSystemDataParameter ¶m)
{
if (this->isActive())
{
assert(!(param._isFluids && param._isWall) && "Particle cannot be fluid AND wall at the same time!");
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
singletonHolder.getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread,
[this, particleSystemId = param._particleSystemId, particlePosDataCopy = FuncMovePass<decltype(_pipe->fastOptimizedTransCopy(param))>{ _pipe->fastOptimizedTransCopy(param) }, isFluids = param._isFluids, isWall = param._isWall, pos = param._position]() mutable
{
if (_forceRenderer->prepareData(particleSystemId, particlePosDataCopy._object, _selectedParticle))
{
if (this->hasSelectedParticle() && particleSystemId == _selectedParticle.first)
{
_kernelEffectArea->setAreaPosition(particlePosDataCopy._object[_selectedParticle.second]);
}
_graphicParticlesSystem->refreshParticleSystemData(_directXController->getDirectXDevice(), particleSystemId, std::move(particlePosDataCopy._object), isFluids, isWall);
if (!isFluids && !isWall)
{
Storm::GraphicRigidBody ¤tGraphicRb = *_meshesMap.find(particleSystemId)->second;
currentGraphicRb.setRbPosition(pos);
}
_dirty = true;
}
});
}
}
void Storm::GraphicManager::pushConstraintData(const std::vector<Storm::Vector3> &constraintsVisuData)
{
if (this->isActive())
{
_graphicConstraintsSystem->refreshConstraintsData(_directXController->getDirectXDevice(), constraintsVisuData);
}
}
void Storm::GraphicManager::pushParticleSelectionForceData(const Storm::Vector3 &selectedParticlePos, const Storm::Vector3 &selectedParticleForce)
{
if (this->isActive())
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
singletonHolder.getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread,
[this, selectedParticlePos, selectedParticleForce]() mutable
{
_forceRenderer->updateForceData(_directXController->getDirectXDevice(), _parameters, selectedParticlePos, selectedParticleForce);
_dirty = true;
});
}
}
void Storm::GraphicManager::pushNormalsData(const std::vector<Storm::Vector3>& positions, const std::vector<Storm::Vector3>& normals)
{
if (this->isActive())
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
singletonHolder.getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread,
[this, positions, normals]()
{
_graphicNormals->updateNormalsData(_directXController->getDirectXDevice(), _parameters, positions, normals);
_displayNormals = true;
_dirty = true;
});
}
}
void Storm::GraphicManager::createGraphicsField(const std::wstring_view &fieldName, std::wstring &&fieldValueStr)
{
if (this->isActive())
{
assert(_fieldsMap.find(fieldName) == std::end(_fieldsMap) && "We shouldn't create another field with the same name!");
_fieldsMap[fieldName] = std::move(fieldValueStr);
_directXController->notifyFieldCount(_fieldsMap.size());
_dirty = true;
}
}
void Storm::GraphicManager::removeGraphicsField(const std::wstring_view &fieldName)
{
if (this->isActive())
{
if (const auto found = _fieldsMap.find(fieldName); found != std::end(_fieldsMap))
{
_fieldsMap.erase(found);
_directXController->notifyFieldCount(_fieldsMap.size());
_dirty = true;
}
else
{
assert(false && "We shouldn't remove a field that doesn't exist!");
}
}
}
void Storm::GraphicManager::updateGraphicsField(std::vector<std::pair<std::wstring_view, std::wstring>> &&rawFields)
{
if (this->isActive())
{
for (auto &field : rawFields)
{
this->updateGraphicsField(field.first, std::move(field.second));
}
}
}
void Storm::GraphicManager::updateGraphicsField(const std::wstring_view &fieldName, std::wstring &&fieldValue)
{
if (auto found = _fieldsMap.find(fieldName); found != std::end(_fieldsMap))
{
found->second = std::move(fieldValue);
_dirty = true;
}
}
std::size_t Storm::GraphicManager::getFieldCount() const
{
return _fieldsMap.size();
}
void Storm::GraphicManager::convertScreenPositionToRay(const Storm::Vector2 &screenPos, Storm::Vector3 &outRayOrigin, Storm::Vector3 &outRayDirection) const
{
assert(Storm::isGraphicThread() && "this method should only be executed on graphic thread.");
if (this->isActive())
{
_camera->convertScreenPositionToRay(screenPos, outRayOrigin, outRayDirection);
}
}
void Storm::GraphicManager::getClippingPlaneValues(float &outZNear, float &outZFar) const
{
assert(Storm::isGraphicThread() && "this method should only be executed on graphic thread.");
if (this->isActive())
{
outZNear = _camera->getNearPlane();
outZFar = _camera->getFarPlane();
}
else
{
outZNear = 0.f;
outZFar = 0.f;
}
}
Storm::Vector3 Storm::GraphicManager::get3DPosOfScreenPixel(const Storm::Vector2 &screenPos) const
{
// Screen pixel positions to 3D
Storm::Vector3 vectClipSpace3DPos{
screenPos.x(),
screenPos.y(),
0.f
};
// Transform the screen pixel positions to render target pixel texture position.
_camera->rescaleScreenPosition(vectClipSpace3DPos.x(), vectClipSpace3DPos.y());
// Apply the Z-buffer to the Z position, and we would have the 3D clip space position of the selected pixel.
vectClipSpace3DPos.z() = _directXController->getDepthBufferAtPixel(static_cast<int>(vectClipSpace3DPos.x()), static_cast<int>(vectClipSpace3DPos.y()));
return _camera->convertScreenPositionTo3DPosition(vectClipSpace3DPos);
}
void Storm::GraphicManager::safeSetSelectedParticle(unsigned int particleSystemId, std::size_t particleIndex)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread, [this, particleSystemId, particleIndex]()
{
_selectedParticle.first = particleSystemId;
_selectedParticle.second = particleIndex;
_kernelEffectArea->setHasParticleHook(true);
_dirty = true;
});
}
}
void Storm::GraphicManager::safeClearSelectedParticle()
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread, [this]()
{
_selectedParticle.first = std::numeric_limits<decltype(_selectedParticle.first)>::max();
_kernelEffectArea->setHasParticleHook(false);
_dirty = true;
});
}
}
void Storm::GraphicManager::clearNormalsData()
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(ThreadEnumeration::GraphicsThread, [this]()
{
_displayNormals = false;
_dirty = true;
});
}
}
void Storm::GraphicManager::setUIFieldEnabled(bool enable)
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, enable]()
{
_directXController->setUIFieldDrawEnabled(enable);
_dirty = true;
});
}
const Storm::Camera& Storm::GraphicManager::getCamera() const
{
return *_camera;
}
const Storm::DirectXController& Storm::GraphicManager::getController() const
{
return *_directXController;
}
void Storm::GraphicManager::setTargetPositionTo(const Storm::Vector3 &newTargetPosition)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, newTargetPosition]()
{
_camera->setTarget(newTargetPosition.x(), newTargetPosition.y(), newTargetPosition.z());
_dirty = true;
});
}
}
void Storm::GraphicManager::changeBlowerState(const std::size_t blowerId, const Storm::BlowerState newState)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, blowerId, newState]()
{
_blowersMap[blowerId]->setBlowerState(newState);
_dirty = true;
});
}
}
bool Storm::GraphicManager::hasSelectedParticle() const
{
return this->isActive() && _selectedParticle.first != std::numeric_limits<decltype(_selectedParticle.first)>::max();
}
void Storm::GraphicManager::notifyViewportRescaled(int newWidth, int newHeight)
{
_camera->setRescaledDimension(static_cast<float>(newWidth), static_cast<float>(newHeight));
}
void Storm::GraphicManager::cycleColoredSetting()
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::MainThread, [this]()
{
_pipe->cycleColoredSetting();
_dirty = true;
});
}
}
void Storm::GraphicManager::setColorSettingMinMaxValue(float minValue, float maxValue)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::MainThread, [this, minValue, maxValue]()
{
_pipe->setMinMaxColorationValue(minValue, maxValue);
_dirty = true;
});
}
}
void Storm::GraphicManager::setUseColorSetting(const Storm::ColoredSetting colorSetting)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::MainThread, [this, colorSetting]()
{
_pipe->setUsedColorSetting(colorSetting);
_dirty = true;
});
}
}
void Storm::GraphicManager::showCoordinateSystemAxis(const bool shouldShow)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, shouldShow]()
{
_coordSystemNonOwningPtr->show(shouldShow);
_dirty = true;
});
}
}
void Storm::GraphicManager::showGridVisibility(const bool shouldShow)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, shouldShow]()
{
if (_gridNonOwningPtr->setVisibility(shouldShow))
{
_dirty = true;
}
});
}
}
void Storm::GraphicManager::setKernelAreaRadius(const float radius)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, radius]()
{
_kernelEffectArea->setAreaRadius(radius);
_dirty = true;
});
}
}
void Storm::GraphicManager::lockNearPlaneOnWatchedRb(unsigned int watchedRbId)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, watchedRbId]()
{
if (const auto found = _meshesMap.find(static_cast<unsigned int>(watchedRbId)); found != std::end(_meshesMap))
{
const auto* old = _watchedRbNonOwningPtr;
_watchedRbNonOwningPtr = found->second.get();
if (old != nullptr)
{
_fields->deleteField(STORM_WATCHED_RB_POSITION);
}
_fields->bindField(STORM_WATCHED_RB_POSITION, _watchedRbNonOwningPtr->getRbPosition());
_dirty = true;
}
else
{
Storm::throwException<Storm::Exception>("Cannot find the rigid body to lock the near plane on. Requested id was " + std::to_string(watchedRbId));
}
});
}
}
void Storm::GraphicManager::unlockNearPlaneOnWatchedRb()
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this]()
{
if (_watchedRbNonOwningPtr)
{
_watchedRbNonOwningPtr = nullptr;
_fields->deleteField(STORM_WATCHED_RB_POSITION);
}
});
}
}
void Storm::GraphicManager::stopTrackingTranslationOnWatchedRb()
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this]()
{
_shouldTrackRbTranslation = false;
});
}
}
void Storm::GraphicManager::checkUserCanChangeNearPlane() const
{
if (_watchedRbNonOwningPtr != nullptr)
{
Storm::throwException<Storm::Exception>("User cannot change the near plane value because it is locked on a rigid body!");
}
}
void Storm::GraphicManager::setVectMultiplicatorCoeff(const float newCoeff)
{
if (this->isActive())
{
if (newCoeff <= 0.f)
{
Storm::throwException<Storm::Exception>("Vectors multiplication coefficient must be strictly greater than 0! Received value was " + std::to_string(newCoeff) + ".");
}
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, newCoeff]()
{
if (_parameters._vectNormMultiplicator != newCoeff)
{
const float oldCoeff = _parameters._vectNormMultiplicator;
_parameters._vectNormMultiplicator = newCoeff;
const auto &device = _directXController->getDirectXDevice();
_forceRenderer->refreshForceData(device, _parameters);
_graphicNormals->refreshNormalsData(device, _parameters, oldCoeff);
_dirty = true;
}
});
}
}
void Storm::GraphicManager::makeCutAroundWatchedRb(const Storm::GraphicCutMode cutMode)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, cutMode]()
{
if (_watchedRbNonOwningPtr)
{
this->makeCutAroundRigidbody(_watchedRbNonOwningPtr->getID(), cutMode);
}
else
{
LOG_ERROR << "No watched rb. Skipping cut.";
}
});
}
}
void Storm::GraphicManager::makeCutAroundRigidbody(const unsigned int rbId, const Storm::GraphicCutMode cutMode)
{
if (this->isActive())
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
Storm::IThreadManager &threadMgr = singletonHolder.getSingleton<Storm::IThreadManager>();
switch (cutMode)
{
case Storm::GraphicCutMode::Kernel:
threadMgr.executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, rbId]()
{
if (_watchedRbNonOwningPtr)
{
if (_watchedRbNonOwningPtr->getID() != rbId)
{
Storm::throwException<Storm::Exception>("We have a watched rb locked but we requested to set the cut on another rb, this is forbidden!");
}
_camera->makeCut(_watchedRbNonOwningPtr->getRbPosition(), _kernelEffectArea->getAreaRadius());
}
else if (const auto meshesFound = _meshesMap.find(rbId); meshesFound != std::end(_meshesMap))
{
_camera->makeCut(meshesFound->second->getRbPosition(), _kernelEffectArea->getAreaRadius());
}
else
{
LOG_ERROR << "Cannot find the graphic mesh specified by id " << rbId;
}
});
break;
case Storm::GraphicCutMode::Particle:
{
const Storm::IConfigManager &configMgr = singletonHolder.getSingleton<Storm::IConfigManager>();
threadMgr.executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, rbId, particleRadius = configMgr.getSceneSimulationConfig()._particleRadius]()
{
if (_watchedRbNonOwningPtr)
{
if (_watchedRbNonOwningPtr->getID() != rbId)
{
Storm::throwException<Storm::Exception>("We have a watched rb locked but we requested to set the cut on another rb, this is forbidden!");
}
_camera->makeCut(_watchedRbNonOwningPtr->getRbPosition(), particleRadius);
}
else if (const auto meshesFound = _meshesMap.find(rbId); meshesFound != std::end(_meshesMap))
{
_camera->makeCut(meshesFound->second->getRbPosition(), particleRadius);
}
else
{
LOG_ERROR << "Cannot find the graphic mesh specified by id " << rbId;
}
});
break;
}
default:
Storm::throwException<Storm::Exception>("Unknown cut mode (" + Storm::toStdString(cutMode) + ")");
}
}
}
void Storm::GraphicManager::makeCutAroundSelectedParticle(const Storm::GraphicCutMode cutMode)
{
if (this->isActive())
{
const Storm::SingletonHolder &singletonHolder = Storm::SingletonHolder::instance();
Storm::IThreadManager &threadMgr = singletonHolder.getSingleton<Storm::IThreadManager>();
switch (cutMode)
{
case Storm::GraphicCutMode::Kernel:
threadMgr.executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this]()
{
if (_watchedRbNonOwningPtr)
{
Storm::throwException<Storm::Exception>("We have a watched rb locked but we requested to make a cut, this is forbidden (except a cut on the watched rb center)!");
}
if (this->hasSelectedParticle())
{
_camera->makeCut(_kernelEffectArea->getAreaPosition(), _kernelEffectArea->getAreaRadius());
}
else
{
LOG_ERROR << "No selected particle. Skipping cut.";
}
});
break;
case Storm::GraphicCutMode::Particle:
threadMgr.executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, &singletonHolder]()
{
if (_watchedRbNonOwningPtr)
{
Storm::throwException<Storm::Exception>("We have a watched rb locked but we requested to make a cut, this is forbidden (except a cut on the watched rb center)!");
}
if (this->hasSelectedParticle())
{
const Storm::IConfigManager &configMgr = singletonHolder.getSingleton<Storm::IConfigManager>();
_camera->makeCut(_kernelEffectArea->getAreaPosition(), configMgr.getSceneSimulationConfig()._particleRadius);
}
else
{
LOG_ERROR << "No selected particle. Skipping cut.";
}
});
break;
}
}
}
void Storm::GraphicManager::displayDynamicRbInFull(bool enable)
{
if (this->isActive())
{
Storm::SingletonHolder::instance().getSingleton<Storm::IThreadManager>().executeOnThread(Storm::ThreadEnumeration::GraphicsThread, [this, enable]()
{
_rbNoNearPlaneCut = enable;
_dirty = true;
});
}
}
| 35.025562 | 263 | 0.720508 | SunlayGGX |
8d06bb8ff15ad19f79562a2c0686b0f556a96a2e | 3,505 | hpp | C++ | include/gridtools/stencil_composition/grid_base.hpp | wdeconinck/gridtools | 1811413f6e22a8f1205e542f5354daaae7c5554b | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/stencil_composition/grid_base.hpp | wdeconinck/gridtools | 1811413f6e22a8f1205e542f5354daaae7c5554b | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/stencil_composition/grid_base.hpp | wdeconinck/gridtools | 1811413f6e22a8f1205e542f5354daaae7c5554b | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include "../common/array.hpp"
#include "../common/halo_descriptor.hpp"
#include "axis.hpp"
#include "interval.hpp"
namespace gridtools {
namespace _impl {
/*
* @brief convert an array of intervals in an array of indices of splitters
*/
template <size_t NIntervals>
array<uint_t, NIntervals + 1> intervals_to_indices(const array<uint_t, NIntervals> &intervals) {
array<uint_t, NIntervals + 1> indices;
indices[0] = 0;
indices[1] = intervals[0];
for (size_t i = 2; i < NIntervals + 1; ++i) {
indices[i] = indices[i - 1] + intervals[i - 1];
}
return indices;
}
} // namespace _impl
template <typename Axis>
struct grid_base {
GT_STATIC_ASSERT((is_interval<Axis>::value), GT_INTERNAL_ERROR);
typedef Axis axis_type;
static constexpr int_t size = Axis::ToLevel::splitter - Axis::FromLevel::splitter + 1;
array<uint_t, size> value_list;
private:
halo_descriptor m_direction_i;
halo_descriptor m_direction_j;
public:
/**
* @brief standard ctor
* @param direction_i halo_descriptor in i direction
* @param direction_j halo_descriptor in j direction
* @param value_list gridtools::array with splitter positions
*/
GT_FUNCTION
explicit grid_base(halo_descriptor const &direction_i,
halo_descriptor const &direction_j,
const array<uint_t, size> &value_list)
: value_list(value_list), m_direction_i(direction_i), m_direction_j(direction_j) {}
GT_FUNCTION
uint_t i_low_bound() const { return m_direction_i.begin(); }
GT_FUNCTION
uint_t i_high_bound() const { return m_direction_i.end(); }
GT_FUNCTION
uint_t j_low_bound() const { return m_direction_j.begin(); }
GT_FUNCTION
uint_t j_high_bound() const { return m_direction_j.end(); }
template <class Level, int_t Offset = Level::offset>
GT_FUNCTION std::enable_if_t<(Offset > 0), uint_t> value_at() const {
GT_STATIC_ASSERT((is_level<Level>::value), GT_INTERNAL_ERROR);
return value_list[Level::splitter] + Offset - 1;
}
template <class Level, int_t Offset = Level::offset>
GT_FUNCTION std::enable_if_t<(Offset <= 0), uint_t> value_at() const {
GT_STATIC_ASSERT((is_level<Level>::value), GT_INTERNAL_ERROR);
return value_list[Level::splitter] - static_cast<uint_t>(-Offset);
}
GT_FUNCTION uint_t k_min() const { return value_at<typename Axis::FromLevel>(); }
GT_FUNCTION uint_t k_max() const {
// -1 because the axis has to be one level bigger than the largest k interval
return value_at<typename Axis::ToLevel>() - 1;
}
/**
* The total length of the k dimension as defined by the axis.
*/
GT_FUNCTION
uint_t k_total_length() const { return k_max() - k_min() + 1; }
GT_FUNCTION halo_descriptor const &direction_i() const { return m_direction_i; }
GT_FUNCTION halo_descriptor const &direction_j() const { return m_direction_j; }
};
} // namespace gridtools
| 34.029126 | 104 | 0.624251 | wdeconinck |
8d0b23d273d8c7fdc09bfe65d79698e92a7ec6d7 | 3,334 | cpp | C++ | sources/chap02/ex04.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | 4 | 2022-03-12T14:42:21.000Z | 2022-03-30T02:09:55.000Z | sources/chap02/ex04.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | null | null | null | sources/chap02/ex04.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | 1 | 2022-03-29T18:17:55.000Z | 2022-03-29T18:17:55.000Z | #include "vector.h"
#include "test_framework.h"
using namespace clazy_framework;
// 这个例子讨论:如何在向量中进行批量删除?
// 输入:向量V,条件P
// 输出:向量V中删除所有符合条件P的元素,并返回删除的元素数量
template <typename T>
using Vector = clazy::Vector<T>;
template <typename T>
class BatchRemove : public Algorithm<int, Vector<T>&, const Predicate<T>&> {
protected:
virtual void batchRemove(Vector<T>& V, const Predicate<T>& P) = 0;
public:
int apply(Vector<T>& V, const Predicate<T>& P) override {
int old_size = V.size();
batchRemove(V, P);
return old_size - V.size();
}
};
// 最朴素的想法是:逐个查找、逐个删除
template <typename T>
class BatchRemoveSFSR : public BatchRemove<T> {
protected:
virtual void batchRemove(Vector<T>& V, const Predicate<T>& P) override {
Rank r = 0;
while (r = find_if(begin(V), end(V), P) - begin(V), r < V.size()) { // 只要有满足条件的元素
V.remove(r); // 就把该元素删除(每轮循环找到一个、删除一个)
} // 直到没有满足条件的元素为止
}
};
// 第二种想法:全局查找、逐个删除
template <typename T>
class BatchRemoveGFSR : public BatchRemove<T> {
protected:
virtual void batchRemove(Vector<T>& V, const Predicate<T>& P) override {
Rank r = 0;
while (r = find_if(begin(V) + r, end(V), P) - begin(V), r < V.size()) {
V.remove(r); // 改为从V[r]开始查找,因为之前的元素已经被找过一次了
} // 这样find_if加起来,总共也只遍历了V一次
}
};
// 第三种想法:全局查找、全局删除
template <typename T>
class BatchRemoveGFGR : public BatchRemove<T> {
protected:
virtual void batchRemove(Vector<T>& V, const Predicate<T>& P) override {
Rank r_last = 0, r = 0; // 需要记录上次的r,每次移动一个区间
int offset = -1; // 向前移动的偏移量
do {
r = find_if(begin(V) + r, end(V), P) - begin(V);
if (++offset > 0) { // 删除一个元素之后,下一个区间移动偏移量+1
copy(begin(V) + r_last + 1, begin(V) + r, begin(V) + r_last + 1 - offset);
} // 注意最后一段也需要移动,所以这里用了do-while循环,与前面不一样
r_last = r++; // 更新记录上次的r,并需要让r向前移动(因为V[r]并没有被实际删除)
} while (r < V.size());
V.resize(V.size() - offset); // 直接修改V的规模,丢弃后面的元素。因为后面不满足P的元素已经被移动到前面去了
} // find_if加起来只遍历了V一次,copy加起来也只遍历了V一次
};
// 第三种想法:全局查找、全局删除 的 另一种实现形式(快慢指针)
// 快指针查找,慢指针赋值,写法更加简洁
template <typename T>
class BatchRemoveGFGR_FSP : public BatchRemove<T> {
protected:
virtual void batchRemove(Vector<T>& V, const Predicate<T>& P) override {
auto it_assign = begin(V); // 赋值指针(慢指针)
for (auto it_find = begin(V); it_find != end(V); it_find++) { // 查找指针(快指针)
if (!P(*it_find)) { // 如果是不会被删除的元素
*(it_assign++) = *it_find; // 则将其赋值到赋值指针的位置上
} // 否则将其丢弃,赋值指针不移动
}
V.resize(it_assign - begin(V)); // 修改V的规模,丢弃后面的元素
}
};
int testData[] { 10, 100, 1000, 10000, 100'000 }; // 测试的向量规模
bool is_even(const int& x) { return x % 2 == 0; } // 测试用例:删除所有的偶数
int main() {
TestFramework<BatchRemove<int>,
BatchRemoveSFSR<int>,
BatchRemoveGFSR<int>,
BatchRemoveGFGR<int>,
BatchRemoveGFGR_FSP<int>> tf;
for (int n : testData) {
cout << "Testing n = " << n << endl;
Vector<int> V(n);
for (int i = 0; i < n; i++) V[i] = i;
tf.test(V, is_even);
}
}
| 34.020408 | 89 | 0.561188 | ClazyChen |
8d0c3ba96fea566fbc08b8183a54c9ea9e979db9 | 492 | cpp | C++ | agent/browser/ie/urlBlast/UrlMgrBase.cpp | LeeLiangze/web_test | 50ce21afb153b105569e31ef08ddc098743208e5 | [
"IJG"
] | null | null | null | agent/browser/ie/urlBlast/UrlMgrBase.cpp | LeeLiangze/web_test | 50ce21afb153b105569e31ef08ddc098743208e5 | [
"IJG"
] | null | null | null | agent/browser/ie/urlBlast/UrlMgrBase.cpp | LeeLiangze/web_test | 50ce21afb153b105569e31ef08ddc098743208e5 | [
"IJG"
] | null | null | null | #include "StdAfx.h"
#include "UrlMgrBase.h"
CUrlMgrBase::CUrlMgrBase(CLog &logRef):log(logRef)
{
// create a NULL DACL we will re-use everywhere we do file access
ZeroMemory(&nullDacl, sizeof(nullDacl));
nullDacl.nLength = sizeof(nullDacl);
nullDacl.bInheritHandle = FALSE;
if( InitializeSecurityDescriptor(&SD, SECURITY_DESCRIPTOR_REVISION) )
if( SetSecurityDescriptorDacl(&SD, TRUE,(PACL)NULL, FALSE) )
nullDacl.lpSecurityDescriptor = &SD;
}
CUrlMgrBase::~CUrlMgrBase(void)
{
}
| 27.333333 | 70 | 0.75813 | LeeLiangze |
8d0cb3c9044dbd57d589ec19765b3416ab0e9938 | 25,926 | cc | C++ | src/compiler.cc | asakidaisuke/levi | 3e7ec7176d4d58b9685e01a5c9c195cfa0cdba2e | [
"MIT"
] | null | null | null | src/compiler.cc | asakidaisuke/levi | 3e7ec7176d4d58b9685e01a5c9c195cfa0cdba2e | [
"MIT"
] | null | null | null | src/compiler.cc | asakidaisuke/levi | 3e7ec7176d4d58b9685e01a5c9c195cfa0cdba2e | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include "compiler.hpp"
#include "scanner.hpp"
using namespace std::placeholders;
void Compiler::add_this_to_compiler(FunctionType type){
int index = currentCompiler->compilerState.localCount++;
Local* local = ¤tCompiler->compilerState.locals[index];
local->depth = 0;
local->isCaptured = false;
if(type != TYPE_FUNCTION){
std::string* this_ = new std::string("this");
local->name.start = this_->begin();
local->name.length = 4;
}else{
std::string* none = new std::string("");
local->name.start = none->begin();
local->name.length = 0;
}
}
void Compiler::setCurrent(Compiler* compiler){
currentCompiler = compiler;
}
void Compiler::advance(){
parser.previous = parser.current;
for(;;){
parser.current = scanner.scanToken();
if(parser.current.type != TOKEN_ERROR) break;
errorAtCurrent(
std::string(
parser.current.start,
parser.current.start + parser.current.length)
);
}
}
void Compiler::consume(TokenType type, std::string message){
if(parser.current.type == type){
advance();
return;
}
errorAtCurrent(message);
}
bool Compiler::match(TokenType type){
if(!check(type)) return false;
advance();
return true;
}
bool Compiler::check(TokenType type){
return parser.current.type == type;
}
Chunk* Compiler::currentChunk(){
return currentCompiler->compilerState.function->chunk.get();
}
ObjFunction* Compiler::endCompiler(){
emitReturn();
ObjFunction* local_function = currentCompiler->compilerState.function;
#ifdef DEBUG_PRINT_CODE
if (!parser.hadError){
disassembleChunk(local_function->name, local_function->chunk.get());
}
#endif
return local_function;
}
void Compiler::binary(){
TokenType operatorType = parser.previous.type;
ParseRule* rule = getRule(operatorType);
parsePrecedence((Precedence)(rule->precedence + 1));
switch(operatorType){
case TOKEN_BANG_EQUAL:{
emitByte(OP_EQUAL);
emitByte(OP_NOT);
break;}
case TOKEN_EQUAL_EQUAL:
emitByte(OP_EQUAL); break;
case TOKEN_GREATER:
emitByte(OP_GREATER); break;
case TOKEN_GREATER_EQUAL:{
emitByte(OP_LESS);
emitByte(OP_NOT);
break;}
case TOKEN_LESS:
emitByte(OP_LESS); break;
case TOKEN_LESS_EQUAL:{
emitByte(OP_GREATER);
emitByte(OP_NOT);
break;}
case TOKEN_PLUS: emitByte(OP_ADD); break;
case TOKEN_MINUS: emitByte(OP_SUBTRACT); break;
case TOKEN_STAR: emitByte(OP_MULTIPLY); break;
case TOKEN_SLASH: emitByte(OP_DIVIDE); break;
default: return;
}
}
void Compiler::expression(){
parsePrecedence(PREC_ASSIGNMENT);
}
Token Compiler::syntheticToken(std::string text){
Token token;
token.start = text.begin();
token.length = text.size();
return token;
}
void Compiler::printStatement(){
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after value.");
emitByte(OP_PRINT);
}
void Compiler::forStatement(){
beginScope();
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
if(match(TOKEN_SEMICOLON)){
} else if(match(TOKEN_VAR)){
varDeclaration();
} else {
expressionStatement();
}
int loopStart = currentChunk()->getChunk()->size();
int exitJump = -1;
if(!match(TOKEN_SEMICOLON)){
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after loop condition.");
exitJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
}
if (!match(TOKEN_RIGHT_PAREN)) {
int bodyJump = emitJump(OP_JUMP);
int incrementStart = currentChunk()->getChunk()->size();
expression();
emitByte(OP_POP);
consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
emitLoop(loopStart);
loopStart = incrementStart;
patchJump(bodyJump);
}
statement();
emitLoop(loopStart);
if(exitJump != -1){
patchJump(exitJump);
emitByte(OP_POP);
}
endScope();
}
void Compiler::whileStatement(){
int loopStart = currentChunk()->getChunk()->size();
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
int exitJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
statement();
emitLoop(loopStart);
patchJump(exitJump);
emitByte(OP_POP);
}
void Compiler::expressionStatement(){
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after expression.");
emitByte(OP_POP);
}
void Compiler::ifStatement(){
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'if'.");
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
int thenJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
statement();
int elseJump = emitJump(OP_JUMP);
patchJump(thenJump);
emitByte(OP_POP);
if(match(TOKEN_ELSE)) statement();
patchJump(elseJump);
}
void Compiler::returnStatement(){
if(currentCompiler->compilerState.type == TYPE_SCRIPT){
error("Can't return from top-level code.");
}
if (match(TOKEN_SEMICOLON)) {
emitReturn();
} else {
if (currentCompiler->compilerState.type == TYPE_INITIALIZER) {
error("Can't return a value from an initializer.");
}
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after return value.");
emitByte(OP_RETURN);
}
}
void Compiler::statement(){
if(match(TOKEN_PRINT)){
printStatement();
}else if(match(TOKEN_IF)){
ifStatement();
}else if(match(TOKEN_WHILE)){
whileStatement();
}else if(match(TOKEN_FOR)){
forStatement();
}else if(match(TOKEN_RETURN)){
returnStatement();
}else if(match(TOKEN_LEFT_BRACE)){
beginScope();
block();
endScope();
}else{
expressionStatement();
}
}
void Compiler::beginScope(){
currentCompiler->compilerState.scopeDepth++;
}
void Compiler::endScope(){
currentCompiler->compilerState.scopeDepth--;
while(compilerState.localCount > 0 && compilerState.locals[compilerState.localCount-1].depth >
compilerState.scopeDepth){
if (currentCompiler->compilerState.locals[currentCompiler->compilerState.localCount-1].isCaptured){
emitByte(OP_CLOSE_UPVALUE);
}else{
emitByte(OP_POP);
}
compilerState.localCount--;
}
}
void Compiler::block(){
while(!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)){
declaration();
}
consume(TOKEN_RIGHT_BRACE, "Expect '}' after block." );
}
void Compiler::method(){
consume(TOKEN_IDENTIFIER, "Expect method name.");
uint8_t constant = identifierConstant(&parser.previous);
FunctionType type = TYPE_METHOD;
if(parser.previous.length == 4 &&\
std::string(parser.previous.start,
parser.previous.start + parser.previous.length) ==\
std::string("init")){
type = TYPE_INITIALIZER;
}
function(type);
emitByte(OP_METHOD);
emitByte(constant);
}
void Compiler::classDeclaration(){
consume(TOKEN_IDENTIFIER, "Expect class name");
Token className = parser.previous;
uint8_t nameConstant = identifierConstant(&parser.previous);
declareVariable();
emitByte(OP_CLASS);
emitByte(nameConstant);
defineVariable(nameConstant);
ClassCompiler classCompiler;
classCompiler.enclosing = currentClass;
currentClass = &classCompiler;
if(match(TOKEN_LESS)){
consume(TOKEN_IDENTIFIER, "Expect superclass name.");
variable(false);
if(identifierEqual(&className, &parser.previous)){
error("A class can't inherit from itself.");
}
beginScope();
addLocal(syntheticToken("super"));
defineVariable(0);
namedVariable(className, false);
emitByte(OP_INHERIT);
classCompiler.hasSuperclass = true;
}
namedVariable(className, false);
consume(TOKEN_LEFT_BRACE, "Expect '{' before class body.");
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)){
method();
}
consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");
emitByte(OP_POP);
currentClass = currentClass->enclosing;
}
void Compiler::varDeclaration(){
uint8_t global = parseVariable("Expect variable name.");
if(match(TOKEN_EQUAL)){
expression();
}else{
emitByte(OP_NIL);
}
consume(TOKEN_SEMICOLON, "Expect ';' after variable declaration.");
defineVariable(global);
}
void Compiler::funDeclaration(){
uint8_t global = parseVariable("Expect function name.");
markInitialized();
function(TYPE_FUNCTION);
defineVariable(global);
}
void Compiler::declaration(){
if (match(TOKEN_VAR)){
varDeclaration();
}else if(match(TOKEN_FUN)){
funDeclaration();
}else if(match(TOKEN_CLASS)){
classDeclaration();
}else{
statement();
}
if(parser.panicMode) synchronize();
}
void Compiler::synchronize(){
parser.panicMode = false;
while(parser.current.type != TOKEN_EOF){
if(parser.previous.type == TOKEN_SEMICOLON) exit(1);
switch(parser.current.type){
case TOKEN_CLASS:
case TOKEN_FUN:
case TOKEN_VAR:
case TOKEN_FOR:
case TOKEN_IF:
case TOKEN_WHILE:
case TOKEN_PRINT:
case TOKEN_RETURN:
return;
default:
;
}
advance();
}
}
uint8_t Compiler::makeConstant(value_t val) {
int constant = currentChunk()->addConstantToValue(val);
if (constant > UINT8_MAX) {
error("Too many constants in one chunk.");
return 0;
}
return (uint8_t)constant;
}
void Compiler::string(){
ObjString* objString = new ObjString;
Object::getObjString(
std::string(parser.previous.start + 1,
parser.previous.start + parser.previous.length-1),
objString
);
emitConstant(OBJ_VAL(objString));
}
int Compiler::resolveLocal(CompilerState* compilerState, Token* name){
for(int i = compilerState->localCount-1; i >=0; i--){
Local* local = &compilerState->locals[i];
if (identifierEqual(name, &local->name)){
if(local->depth == -1){
error("Cant't read local variable in its own initializer.");
}
return i;
}
}
return -1;
}
int Compiler::resolveUpvalue(Compiler* compiler, Token* name){
if(compiler->encloseCompiler == NULL) return -1;
int local = resolveLocal(&compiler->encloseCompiler->compilerState, name);
if(local != -1){
compiler->encloseCompiler->compilerState.locals[local].isCaptured = true;
return addUpvalue(compiler, (uint8_t)local, true);
}
return -1;
}
int Compiler::addUpvalue(Compiler* compiler, uint8_t index, bool isLocal){
int upvalueCount = compiler->compilerState.function->upvalueCount;
for (int i = 0; i < upvalueCount; i++) {
Upvalue* upvalue = &compiler->compilerState.upvalues[i];
if (upvalue->index == index && upvalue->isLocal == isLocal) {
return i;
}
}
if(upvalueCount == UINT8_COUNT){
error("Too many closure variables in function.");
return 0;
}
compiler->compilerState.upvalues[upvalueCount].isLocal = isLocal;
compiler->compilerState.upvalues[upvalueCount].index = index;
return compiler->compilerState.function->upvalueCount++;
}
void Compiler::namedVariable(Token name, bool canAssign){
uint8_t getOp, setOp;
int arg = resolveLocal(¤tCompiler->compilerState, &name);
if(arg != -1){
getOp = OP_GET_LOCAL;
setOp = OP_SET_LOCAL;
}else if((arg = resolveUpvalue(currentCompiler, &name)) != -1){
getOp = OP_GET_UPVALUE;
setOp = OP_SET_UPVALUE;
}else{
arg = identifierConstant(&name);
getOp = OP_GET_GLOBAL;
setOp = OP_SET_GLOBAL;
}
if(canAssign && match(TOKEN_EQUAL)){
expression();
emitByte(setOp);
emitByte((uint8_t)arg);
}else{
emitByte(getOp);
emitByte((uint8_t)arg);
}
}
void Compiler::variable(bool canAssign){
namedVariable(parser.previous, canAssign);
}
void Compiler::number(){
double value = std::stod(
std::string(
parser.previous.start,
parser.previous.start + parser.previous.length
));
emitConstant(NUMBER_VAL(value));
}
void Compiler::literal(){
switch(parser.previous.type){
case TOKEN_FALSE: emitByte(OP_FALSE); break;
case TOKEN_NIL: emitByte(OP_NIL); break;
case TOKEN_TRUE: emitByte(OP_TRUE); break;
default: return;
}
}
void Compiler::function(FunctionType type){
Compiler compiler(source);
Compiler* temp = currentCompiler; // move current one
Compiler** temp_ptr = ¤tCompiler;
Compiler* new_ptr = &compiler;
*temp_ptr = new_ptr;
// add name of the function
currentCompiler->encloseCompiler = temp;
currentCompiler->compilerState.function->name =\
std::string(parser.previous.start,
parser.previous.start + parser.previous.length);
currentCompiler->compilerState.type = type;
beginScope();
add_this_to_compiler(type);
consume(TOKEN_LEFT_PAREN, "Expect '(' after function name.");
if(!check(TOKEN_RIGHT_PAREN)){
do {
currentCompiler->compilerState.function->arity++;
if(currentCompiler->compilerState.function->arity > 255){
errorAtCurrent("Can't have more than parameter name.");
}
uint8_t constant = parseVariable("Expect parameter name.");
defineVariable(constant);
} while(match(TOKEN_COMMA));
}
consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters.");
consume(TOKEN_LEFT_BRACE, "Expect '{' before function body.");
block();
ObjFunction* function = endCompiler();
currentCompiler = currentCompiler->encloseCompiler; // regain current one
emitByte(OP_CLOSURE);
emitByte(makeConstant(OBJ_VAL(function)));
for (int i = 0; i < function->upvalueCount; i++){
emitByte(compiler.compilerState.upvalues[i].isLocal ? 1 : 0);
emitByte(compiler.compilerState.upvalues[i].index);
}
}
void Compiler::call(bool canAssign){
uint8_t argCount = argumentList();
emitByte(OP_CALL);
emitByte(argCount);
}
void Compiler::dot(bool canAssign){
consume(TOKEN_IDENTIFIER, "Expect property name after '.'.");
uint8_t name = identifierConstant(&parser.previous);
if(canAssign && match(TOKEN_EQUAL)){
expression();
emitByte(OP_SET_PROPERTY);
emitByte(name);
}else if(match(TOKEN_LEFT_PAREN)){
uint8_t argCount = argumentList();
emitByte(OP_INVOKE);
emitByte(name);
emitByte(argCount);
}else{
emitByte(OP_GET_PROPERTY);
emitByte(name);
}
}
uint8_t Compiler::argumentList(){
uint8_t argCount = 0;
if(!check(TOKEN_RIGHT_PAREN)){
do {
expression();
if(argCount == 255){
error("Can't have more than 255 arguments.");
}
argCount++;
} while(match(TOKEN_COMMA));
}
consume(TOKEN_RIGHT_PAREN, "Expect ')' after arguments.");
return argCount;
}
void Compiler::patchJump(int offset){
int jump = currentChunk()->getChunk()->size() - offset - 2;
if(jump > UINT16_MAX){
error("Too much code to jump over.");
}
(*currentChunk()->getChunk())[offset] = (jump >> 8) & 0xff;
(*currentChunk()->getChunk())[offset+1] = jump & 0xff;
}
int Compiler::emitJump(uint8_t instruction){
emitByte(instruction);
emitByte(0xff);
emitByte(0xff);
return currentChunk()->getChunk()->size() - 2;
}
void Compiler::emitConstant(value_t input_val){
currentChunk()->writeChunk(OP_CONSTANT, parser.previous.line);
currentChunk()->writeValue(input_val, parser.previous.line);
}
void Compiler::emitByte(uint8_t op_code){
currentChunk()->writeChunk(op_code, parser.previous.line);
}
void Compiler::emitLoop(int loopStart){
emitByte(OP_LOOP);
int offset = currentChunk()->getChunk()->size() - loopStart + 2;
if(offset > UINT16_MAX) error("Loop body too large.");
emitByte((offset >> 8) & 0xff);
emitByte(offset & 0xff);
}
void Compiler::emitReturn(){
if(currentCompiler->compilerState.type == TYPE_INITIALIZER){
emitByte(OP_GET_LOCAL);
emitByte(0);
}else{
emitByte(OP_NIL);
}
emitByte(OP_RETURN);
}
void Compiler::grouping(){
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.");
}
void Compiler::unary(){
TokenType operatorType = parser.previous.type;
expression();
switch(operatorType){
case TOKEN_BANG:{
emitByte(OP_NOT);
break;
}
case TOKEN_MINUS: {
emitByte(OP_NEGATE);
break;}
default:
return;
}
}
uint8_t Compiler::parseVariable(std::string errorMessage){
consume(TOKEN_IDENTIFIER, errorMessage);
declareVariable();
if(currentCompiler->compilerState.scopeDepth > 0) return 0;
return identifierConstant(&parser.previous);
}
void Compiler::markInitialized(){
currentCompiler->compilerState.locals[currentCompiler->compilerState.localCount-1].depth = currentCompiler->compilerState.scopeDepth;
}
bool Compiler::identifierEqual(Token* a, Token* b){
if(a->length != b->length) return false;
return std::string(a->start, a->start + a->length) == \
std::string(b->start, b->start + b->length);
}
void Compiler::declareVariable(){
if(currentCompiler->compilerState.scopeDepth == 0) return;
Token* name = &parser.previous;
// look above level local variable
for(int i=currentCompiler->compilerState.localCount-1; i>=0; i--){
Local* local = ¤tCompiler->compilerState.locals[i];
if(local->depth != -1 && local->depth < currentCompiler->compilerState.scopeDepth){
break;
}
if(identifierEqual(name, &local->name)){
error("Already a variable with this name in this scope.");
}
}
addLocal(*name);
}
void Compiler::addLocal(Token name){
if(currentCompiler->compilerState.localCount == UINT8_COUNT){
error("Too many local variables in function.");
return;
}
Local* local = ¤tCompiler->compilerState.locals[currentCompiler->compilerState.localCount++];
local->name = name;
local->depth = currentCompiler->compilerState.scopeDepth;
local->isCaptured = false;
}
void Compiler::defineVariable(uint8_t global){
if(currentCompiler->compilerState.scopeDepth > 0){
markInitialized();
return;
}
emitByte(OP_DEFINE_GLOBAL);
emitByte(global);
}
void Compiler::and_(bool canAssign){
int endJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
parsePrecedence(PREC_AND);
patchJump(endJump);
}
void Compiler::or_(bool canAssign){
int elseJump = emitJump(OP_JUMP_IF_FALSE);
int endJump = emitJump(OP_JUMP);
patchJump(elseJump);
emitByte(OP_POP);
parsePrecedence(PREC_OR);
patchJump(endJump);
}
void Compiler::this_(bool canAssign){
if(currentClass==NULL){
error("Can't use 'this' outside of a class.");
return;
}
variable(false);
}
void Compiler::super_(bool canAssign){
if(currentClass == NULL){
error("Can't use 'super' outside of a class.");
}else if(!currentClass->hasSuperclass){
error("Can't use 'super' in a class with no superclass.");
}
consume(TOKEN_DOT, "Expect '.' after 'super'.");
consume(TOKEN_IDENTIFIER, "Expect superclass method name.");
uint8_t name = identifierConstant(&parser.previous);
namedVariable(syntheticToken("this"), false);
if (match(TOKEN_LEFT_PAREN)) {
uint8_t argCount = argumentList();
namedVariable(syntheticToken("super"), false);
emitByte(OP_SUPER_INVOKE);
emitByte(name);
emitByte(argCount);
} else {
namedVariable(syntheticToken("super"), false);
emitByte(OP_GET_SUPER);
emitByte(name);
}
}
uint8_t Compiler::identifierConstant(Token* name){
ObjString* objString = new ObjString;
Object::getObjString(
std::string(name->start, name->start + name->length),
objString
);
return makeConstant(OBJ_VAL(objString));
}
void Compiler::parsePrecedence(Precedence precedence){
advance();
auto prefixRule = getRule(parser.previous.type)->prefix;
if(prefixRule == NULL){
error("Expect expression.");
return;
}
prefixRule();
while(precedence <= getRule(parser.current.type)->precedence){
advance();
auto infixRule = getRule(parser.previous.type)->infix;
infixRule();
}
}
ParseRule* Compiler::getRule(TokenType type){
return &rules[type];
}
void Compiler::errorAt(Token* token, std::string message){
if(parser.panicMode) return;
parser.panicMode = true;
std::cout << "[line " << token->line << "] Error";
if(token->type == TOKEN_EOF){
std::cout << " at end" << std::endl;
}else if(token->type == TOKEN_ERROR){
// Nothing
}else{
std::cout << ": " << message << std::endl;
}
parser.hadError = true;
}
ObjFunction* Compiler::compile(std::string source){
// make one element room of first local value
// this is to enable "this"
currentCompiler->compilerState.localCount++;
advance();
while(!match(TOKEN_EOF)){
declaration();
}
ObjFunction* function = endCompiler();
if(parser.hadError) return NULL;
return function;
}
void Compiler::init_rules(){
rules[TOKEN_LEFT_PAREN] = ParseRule{
std::bind(&Compiler::grouping, this), std::bind(&Compiler::call, this, true), PREC_CALL};
rules[TOKEN_RIGHT_PAREN] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_LEFT_BRACE] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_RIGHT_BRACE] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_COMMA] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_DOT] = ParseRule{
NULL, std::bind(&Compiler::dot, this, true), PREC_CALL};
rules[TOKEN_MINUS] = ParseRule{
std::bind(&Compiler::unary, this), std::bind(&Compiler::binary, this), PREC_TERM};
rules[TOKEN_PLUS] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_TERM};
rules[TOKEN_SEMICOLON] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_SLASH] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_FACTOR};
rules[TOKEN_STAR] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_FACTOR};
rules[TOKEN_BANG] = ParseRule{
std::bind(&Compiler::unary, this), NULL, PREC_NONE};
rules[TOKEN_BANG_EQUAL] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_EQUALITY};
rules[TOKEN_EQUAL] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_EQUAL_EQUAL] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_COMPARISON};
rules[TOKEN_GREATER] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_COMPARISON};
rules[TOKEN_GREATER_EQUAL] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_COMPARISON};
rules[TOKEN_LESS] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_COMPARISON};
rules[TOKEN_LESS_EQUAL] = ParseRule{
NULL, std::bind(&Compiler::binary, this), PREC_COMPARISON};
rules[TOKEN_IDENTIFIER] = ParseRule{
std::bind(&Compiler::variable, this, true), NULL, PREC_NONE};
rules[TOKEN_STRING] = ParseRule{
std::bind(&Compiler::string, this), NULL, PREC_NONE};
rules[TOKEN_NUMBER] = ParseRule{
std::bind(&Compiler::number, this), NULL, PREC_NONE};
rules[TOKEN_AND] = ParseRule{
NULL, std::bind(&Compiler::and_, this, true), PREC_AND};
rules[TOKEN_CLASS] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_ELSE] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_FALSE] = ParseRule{
std::bind(&Compiler::literal, this), NULL, PREC_NONE};
rules[TOKEN_FOR] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_FUN] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_IF] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_NIL] = ParseRule{
std::bind(&Compiler::literal, this), NULL, PREC_NONE};
rules[TOKEN_OR] = ParseRule{
NULL, std::bind(&Compiler::or_, this, true), PREC_OR};
rules[TOKEN_PRINT] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_RETURN] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_SUPER] = ParseRule{
std::bind(&Compiler::super_, this, true), NULL, PREC_NONE};
rules[TOKEN_THIS] = ParseRule{
std::bind(&Compiler::this_, this, true), NULL, PREC_NONE};
rules[TOKEN_TRUE] = ParseRule{
std::bind(&Compiler::literal, this), NULL, PREC_NONE};
rules[TOKEN_VAR] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_WHILE] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_ERROR] = ParseRule{
NULL, NULL, PREC_NONE};
rules[TOKEN_EOF] = ParseRule{
NULL, NULL, PREC_NONE};
}
| 29.461364 | 137 | 0.629831 | asakidaisuke |
8d0e1faf5f399197e5b2c1b98f94b393417f43f7 | 2,424 | cpp | C++ | 05-Functions/Program_6-19.cpp | ringosimonchen0820/How-to-C-- | 69b0310e6aeab25a7e2eed41e4d6cff85a034e00 | [
"MIT"
] | null | null | null | 05-Functions/Program_6-19.cpp | ringosimonchen0820/How-to-C-- | 69b0310e6aeab25a7e2eed41e4d6cff85a034e00 | [
"MIT"
] | 1 | 2020-10-11T18:39:08.000Z | 2020-10-11T18:39:17.000Z | 05-Functions/Program_6-19.cpp | ringosimonchen0820/How-to-C-- | 69b0310e6aeab25a7e2eed41e4d6cff85a034e00 | [
"MIT"
] | 2 | 2020-10-12T20:33:32.000Z | 2020-10-12T20:34:00.000Z | // This program calculates gross pay.
#include <iostream>
#include <iomanip>
using namespace std;
// Global constatns
const double PAY_RATE = 22.55; // Hourly pay rate
const double BASE_HOURS = 40.0; // Max non-overtime hours
const double OT_MULTIPLIER = 1.5; // Overtime multiplier
// Function prototypes
double getBasePay(double);
double getOvertimePay(double);
int main()
{
double hours, // Hours worked
basePay, // Base pay
overtime = 0.0, // Overtime pay
totalPay; // Total pay
// Get the number of hours worked.
cout << "How many hours did you work? ";
cin >> hours;
// Get the amount of base pay.
basePay = getBasePay(hours);
// Get overtimePay, if any.
if (hours > BASE_HOURS)
overtime = getOvertimePay(hours);
// Calculate the total pay.
totalPay = basePay + overtime;
// Set up numeric output formatting.
cout << setprecision(2) << fixed << showpoint;
// Display the pay.
cout << "Base pay: $" << basePay << endl
<< "Overtime pay $" << overtime << endl
<< "Total pay $" << totalPay << endl;
return 0;
}
//********************************************************
//* The getBasePay function accepts the number of hours *
//* worked as an argument and returns the employee's *
//* pay for non-overtime houes. *
//********************************************************
double getBasePay(double hoursWorked)
{
double basePay; // To hold base pay
// Determine base pay.
if (hoursWorked > BASE_HOURS)
basePay = BASE_HOURS * PAY_RATE;
else
basePay = hoursWorked * PAY_RATE;
return basePay;
}
//********************************************************
//* The getOvertimePay function accepts the number *
//* of hours worked as an argument and returns the *
//* employee's overtime pay. *
//********************************************************
double getOvertimePay(double hoursWorked)
{
double overtimePay; // To hold overtime pay
// Determine overtime pay.
if (hoursWorked > BASE_HOURS)
{
overtimePay = (hoursWorked - BASE_HOURS) * PAY_RATE * OT_MULTIPLIER;
}
else
overtimePay = 0.0;
return overtimePay;
} | 27.235955 | 76 | 0.52929 | ringosimonchen0820 |
8d120de691074bde58afcc466e3bde6c9af0f678 | 64,592 | cpp | C++ | src/add-ons/kernel/file_systems/bfs/kernel_interface.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | 2 | 2021-11-30T22:17:42.000Z | 2022-02-04T20:57:17.000Z | src/add-ons/kernel/file_systems/bfs/kernel_interface.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | null | null | null | src/add-ons/kernel/file_systems/bfs/kernel_interface.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | null | null | null | /*
* Copyright 2001-2020, Axel Dörfler, axeld@pinc-software.de.
* This file may be used under the terms of the MIT License.
*/
//! file system interface to Haiku's vnode layer
#include "Attribute.h"
#include "CheckVisitor.h"
#include "Debug.h"
#include "Volume.h"
#include "Inode.h"
#include "Index.h"
#include "BPlusTree.h"
#include "Query.h"
#include "ResizeVisitor.h"
#include "bfs_control.h"
#include "bfs_disk_system.h"
// TODO: temporary solution as long as there is no public I/O requests API
#ifndef FS_SHELL
# include <io_requests.h>
# include <util/fs_trim_support.h>
#endif
#define BFS_IO_SIZE 65536
#if defined(BFS_LITTLE_ENDIAN_ONLY)
#define BFS_ENDIAN_SUFFIX ""
#define BFS_ENDIAN_PRETTY_SUFFIX ""
#else
#define BFS_ENDIAN_SUFFIX "_big"
#define BFS_ENDIAN_PRETTY_SUFFIX " (Big Endian)"
#endif
struct identify_cookie {
disk_super_block super_block;
};
extern void fill_stat_buffer(Inode* inode, struct stat& stat);
static void
fill_stat_time(const bfs_inode& node, struct stat& stat)
{
bigtime_t now = real_time_clock_usecs();
stat.st_atim.tv_sec = now / 1000000LL;
stat.st_atim.tv_nsec = (now % 1000000LL) * 1000;
stat.st_mtim.tv_sec = bfs_inode::ToSecs(node.LastModifiedTime());
stat.st_mtim.tv_nsec = bfs_inode::ToNsecs(node.LastModifiedTime());
stat.st_crtim.tv_sec = bfs_inode::ToSecs(node.CreateTime());
stat.st_crtim.tv_nsec = bfs_inode::ToNsecs(node.CreateTime());
// For BeOS compatibility, if on-disk ctime is invalid, fall back to mtime:
bigtime_t changeTime = node.StatusChangeTime();
if (changeTime < node.LastModifiedTime())
stat.st_ctim = stat.st_mtim;
else {
stat.st_ctim.tv_sec = bfs_inode::ToSecs(changeTime);
stat.st_ctim.tv_nsec = bfs_inode::ToNsecs(changeTime);
}
}
void
fill_stat_buffer(Inode* inode, struct stat& stat)
{
const bfs_inode& node = inode->Node();
stat.st_dev = inode->GetVolume()->ID();
stat.st_ino = inode->ID();
stat.st_nlink = 1;
stat.st_blksize = BFS_IO_SIZE;
stat.st_uid = node.UserID();
stat.st_gid = node.GroupID();
stat.st_mode = node.Mode();
stat.st_type = node.Type();
fill_stat_time(node, stat);
if (inode->IsSymLink() && (inode->Flags() & INODE_LONG_SYMLINK) == 0) {
// symlinks report the size of the link here
stat.st_size = strlen(node.short_symlink);
} else
stat.st_size = inode->Size();
stat.st_blocks = inode->AllocatedSize() / 512;
}
//! bfs_io() callback hook
static status_t
iterative_io_get_vecs_hook(void* cookie, io_request* request, off_t offset,
size_t size, struct file_io_vec* vecs, size_t* _count)
{
Inode* inode = (Inode*)cookie;
return file_map_translate(inode->Map(), offset, size, vecs, _count,
inode->GetVolume()->BlockSize());
}
//! bfs_io() callback hook
static status_t
iterative_io_finished_hook(void* cookie, io_request* request, status_t status,
bool partialTransfer, size_t bytesTransferred)
{
Inode* inode = (Inode*)cookie;
rw_lock_read_unlock(&inode->Lock());
return B_OK;
}
// #pragma mark - Scanning
static float
bfs_identify_partition(int fd, partition_data* partition, void** _cookie)
{
disk_super_block superBlock;
status_t status = Volume::Identify(fd, &superBlock);
if (status != B_OK)
return -1;
identify_cookie* cookie = new(std::nothrow) identify_cookie;
if (cookie == NULL)
return -1;
memcpy(&cookie->super_block, &superBlock, sizeof(disk_super_block));
*_cookie = cookie;
return 0.85f;
}
static status_t
bfs_scan_partition(int fd, partition_data* partition, void* _cookie)
{
identify_cookie* cookie = (identify_cookie*)_cookie;
partition->status = B_PARTITION_VALID;
partition->flags |= B_PARTITION_FILE_SYSTEM;
partition->content_size = cookie->super_block.NumBlocks()
* cookie->super_block.BlockSize();
partition->block_size = cookie->super_block.BlockSize();
partition->content_name = strdup(cookie->super_block.name);
if (partition->content_name == NULL)
return B_NO_MEMORY;
return B_OK;
}
static void
bfs_free_identify_partition_cookie(partition_data* partition, void* _cookie)
{
identify_cookie* cookie = (identify_cookie*)_cookie;
delete cookie;
}
// #pragma mark -
static status_t
bfs_mount(fs_volume* _volume, const char* device, uint32 flags,
const char* args, ino_t* _rootID)
{
FUNCTION();
Volume* volume = new(std::nothrow) Volume(_volume);
if (volume == NULL)
return B_NO_MEMORY;
status_t status = volume->Mount(device, flags);
if (status != B_OK) {
delete volume;
RETURN_ERROR(status);
}
_volume->private_volume = volume;
_volume->ops = &gBFSVolumeOps;
*_rootID = volume->ToVnode(volume->Root());
INFORM(("mounted \"%s\" (root node at %" B_PRIdINO ", device = %s)\n",
volume->Name(), *_rootID, device));
return B_OK;
}
static status_t
bfs_unmount(fs_volume* _volume)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
status_t status = volume->Unmount();
delete volume;
RETURN_ERROR(status);
}
static status_t
bfs_read_fs_stat(fs_volume* _volume, struct fs_info* info)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
MutexLocker locker(volume->Lock());
// File system flags.
info->flags = B_FS_IS_PERSISTENT | B_FS_HAS_ATTR | B_FS_HAS_MIME
| (volume->IndicesNode() != NULL ? B_FS_HAS_QUERY : 0)
| (volume->IsReadOnly() ? B_FS_IS_READONLY : 0)
| B_FS_SUPPORTS_MONITOR_CHILDREN;
info->io_size = BFS_IO_SIZE;
// whatever is appropriate here?
info->block_size = volume->BlockSize();
info->total_blocks = volume->NumBlocks();
info->free_blocks = volume->FreeBlocks();
// Volume name
strlcpy(info->volume_name, volume->Name(), sizeof(info->volume_name));
// File system name
strlcpy(info->fsh_name, "bfs", sizeof(info->fsh_name));
return B_OK;
}
static status_t
bfs_write_fs_stat(fs_volume* _volume, const struct fs_info* info, uint32 mask)
{
FUNCTION_START(("mask = %" B_PRId32 "\n", mask));
Volume* volume = (Volume*)_volume->private_volume;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
MutexLocker locker(volume->Lock());
status_t status = B_BAD_VALUE;
if (mask & FS_WRITE_FSINFO_NAME) {
disk_super_block& superBlock = volume->SuperBlock();
strncpy(superBlock.name, info->volume_name,
sizeof(superBlock.name) - 1);
superBlock.name[sizeof(superBlock.name) - 1] = '\0';
status = volume->WriteSuperBlock();
}
return status;
}
static status_t
bfs_sync(fs_volume* _volume)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
return volume->Sync();
}
// #pragma mark -
/*! Reads in the node from disk and creates an inode object from it.
*/
static status_t
bfs_get_vnode(fs_volume* _volume, ino_t id, fs_vnode* _node, int* _type,
uint32* _flags, bool reenter)
{
//FUNCTION_START(("ino_t = %Ld\n", id));
Volume* volume = (Volume*)_volume->private_volume;
// first inode may be after the log area, we don't go through
// the hassle and try to load an earlier block from disk
if (id < volume->ToBlock(volume->Log()) + volume->Log().Length()
|| id > volume->NumBlocks()) {
INFORM(("inode at %" B_PRIdINO " requested!\n", id));
return B_ERROR;
}
CachedBlock cached(volume);
status_t status = cached.SetTo(id);
if (status != B_OK) {
FATAL(("could not read inode: %" B_PRIdINO ": %s\n", id,
strerror(status)));
return status;
}
bfs_inode* node = (bfs_inode*)cached.Block();
status = node->InitCheck(volume);
if (status != B_OK) {
if ((node->Flags() & INODE_DELETED) != 0) {
INFORM(("inode at %" B_PRIdINO " is already deleted!\n", id));
} else {
FATAL(("inode at %" B_PRIdINO " could not be read: %s!\n", id,
strerror(status)));
}
return status;
}
Inode* inode = new(std::nothrow) Inode(volume, id);
if (inode == NULL)
return B_NO_MEMORY;
status = inode->InitCheck(false);
if (status != B_OK)
delete inode;
if (status == B_OK) {
_node->private_node = inode;
_node->ops = &gBFSVnodeOps;
*_type = inode->Mode();
*_flags = 0;
}
return status;
}
static status_t
bfs_put_vnode(fs_volume* _volume, fs_vnode* _node, bool reenter)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
// since a directory's size can be changed without having it opened,
// we need to take care about their preallocated blocks here
if (!volume->IsReadOnly() && !volume->IsCheckingThread()
&& inode->NeedsTrimming()) {
Transaction transaction(volume, inode->BlockNumber());
if (inode->TrimPreallocation(transaction) == B_OK)
transaction.Done();
else if (transaction.HasParent()) {
// TODO: for now, we don't let sub-transactions fail
transaction.Done();
}
}
delete inode;
return B_OK;
}
static status_t
bfs_remove_vnode(fs_volume* _volume, fs_vnode* _node, bool reenter)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
// If the inode isn't in use anymore, we were called before
// bfs_unlink() returns - in this case, we can just use the
// transaction which has already deleted the inode.
Transaction transaction(volume, volume->ToBlock(inode->Parent()));
// The file system check functionality uses this flag to prevent the space
// used up by the inode from being freed - this flag is set only in
// situations where this does not cause any harm as the block bitmap will
// get fixed anyway in this case).
if ((inode->Flags() & INODE_DONT_FREE_SPACE) != 0) {
delete inode;
return B_OK;
}
ASSERT((inode->Flags() & INODE_DELETED) != 0);
status_t status = inode->Free(transaction);
if (status == B_OK) {
status = transaction.Done();
} else if (transaction.HasParent()) {
// TODO: for now, we don't let sub-transactions fail
status = transaction.Done();
}
volume->RemovedInodes().Remove(inode);
// TODO: the VFS currently does not allow this to fail
delete inode;
return status;
}
static bool
bfs_can_page(fs_volume* _volume, fs_vnode* _v, void* _cookie)
{
// TODO: we're obviously not even asked...
return false;
}
static status_t
bfs_read_pages(fs_volume* _volume, fs_vnode* _node, void* _cookie,
off_t pos, const iovec* vecs, size_t count, size_t* _numBytes)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
if (inode->FileCache() == NULL)
RETURN_ERROR(B_BAD_VALUE);
InodeReadLocker _(inode);
uint32 vecIndex = 0;
size_t vecOffset = 0;
size_t bytesLeft = *_numBytes;
status_t status;
while (true) {
file_io_vec fileVecs[8];
size_t fileVecCount = 8;
status = file_map_translate(inode->Map(), pos, bytesLeft, fileVecs,
&fileVecCount, 0);
if (status != B_OK && status != B_BUFFER_OVERFLOW)
break;
bool bufferOverflow = status == B_BUFFER_OVERFLOW;
size_t bytes = bytesLeft;
status = read_file_io_vec_pages(volume->Device(), fileVecs,
fileVecCount, vecs, count, &vecIndex, &vecOffset, &bytes);
if (status != B_OK || !bufferOverflow)
break;
pos += bytes;
bytesLeft -= bytes;
}
return status;
}
static status_t
bfs_write_pages(fs_volume* _volume, fs_vnode* _node, void* _cookie,
off_t pos, const iovec* vecs, size_t count, size_t* _numBytes)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (inode->FileCache() == NULL)
RETURN_ERROR(B_BAD_VALUE);
InodeReadLocker _(inode);
uint32 vecIndex = 0;
size_t vecOffset = 0;
size_t bytesLeft = *_numBytes;
status_t status;
while (true) {
file_io_vec fileVecs[8];
size_t fileVecCount = 8;
status = file_map_translate(inode->Map(), pos, bytesLeft, fileVecs,
&fileVecCount, 0);
if (status != B_OK && status != B_BUFFER_OVERFLOW)
break;
bool bufferOverflow = status == B_BUFFER_OVERFLOW;
size_t bytes = bytesLeft;
status = write_file_io_vec_pages(volume->Device(), fileVecs,
fileVecCount, vecs, count, &vecIndex, &vecOffset, &bytes);
if (status != B_OK || !bufferOverflow)
break;
pos += bytes;
bytesLeft -= bytes;
}
return status;
}
static status_t
bfs_io(fs_volume* _volume, fs_vnode* _node, void* _cookie, io_request* request)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
#ifndef FS_SHELL
if (io_request_is_write(request) && volume->IsReadOnly()) {
notify_io_request(request, B_READ_ONLY_DEVICE);
return B_READ_ONLY_DEVICE;
}
#endif
if (inode->FileCache() == NULL) {
#ifndef FS_SHELL
notify_io_request(request, B_BAD_VALUE);
#endif
RETURN_ERROR(B_BAD_VALUE);
}
// We lock the node here and will unlock it in the "finished" hook.
rw_lock_read_lock(&inode->Lock());
return do_iterative_fd_io(volume->Device(), request,
iterative_io_get_vecs_hook, iterative_io_finished_hook, inode);
}
static status_t
bfs_get_file_map(fs_volume* _volume, fs_vnode* _node, off_t offset, size_t size,
struct file_io_vec* vecs, size_t* _count)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
int32 blockShift = volume->BlockShift();
uint32 index = 0, max = *_count;
block_run run;
off_t fileOffset;
//FUNCTION_START(("offset = %Ld, size = %lu\n", offset, size));
while (true) {
status_t status = inode->FindBlockRun(offset, run, fileOffset);
if (status != B_OK)
return status;
vecs[index].offset = volume->ToOffset(run) + offset - fileOffset;
vecs[index].length = ((uint32)run.Length() << blockShift)
- offset + fileOffset;
// are we already done?
if ((uint64)size <= (uint64)vecs[index].length
|| (uint64)offset + (uint64)vecs[index].length
>= (uint64)inode->Size()) {
if ((uint64)offset + (uint64)vecs[index].length
> (uint64)inode->Size()) {
// make sure the extent ends with the last official file
// block (without taking any preallocations into account)
vecs[index].length = round_up(inode->Size() - offset,
volume->BlockSize());
}
*_count = index + 1;
return B_OK;
}
offset += vecs[index].length;
size -= vecs[index].length;
index++;
if (index >= max) {
// we're out of file_io_vecs; let's bail out
*_count = index;
return B_BUFFER_OVERFLOW;
}
}
// can never get here
return B_ERROR;
}
// #pragma mark -
static status_t
bfs_lookup(fs_volume* _volume, fs_vnode* _directory, const char* file,
ino_t* _vnodeID)
{
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
InodeReadLocker locker(directory);
// check access permissions
status_t status = directory->CheckPermissions(X_OK);
if (status != B_OK)
RETURN_ERROR(status);
BPlusTree* tree = directory->Tree();
if (tree == NULL)
RETURN_ERROR(B_BAD_VALUE);
status = tree->Find((uint8*)file, (uint16)strlen(file), _vnodeID);
if (status != B_OK) {
//PRINT(("bfs_walk() could not find %Ld:\"%s\": %s\n", directory->BlockNumber(), file, strerror(status)));
if (status == B_ENTRY_NOT_FOUND)
entry_cache_add_missing(volume->ID(), directory->ID(), file);
return status;
}
entry_cache_add(volume->ID(), directory->ID(), file, *_vnodeID);
locker.Unlock();
Inode* inode;
status = get_vnode(volume->FSVolume(), *_vnodeID, (void**)&inode);
if (status != B_OK) {
REPORT_ERROR(status);
return B_ENTRY_NOT_FOUND;
}
return B_OK;
}
static status_t
bfs_get_vnode_name(fs_volume* _volume, fs_vnode* _node, char* buffer,
size_t bufferSize)
{
Inode* inode = (Inode*)_node->private_node;
return inode->GetName(buffer, bufferSize);
}
static status_t
bfs_ioctl(fs_volume* _volume, fs_vnode* _node, void* _cookie, uint32 cmd,
void* buffer, size_t bufferLength)
{
FUNCTION_START(("node = %p, cmd = %" B_PRIu32 ", buf = %p"
", len = %" B_PRIuSIZE "\n", _node, cmd, buffer, bufferLength));
Volume* volume = (Volume*)_volume->private_volume;
switch (cmd) {
#ifndef FS_SHELL
case B_TRIM_DEVICE:
{
fs_trim_data* trimData;
MemoryDeleter deleter;
status_t status = get_trim_data_from_user(buffer, bufferLength,
deleter, trimData);
if (status != B_OK)
return status;
trimData->trimmed_size = 0;
for (uint32 i = 0; i < trimData->range_count; i++) {
uint64 trimmedSize = 0;
status_t status = volume->Allocator().Trim(
trimData->ranges[i].offset, trimData->ranges[i].size,
trimmedSize);
if (status != B_OK)
return status;
trimData->trimmed_size += trimmedSize;
}
return copy_trim_data_to_user(buffer, trimData);
}
#endif
case BFS_IOCTL_VERSION:
{
uint32 version = 0x10000;
return user_memcpy(buffer, &version, sizeof(uint32));
}
case BFS_IOCTL_START_CHECKING:
{
// start checking
status_t status = volume->CreateCheckVisitor();
if (status != B_OK)
return status;
CheckVisitor* checker = volume->CheckVisitor();
if (user_memcpy(&checker->Control(), buffer,
sizeof(check_control)) != B_OK) {
return B_BAD_ADDRESS;
}
status = checker->StartBitmapPass();
if (status == B_OK) {
file_cookie* cookie = (file_cookie*)_cookie;
cookie->open_mode |= BFS_OPEN_MODE_CHECKING;
}
return status;
}
case BFS_IOCTL_STOP_CHECKING:
{
// stop checking
CheckVisitor* checker = volume->CheckVisitor();
if (checker == NULL)
return B_NO_INIT;
status_t status = checker->StopChecking();
if (status == B_OK) {
file_cookie* cookie = (file_cookie*)_cookie;
cookie->open_mode &= ~BFS_OPEN_MODE_CHECKING;
status = user_memcpy(buffer, &checker->Control(),
sizeof(check_control));
}
volume->DeleteCheckVisitor();
volume->SetCheckingThread(-1);
return status;
}
case BFS_IOCTL_CHECK_NEXT_NODE:
{
// check next
CheckVisitor* checker = volume->CheckVisitor();
if (checker == NULL)
return B_NO_INIT;
volume->SetCheckingThread(find_thread(NULL));
checker->Control().errors = 0;
status_t status = checker->Next();
if (status == B_ENTRY_NOT_FOUND) {
checker->Control().status = B_ENTRY_NOT_FOUND;
// tells StopChecking() that we finished the pass
if (checker->Pass() == BFS_CHECK_PASS_BITMAP) {
if (checker->WriteBackCheckBitmap() == B_OK)
status = checker->StartIndexPass();
}
}
if (status == B_OK) {
status = user_memcpy(buffer, &checker->Control(),
sizeof(check_control));
}
return status;
}
case BFS_IOCTL_UPDATE_BOOT_BLOCK:
{
// let's makebootable (or anyone else) update the boot block
// while BFS is mounted
update_boot_block update;
if (bufferLength != sizeof(update_boot_block))
return B_BAD_VALUE;
if (user_memcpy(&update, buffer, sizeof(update_boot_block)) != B_OK)
return B_BAD_ADDRESS;
uint32 minOffset = offsetof(disk_super_block, pad_to_block);
if (update.offset < minOffset
|| update.offset >= 512 || update.length > 512 - minOffset
|| update.length + update.offset > 512) {
return B_BAD_VALUE;
}
if (user_memcpy((uint8*)&volume->SuperBlock() + update.offset,
update.data, update.length) != B_OK) {
return B_BAD_ADDRESS;
}
return volume->WriteSuperBlock();
}
case BFS_IOCTL_RESIZE:
{
if (bufferLength != sizeof(uint64))
return B_BAD_VALUE;
uint64 size;
if (user_memcpy((uint8*)&size, buffer, sizeof(uint64)) != B_OK)
return B_BAD_ADDRESS;
ResizeVisitor resizer(volume);
return resizer.Resize(size, -1);
}
#ifdef DEBUG_FRAGMENTER
case 56741:
{
BlockAllocator& allocator = volume->Allocator();
allocator.Fragment();
return B_OK;
}
#endif
#ifdef DEBUG
case 56742:
{
// allocate all free blocks and zero them out
// (a test for the BlockAllocator)!
BlockAllocator& allocator = volume->Allocator();
Transaction transaction(volume, 0);
CachedBlock cached(volume);
block_run run;
while (allocator.AllocateBlocks(transaction, 8, 0, 64, 1, run)
== B_OK) {
PRINT(("write block_run(%" B_PRId32 ", %" B_PRIu16
", %" B_PRIu16 ")\n", run.allocation_group, run.start,
run.length));
for (int32 i = 0;i < run.length;i++) {
status_t status = cached.SetToWritable(transaction, run);
if (status == B_OK)
memset(cached.WritableBlock(), 0, volume->BlockSize());
}
}
return B_OK;
}
#endif
}
return B_DEV_INVALID_IOCTL;
}
/*! Sets the open-mode flags for the open file cookie - only
supports O_APPEND currently, but that should be sufficient
for a file system.
*/
static status_t
bfs_set_flags(fs_volume* _volume, fs_vnode* _node, void* _cookie, int flags)
{
FUNCTION_START(("node = %p, flags = %d", _node, flags));
file_cookie* cookie = (file_cookie*)_cookie;
cookie->open_mode = (cookie->open_mode & ~O_APPEND) | (flags & O_APPEND);
return B_OK;
}
static status_t
bfs_fsync(fs_volume* _volume, fs_vnode* _node)
{
FUNCTION();
Inode* inode = (Inode*)_node->private_node;
return inode->Sync();
}
static status_t
bfs_read_stat(fs_volume* _volume, fs_vnode* _node, struct stat* stat)
{
FUNCTION();
Inode* inode = (Inode*)_node->private_node;
fill_stat_buffer(inode, *stat);
return B_OK;
}
static status_t
bfs_write_stat(fs_volume* _volume, fs_vnode* _node, const struct stat* stat,
uint32 mask)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
// TODO: we should definitely check a bit more if the new stats are
// valid - or even better, the VFS should check this before calling us
bfs_inode& node = inode->Node();
bool updateTime = false;
uid_t uid = geteuid();
bool isOwnerOrRoot = uid == 0 || uid == (uid_t)node.UserID();
bool hasWriteAccess = inode->CheckPermissions(W_OK) == B_OK;
Transaction transaction(volume, inode->BlockNumber());
inode->WriteLockInTransaction(transaction);
if ((mask & B_STAT_SIZE) != 0 && inode->Size() != stat->st_size) {
// Since B_STAT_SIZE is the only thing that can fail directly, we
// do it first, so that the inode state will still be consistent
// with the on-disk version
if (inode->IsDirectory())
return B_IS_A_DIRECTORY;
if (!inode->IsFile())
return B_BAD_VALUE;
if (!hasWriteAccess)
RETURN_ERROR(B_NOT_ALLOWED);
off_t oldSize = inode->Size();
status_t status = inode->SetFileSize(transaction, stat->st_size);
if (status != B_OK)
return status;
// fill the new blocks (if any) with zeros
if ((mask & B_STAT_SIZE_INSECURE) == 0) {
// We must not keep the inode locked during a write operation,
// or else we might deadlock.
rw_lock_write_unlock(&inode->Lock());
inode->FillGapWithZeros(oldSize, inode->Size());
rw_lock_write_lock(&inode->Lock());
}
if (!inode->IsDeleted()) {
Index index(volume);
index.UpdateSize(transaction, inode);
updateTime = true;
}
}
if ((mask & B_STAT_UID) != 0) {
// only root should be allowed
if (uid != 0)
RETURN_ERROR(B_NOT_ALLOWED);
node.uid = HOST_ENDIAN_TO_BFS_INT32(stat->st_uid);
updateTime = true;
}
if ((mask & B_STAT_GID) != 0) {
// only the user or root can do that
if (!isOwnerOrRoot)
RETURN_ERROR(B_NOT_ALLOWED);
node.gid = HOST_ENDIAN_TO_BFS_INT32(stat->st_gid);
updateTime = true;
}
if ((mask & B_STAT_MODE) != 0) {
// only the user or root can do that
if (!isOwnerOrRoot)
RETURN_ERROR(B_NOT_ALLOWED);
PRINT(("original mode = %u, stat->st_mode = %u\n",
(unsigned int)node.Mode(), (unsigned int)stat->st_mode));
node.mode = HOST_ENDIAN_TO_BFS_INT32((node.Mode() & ~S_IUMSK)
| (stat->st_mode & S_IUMSK));
updateTime = true;
}
if ((mask & B_STAT_CREATION_TIME) != 0) {
// the user or root can do that or any user with write access
if (!isOwnerOrRoot && !hasWriteAccess)
RETURN_ERROR(B_NOT_ALLOWED);
node.create_time
= HOST_ENDIAN_TO_BFS_INT64(bfs_inode::ToInode(stat->st_crtim));
}
if ((mask & B_STAT_MODIFICATION_TIME) != 0) {
// the user or root can do that or any user with write access
if (!isOwnerOrRoot && !hasWriteAccess)
RETURN_ERROR(B_NOT_ALLOWED);
if (!inode->InLastModifiedIndex()) {
// directory modification times are not part of the index
node.last_modified_time
= HOST_ENDIAN_TO_BFS_INT64(bfs_inode::ToInode(stat->st_mtim));
} else if (!inode->IsDeleted()) {
// Index::UpdateLastModified() will set the new time in the inode
Index index(volume);
index.UpdateLastModified(transaction, inode,
bfs_inode::ToInode(stat->st_mtim));
}
}
if ((mask & B_STAT_CHANGE_TIME) != 0 || updateTime) {
// the user or root can do that or any user with write access
if (!isOwnerOrRoot && !hasWriteAccess)
RETURN_ERROR(B_NOT_ALLOWED);
bigtime_t newTime;
if ((mask & B_STAT_CHANGE_TIME) == 0)
newTime = bfs_inode::ToInode(real_time_clock_usecs());
else
newTime = bfs_inode::ToInode(stat->st_ctim);
node.status_change_time = HOST_ENDIAN_TO_BFS_INT64(newTime);
}
status_t status = inode->WriteBack(transaction);
if (status == B_OK)
status = transaction.Done();
if (status == B_OK)
notify_stat_changed(volume->ID(), inode->ParentID(), inode->ID(), mask);
return status;
}
status_t
bfs_create(fs_volume* _volume, fs_vnode* _directory, const char* name,
int openMode, int mode, void** _cookie, ino_t* _vnodeID)
{
FUNCTION_START(("name = \"%s\", perms = %d, openMode = %d\n", name, mode,
openMode));
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (!directory->IsDirectory())
RETURN_ERROR(B_BAD_TYPE);
// We are creating the cookie at this point, so that we don't have
// to remove the inode if we don't have enough free memory later...
file_cookie* cookie = new(std::nothrow) file_cookie;
if (cookie == NULL)
RETURN_ERROR(B_NO_MEMORY);
// initialize the cookie
cookie->open_mode = openMode;
cookie->last_size = 0;
cookie->last_notification = system_time();
Transaction transaction(volume, directory->BlockNumber());
Inode* inode;
bool created;
status_t status = Inode::Create(transaction, directory, name,
S_FILE | (mode & S_IUMSK), openMode, 0, &created, _vnodeID, &inode);
// Disable the file cache, if requested?
if (status == B_OK && (openMode & O_NOCACHE) != 0
&& inode->FileCache() != NULL) {
status = file_cache_disable(inode->FileCache());
}
entry_cache_add(volume->ID(), directory->ID(), name, *_vnodeID);
if (status == B_OK)
status = transaction.Done();
if (status == B_OK) {
// register the cookie
*_cookie = cookie;
if (created) {
notify_entry_created(volume->ID(), directory->ID(), name,
*_vnodeID);
}
} else {
entry_cache_remove(volume->ID(), directory->ID(), name);
delete cookie;
}
return status;
}
static status_t
bfs_create_symlink(fs_volume* _volume, fs_vnode* _directory, const char* name,
const char* path, int mode)
{
FUNCTION_START(("name = \"%s\", path = \"%s\"\n", name, path));
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (!directory->IsDirectory())
RETURN_ERROR(B_BAD_TYPE);
status_t status = directory->CheckPermissions(W_OK);
if (status < B_OK)
RETURN_ERROR(status);
Transaction transaction(volume, directory->BlockNumber());
Inode* link;
off_t id;
status = Inode::Create(transaction, directory, name, S_SYMLINK | 0777,
0, 0, NULL, &id, &link);
if (status < B_OK)
RETURN_ERROR(status);
size_t length = strlen(path);
if (length < SHORT_SYMLINK_NAME_LENGTH) {
strcpy(link->Node().short_symlink, path);
} else {
link->Node().flags |= HOST_ENDIAN_TO_BFS_INT32(INODE_LONG_SYMLINK
| INODE_LOGGED);
// links usually don't have a file cache attached - but we now need one
link->SetFileCache(file_cache_create(volume->ID(), link->ID(), 0));
link->SetMap(file_map_create(volume->ID(), link->ID(), 0));
// The following call will have to write the inode back, so
// we don't have to do that here...
status = link->WriteAt(transaction, 0, (const uint8*)path, &length);
}
if (status == B_OK)
status = link->WriteBack(transaction);
// Inode::Create() left the inode locked in memory, and also doesn't
// publish links
publish_vnode(volume->FSVolume(), id, link, &gBFSVnodeOps, link->Mode(), 0);
put_vnode(volume->FSVolume(), id);
if (status == B_OK) {
entry_cache_add(volume->ID(), directory->ID(), name, id);
status = transaction.Done();
if (status == B_OK)
notify_entry_created(volume->ID(), directory->ID(), name, id);
else
entry_cache_remove(volume->ID(), directory->ID(), name);
}
return status;
}
status_t
bfs_link(fs_volume* _volume, fs_vnode* dir, const char* name, fs_vnode* node)
{
FUNCTION_START(("name = \"%s\"\n", name));
// This one won't be implemented in a binary compatible BFS
return B_UNSUPPORTED;
}
status_t
bfs_unlink(fs_volume* _volume, fs_vnode* _directory, const char* name)
{
FUNCTION_START(("name = \"%s\"\n", name));
if (!strcmp(name, "..") || !strcmp(name, "."))
return B_NOT_ALLOWED;
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
status_t status = directory->CheckPermissions(W_OK);
if (status < B_OK)
return status;
Transaction transaction(volume, directory->BlockNumber());
off_t id;
status = directory->Remove(transaction, name, &id);
if (status == B_OK) {
entry_cache_remove(volume->ID(), directory->ID(), name);
status = transaction.Done();
if (status == B_OK)
notify_entry_removed(volume->ID(), directory->ID(), name, id);
else
entry_cache_add(volume->ID(), directory->ID(), name, id);
}
return status;
}
status_t
bfs_rename(fs_volume* _volume, fs_vnode* _oldDir, const char* oldName,
fs_vnode* _newDir, const char* newName)
{
FUNCTION_START(("oldDir = %p, oldName = \"%s\", newDir = %p, newName = "
"\"%s\"\n", _oldDir, oldName, _newDir, newName));
Volume* volume = (Volume*)_volume->private_volume;
Inode* oldDirectory = (Inode*)_oldDir->private_node;
Inode* newDirectory = (Inode*)_newDir->private_node;
// are we already done?
if (oldDirectory == newDirectory && !strcmp(oldName, newName))
return B_OK;
Transaction transaction(volume, oldDirectory->BlockNumber());
oldDirectory->WriteLockInTransaction(transaction);
if (oldDirectory != newDirectory)
newDirectory->WriteLockInTransaction(transaction);
// are we allowed to do what we've been told?
status_t status = oldDirectory->CheckPermissions(W_OK);
if (status == B_OK)
status = newDirectory->CheckPermissions(W_OK);
if (status != B_OK)
return status;
// Get the directory's tree, and a pointer to the inode which should be
// changed
BPlusTree* tree = oldDirectory->Tree();
if (tree == NULL)
RETURN_ERROR(B_BAD_VALUE);
off_t id;
status = tree->Find((const uint8*)oldName, strlen(oldName), &id);
if (status != B_OK)
RETURN_ERROR(status);
Vnode vnode(volume, id);
Inode* inode;
if (vnode.Get(&inode) != B_OK)
return B_IO_ERROR;
// Don't move a directory into one of its children - we soar up
// from the newDirectory to either the root node or the old
// directory, whichever comes first.
// If we meet our inode on that way, we have to bail out.
if (oldDirectory != newDirectory) {
ino_t parent = newDirectory->ID();
ino_t root = volume->RootNode()->ID();
while (true) {
if (parent == id)
return B_BAD_VALUE;
else if (parent == root || parent == oldDirectory->ID())
break;
Vnode vnode(volume, parent);
Inode* parentNode;
if (vnode.Get(&parentNode) != B_OK)
return B_ERROR;
parent = volume->ToVnode(parentNode->Parent());
}
}
// Everything okay? Then lets get to work...
// First, try to make sure there is nothing that will stop us in
// the target directory - since this is the only non-critical
// failure, we will test this case first
BPlusTree* newTree = tree;
if (newDirectory != oldDirectory) {
newTree = newDirectory->Tree();
if (newTree == NULL)
RETURN_ERROR(B_BAD_VALUE);
}
status = newTree->Insert(transaction, (const uint8*)newName,
strlen(newName), id);
if (status == B_NAME_IN_USE) {
// If there is already a file with that name, we have to remove
// it, as long it's not a directory with files in it
off_t clobber;
if (newTree->Find((const uint8*)newName, strlen(newName), &clobber)
< B_OK)
return B_NAME_IN_USE;
if (clobber == id)
return B_BAD_VALUE;
Vnode vnode(volume, clobber);
Inode* other;
if (vnode.Get(&other) < B_OK)
return B_NAME_IN_USE;
// only allowed, if either both nodes are directories or neither is
if (inode->IsDirectory() != other->IsDirectory())
return other->IsDirectory() ? B_IS_A_DIRECTORY : B_NOT_A_DIRECTORY;
status = newDirectory->Remove(transaction, newName, NULL,
other->IsDirectory());
if (status < B_OK)
return status;
entry_cache_remove(volume->ID(), newDirectory->ID(), newName);
notify_entry_removed(volume->ID(), newDirectory->ID(), newName,
clobber);
status = newTree->Insert(transaction, (const uint8*)newName,
strlen(newName), id);
}
if (status != B_OK)
return status;
inode->WriteLockInTransaction(transaction);
volume->UpdateLiveQueriesRenameMove(inode, oldDirectory->ID(), oldName,
newDirectory->ID(), newName);
// update the name only when they differ
if (strcmp(oldName, newName)) {
status = inode->SetName(transaction, newName);
if (status == B_OK) {
Index index(volume);
index.UpdateName(transaction, oldName, newName, inode);
}
}
if (status == B_OK) {
status = tree->Remove(transaction, (const uint8*)oldName,
strlen(oldName), id);
if (status == B_OK) {
inode->Parent() = newDirectory->BlockRun();
// if it's a directory, update the parent directory pointer
// in its tree if necessary
BPlusTree* movedTree = inode->Tree();
if (oldDirectory != newDirectory
&& inode->IsDirectory()
&& movedTree != NULL) {
status = movedTree->Replace(transaction, (const uint8*)"..",
2, newDirectory->ID());
if (status == B_OK) {
// update/add the cache entry for the parent
entry_cache_add(volume->ID(), id, "..", newDirectory->ID());
}
}
if (status == B_OK && newDirectory != oldDirectory)
status = oldDirectory->ContainerContentsChanged(transaction);
if (status == B_OK)
status = newDirectory->ContainerContentsChanged(transaction);
if (status == B_OK)
status = inode->WriteBack(transaction);
if (status == B_OK) {
entry_cache_remove(volume->ID(), oldDirectory->ID(), oldName);
entry_cache_add(volume->ID(), newDirectory->ID(), newName, id);
status = transaction.Done();
if (status == B_OK) {
notify_entry_moved(volume->ID(), oldDirectory->ID(),
oldName, newDirectory->ID(), newName, id);
return B_OK;
}
entry_cache_remove(volume->ID(), newDirectory->ID(), newName);
entry_cache_add(volume->ID(), oldDirectory->ID(), oldName, id);
}
}
}
return status;
}
static status_t
bfs_open(fs_volume* _volume, fs_vnode* _node, int openMode, void** _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
// Opening a directory read-only is allowed, although you can't read
// any data from it.
if (inode->IsDirectory() && (openMode & O_RWMASK) != O_RDONLY)
return B_IS_A_DIRECTORY;
if ((openMode & O_DIRECTORY) != 0 && !inode->IsDirectory())
return B_NOT_A_DIRECTORY;
status_t status = inode->CheckPermissions(open_mode_to_access(openMode)
| ((openMode & O_TRUNC) != 0 ? W_OK : 0));
if (status != B_OK)
RETURN_ERROR(status);
file_cookie* cookie = new(std::nothrow) file_cookie;
if (cookie == NULL)
RETURN_ERROR(B_NO_MEMORY);
ObjectDeleter<file_cookie> cookieDeleter(cookie);
// initialize the cookie
cookie->open_mode = openMode & BFS_OPEN_MODE_USER_MASK;
cookie->last_size = inode->Size();
cookie->last_notification = system_time();
// Disable the file cache, if requested?
CObjectDeleter<void, void, file_cache_enable> fileCacheEnabler;
if ((openMode & O_NOCACHE) != 0 && inode->FileCache() != NULL) {
status = file_cache_disable(inode->FileCache());
if (status != B_OK)
return status;
fileCacheEnabler.SetTo(inode->FileCache());
}
// Should we truncate the file?
if ((openMode & O_TRUNC) != 0) {
if ((openMode & O_RWMASK) == O_RDONLY)
return B_NOT_ALLOWED;
Transaction transaction(volume, inode->BlockNumber());
inode->WriteLockInTransaction(transaction);
status_t status = inode->SetFileSize(transaction, 0);
if (status == B_OK)
status = inode->WriteBack(transaction);
if (status == B_OK)
status = transaction.Done();
if (status != B_OK)
return status;
}
fileCacheEnabler.Detach();
cookieDeleter.Detach();
*_cookie = cookie;
return B_OK;
}
static status_t
bfs_read(fs_volume* _volume, fs_vnode* _node, void* _cookie, off_t pos,
void* buffer, size_t* _length)
{
//FUNCTION();
Inode* inode = (Inode*)_node->private_node;
if (!inode->HasUserAccessableStream()) {
*_length = 0;
return inode->IsDirectory() ? B_IS_A_DIRECTORY : B_BAD_VALUE;
}
return inode->ReadAt(pos, (uint8*)buffer, _length);
}
static status_t
bfs_write(fs_volume* _volume, fs_vnode* _node, void* _cookie, off_t pos,
const void* buffer, size_t* _length)
{
//FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (!inode->HasUserAccessableStream()) {
*_length = 0;
return inode->IsDirectory() ? B_IS_A_DIRECTORY : B_BAD_VALUE;
}
file_cookie* cookie = (file_cookie*)_cookie;
if (cookie->open_mode & O_APPEND)
pos = inode->Size();
Transaction transaction;
// We are not starting the transaction here, since
// it might not be needed at all (the contents of
// regular files aren't logged)
status_t status = inode->WriteAt(transaction, pos, (const uint8*)buffer,
_length);
if (status == B_OK)
status = transaction.Done();
if (status == B_OK) {
InodeReadLocker locker(inode);
// periodically notify if the file size has changed
// TODO: should we better test for a change in the last_modified time only?
if (!inode->IsDeleted() && cookie->last_size != inode->Size()
&& system_time() > cookie->last_notification
+ INODE_NOTIFICATION_INTERVAL) {
notify_stat_changed(volume->ID(), inode->ParentID(), inode->ID(),
B_STAT_MODIFICATION_TIME | B_STAT_SIZE | B_STAT_INTERIM_UPDATE);
cookie->last_size = inode->Size();
cookie->last_notification = system_time();
}
}
return status;
}
static status_t
bfs_close(fs_volume* _volume, fs_vnode* _node, void* _cookie)
{
FUNCTION();
return B_OK;
}
static status_t
bfs_free_cookie(fs_volume* _volume, fs_vnode* _node, void* _cookie)
{
FUNCTION();
file_cookie* cookie = (file_cookie*)_cookie;
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
Transaction transaction;
bool needsTrimming = false;
if (!volume->IsReadOnly() && !volume->IsCheckingThread()) {
InodeReadLocker locker(inode);
needsTrimming = inode->NeedsTrimming();
if ((cookie->open_mode & O_RWMASK) != 0
&& !inode->IsDeleted()
&& (needsTrimming
|| inode->OldLastModified() != inode->LastModified()
|| (inode->InSizeIndex()
// TODO: this can prevent the size update notification
// for nodes not in the index!
&& inode->OldSize() != inode->Size()))) {
locker.Unlock();
transaction.Start(volume, inode->BlockNumber());
}
}
status_t status = transaction.IsStarted() ? B_OK : B_ERROR;
if (status == B_OK) {
inode->WriteLockInTransaction(transaction);
// trim the preallocated blocks and update the size,
// and last_modified indices if needed
bool changedSize = false, changedTime = false;
Index index(volume);
if (needsTrimming) {
status = inode->TrimPreallocation(transaction);
if (status < B_OK) {
FATAL(("Could not trim preallocated blocks: inode %" B_PRIdINO
", transaction %d: %s!\n", inode->ID(),
(int)transaction.ID(), strerror(status)));
// we still want this transaction to succeed
status = B_OK;
}
}
if (inode->OldSize() != inode->Size()) {
if (inode->InSizeIndex())
index.UpdateSize(transaction, inode);
changedSize = true;
}
if (inode->OldLastModified() != inode->LastModified()) {
if (inode->InLastModifiedIndex()) {
index.UpdateLastModified(transaction, inode,
inode->LastModified());
}
changedTime = true;
// updating the index doesn't write back the inode
inode->WriteBack(transaction);
}
if (changedSize || changedTime) {
notify_stat_changed(volume->ID(), inode->ParentID(), inode->ID(),
(changedTime ? B_STAT_MODIFICATION_TIME : 0)
| (changedSize ? B_STAT_SIZE : 0));
}
}
if (status == B_OK)
transaction.Done();
if ((cookie->open_mode & BFS_OPEN_MODE_CHECKING) != 0) {
// "chkbfs" exited abnormally, so we have to stop it here...
FATAL(("check process was aborted!\n"));
volume->CheckVisitor()->StopChecking();
volume->DeleteCheckVisitor();
}
if ((cookie->open_mode & O_NOCACHE) != 0 && inode->FileCache() != NULL)
file_cache_enable(inode->FileCache());
delete cookie;
return B_OK;
}
/*! Checks access permissions, return B_NOT_ALLOWED if the action
is not allowed.
*/
static status_t
bfs_access(fs_volume* _volume, fs_vnode* _node, int accessMode)
{
//FUNCTION();
Inode* inode = (Inode*)_node->private_node;
status_t status = inode->CheckPermissions(accessMode);
if (status < B_OK)
RETURN_ERROR(status);
return B_OK;
}
static status_t
bfs_read_link(fs_volume* _volume, fs_vnode* _node, char* buffer,
size_t* _bufferSize)
{
FUNCTION();
Inode* inode = (Inode*)_node->private_node;
if (!inode->IsSymLink())
RETURN_ERROR(B_BAD_VALUE);
if ((inode->Flags() & INODE_LONG_SYMLINK) != 0) {
status_t status = inode->ReadAt(0, (uint8*)buffer, _bufferSize);
if (status < B_OK)
RETURN_ERROR(status);
*_bufferSize = inode->Size();
return B_OK;
}
size_t linkLength = strlen(inode->Node().short_symlink);
size_t bytesToCopy = min_c(linkLength, *_bufferSize);
*_bufferSize = linkLength;
memcpy(buffer, inode->Node().short_symlink, bytesToCopy);
return B_OK;
}
// #pragma mark - Directory functions
static status_t
bfs_create_dir(fs_volume* _volume, fs_vnode* _directory, const char* name,
int mode)
{
FUNCTION_START(("name = \"%s\", perms = %d\n", name, mode));
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (!directory->IsDirectory())
RETURN_ERROR(B_BAD_TYPE);
status_t status = directory->CheckPermissions(W_OK);
if (status < B_OK)
RETURN_ERROR(status);
Transaction transaction(volume, directory->BlockNumber());
// Inode::Create() locks the inode if we pass the "id" parameter, but we
// need it anyway
off_t id;
status = Inode::Create(transaction, directory, name,
S_DIRECTORY | (mode & S_IUMSK), 0, 0, NULL, &id);
if (status == B_OK) {
put_vnode(volume->FSVolume(), id);
entry_cache_add(volume->ID(), directory->ID(), name, id);
status = transaction.Done();
if (status == B_OK)
notify_entry_created(volume->ID(), directory->ID(), name, id);
else
entry_cache_remove(volume->ID(), directory->ID(), name);
}
return status;
}
static status_t
bfs_remove_dir(fs_volume* _volume, fs_vnode* _directory, const char* name)
{
FUNCTION_START(("name = \"%s\"\n", name));
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
Transaction transaction(volume, directory->BlockNumber());
off_t id;
status_t status = directory->Remove(transaction, name, &id, true);
if (status == B_OK) {
// Remove the cache entry for the directory and potentially also
// the parent entry still belonging to the directory
entry_cache_remove(volume->ID(), directory->ID(), name);
entry_cache_remove(volume->ID(), id, "..");
status = transaction.Done();
if (status == B_OK)
notify_entry_removed(volume->ID(), directory->ID(), name, id);
else {
entry_cache_add(volume->ID(), directory->ID(), name, id);
entry_cache_add(volume->ID(), id, "..", id);
}
}
return status;
}
/*! Opens a directory ready to be traversed.
bfs_open_dir() is also used by bfs_open_index_dir().
*/
static status_t
bfs_open_dir(fs_volume* _volume, fs_vnode* _node, void** _cookie)
{
FUNCTION();
Inode* inode = (Inode*)_node->private_node;
status_t status = inode->CheckPermissions(R_OK);
if (status < B_OK)
RETURN_ERROR(status);
// we don't ask here for directories only, because the bfs_open_index_dir()
// function utilizes us (so we must be able to open indices as well)
if (!inode->IsContainer())
RETURN_ERROR(B_NOT_A_DIRECTORY);
BPlusTree* tree = inode->Tree();
if (tree == NULL)
RETURN_ERROR(B_BAD_VALUE);
TreeIterator* iterator = new(std::nothrow) TreeIterator(tree);
if (iterator == NULL)
RETURN_ERROR(B_NO_MEMORY);
*_cookie = iterator;
return B_OK;
}
static status_t
bfs_read_dir(fs_volume* _volume, fs_vnode* _node, void* _cookie,
struct dirent* dirent, size_t bufferSize, uint32* _num)
{
FUNCTION();
TreeIterator* iterator = (TreeIterator*)_cookie;
Volume* volume = (Volume*)_volume->private_volume;
uint32 maxCount = *_num;
uint32 count = 0;
while (count < maxCount && bufferSize > sizeof(struct dirent)) {
ino_t id;
uint16 length;
size_t nameBufferSize = bufferSize - offsetof(struct dirent, d_name);
status_t status = iterator->GetNextEntry(dirent->d_name, &length,
nameBufferSize, &id);
if (status == B_ENTRY_NOT_FOUND)
break;
if (status == B_BUFFER_OVERFLOW) {
// the remaining name buffer length was too small
if (count == 0)
RETURN_ERROR(B_BUFFER_OVERFLOW);
break;
}
if (status != B_OK)
RETURN_ERROR(status);
ASSERT(length < nameBufferSize);
dirent->d_dev = volume->ID();
dirent->d_ino = id;
dirent->d_reclen = offsetof(struct dirent, d_name) + length + 1;
bufferSize -= dirent->d_reclen;
dirent = (struct dirent*)((uint8*)dirent + dirent->d_reclen);
count++;
}
*_num = count;
return B_OK;
}
/*! Sets the TreeIterator back to the beginning of the directory. */
static status_t
bfs_rewind_dir(fs_volume* /*_volume*/, fs_vnode* /*node*/, void* _cookie)
{
FUNCTION();
TreeIterator* iterator = (TreeIterator*)_cookie;
return iterator->Rewind();
}
static status_t
bfs_close_dir(fs_volume* /*_volume*/, fs_vnode* /*node*/, void* /*_cookie*/)
{
FUNCTION();
return B_OK;
}
static status_t
bfs_free_dir_cookie(fs_volume* _volume, fs_vnode* node, void* _cookie)
{
delete (TreeIterator*)_cookie;
return B_OK;
}
// #pragma mark - Attribute functions
static status_t
bfs_open_attr_dir(fs_volume* _volume, fs_vnode* _node, void** _cookie)
{
Inode* inode = (Inode*)_node->private_node;
FUNCTION();
AttributeIterator* iterator = new(std::nothrow) AttributeIterator(inode);
if (iterator == NULL)
RETURN_ERROR(B_NO_MEMORY);
*_cookie = iterator;
return B_OK;
}
static status_t
bfs_close_attr_dir(fs_volume* _volume, fs_vnode* node, void* cookie)
{
FUNCTION();
return B_OK;
}
static status_t
bfs_free_attr_dir_cookie(fs_volume* _volume, fs_vnode* node, void* _cookie)
{
FUNCTION();
AttributeIterator* iterator = (AttributeIterator*)_cookie;
delete iterator;
return B_OK;
}
static status_t
bfs_rewind_attr_dir(fs_volume* _volume, fs_vnode* _node, void* _cookie)
{
FUNCTION();
AttributeIterator* iterator = (AttributeIterator*)_cookie;
RETURN_ERROR(iterator->Rewind());
}
static status_t
bfs_read_attr_dir(fs_volume* _volume, fs_vnode* node, void* _cookie,
struct dirent* dirent, size_t bufferSize, uint32* _num)
{
FUNCTION();
AttributeIterator* iterator = (AttributeIterator*)_cookie;
uint32 type;
size_t length;
status_t status = iterator->GetNext(dirent->d_name, &length, &type,
&dirent->d_ino);
if (status == B_ENTRY_NOT_FOUND) {
*_num = 0;
return B_OK;
} else if (status != B_OK) {
RETURN_ERROR(status);
}
Volume* volume = (Volume*)_volume->private_volume;
dirent->d_dev = volume->ID();
dirent->d_reclen = offsetof(struct dirent, d_name) + length + 1;
*_num = 1;
return B_OK;
}
static status_t
bfs_create_attr(fs_volume* _volume, fs_vnode* _node, const char* name,
uint32 type, int openMode, void** _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
Inode* inode = (Inode*)_node->private_node;
Attribute attribute(inode);
return attribute.Create(name, type, openMode, (attr_cookie**)_cookie);
}
static status_t
bfs_open_attr(fs_volume* _volume, fs_vnode* _node, const char* name,
int openMode, void** _cookie)
{
FUNCTION();
Inode* inode = (Inode*)_node->private_node;
Attribute attribute(inode);
return attribute.Open(name, openMode, (attr_cookie**)_cookie);
}
static status_t
bfs_close_attr(fs_volume* _volume, fs_vnode* _file, void* cookie)
{
return B_OK;
}
static status_t
bfs_free_attr_cookie(fs_volume* _volume, fs_vnode* _file, void* cookie)
{
delete (attr_cookie*)cookie;
return B_OK;
}
static status_t
bfs_read_attr(fs_volume* _volume, fs_vnode* _file, void* _cookie, off_t pos,
void* buffer, size_t* _length)
{
FUNCTION();
attr_cookie* cookie = (attr_cookie*)_cookie;
Inode* inode = (Inode*)_file->private_node;
Attribute attribute(inode, cookie);
return attribute.Read(cookie, pos, (uint8*)buffer, _length);
}
static status_t
bfs_write_attr(fs_volume* _volume, fs_vnode* _file, void* _cookie,
off_t pos, const void* buffer, size_t* _length)
{
FUNCTION();
attr_cookie* cookie = (attr_cookie*)_cookie;
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_file->private_node;
Transaction transaction(volume, inode->BlockNumber());
Attribute attribute(inode, cookie);
bool created;
status_t status = attribute.Write(transaction, cookie, pos,
(const uint8*)buffer, _length, &created);
if (status == B_OK) {
status = transaction.Done();
if (status == B_OK) {
notify_attribute_changed(volume->ID(), inode->ParentID(),
inode->ID(), cookie->name,
created ? B_ATTR_CREATED : B_ATTR_CHANGED);
notify_stat_changed(volume->ID(), inode->ParentID(), inode->ID(),
B_STAT_CHANGE_TIME);
}
}
return status;
}
static status_t
bfs_read_attr_stat(fs_volume* _volume, fs_vnode* _file, void* _cookie,
struct stat* stat)
{
FUNCTION();
attr_cookie* cookie = (attr_cookie*)_cookie;
Inode* inode = (Inode*)_file->private_node;
Attribute attribute(inode, cookie);
return attribute.Stat(*stat);
}
static status_t
bfs_write_attr_stat(fs_volume* _volume, fs_vnode* file, void* cookie,
const struct stat* stat, int statMask)
{
// TODO: Implement (at least setting the size)!
return EOPNOTSUPP;
}
static status_t
bfs_rename_attr(fs_volume* _volume, fs_vnode* fromFile, const char* fromName,
fs_vnode* toFile, const char* toName)
{
FUNCTION_START(("name = \"%s\", to = \"%s\"\n", fromName, toName));
// TODO: implement bfs_rename_attr()!
// There will probably be an API to move one attribute to another file,
// making that function much more complicated - oh joy ;-)
return EOPNOTSUPP;
}
static status_t
bfs_remove_attr(fs_volume* _volume, fs_vnode* _node, const char* name)
{
FUNCTION_START(("name = \"%s\"\n", name));
Volume* volume = (Volume*)_volume->private_volume;
Inode* inode = (Inode*)_node->private_node;
status_t status = inode->CheckPermissions(W_OK);
if (status != B_OK)
return status;
Transaction transaction(volume, inode->BlockNumber());
status = inode->RemoveAttribute(transaction, name);
if (status == B_OK)
status = transaction.Done();
if (status == B_OK) {
notify_attribute_changed(volume->ID(), inode->ParentID(), inode->ID(),
name, B_ATTR_REMOVED);
}
return status;
}
// #pragma mark - Special Nodes
status_t
bfs_create_special_node(fs_volume* _volume, fs_vnode* _directory,
const char* name, fs_vnode* subVnode, mode_t mode, uint32 flags,
fs_vnode* _superVnode, ino_t* _nodeID)
{
// no need to support entry-less nodes
if (name == NULL)
return B_UNSUPPORTED;
FUNCTION_START(("name = \"%s\", mode = %u, flags = 0x%" B_PRIx32
", subVnode: %p\n", name, (unsigned int)mode, flags, subVnode));
Volume* volume = (Volume*)_volume->private_volume;
Inode* directory = (Inode*)_directory->private_node;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
if (!directory->IsDirectory())
RETURN_ERROR(B_BAD_TYPE);
status_t status = directory->CheckPermissions(W_OK);
if (status < B_OK)
RETURN_ERROR(status);
Transaction transaction(volume, directory->BlockNumber());
off_t id;
Inode* inode;
status = Inode::Create(transaction, directory, name, mode, O_EXCL, 0, NULL,
&id, &inode, subVnode ? subVnode->ops : NULL, flags);
if (status == B_OK) {
_superVnode->private_node = inode;
_superVnode->ops = &gBFSVnodeOps;
*_nodeID = id;
entry_cache_add(volume->ID(), directory->ID(), name, id);
status = transaction.Done();
if (status == B_OK)
notify_entry_created(volume->ID(), directory->ID(), name, id);
else
entry_cache_remove(volume->ID(), directory->ID(), name);
}
return status;
}
// #pragma mark - Index functions
static status_t
bfs_open_index_dir(fs_volume* _volume, void** _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
if (volume->IndicesNode() == NULL) {
// This volume does not have any indices
RETURN_ERROR(B_ENTRY_NOT_FOUND);
}
// Since the indices root node is just a directory, and we are storing
// a pointer to it in our Volume object, we can just use the directory
// traversal functions.
// In fact we're storing it in the Volume object for that reason.
fs_vnode indicesNode;
indicesNode.private_node = volume->IndicesNode();
RETURN_ERROR(bfs_open_dir(_volume, &indicesNode, _cookie));
}
static status_t
bfs_close_index_dir(fs_volume* _volume, void* _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
fs_vnode indicesNode;
indicesNode.private_node = volume->IndicesNode();
RETURN_ERROR(bfs_close_dir(_volume, &indicesNode, _cookie));
}
static status_t
bfs_free_index_dir_cookie(fs_volume* _volume, void* _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
fs_vnode indicesNode;
indicesNode.private_node = volume->IndicesNode();
RETURN_ERROR(bfs_free_dir_cookie(_volume, &indicesNode, _cookie));
}
static status_t
bfs_rewind_index_dir(fs_volume* _volume, void* _cookie)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
fs_vnode indicesNode;
indicesNode.private_node = volume->IndicesNode();
RETURN_ERROR(bfs_rewind_dir(_volume, &indicesNode, _cookie));
}
static status_t
bfs_read_index_dir(fs_volume* _volume, void* _cookie, struct dirent* dirent,
size_t bufferSize, uint32* _num)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
fs_vnode indicesNode;
indicesNode.private_node = volume->IndicesNode();
RETURN_ERROR(bfs_read_dir(_volume, &indicesNode, _cookie, dirent,
bufferSize, _num));
}
static status_t
bfs_create_index(fs_volume* _volume, const char* name, uint32 type,
uint32 flags)
{
FUNCTION_START(("name = \"%s\", type = %" B_PRIu32
", flags = %" B_PRIu32 "\n", name, type, flags));
Volume* volume = (Volume*)_volume->private_volume;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
// only root users are allowed to create indices
if (geteuid() != 0)
return B_NOT_ALLOWED;
Transaction transaction(volume, volume->Indices());
Index index(volume);
status_t status = index.Create(transaction, name, type);
if (status == B_OK)
status = transaction.Done();
RETURN_ERROR(status);
}
static status_t
bfs_remove_index(fs_volume* _volume, const char* name)
{
FUNCTION();
Volume* volume = (Volume*)_volume->private_volume;
if (volume->IsReadOnly())
return B_READ_ONLY_DEVICE;
// only root users are allowed to remove indices
if (geteuid() != 0)
return B_NOT_ALLOWED;
Inode* indices = volume->IndicesNode();
if (indices == NULL)
return B_ENTRY_NOT_FOUND;
Transaction transaction(volume, volume->Indices());
status_t status = indices->Remove(transaction, name);
if (status == B_OK)
status = transaction.Done();
RETURN_ERROR(status);
}
static status_t
bfs_stat_index(fs_volume* _volume, const char* name, struct stat* stat)
{
FUNCTION_START(("name = %s\n", name));
Volume* volume = (Volume*)_volume->private_volume;
Index index(volume);
status_t status = index.SetTo(name);
if (status < B_OK)
RETURN_ERROR(status);
bfs_inode& node = index.Node()->Node();
stat->st_type = index.Type();
stat->st_mode = node.Mode();
stat->st_size = node.data.Size();
stat->st_blocks = index.Node()->AllocatedSize() / 512;
stat->st_nlink = 1;
stat->st_blksize = 65536;
stat->st_uid = node.UserID();
stat->st_gid = node.GroupID();
fill_stat_time(node, *stat);
return B_OK;
}
// #pragma mark - Query functions
static status_t
bfs_open_query(fs_volume* _volume, const char* queryString, uint32 flags,
port_id port, uint32 token, void** _cookie)
{
FUNCTION_START(("bfs_open_query(\"%s\", flags = %" B_PRIu32
", port_id = %" B_PRId32 ", token = %" B_PRIu32 ")\n",
queryString, flags, port, token));
Volume* volume = (Volume*)_volume->private_volume;
Expression* expression = new(std::nothrow) Expression((char*)queryString);
if (expression == NULL)
RETURN_ERROR(B_NO_MEMORY);
if (expression->InitCheck() < B_OK) {
INFORM(("Could not parse query \"%s\", stopped at: \"%s\"\n",
queryString, expression->Position()));
delete expression;
RETURN_ERROR(B_BAD_VALUE);
}
Query* query = new(std::nothrow) Query(volume, expression, flags);
if (query == NULL) {
delete expression;
RETURN_ERROR(B_NO_MEMORY);
}
if (flags & B_LIVE_QUERY)
query->SetLiveMode(port, token);
*_cookie = (void*)query;
return B_OK;
}
static status_t
bfs_close_query(fs_volume* _volume, void* cookie)
{
FUNCTION();
return B_OK;
}
static status_t
bfs_free_query_cookie(fs_volume* _volume, void* cookie)
{
FUNCTION();
Query* query = (Query*)cookie;
Expression* expression = query->GetExpression();
delete query;
delete expression;
return B_OK;
}
static status_t
bfs_read_query(fs_volume* /*_volume*/, void* cookie, struct dirent* dirent,
size_t bufferSize, uint32* _num)
{
FUNCTION();
Query* query = (Query*)cookie;
status_t status = query->GetNextEntry(dirent, bufferSize);
if (status == B_OK)
*_num = 1;
else if (status == B_ENTRY_NOT_FOUND)
*_num = 0;
else
return status;
return B_OK;
}
static status_t
bfs_rewind_query(fs_volume* /*_volume*/, void* cookie)
{
FUNCTION();
Query* query = (Query*)cookie;
return query->Rewind();
}
// #pragma mark -
static uint32
bfs_get_supported_operations(partition_data* partition, uint32 mask)
{
// TODO: We should at least check the partition size.
return B_DISK_SYSTEM_SUPPORTS_INITIALIZING
| B_DISK_SYSTEM_SUPPORTS_CONTENT_NAME
| B_DISK_SYSTEM_SUPPORTS_WRITING;
}
static status_t
bfs_initialize(int fd, partition_id partitionID, const char* name,
const char* parameterString, off_t /*partitionSize*/, disk_job_id job)
{
// check name
status_t status = check_volume_name(name);
if (status != B_OK)
return status;
// parse parameters
initialize_parameters parameters;
status = parse_initialize_parameters(parameterString, parameters);
if (status != B_OK)
return status;
update_disk_device_job_progress(job, 0);
// initialize the volume
Volume volume(NULL);
status = volume.Initialize(fd, name, parameters.blockSize,
parameters.flags);
if (status < B_OK) {
INFORM(("Initializing volume failed: %s\n", strerror(status)));
return status;
}
// rescan partition
status = scan_partition(partitionID);
if (status != B_OK)
return status;
update_disk_device_job_progress(job, 1);
// print some info, if desired
if (parameters.verbose) {
disk_super_block super = volume.SuperBlock();
INFORM(("Disk was initialized successfully.\n"));
INFORM(("\tname: \"%s\"\n", super.name));
INFORM(("\tnum blocks: %" B_PRIdOFF "\n", super.NumBlocks()));
INFORM(("\tused blocks: %" B_PRIdOFF "\n", super.UsedBlocks()));
INFORM(("\tblock size: %u bytes\n", (unsigned)super.BlockSize()));
INFORM(("\tnum allocation groups: %d\n",
(int)super.AllocationGroups()));
INFORM(("\tallocation group size: %ld blocks\n",
1L << super.AllocationGroupShift()));
INFORM(("\tlog size: %u blocks\n", super.log_blocks.Length()));
}
return B_OK;
}
static status_t
bfs_uninitialize(int fd, partition_id partitionID, off_t partitionSize,
uint32 blockSize, disk_job_id job)
{
if (blockSize == 0)
return B_BAD_VALUE;
update_disk_device_job_progress(job, 0.0);
// just overwrite the superblock
disk_super_block superBlock;
memset(&superBlock, 0, sizeof(superBlock));
if (write_pos(fd, 512, &superBlock, sizeof(superBlock)) < 0)
return errno;
update_disk_device_job_progress(job, 1.0);
return B_OK;
}
// #pragma mark -
static status_t
bfs_std_ops(int32 op, ...)
{
switch (op) {
case B_MODULE_INIT:
#ifdef BFS_DEBUGGER_COMMANDS
add_debugger_commands();
#endif
return B_OK;
case B_MODULE_UNINIT:
#ifdef BFS_DEBUGGER_COMMANDS
remove_debugger_commands();
#endif
return B_OK;
default:
return B_ERROR;
}
}
fs_volume_ops gBFSVolumeOps = {
&bfs_unmount,
&bfs_read_fs_stat,
&bfs_write_fs_stat,
&bfs_sync,
&bfs_get_vnode,
/* index directory & index operations */
&bfs_open_index_dir,
&bfs_close_index_dir,
&bfs_free_index_dir_cookie,
&bfs_read_index_dir,
&bfs_rewind_index_dir,
&bfs_create_index,
&bfs_remove_index,
&bfs_stat_index,
/* query operations */
&bfs_open_query,
&bfs_close_query,
&bfs_free_query_cookie,
&bfs_read_query,
&bfs_rewind_query,
};
fs_vnode_ops gBFSVnodeOps = {
/* vnode operations */
&bfs_lookup,
&bfs_get_vnode_name,
&bfs_put_vnode,
&bfs_remove_vnode,
/* VM file access */
&bfs_can_page,
&bfs_read_pages,
&bfs_write_pages,
&bfs_io,
NULL, // cancel_io()
&bfs_get_file_map,
&bfs_ioctl,
&bfs_set_flags,
NULL, // fs_select
NULL, // fs_deselect
&bfs_fsync,
&bfs_read_link,
&bfs_create_symlink,
&bfs_link,
&bfs_unlink,
&bfs_rename,
&bfs_access,
&bfs_read_stat,
&bfs_write_stat,
NULL, // fs_preallocate
/* file operations */
&bfs_create,
&bfs_open,
&bfs_close,
&bfs_free_cookie,
&bfs_read,
&bfs_write,
/* directory operations */
&bfs_create_dir,
&bfs_remove_dir,
&bfs_open_dir,
&bfs_close_dir,
&bfs_free_dir_cookie,
&bfs_read_dir,
&bfs_rewind_dir,
/* attribute directory operations */
&bfs_open_attr_dir,
&bfs_close_attr_dir,
&bfs_free_attr_dir_cookie,
&bfs_read_attr_dir,
&bfs_rewind_attr_dir,
/* attribute operations */
&bfs_create_attr,
&bfs_open_attr,
&bfs_close_attr,
&bfs_free_attr_cookie,
&bfs_read_attr,
&bfs_write_attr,
&bfs_read_attr_stat,
&bfs_write_attr_stat,
&bfs_rename_attr,
&bfs_remove_attr,
/* special nodes */
&bfs_create_special_node
};
static file_system_module_info sBeFileSystem = {
{
"file_systems/bfs" BFS_ENDIAN_SUFFIX B_CURRENT_FS_API_VERSION,
0,
bfs_std_ops,
},
"bfs" BFS_ENDIAN_SUFFIX, // short_name
"Be File System" BFS_ENDIAN_PRETTY_SUFFIX, // pretty_name
// DDM flags
0
// | B_DISK_SYSTEM_SUPPORTS_CHECKING
// | B_DISK_SYSTEM_SUPPORTS_REPAIRING
// | B_DISK_SYSTEM_SUPPORTS_RESIZING
// | B_DISK_SYSTEM_SUPPORTS_MOVING
// | B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_NAME
// | B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_PARAMETERS
| B_DISK_SYSTEM_SUPPORTS_INITIALIZING
| B_DISK_SYSTEM_SUPPORTS_CONTENT_NAME
// | B_DISK_SYSTEM_SUPPORTS_DEFRAGMENTING
// | B_DISK_SYSTEM_SUPPORTS_DEFRAGMENTING_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_CHECKING_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_REPAIRING_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_RESIZING_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_MOVING_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_NAME_WHILE_MOUNTED
// | B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_PARAMETERS_WHILE_MOUNTED
| B_DISK_SYSTEM_SUPPORTS_WRITING
,
// scanning
bfs_identify_partition,
bfs_scan_partition,
bfs_free_identify_partition_cookie,
NULL, // free_partition_content_cookie()
&bfs_mount,
/* capability querying operations */
&bfs_get_supported_operations,
NULL, // validate_resize
NULL, // validate_move
NULL, // validate_set_content_name
NULL, // validate_set_content_parameters
NULL, // validate_initialize,
/* shadow partition modification */
NULL, // shadow_changed
/* writing */
NULL, // defragment
NULL, // repair
NULL, // resize
NULL, // move
NULL, // set_content_name
NULL, // set_content_parameters
bfs_initialize,
bfs_uninitialize
};
module_info* modules[] = {
(module_info*)&sBeFileSystem,
NULL,
};
| 24.597106 | 108 | 0.704654 | Yn0ga |
8d1352ceb002d4a7a023082ddc6ae2d3320ca35a | 4,789 | cc | C++ | common/window.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | 5 | 2021-01-25T01:51:58.000Z | 2022-03-18T22:50:10.000Z | common/window.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | null | null | null | common/window.cc | joone/opengl-wayland | 76355d9fbe160c3991577fe206350d5f992a9395 | [
"BSD-2-Clause"
] | null | null | null | #include <assert.h>
#include "window.h"
#include "wayland_platform.h"
#include "gl.h"
void redraw(void* data, struct wl_callback* callback, unsigned int time);
const struct wl_callback_listener frame_listener = {redraw};
void redraw(void* data, struct wl_callback* callback, unsigned int time) {
WaylandWindow* window = static_cast<WaylandWindow*>(data);
struct wl_region* region;
assert(window->callback == callback);
window->callback = NULL;
if (callback)
wl_callback_destroy(callback);
if (!window->configured)
return;
window->drawPtr(window);
if (window->opaque || window->fullscreen) {
region = wl_compositor_create_region(window->display->compositor);
wl_region_add(region, 0, 0, window->geometry.width,
window->geometry.height);
wl_surface_set_opaque_region(window->surface, region);
wl_region_destroy(region);
} else {
wl_surface_set_opaque_region(window->surface, NULL);
}
window->callback = wl_surface_frame(window->surface);
wl_callback_add_listener(window->callback, &frame_listener, window);
eglSwapBuffers(window->display->egl.dpy, window->egl_surface);
}
static void handle_ping(void* data,
struct wl_shell_surface* shell_surface,
uint32_t serial) {
wl_shell_surface_pong(shell_surface, serial);
}
static void handle_configure(void* data,
struct wl_shell_surface* shell_surface,
uint32_t edges,
int32_t width,
int32_t height) {
WaylandWindow* window = static_cast<WaylandWindow*>(data);
if (window->native)
wl_egl_window_resize(window->native, width, height, 0, 0);
window->geometry.width = width;
window->geometry.height = height;
if (!window->fullscreen)
window->window_size = window->geometry;
}
static void handle_popup_done(void* data,
struct wl_shell_surface* shell_surface) {}
static const struct wl_shell_surface_listener shell_surface_listener = {
handle_ping, handle_configure, handle_popup_done};
static void configure_callback(void* data,
struct wl_callback* callback,
uint32_t time) {
WaylandWindow* window = static_cast<WaylandWindow*>(data);
wl_callback_destroy(callback);
window->configured = 1;
if (window->callback == NULL)
redraw(data, NULL, time);
}
static struct wl_callback_listener configure_callback_listener = {
configure_callback,
};
WaylandWindow::WaylandWindow() : fullscreen(1), callback(nullptr) {
}
void WaylandWindow::toggle_fullscreen() {
struct wl_callback* callback;
fullscreen = fullscreen^1;
configured = 0;
if (fullscreen) {
wl_shell_surface_set_fullscreen(shell_surface,
WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
0, NULL);
} else {
wl_shell_surface_set_toplevel(shell_surface);
handle_configure(this, shell_surface, 0,
window_size.width, window_size.height);
}
callback = wl_display_sync(display->display_);
wl_callback_add_listener(callback, &configure_callback_listener, this);
}
void WaylandWindow::create_surface(unsigned width, unsigned height) {
EGLBoolean ret;
window_size.width = width;
window_size.height = height;
surface = wl_compositor_create_surface(display->compositor);
shell_surface =
wl_shell_get_shell_surface(display->shell, surface);
wl_shell_surface_add_listener(shell_surface, &shell_surface_listener,
this);
native = wl_egl_window_create(
surface, window_size.width, window_size.height);
egl_surface = eglCreateWindowSurface(
display->egl.dpy, display->egl.conf, (EGLNativeWindowType)native, NULL);
wl_shell_surface_set_title(shell_surface, "simple-egl");
ret = eglMakeCurrent(display->egl.dpy, egl_surface,
egl_surface, display->egl.ctx);
assert(ret == EGL_TRUE);
toggle_fullscreen();
}
void WaylandWindow::destroy_surface() {
/* Required, otherwise segfault in egl_dri2.c: dri2_make_current()
* on eglReleaseThread(). */
eglMakeCurrent(display->egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
eglDestroySurface(display->egl.dpy, egl_surface);
wl_egl_window_destroy(native);
wl_shell_surface_destroy(shell_surface);
wl_surface_destroy(surface);
if (callback)
wl_callback_destroy(callback);
}
void usage(int error_code) {
fprintf(stderr,
"Usage: simple-egl [OPTIONS]\n\n"
" -f\tRun in fullscreen mode\n"
" -o\tCreate an opaque surface\n"
" -h\tThis help text\n\n");
exit(error_code);
}
| 29.024242 | 79 | 0.679474 | joone |
8d264bfb3b77c4ef13684ae6188820be0c1ff5ec | 382 | cpp | C++ | gui/button.cpp | TaimoorRana/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 3 | 2016-05-23T09:39:08.000Z | 2016-10-08T03:28:24.000Z | gui/button.cpp | TaimoorRana/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 3 | 2017-09-11T00:51:55.000Z | 2017-09-11T00:52:05.000Z | gui/button.cpp | Taimoorrana1/Risk | ed96461f2b87d6336e50b27a35f50946e9125c86 | [
"MIT"
] | 1 | 2017-02-12T19:35:39.000Z | 2017-02-12T19:35:39.000Z | #include "button.h"
#include <iostream>
Button::Button(QString label)
{
this->setText(label);
}
void Button::pressed(Player &playerAttacker, Country &attackingCountry, Player &playerDefender, Country &defendingCountry)
{
WarReferee war;
war.startWar(playerAttacker,attackingCountry,playerDefender,defendingCountry);
}
void Button::test()
{
std::cout << "test";
}
| 20.105263 | 122 | 0.735602 | TaimoorRana |
8d29d6e91cd2ac4a4ba608b955f4d920a443a366 | 76 | cpp | C++ | case3msg.cpp | SYSU-Unmaned-System-Team/asc_-work-station | caef9002b93e01219418f891640773f21b08ba73 | [
"MulanPSL-1.0"
] | null | null | null | case3msg.cpp | SYSU-Unmaned-System-Team/asc_-work-station | caef9002b93e01219418f891640773f21b08ba73 | [
"MulanPSL-1.0"
] | null | null | null | case3msg.cpp | SYSU-Unmaned-System-Team/asc_-work-station | caef9002b93e01219418f891640773f21b08ba73 | [
"MulanPSL-1.0"
] | null | null | null | #include "case3msg.h"
case3Msg::case3Msg()
{
}
case3Msg::~case3Msg()
{
}
| 6.909091 | 21 | 0.631579 | SYSU-Unmaned-System-Team |
8d2f129256fe2f3ce796b128985bcb371abe5dc0 | 13,810 | cpp | C++ | plugins/eoc_relay_plugin/icp_connection.cpp | aiguo186/eocs | acc6086ab7b6075bba3271199e773ff0fbbe017e | [
"MIT"
] | 24 | 2018-12-25T03:52:10.000Z | 2021-03-22T12:16:27.000Z | plugins/eoc_relay_plugin/icp_connection.cpp | aiguo186/eocs | acc6086ab7b6075bba3271199e773ff0fbbe017e | [
"MIT"
] | 14 | 2018-12-13T03:19:09.000Z | 2019-05-10T02:17:09.000Z | plugins/eoc_relay_plugin/icp_connection.cpp | aiguo186/eocs | acc6086ab7b6075bba3271199e773ff0fbbe017e | [
"MIT"
] | 12 | 2018-12-12T10:37:35.000Z | 2019-07-10T08:39:17.000Z | #include "icp_relay.hpp"
#include "api.hpp"
#include "message.hpp"
#include <fc/log/logger.hpp>
#include "icp_connection.hpp"
#include <eosio/eoc_relay_plugin/eoc_relay_plugin.hpp>
namespace eoc_icp {
using icp_connection_ptr = std::shared_ptr<icp_connection>;
using icp_connection_wptr = std::weak_ptr<icp_connection>;
using socket_ptr = std::shared_ptr<tcp::socket>;
using icp_net_message_ptr = std::shared_ptr<icp_net_message>;
extern uint16_t icp_net_version_base ;
extern uint16_t icp_net_version_range ;
extern uint16_t icp_proto_explicit_sync ;
extern uint16_t icp_net_version ;
void
handshake_initializer::populate(icp_handshake_message &hello)
{
hello.network_version = icp_net_version_base + icp_net_version;
relay *my_impl = app().find_plugin<eoc_relay_plugin>()->get_relay_pointer();
hello.chain_id = my_impl->chain_id;
hello.node_id = my_impl->node_id;
hello.key = my_impl->get_authentication_key();
hello.time = std::chrono::system_clock::now().time_since_epoch().count();
hello.token = fc::sha256::hash(hello.time);
hello.sig = my_impl->sign_compact(hello.key, hello.token);
// If we couldn't sign, don't send a token.
if (hello.sig == chain::signature_type())
hello.token = sha256();
hello.p2p_address = my_impl->p2p_address + " - " + hello.node_id.str().substr(0, 7);
#if defined(__APPLE__)
hello.os = "osx";
#elif defined(__linux__)
hello.os = "linux";
#elif defined(_MSC_VER)
hello.os = "win32";
#else
hello.os = "other";
#endif
hello.agent = my_impl->user_agent_name;
controller &cc = my_impl->chain_plug->chain();
hello.head_id = fc::sha256();
hello.last_irreversible_block_id = fc::sha256();
hello.head_num = cc.fork_db_head_block_num();
hello.last_irreversible_block_num = cc.last_irreversible_block_num();
if (hello.last_irreversible_block_num)
{
try
{
hello.last_irreversible_block_id = cc.get_block_id_for_num(hello.last_irreversible_block_num);
}
catch (const unknown_block_exception &ex)
{
ilog("caught unkown_block");
hello.last_irreversible_block_num = 0;
}
}
if (hello.head_num)
{
try
{
hello.head_id = cc.get_block_id_for_num(hello.head_num);
}
catch (const unknown_block_exception &ex)
{
hello.head_num = 0;
}
}
}
icp_connection::icp_connection(string endpoint)
: socket(std::make_shared<tcp::socket>(std::ref(app().get_io_service()))),
node_id(),
sent_handshake_count(0),
connecting(false),
syncing(false),
protocol_version(0),
peer_addr(endpoint),
response_expected(),
fork_head(),
fork_head_num(0),
last_handshake_recv(),
last_handshake_sent(),
no_retry(icp_no_reason)
{
wlog("created icp_connection to ${n}", ("n", endpoint));
initialize();
}
icp_connection::icp_connection(socket_ptr s)
: socket(s),
node_id(),
sent_handshake_count(0),
connecting(false),
syncing(false),
protocol_version(0),
peer_addr(),
response_expected(),
fork_head(),
fork_head_num(0),
last_handshake_recv(),
last_handshake_sent(),
no_retry(icp_no_reason)
{
wlog("accepted network icp_connection");
initialize();
}
icp_connection::~icp_connection() {}
void icp_connection::initialize()
{
my_impl = app().find_plugin<eoc_relay_plugin>()->get_relay_pointer();
auto *rnd = node_id.data();
rnd[0] = 0;
response_expected.reset(new boost::asio::steady_timer(app().get_io_service()));
}
bool icp_connection::connected()
{
return (socket && socket->is_open() && !connecting);
}
bool icp_connection::current()
{
return (connected() && !syncing);
}
void icp_connection::reset()
{
}
void icp_connection::flush_queues()
{
write_queue.clear();
}
void icp_connection::close()
{
if (socket)
{
socket->close();
}
else
{
wlog("no socket to close!");
}
flush_queues();
connecting = false;
syncing = false;
reset();
sent_handshake_count = 0;
//ilog("close connection , count is ${g}",("g",sent_handshake_count));
//my_impl->sync_master->reset_lib_num(shared_from_this());
//fc_dlog(logger, "canceling wait on ${p}", ("p",peer_name()));
cancel_wait();
pending_message_buffer.reset();
}
void icp_connection::stop_send()
{
syncing = false;
}
const string icp_connection::peer_name()
{
if (!last_handshake_recv.p2p_address.empty())
{
return last_handshake_recv.p2p_address;
}
if (!peer_addr.empty())
{
return peer_addr;
}
return "connecting client";
}
void icp_connection::queue_write(std::shared_ptr<vector<char>> buff,
bool trigger_send,
std::function<void(boost::system::error_code, std::size_t)> callback)
{
write_queue.push_back({buff, callback});
if (out_queue.empty() && trigger_send)
do_queue_write();
}
//process_next_message
bool icp_connection::process_next_message(relay &impl, uint32_t message_length)
{
try
{
// If it is a signed_block, then save the raw message for the cache
// This must be done before we unpack the message.
// This code is copied from fc::io::unpack(..., unsigned_int)
auto index = pending_message_buffer.read_index();
uint64_t which = 0;
char b = 0;
uint8_t by = 0;
do
{
pending_message_buffer.peek(&b, 1, index);
which |= uint32_t(uint8_t(b) & 0x7f) << by;
by += 7;
} while (uint8_t(b) & 0x80 && by < 32);
// if (which == uint64_t(net_message::tag<signed_block>::value)) {
// blk_buffer.resize(message_length);
// auto index = pending_message_buffer.read_index();
// pending_message_buffer.peek(blk_buffer.data(), message_length, index);
// }
auto ds = pending_message_buffer.create_datastream();
icp_net_message msg;
fc::raw::unpack(ds, msg);
icp_msgHandler m(impl, shared_from_this());
msg.visit(m);
}
catch (const fc::exception &e)
{
edump((e.to_detail_string()));
impl.close(shared_from_this());
return false;
}
return true;
}
void icp_connection::update_local_head(const head &h)
{
head_local = h;
}
void icp_connection::do_queue_write()
{
if (write_queue.empty() || !out_queue.empty())
return;
icp_connection_wptr c(shared_from_this());
if (!socket->is_open())
{
// fc_elog(logger,"socket not open to ${p}",("p",peer_name()));
// my_impl->close(c.lock());
return;
}
std::vector<boost::asio::const_buffer> bufs;
while (write_queue.size() > 0)
{
auto &m = write_queue.front();
bufs.push_back(boost::asio::buffer(*m.buff));
out_queue.push_back(m);
write_queue.pop_front();
}
boost::asio::async_write(*socket, bufs, [c,this](boost::system::error_code ec, std::size_t w) {
try
{
auto conn = c.lock();
if (!conn)
return;
for (auto &m : conn->out_queue)
{
m.callback(ec, w);
}
if (ec)
{
string pname = conn ? conn->peer_name() : "no icp_connection name";
if (ec.value() != boost::asio::error::eof)
{
elog("Error sending to peer ${p}: ${i}", ("p", pname)("i", ec.message()));
}
else
{
ilog("icp_connection closure detected on write to ${p}", ("p", pname));
}
my_impl->close(conn);
return;
}
while (conn->out_queue.size() > 0)
{
conn->out_queue.pop_front();
}
//conn->enqueue_sync_block();
conn->do_queue_write();
}
catch (const std::exception &ex)
{
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no icp_connection name";
elog("Exception in do_queue_write to ${p} ${s}", ("p", pname)("s", ex.what()));
}
catch (const fc::exception &ex)
{
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no icp_connection name";
elog("Exception in do_queue_write to ${p} ${s}", ("p", pname)("s", ex.to_string()));
}
catch (...)
{
auto conn = c.lock();
string pname = conn ? conn->peer_name() : "no icp_connection name";
elog("Exception in do_queue_write to ${p}", ("p", pname));
}
});
}
void icp_connection::send_handshake()
{
handshake_initializer::populate(last_handshake_sent);
last_handshake_sent.generation = ++sent_handshake_count;
//ilog("after send handshake , count is ${g}",("g",sent_handshake_count));
ilog("Sending handshake generation ${g} to ${ep}",
("g", last_handshake_sent.generation)("ep", peer_name()));
fc_dlog(icp_logger, "Sending handshake generation ${g} to ${ep}",
("g", last_handshake_sent.generation)("ep", peer_name()));
enqueue(last_handshake_sent);
}
void icp_connection::send_icp_net_msg(const icp_net_message &msg)
{
enqueue(msg);
}
void icp_connection::enqueue(const icp_net_message &m, bool trigger_send)
{
icp_go_away_reason close_after_send = icp_no_reason;
if (m.contains<icp_go_away_message>())
{
close_after_send = m.get<icp_go_away_message>().reason;
}
uint32_t payload_size = fc::raw::pack_size(m);
char *header = reinterpret_cast<char *>(&payload_size);
size_t header_size = sizeof(payload_size);
size_t buffer_size = header_size + payload_size;
auto send_buffer = std::make_shared<vector<char>>(buffer_size);
fc::datastream<char *> ds(send_buffer->data(), buffer_size);
ds.write(header, header_size);
fc::raw::pack(ds, m);
icp_connection_wptr weak_this = shared_from_this();
auto relay_temp = my_impl;
queue_write(send_buffer, trigger_send,
[weak_this, close_after_send, relay_temp](boost::system::error_code ec, std::size_t) {
icp_connection_ptr conn = weak_this.lock();
if (conn)
{
if (close_after_send != icp_no_reason)
{
elog("sent a go away message: ${r}, closing connection to ${p}", ("r", reason_str(close_after_send))("p", conn->peer_name()));
relay_temp->close(conn);
return;
}
}
else
{
fc_wlog(icp_logger, "connection expired before enqueued net_message called callback!");
}
});
}
void icp_connection::cancel_wait()
{
if (response_expected)
response_expected->cancel();
}
void icp_connection::sync_wait()
{
response_expected->expires_from_now(my_impl->resp_expected_period);
icp_connection_wptr c(shared_from_this());
response_expected->async_wait([c](boost::system::error_code ec) {
icp_connection_ptr conn = c.lock();
if (!conn)
{
// icp_connection was destroyed before this lambda was delivered
return;
}
conn->sync_timeout(ec);
});
}
void icp_connection::fetch_wait()
{
// response_expected->expires_from_now( my_impl->resp_expected_period);
// icp_connection_wptr c(shared_from_this());
// response_expected->async_wait( [c]( boost::system::error_code ec){
// icp_connection_ptr conn = c.lock();
// if (!conn) {
// // icp_connection was destroyed before this lambda was delivered
// return;
// }
// conn->fetch_timeout(ec);
// } );
}
void icp_connection::sync_timeout(boost::system::error_code ec)
{
// if( !ec ) {
// my_impl->sync_master->reassign_fetch (shared_from_this(),benign_other);
// }
// else if( ec == boost::asio::error::operation_aborted) {
// }
// else {
// elog ("setting timer for sync request got error ${ec}",("ec", ec.message()));
// }
}
void icp_connection::fetch_timeout(boost::system::error_code ec)
{
// if( !ec ) {
// if( pending_fetch.valid() && !( pending_fetch->req_trx.empty( ) || pending_fetch->req_blocks.empty( ) ) ) {
// my_impl->dispatcher->retry_fetch (shared_from_this() );
// }
// }
// else if( ec == boost::asio::error::operation_aborted ) {
// if( !connected( ) ) {
// fc_dlog(logger, "fetch timeout was cancelled due to dead icp_connection");
// }
// }
// else {
// elog( "setting timer for fetch request got error ${ec}", ("ec", ec.message( ) ) );
// }
}
}
| 31.747126 | 153 | 0.564374 | aiguo186 |
8d2f9bfc0f1e2b8e955b9ab40b0d4bb2ef906017 | 6,410 | cpp | C++ | src_c/adapter.cpp | ptenbrock/SimpleBLE | 84e7b99d9560f54b4a18db6def16c4ca09f750a8 | [
"MIT"
] | 45 | 2021-08-31T02:04:10.000Z | 2022-03-26T02:26:18.000Z | src_c/adapter.cpp | ptenbrock/SimpleBLE | 84e7b99d9560f54b4a18db6def16c4ca09f750a8 | [
"MIT"
] | 32 | 2021-09-08T05:11:00.000Z | 2022-03-29T07:13:31.000Z | src_c/adapter.cpp | ptenbrock/SimpleBLE | 84e7b99d9560f54b4a18db6def16c4ca09f750a8 | [
"MIT"
] | 8 | 2021-08-31T01:53:34.000Z | 2022-01-31T17:57:45.000Z | #include <simpleble_c/adapter.h>
#include <simpleble/AdapterSafe.h>
#include <cstring>
size_t simpleble_adapter_get_count(void) {
return SimpleBLE::Safe::Adapter::get_adapters().value_or(std::vector<SimpleBLE::Safe::Adapter>()).size();
}
simpleble_adapter_t simpleble_adapter_get_handle(size_t index) {
auto adapter_list = SimpleBLE::Safe::Adapter::get_adapters().value_or(std::vector<SimpleBLE::Safe::Adapter>());
if (index >= adapter_list.size()) {
return nullptr;
}
SimpleBLE::Safe::Adapter* handle = new SimpleBLE::Safe::Adapter(adapter_list[index]);
return handle;
}
void simpleble_adapter_release_handle(simpleble_adapter_t handle) {
if (handle == nullptr) {
return;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
delete adapter;
}
char* simpleble_adapter_identifier(simpleble_adapter_t handle) {
if (handle == nullptr) {
return nullptr;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
std::string identifier = adapter->identifier().value_or("");
char* c_identifier = (char*)malloc(identifier.size() + 1);
strcpy(c_identifier, identifier.c_str());
return c_identifier;
}
char* simpleble_adapter_address(simpleble_adapter_t handle) {
if (handle == nullptr) {
return nullptr;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
std::string address = adapter->address().value_or("");
char* c_address = (char*)malloc(address.size() + 1);
strcpy(c_address, address.c_str());
return c_address;
}
simpleble_err_t simpleble_adapter_scan_start(simpleble_adapter_t handle) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
return adapter->scan_start() ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_scan_stop(simpleble_adapter_t handle) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
return adapter->scan_stop() ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_scan_is_active(simpleble_adapter_t handle, bool* active) {
if (handle == nullptr || active == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
std::optional<bool> is_active = adapter->scan_is_active();
*active = is_active.value_or(false);
return is_active.has_value() ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_scan_for(simpleble_adapter_t handle, int timeout_ms) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
return adapter->scan_for(timeout_ms) ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
size_t simpleble_adapter_scan_get_results_count(simpleble_adapter_t handle) {
if (handle == nullptr) {
return 0;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
return adapter->scan_get_results().value_or(std::vector<SimpleBLE::Safe::Peripheral>()).size();
}
simpleble_peripheral_t simpleble_adapter_scan_get_results_handle(simpleble_adapter_t handle, size_t index) {
if (handle == nullptr) {
return nullptr;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
std::vector<SimpleBLE::Safe::Peripheral> results = adapter->scan_get_results().value_or(
std::vector<SimpleBLE::Safe::Peripheral>());
if (index >= results.size()) {
return nullptr;
}
SimpleBLE::Safe::Peripheral* peripheral_handle = new SimpleBLE::Safe::Peripheral(results[index]);
return peripheral_handle;
}
simpleble_err_t simpleble_adapter_set_callback_on_scan_start(simpleble_adapter_t handle,
void (*callback)(simpleble_adapter_t, void*),
void* userdata) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
bool success = adapter->set_callback_on_scan_start([=]() { callback(handle, userdata); });
return success ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_set_callback_on_scan_stop(simpleble_adapter_t handle,
void (*callback)(simpleble_adapter_t, void*),
void* userdata) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
bool success = adapter->set_callback_on_scan_stop([=]() { callback(handle, userdata); });
return success ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_set_callback_on_scan_updated(
simpleble_adapter_t handle, void (*callback)(simpleble_adapter_t, simpleble_peripheral_t, void*), void* userdata) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
bool success = adapter->set_callback_on_scan_updated([=](SimpleBLE::Safe::Peripheral peripheral) {
// Create a peripheral handle
SimpleBLE::Safe::Peripheral* peripheral_handle = new SimpleBLE::Safe::Peripheral(peripheral);
callback(handle, peripheral_handle, userdata);
});
return success ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
simpleble_err_t simpleble_adapter_set_callback_on_scan_found(
simpleble_adapter_t handle, void (*callback)(simpleble_adapter_t, simpleble_peripheral_t, void*), void* userdata) {
if (handle == nullptr) {
return SIMPLEBLE_FAILURE;
}
SimpleBLE::Safe::Adapter* adapter = (SimpleBLE::Safe::Adapter*)handle;
bool success = adapter->set_callback_on_scan_found([=](SimpleBLE::Safe::Peripheral peripheral) {
// Create a peripheral handle
SimpleBLE::Safe::Peripheral* peripheral_handle = new SimpleBLE::Safe::Peripheral(peripheral);
callback(handle, peripheral_handle, userdata);
});
return success ? SIMPLEBLE_SUCCESS : SIMPLEBLE_FAILURE;
}
| 36.214689 | 119 | 0.6883 | ptenbrock |
8d311660139afa4d82782e1f55edf337196c1a40 | 1,012 | cpp | C++ | view-cmake/src/ChrosomeChoice.cpp | limeng12/GenomeBrowser-CPlusPlus | 63d41a55d013cee9208e244cf154901461e12a30 | [
"BSD-3-Clause-Attribution"
] | 2 | 2019-10-14T09:29:38.000Z | 2021-04-25T00:16:40.000Z | view-cmake/src/ChrosomeChoice.cpp | limeng12/GenomeBrowser-CPlusPlus | 63d41a55d013cee9208e244cf154901461e12a30 | [
"BSD-3-Clause-Attribution"
] | null | null | null | view-cmake/src/ChrosomeChoice.cpp | limeng12/GenomeBrowser-CPlusPlus | 63d41a55d013cee9208e244cf154901461e12a30 | [
"BSD-3-Clause-Attribution"
] | null | null | null | #include "ChrosomeChoice.h"
wxBEGIN_EVENT_TABLE(ChrosomeChoice, wxListView)
EVT_LEFT_UP(ChrosomeChoice::OnDoubleClick)
wxEND_EVENT_TABLE()
ChrosomeChoice::ChrosomeChoice(/*pilot_viewFrame& parent):root(parent*/){
}
void ChrosomeChoice::Init(){
}
bool ChrosomeChoice::Create(wxWindow* parent){
return wxListView::Create(parent,1,wxDefaultPosition,wxDefaultSize);
}
wxWindow* ChrosomeChoice::GetControl(){
return this;
}
void ChrosomeChoice::SetStringValue(const wxString& s){
int n = wxListView::FindItem(-1,s);
if ( n >= 0 && n < wxListView::GetItemCount() )
wxListView::Select(n);
}
wxString ChrosomeChoice::GetStringValue() const{
if ( m_value >= 0 )
return wxListView::GetItemText(m_value);
return wxEmptyString;
}
void ChrosomeChoice::OnComboDoubleClick(){
//m_value=wxListView::GetFirstSelected();
// Dismiss();
//root.OnSelectChr();
}
void ChrosomeChoice::OnDoubleClick(wxMouseEvent& event){
m_value=wxListView::GetFirstSelected();
Dismiss();
}
| 19.843137 | 73 | 0.728261 | limeng12 |
8d349ab631f821a9820afc19d48db2c8446fadb0 | 15,842 | cpp | C++ | SDKs/CryCode/3.8.1/GameDll/AI/SearchModule.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | SDKs/CryCode/3.7.0/GameDll/AI/SearchModule.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | null | null | null | SDKs/CryCode/3.7.0/GameDll/AI/SearchModule.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | #include "StdAfx.h"
#include "SearchModule.h"
#include <IAgent.h>
#include <IAISystem.h>
#include <IAIObject.h>
#include <IRenderAuxGeom.h>
#include <ICoverSystem.h>
#include <VisionMapTypes.h>
#include "Agent.h"
#include "GameCVars.h"
SearchSpot::SearchSpot()
: m_pos(ZERO)
, m_status(NotSearchedYet)
, m_assigneeID(0)
, m_searchTimeoutLeft(0.0f)
, m_isTargetSearchSpot(false)
, m_lastTimeObserved(0.0f)
{
}
SearchSpot::~SearchSpot()
{
if (m_visionID)
{
assert(gEnv->pAISystem);
IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap();
visionMap.UnregisterObservable(m_visionID);
m_visionID = VisionID();
}
}
void SearchSpot::Init(const Vec3& pos, bool isTargetSpot /*= false*/ )
{
assert(pos.IsValid());
m_pos = pos;
m_status = NotSearchedYet;
m_isTargetSearchSpot = isTargetSpot;
assert(!m_visionID);
if (!m_visionID)
{
assert(gEnv->pAISystem);
IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap();
static unsigned int searchSpotCounter = 0;
string visionName;
visionName.Format("SearchSpot%d", searchSpotCounter++);
m_visionID = visionMap.CreateVisionID(visionName);
ObservableParams observableParams;
observableParams.observablePositionsCount = 1;
observableParams.observablePositions[0] = pos;
observableParams.typeMask = SearchSpots;
observableParams.faction = 31;
visionMap.RegisterObservable(m_visionID, observableParams);
}
}
void SearchSpot::DebugDraw(float searchTimeOut)
{
ColorB spotColor;
switch (m_status)
{
case NotSearchedYet:
spotColor = ColorB(0, 0, 255);
break;
case BeingSearchedRightAboutNow:
spotColor = ColorB(255, 255, 0);
break;
case Searched:
spotColor = ColorB(0, 255, 0);
break;
case Unreachable:
spotColor = ColorB(255, 0, 0);
break;
case SearchedTimingOut:
if(searchTimeOut)
{
uint8 green = (uint8)(255 * clamp_tpl( (m_searchTimeoutLeft / (searchTimeOut / 2.0f)), 0.0f, 1.0f));
uint8 blue = (uint8)(255 * clamp_tpl(((searchTimeOut - m_searchTimeoutLeft) / (searchTimeOut / 2.0f)), 0.0f, 1.0f));
spotColor = ColorB(0, green, blue);
}
break;
}
IRenderAuxGeom* pDebugRenderer = gEnv->pRenderer->GetIRenderAuxGeom();
pDebugRenderer->DrawSphere(m_pos, 0.3f, spotColor);
if (m_assigneeID)
{
Agent agent(m_assigneeID);
if (agent)
pDebugRenderer->DrawLine(agent.GetPos(), ColorB(255, 255, 0), m_pos, ColorB(255, 255, 0), 2.0f);
}
}
bool SearchSpot::IsAssignedTo(EntityId entityID) const
{
return m_assigneeID == entityID;
}
void SearchSpot::AssignTo(EntityId entityID)
{
m_assigneeID = entityID;
}
void SearchSpot::MarkAsSearchedBy(SearchActor& participant, float timeout)
{
if(m_assigneeID)
{
if (IsAssignedTo(participant.entityID))
{
Agent agent(participant.entityID);
if (agent)
{
if(m_isTargetSearchSpot)
agent.SetSignal(0, "OnTargetSearchSpotSeen");
agent.SetSignal(0, "OnAssignedSearchSpotSeen");
}
}
else
{
Agent agent(m_assigneeID);
if (agent)
{
agent.SetSignal(0, "OnAssignedSearchSpotSeenBySomeoneElse");
}
}
m_assigneeID = 0;
}
if(timeout > 0.0f)
{
m_searchTimeoutLeft = timeout;
m_status = SearchedTimingOut;
}
else
m_status = Searched;
m_lastTimeObserved = gEnv->pTimer->GetFrameStartTime();
}
void SearchSpot::MarkAsUnreachable()
{
m_status = Unreachable;
m_assigneeID = 0;
}
void SearchSpot::UpdateSearchedTimeout(float frameTime)
{
m_searchTimeoutLeft -= frameTime;
if(m_searchTimeoutLeft < 0.0f)
m_status = NotSearchedYet;
}
void SearchSpot::Serialize(TSerialize ser)
{
// VisionID is not serialized. It will be created in InitSearchSpots.
ser.Value("pos", m_pos);
ser.Value("assigneeID", m_assigneeID);
ser.Value("searchTimeoutLeft", m_searchTimeoutLeft);
ser.Value("isTargetSearchSpot", m_isTargetSearchSpot);
uint8 intStatus = (uint8)m_status;
ser.Value("status", intStatus);
if (ser.IsReading())
m_status = (SearchSpotStatus)intStatus;
}
void SearchGroup::Init(int groupID, const Vec3& targetPos, EntityId targetID, float searchSpotTimeout)
{
m_targetPos = targetPos;
m_targetID = targetID;
m_searchSpotTimeout = searchSpotTimeout;
StoreActors(groupID);
GenerateSearchSpots();
}
void SearchGroup::Destroy()
{
IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap();
SearchActorIter it = m_actors.begin();
SearchActorIter end = m_actors.end();
for ( ; it != end; ++it)
{
SearchActor& actor = *it;
visionMap.UnregisterObserver(actor.visionID);
}
m_actors.clear();
}
void SearchGroup::StoreActors(int groupID)
{
assert(m_actors.empty());
IAISystem& aiSystem = *gEnv->pAISystem;
uint groupSize = (uint)aiSystem.GetGroupCount(groupID);
m_actors.reserve(groupSize);
for (uint i = 0; i < groupSize; ++i)
{
if (IAIObject* pAI = aiSystem.GetGroupMember(groupID, i))
m_actors.push_back(SearchActor(pAI->GetEntityID()));
}
InitActors();
}
void SearchGroup::GenerateSearchSpots()
{
assert(m_searchSpots.empty());
const uint32 MaxCoverLocationsPerSurface = 3;
const uint32 MaxCoverLocations = 128;
Vec3 coverLocations[MaxCoverLocations];
const uint32 MaxEyeCount = 16;
Vec3 eyes[MaxEyeCount];
uint32 eyeCount = 0;
std::vector<SearchActor>::iterator actorIt = m_actors.begin();
std::vector<SearchActor>::iterator actorEnd = m_actors.end();
// for ( ; (eyeCount < MaxEyeCount) && (actorIt != actorEnd); ++actorIt)
// {
// SearchActor& actor = (*actorIt);
//
// Agent agent(actor.entityID);
// if(!agent.IsValid())
// continue;
//
// eyes[eyeCount++] = agent.GetPos();
// }
IAISystem& aiSystem = *gEnv->pAISystem;
uint32 locationCount =
aiSystem.GetCoverSystem()->GetCover(m_targetPos, 50.0f, &eyes[0], eyeCount, 0.45f, &coverLocations[0],
MaxCoverLocations, MaxCoverLocationsPerSurface);
// Filter out search spots too close to each other
for (uint32 i = 0; i < locationCount; ++i)
{
for (uint32 j = i + 1; j < locationCount;)
{
const float squaredDistance = coverLocations[i].GetSquaredDistance(coverLocations[j]);
if (squaredDistance < sqr(3.0f))
{
// Too close, remove j
coverLocations[j] = coverLocations[locationCount - 1];
--locationCount;
}
else
++j;
}
}
// Initialize search spots
m_searchSpots.resize(locationCount + 1);
for (uint32 i = 0; i < locationCount; ++i)
{
SearchSpot& spot = m_searchSpots[i];
spot.Init(coverLocations[i] + Vec3(0.0f, 0.0f, 0.5f));
}
// Adding targetSearchSpot to the searchSpots as well
m_searchSpots.back().Init(m_targetPos + Vec3(0.0f, 0.0f, 0.2f), true);
}
float SearchGroup::CalculateScore(SearchSpot& searchSpot, EntityId entityID, SearchSpotQuery* query, Vec3& targetCurrentPos) const
{
assert(query);
Agent agent(entityID);
if (agent.IsValid())
{
const Vec3 spotPosition = searchSpot.GetPos();
const Vec3 agentPosition = agent.GetPos();
const float agentToSpotDistance = agentPosition.GetDistance(spotPosition);
if (agentToSpotDistance < query->minDistanceFromAgent)
{
return -100.0f;
}
float closenessToAgentScore = 0.0f;
closenessToAgentScore = 1.0f - clamp_tpl(agentToSpotDistance, 1.0f, 50.0f) / 50.0f;
const float closenessToTargetScore = 1.0f - clamp_tpl(spotPosition.GetDistance(m_targetPos), 1.0f, 50.0f) / 50.0f;
float closenessToTargetCurrentPosScore = 0.0f;
if (!targetCurrentPos.IsZeroFast())
{
closenessToTargetCurrentPosScore = 1.0f - clamp_tpl(spotPosition.GetDistance(targetCurrentPos), 1.0f, 50.0f) / 50.0f;
}
return
closenessToAgentScore * query->closenessToAgentWeight +
closenessToTargetScore * query->closenessToTargetWeight +
closenessToTargetCurrentPosScore * query->closenessToTargetCurrentPosWeight;
}
else
{
return -100.0f;
}
}
void SearchGroup::Update()
{
IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap();
// Update vision
{
std::vector<SearchActor>::iterator actorIt = m_actors.begin();
std::vector<SearchActor>::iterator actorEnd = m_actors.end();
for ( ; actorIt != actorEnd; ++actorIt)
{
SearchActor& actor = (*actorIt);
Agent agent(actor.entityID);
if(!agent.IsValid())
continue;
ObserverParams observerParams;
observerParams.eyePosition = agent.GetPos();
observerParams.eyeDirection = agent.GetViewDir();
visionMap.ObserverChanged(actor.visionID, observerParams, eChangedPosition | eChangedOrientation);
}
}
// Debug draw target pos
if (g_pGameCVars->ai_DebugSearch)
{
IRenderAuxGeom* pDebugRenderer = gEnv->pRenderer->GetIRenderAuxGeom();
pDebugRenderer->DrawSphere(m_targetPos, 0.6f, ColorB(255, 255, 255, 128));
}
const float frameTime = gEnv->pTimer->GetFrameTime();
std::vector<SearchSpot>::iterator spotIt = m_searchSpots.begin();
std::vector<SearchSpot>::iterator spotEnd = m_searchSpots.end();
for ( ; spotIt != spotEnd; ++spotIt)
{
SearchSpot& searchSpot = (*spotIt);
if (g_pGameCVars->ai_DebugSearch)
searchSpot.DebugDraw(m_searchSpotTimeout);
if(searchSpot.IsTimingOut())
searchSpot.UpdateSearchedTimeout(frameTime);
if (searchSpot.HasBeenSearched())
continue;
// Naive Implementation!
// Go through all the actors and see
// if they see any of the search spots.
// Later on, use a callback for this!
SearchActorIter actorIt = m_actors.begin();
std::vector<SearchActor>::iterator actorEnd = m_actors.end();
for ( ; actorIt != actorEnd; ++actorIt)
{
SearchActor& actor = *actorIt;
if (visionMap.IsVisible(actor.visionID, searchSpot))
{
searchSpot.MarkAsSearchedBy(actor, m_searchSpotTimeout);
break;
}
}
}
}
bool SearchGroup::GetNextSearchPoint(EntityId entityID, SearchSpotQuery* query)
{
if (SearchSpot* best = FindBestSearchSpot(entityID, query))
{
SearchSpot* assignedSearchSpot = GetAssignedSearchSpot(entityID);
if(assignedSearchSpot)
{
assignedSearchSpot->m_assigneeID = 0;
assignedSearchSpot->m_status = NotSearchedYet;
}
assert(query);
query->result = best->GetPos();
best->m_status = BeingSearchedRightAboutNow;
best->m_assigneeID = entityID;
return true;
}
return false;
}
void SearchGroup::MarkAssignedSearchSpotAsUnreachable(EntityId entityID)
{
SearchSpot* assignedSpot = GetAssignedSearchSpot(entityID);
if (assignedSpot)
{
assignedSpot->m_status = Unreachable;
assignedSpot->m_assigneeID = 0;
}
}
void SearchGroup::AddEnteredEntity(const EntityId entityID)
{
stl::push_back_unique(m_enteredEntities, entityID);
}
void SearchGroup::RemoveEnteredEntity(const EntityId entityID)
{
stl::find_and_erase(m_enteredEntities, entityID);
}
bool SearchGroup::IsEmpty() const
{
return m_enteredEntities.empty();
}
SearchSpot* SearchGroup::FindBestSearchSpot(EntityId entityID, SearchSpotQuery* query)
{
SearchSpotIter it = m_searchSpots.begin();
SearchSpotIter end = m_searchSpots.end();
SearchSpot* bestScoredSearchSpot = NULL;
SearchSpot* lastSeenSearchSpot = NULL;
float bestScore = FLT_MIN;
Vec3 targetCurrentPos(ZERO);
if(m_targetID)
{
Agent agent(m_targetID);
if(agent.IsValid())
targetCurrentPos = agent.GetPos();
}
for ( ; it != end; ++it)
{
SearchSpot& searchSpot = (*it);
if (searchSpot.GetStatus() == NotSearchedYet)
{
float score = CalculateScore(searchSpot, entityID, query, targetCurrentPos);
if (score > bestScore)
{
bestScoredSearchSpot = &searchSpot;
bestScore = score;
}
}
if(searchSpot.GetStatus() != Unreachable && searchSpot.GetStatus() != BeingSearchedRightAboutNow)
{
if(!lastSeenSearchSpot || searchSpot.m_lastTimeObserved.GetValue() < lastSeenSearchSpot->m_lastTimeObserved.GetValue())
{
lastSeenSearchSpot = &searchSpot;
}
}
}
return bestScoredSearchSpot ? bestScoredSearchSpot : lastSeenSearchSpot;
}
SearchSpot* SearchGroup::GetAssignedSearchSpot(EntityId entityID)
{
// TODO: Fix this! It is implemented in a suuuuuper naive way.
// It's going through all search spots and sees if it
// has the agent as an assignee. We should have an internal
// representation of the agents so we can store this reference back.
SearchSpotIter it = m_searchSpots.begin();
SearchSpotIter end = m_searchSpots.end();
for ( ; it != end; ++it)
{
SearchSpot& spot = (*it);
if (spot.m_assigneeID == entityID)
return &spot;
}
return NULL;
}
void SearchGroup::InitActors()
{
IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap();
SearchActors::iterator actorIt = m_actors.begin();
SearchActors::iterator actorEnd = m_actors.end();
for ( ; actorIt != actorEnd; ++actorIt)
{
SearchActor& actor = *actorIt;
Agent agent(actor.entityID);
assert(agent.IsValid());
if (agent.IsValid())
{
actor.visionID = visionMap.CreateVisionID(agent.GetName());
ObserverParams observerParams;
observerParams.entityId = actor.entityID;
observerParams.factionsToObserveMask = 0xFFFFFFFF;
observerParams.typeMask = ::SearchSpots;
observerParams.eyePosition = agent.GetPos();
observerParams.eyeDirection = agent.GetViewDir();
observerParams.fovCos = cosf(120.0f);
observerParams.sightRange = 8.0f;
IScriptTable* entityTable = agent.GetScriptTable();
SmartScriptTable properties;
if (entityTable->GetValue("SearchModule", properties))
properties->GetValue("sightRange", observerParams.sightRange);
visionMap.RegisterObserver(actor.visionID, observerParams);
}
}
}
void SearchGroup::InitSearchSpots()
{
SearchSpots::iterator it = m_searchSpots.begin();
SearchSpots::iterator end = m_searchSpots.end();
for ( ; it != end; ++it)
{
SearchSpot& spot = *it;
spot.Init(spot.m_pos, spot.m_isTargetSearchSpot);
}
}
void SearchModule::EntityEnter(EntityId entityID)
{
Agent agent(entityID);
assert(agent.IsValid());
if (agent.IsValid())
{
if (SearchGroup* group = GetGroup(agent.GetGroupID()))
{
group->AddEnteredEntity(entityID);
}
}
}
void SearchModule::EntityLeave(EntityId entityID)
{
Agent agent(entityID);
if (agent.IsValid())
{
const int groupID = agent.GetGroupID();
if (SearchGroup* group = GetGroup(groupID))
{
group->RemoveEnteredEntity(entityID);
if (group->IsEmpty())
{
GroupLeave(groupID);
}
}
}
}
void SearchModule::Reset(bool bUnload)
{
SearchGroupIter it = m_groups.begin();
SearchGroupIter end = m_groups.end();
for ( ; it != end; ++it)
{
SearchGroup& group = it->second;
group.Destroy();
}
m_groups.clear();
}
void SearchModule::Update(float dt)
{
SearchGroupIter it = m_groups.begin();
SearchGroupIter end = m_groups.end();
for ( ; it != end; ++it)
{
SearchGroup& group = it->second;
group.Update();
}
}
void SearchModule::Serialize(TSerialize ser)
{
if (ser.IsReading())
{
Reset(false);
}
}
void SearchModule::PostSerialize()
{
}
void SearchModule::GroupEnter(int groupID, const Vec3& targetPos, EntityId targetID, float searchSpotTimeout)
{
if(GroupExist(groupID))
GroupLeave(groupID);
SearchGroup& group = m_groups[groupID];
group.Init(groupID, targetPos, targetID, searchSpotTimeout);
}
void SearchModule::GroupLeave(int groupID)
{
SearchGroupIter it = m_groups.find(groupID);
if (it != m_groups.end())
{
SearchGroup& group = it->second;
group.Destroy();
m_groups.erase(it);
}
}
bool SearchModule::GetNextSearchPoint(EntityId entityID, SearchSpotQuery* query)
{
Agent agent(entityID);
if (agent)
{
SearchGroup* group = GetGroup(agent.GetGroupID());
if (group)
return group->GetNextSearchPoint(entityID, query);
}
return false;
}
void SearchModule::MarkAssignedSearchSpotAsUnreachable(EntityId entityID)
{
Agent agent(entityID);
if (agent)
{
SearchGroup* group = GetGroup(agent.GetGroupID());
if (group)
return group->MarkAssignedSearchSpotAsUnreachable(entityID);
}
}
bool SearchModule::GroupExist(int groupID) const
{
return m_groups.find(groupID) != m_groups.end();
}
SearchGroup* SearchModule::GetGroup(int groupID)
{
SearchGroupIter it = m_groups.find(groupID);
if (it != m_groups.end())
return &it->second;
return NULL;
} | 23.33137 | 130 | 0.719669 | amrhead |
8d368125441ac76e55e32458dbc1880795411630 | 1,822 | cpp | C++ | src/node-mushrooms/app/project/shroom_task.cpp | cometurrata/mad-hatter | 1f84b2eafbd16258ec47b9db096bc60fc59aa859 | [
"MIT"
] | 4 | 2020-06-14T12:30:07.000Z | 2021-02-08T14:57:50.000Z | src/node-mushrooms/app/project/shroom_task.cpp | cometurrata/mad-hatter | 1f84b2eafbd16258ec47b9db096bc60fc59aa859 | [
"MIT"
] | null | null | null | src/node-mushrooms/app/project/shroom_task.cpp | cometurrata/mad-hatter | 1f84b2eafbd16258ec47b9db096bc60fc59aa859 | [
"MIT"
] | null | null | null | #include <stdint.h>
#include <SmingCore.h>
#include <Libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.h>
#include "http_client.h"
#include "shroom_task.h"
#include "shroom.h"
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp;
#define SDA_PIN 4
#define SCL_PIN 5
#define D8 15
#define D7 13
#define D6 12
#define D5 14
#define D0 16
#define D4 2
#define D3 0
#define D2 4
#define D1 5
#define RX 1
// How many NeoPixels are attached to the Esp8266?
#define NUMPIXELS 10
Shroom shroom1;
Shroom shroom2;
Shroom shroom3;
Shroom shroom4;
#define SHROOM_1_PIN D7
#define SHROOM_2_PIN D5
#define SHROOM_3_PIN D6
#define SHROOM_4_PIN D3
#define SHROOM_1_TOUCH 0
#define SHROOM_2_TOUCH 1
#define SHROOM_3_TOUCH 2
#define SHROOM_4_TOUCH 3
#include "shroom.h"
#include "tasks.h"
static int combinaisonIndex = 0;
// Purple green red blue red
static uint8_t combinaison[5] = { 1, 2, 3, 4, 3};
void checkCombinaison(int id)
{
if (id == combinaison[combinaisonIndex])
{
debugf("checkCombinaison index: %d", combinaisonIndex);
combinaisonIndex++;
if (combinaisonIndex >= 4)
{
combinaisonIndex = 0;
nodeMushrooms.setSolved(true).sendUpdateNow();
}
}
else
{
combinaisonIndex = 0;
}
}
void onTouch(String name)
{
debugf("touched: %s", name.c_str());
checkCombinaison(name.toInt());
}
void shroomInit()
{
Wire.pins(SDA_PIN, SCL_PIN); // SDA, SCL
mcp.begin();
shroom1.init(mcp, SHROOM_1_TOUCH, SHROOM_1_PIN, NUMPIXELS, "1", onTouch);
shroom2.init(mcp, SHROOM_2_TOUCH, SHROOM_2_PIN, NUMPIXELS, "2", onTouch);
shroom3.init(mcp, SHROOM_3_TOUCH, SHROOM_3_PIN, NUMPIXELS, "3", onTouch);
shroom4.init(mcp, SHROOM_4_TOUCH, SHROOM_4_PIN, NUMPIXELS, "4", onTouch);
}
| 21.435294 | 77 | 0.678924 | cometurrata |
8d3bb23eb71b2bff425327e42addd0ee6081a202 | 16,286 | cpp | C++ | SoftRast/Texture.cpp | mathieuchartier/SoftRast | 0987c1abfbe104a403642e96e72c973d69f0f8d1 | [
"MIT"
] | 38 | 2019-04-03T13:43:32.000Z | 2022-02-10T17:29:35.000Z | SoftRast/Texture.cpp | mathieuchartier/SoftRast | 0987c1abfbe104a403642e96e72c973d69f0f8d1 | [
"MIT"
] | 1 | 2019-09-23T23:23:30.000Z | 2019-09-24T09:08:24.000Z | SoftRast/Texture.cpp | mathieuchartier/SoftRast | 0987c1abfbe104a403642e96e72c973d69f0f8d1 | [
"MIT"
] | 5 | 2020-04-23T05:59:48.000Z | 2022-01-30T17:22:43.000Z | #include <string.h>
#include <intrin.h>
#include <immintrin.h>
#include <kt/Memory.h>
#include <kt/Logging.h>
#include "Texture.h"
#include "stb_image.h"
#include "stb_image_resize.h"
#define SR_TILE_TEXTURES (1)
namespace kt
{
template <>
void Serialize(ISerializer* _s, sr::Tex::TextureData& _tex)
{
Serialize(_s, _tex.m_texels);
Serialize(_s, _tex.m_widthLog2);
Serialize(_s, _tex.m_heightLog2);
Serialize(_s, _tex.m_bytesPerPixel);
Serialize(_s, _tex.m_mipOffsets);
Serialize(_s, _tex.m_numMips);
}
}
namespace sr
{
namespace Tex
{
static uint32_t MortonEncode(uint32_t _x, uint32_t _y)
{
constexpr uint32_t pdep_x_mask = 0x55555555; // 0b010101 ...
constexpr uint32_t pdep_y_mask = 0xAAAAAAAA; // 0b101010 ...
return _pdep_u32(_x, pdep_x_mask) | _pdep_u32(_y, pdep_y_mask);
}
// https://lemire.me/blog/2018/01/09/how-fast-can-you-bit-interleave-32-bit-integers-simd-edition/
__m256i interleave_uint8_with_zeros_avx_lut(__m256i word)
{
const __m256i m = _mm256_set_epi8(85, 84, 81, 80, 69, 68,
65, 64, 21, 20, 17, 16, 5, 4, 1, 0, 85, 84,
81, 80, 69, 68, 65, 64, 21, 20, 17, 16, 5,
4, 1, 0);
__m256i lownibbles =
_mm256_shuffle_epi8(m, _mm256_and_si256(word,
_mm256_set1_epi8(0xf)));
__m256i highnibbles = _mm256_and_si256(word,
_mm256_set1_epi8(0xf0));
highnibbles = _mm256_srli_epi16(highnibbles, 4);
highnibbles = _mm256_shuffle_epi8(m, highnibbles);
highnibbles = _mm256_slli_epi16(highnibbles, 8);
return _mm256_or_si256(lownibbles, highnibbles);
}
static __m256i MortonEncode_AVX(__m256i _x, __m256i _y)
{
__m256i const interleaved_x = interleave_uint8_with_zeros_avx_lut(_x);
__m256i const interleaved_y = interleave_uint8_with_zeros_avx_lut(_y);
return _mm256_or_si256(interleaved_x, _mm256_slli_epi32(interleaved_y, 1));
}
constexpr uint32_t c_texTileSizeLog2 = 5;
constexpr uint32_t c_texTileSize = 1 << c_texTileSizeLog2;
constexpr uint32_t c_texTileMask = c_texTileSize - 1;
static void TileTexture(uint8_t const* _src, uint8_t* _dest, uint32_t const dimX_noPad, uint32_t const dimY_noPad)
{
#if SR_TILE_TEXTURES
uint32_t const mipTileWidth = uint32_t(kt::AlignUp(dimX_noPad, c_texTileSize)) >> c_texTileSizeLog2;
// Naive tile+swizzling of texture.
// Go over the texture in linear order, find the tiled offset and morton code the inner tile coordinates.
for (uint32_t yy = 0; yy < dimY_noPad; ++yy)
{
for (uint32_t xx = 0; xx < dimX_noPad; ++xx)
{
uint32_t const linearOffs = yy * dimX_noPad + xx;
uint32_t const tileX = xx >> c_texTileSizeLog2;
uint32_t const tileY = yy >> c_texTileSizeLog2;
uint32_t const inTileAddressX = xx & c_texTileMask;
uint32_t const inTileAddressY = yy & c_texTileMask;
uint32_t const morton = MortonEncode(inTileAddressX, inTileAddressY);
uint32_t const tiledOffs = (tileY * mipTileWidth + tileX) * (c_texTileSize * c_texTileSize) + morton;
memcpy(_dest + tiledOffs * 4, _src + linearOffs * 4, 4);
}
}
#else
memcpy(_dest, _src, dimX_noPad * dimY_noPad * sizeof(uint32_t));
#endif
}
void TextureData::CreateFromFile(char const* _file)
{
Clear();
static uint32_t const req_comp = 4;
int x, y, comp;
uint8_t* srcImageData = stbi_load(_file, &x, &y, &comp, req_comp);
if (!srcImageData)
{
KT_LOG_ERROR("Failed to load texture: %s", _file);
return;
}
KT_SCOPE_EXIT(stbi_image_free(srcImageData));
CreateFromRGBA8(srcImageData, uint32_t(x), uint32_t(y), true);
}
void TextureData::CreateFromRGBA8(uint8_t const* _texels, uint32_t _width, uint32_t _height, bool _calcMips /*= false*/)
{
KT_ASSERT(kt::IsPow2(_width) && kt::IsPow2(_height));
m_widthLog2 = kt::FloorLog2(uint32_t(_width));
m_heightLog2 = kt::FloorLog2(uint32_t(_height));
KT_ASSERT(m_heightLog2 < Config::c_maxTexDimLog2);
KT_ASSERT(m_widthLog2 < Config::c_maxTexDimLog2);
KT_ASSERT((_width % c_texTileSize) == 0);
KT_ASSERT((_height % c_texTileSize) == 0); // TODO: Pad if this isn't true (but will be with 2^x x>=5)
m_bytesPerPixel = 4;
if (!_calcMips)
{
m_numMips = 1;
m_mipOffsets[0] = 0;
m_texels.Resize(_width * _height * m_bytesPerPixel);
TileTexture(_texels, m_texels.Data(), _width, _height);
return;
}
// Calculate mips.
uint32_t const fullMipChainLen = kt::FloorLog2(kt::Max(uint32_t(_width), uint32_t(_height))) + 1; // +1 for base tex.
m_numMips = fullMipChainLen;
struct MipInfo
{
uint32_t m_offs;
uint32_t m_dims[2];
};
uint32_t curMipDataOffset = 0;
MipInfo* mipInfos = (MipInfo*)KT_ALLOCA(sizeof(MipInfo) * fullMipChainLen);
for (uint32_t mipIdx = 0; mipIdx < fullMipChainLen; ++mipIdx)
{
CalcMipDims2D(uint32_t(_width), uint32_t(_height), mipIdx, mipInfos[mipIdx].m_dims);
mipInfos[mipIdx].m_offs = curMipDataOffset;
m_mipOffsets[mipIdx] = curMipDataOffset;
// Align the offset to account for tiling
#if SR_TILE_TEXTURES
uint32_t const mipDimX_tilePad = uint32_t(kt::AlignUp(mipInfos[mipIdx].m_dims[0], c_texTileSize));
uint32_t const mipDimY_tilePad = uint32_t(kt::AlignUp(mipInfos[mipIdx].m_dims[1], c_texTileSize));
#else
uint32_t const mipDimX_tilePad = mipInfos[mipIdx].m_dims[0];
uint32_t const mipDimY_tilePad = mipInfos[mipIdx].m_dims[1];
#endif
curMipDataOffset += mipDimX_tilePad * mipDimY_tilePad * m_bytesPerPixel;
}
m_texels.Resize(curMipDataOffset);
uint8_t* texWritePointer = m_texels.Data();
// tile mip 0
TileTexture(_texels, texWritePointer, mipInfos[0].m_dims[0], mipInfos[0].m_dims[1]);
uint32_t const largestMipSize = _width * _height * m_bytesPerPixel;
uint8_t* tempResizeBuff = (uint8_t*)kt::Malloc(largestMipSize);
KT_SCOPE_EXIT(kt::Free(tempResizeBuff));
for (uint32_t mipIdx = 1; mipIdx < fullMipChainLen; ++mipIdx)
{
MipInfo const& mipInfo = mipInfos[mipIdx];
uint8_t* mipPtr = texWritePointer + mipInfo.m_offs;
uint32_t const mipDimX = mipInfo.m_dims[0];
uint32_t const mipDimY = mipInfo.m_dims[1];
stbir_resize_uint8(_texels, _width, _height, 0, tempResizeBuff, mipDimX, mipDimY, 0, m_bytesPerPixel);
TileTexture(tempResizeBuff, mipPtr, mipDimX, mipDimY);
}
}
void TextureData::Clear()
{
m_texels.ClearAndFree();
}
void CalcMipDims2D(uint32_t _x, uint32_t _y, uint32_t _level, uint32_t o_dims[2])
{
o_dims[0] = kt::Max<uint32_t>(1u, _x >> _level);
o_dims[1] = kt::Max<uint32_t>(1u, _y >> _level);
}
__m256i CalcMipLevels(TextureData const& _tex, __m256 _dudx, __m256 _dudy, __m256 _dvdx, __m256 _dvdy)
{
__m256 const height = _mm256_set1_ps(float(1u << _tex.m_heightLog2));
__m256 const width = _mm256_set1_ps(float(1u << _tex.m_widthLog2));
__m256 const dudx_tex = _mm256_mul_ps(_dudx, width);
__m256 const dudy_tex = _mm256_mul_ps(_dudy, height);
__m256 const dvdx_tex = _mm256_mul_ps(_dvdx, width);
__m256 const dvdy_tex = _mm256_mul_ps(_dvdy, height);
// Work out the texture coordinate with the largest derivative.
// -> max(dot(dudx, dudy), dot(dvdx, dvdy))
__m256 const du_dot2 = _mm256_fmadd_ps(dudx_tex, dudx_tex, _mm256_mul_ps(dudy_tex, dudy_tex));
__m256 const dv_dot2 = _mm256_fmadd_ps(dvdx_tex, dvdx_tex, _mm256_mul_ps(dvdy_tex, dvdy_tex));
// Todo: with proper log2 we can use identity log2(x^(1/2)) == 0.5 * log2(x) and remove sqrt.
__m256 const maxCoord = _mm256_sqrt_ps(_mm256_max_ps(du_dot2, dv_dot2));
// Approximate (floor) log2 by extracting exponent.
return _mm256_min_epi32(_mm256_set1_epi32(_tex.m_numMips - 1), _mm256_max_epi32(_mm256_setzero_si256(), simdutil::ExtractExponent(maxCoord)));
}
static __m256i BoundCoordsWrap(__m256i _coord, __m256i _bound)
{
// Assuming width and height are powers of two.
__m256i const one = _mm256_set1_epi32(1);
return _mm256_and_si256(_coord, _mm256_sub_epi32(_bound, one));
}
static void GatherQuadsAndInterpolate
(
TextureData const& _tex,
uint32_t _mips[8],
__m256i _mipWidth,
__m256i _x0,
__m256i _y0,
__m256i _x1,
__m256i _y1,
__m256& o_r,
__m256& o_g,
__m256& o_b,
__m256& o_a,
float _interpU[8],
float _interpV[8],
uint32_t _execMask
)
{
// Compute the tile offsets.
KT_ALIGNAS(32) uint32_t morton_x0y0[8];
KT_ALIGNAS(32) uint32_t morton_x1y0[8];
KT_ALIGNAS(32) uint32_t morton_x1y1[8];
KT_ALIGNAS(32) uint32_t morton_x0y1[8];
#if SR_TILE_TEXTURES
{
__m256i const tileX0 = _mm256_srli_epi32(_x0, c_texTileSizeLog2);
__m256i const tileY0 = _mm256_srli_epi32(_y0, c_texTileSizeLog2);
__m256i const tileX1 = _mm256_srli_epi32(_x1, c_texTileSizeLog2);
__m256i const tileY1 = _mm256_srli_epi32(_y1, c_texTileSizeLog2);
__m256i const c_texTileMaskAvx = _mm256_set1_epi32(c_texTileMask);
// Compute the inner-tile coordinates.
__m256i const inTileAddressX0 = _mm256_and_si256(_x0, c_texTileMaskAvx);
__m256i const inTileAddressY0 = _mm256_and_si256(_y0, c_texTileMaskAvx);
__m256i const inTileAddressX1 = _mm256_and_si256(_x1, c_texTileMaskAvx);
__m256i const inTileAddressY1 = _mm256_and_si256(_y1, c_texTileMaskAvx);
// TODO: Broken for non pow2 textures (we assert not supporting those though!)
__m256i const texTileSize = _mm256_set1_epi32(c_texTileSize);
__m256i const mipTileWidth = _mm256_srli_epi32(_mm256_max_epi32(_mipWidth, texTileSize), c_texTileSizeLog2);
// Compute the linear offset to the start of each tile (not including bytes per pixel).
__m256i const offs_x0y0 = _mm256_mullo_epi32(_mm256_set1_epi32(c_texTileSize * c_texTileSize), _mm256_add_epi32(_mm256_mullo_epi32(tileY0, mipTileWidth), tileX0));
__m256i const offs_x1y0 = _mm256_mullo_epi32(_mm256_set1_epi32(c_texTileSize * c_texTileSize), _mm256_add_epi32(_mm256_mullo_epi32(tileY0, mipTileWidth), tileX1));
__m256i const offs_x0y1 = _mm256_mullo_epi32(_mm256_set1_epi32(c_texTileSize * c_texTileSize), _mm256_add_epi32(_mm256_mullo_epi32(tileY1, mipTileWidth), tileX0));
__m256i const offs_x1y1 = _mm256_mullo_epi32(_mm256_set1_epi32(c_texTileSize * c_texTileSize), _mm256_add_epi32(_mm256_mullo_epi32(tileY1, mipTileWidth), tileX1));
// Add offset to morton encoded inner tile coordinates, multiply by 4 for bytes per pixel.
// This is the final pixel offset.
_mm256_store_si256((__m256i*)morton_x0y0, _mm256_slli_epi32(_mm256_add_epi32(offs_x0y0, MortonEncode_AVX(inTileAddressX0, inTileAddressY0)), 2));
_mm256_store_si256((__m256i*)morton_x1y0, _mm256_slli_epi32(_mm256_add_epi32(offs_x1y0, MortonEncode_AVX(inTileAddressX1, inTileAddressY0)), 2));
_mm256_store_si256((__m256i*)morton_x1y1, _mm256_slli_epi32(_mm256_add_epi32(offs_x1y1, MortonEncode_AVX(inTileAddressX1, inTileAddressY1)), 2));
_mm256_store_si256((__m256i*)morton_x0y1, _mm256_slli_epi32(_mm256_add_epi32(offs_x0y1, MortonEncode_AVX(inTileAddressX0, inTileAddressY1)), 2));
}
#else
{
_mm256_store_si256((__m256i*)morton_x0y0, _mm256_slli_epi32(_mm256_add_epi32(_x0, _mm256_mullo_epi32(_y0, _mipWidth)), 2));
_mm256_store_si256((__m256i*)morton_x0y1, _mm256_slli_epi32(_mm256_add_epi32(_x0, _mm256_mullo_epi32(_y1, _mipWidth)), 2));
_mm256_store_si256((__m256i*)morton_x1y0, _mm256_slli_epi32(_mm256_add_epi32(_x1, _mm256_mullo_epi32(_y0, _mipWidth)), 2));
_mm256_store_si256((__m256i*)morton_x1y1, _mm256_slli_epi32(_mm256_add_epi32(_x1, _mm256_mullo_epi32(_y1, _mipWidth)), 2));
}
#endif
// | denotes ymm reg split. Each row is a ymm reg.
// If we load AoS with stride like this than we can tranpose independent 4x4 sub matrix in registers without cross lane permutes.
// AoS SoA
// [rgba0|rgba4] [r0123|r4567]
// [rgba1|rgba5] [g0123|g4567]
// [rgba2|rgba6] -> [b0123|b4567]
// [rgba3|rgba7] [b0123|b4567]
// f(x) = float offest
// f(0) = 0
// f(1) = 8
// f(2) = 16
// f(3) = 24
// f(4) = 4
// f(5) = 12
// f(6) = 20
// f(7) = 28
// f = x >= 4 ? (x%4)*8+4 : x*8
KT_ALIGNAS(32) float interpolatedTexels[8 * 4];
// Todo: this assumes that we are shading in lanes and that the execution mask never has any holes, only some bits from msb stripped.
uint32_t const numQuads = kt::Popcnt(_execMask);
for (uint32_t i = 0; i < numQuads; ++i)
{
uint8_t const* mipPtr = _tex.m_texels.Data() + _tex.m_mipOffsets[_mips[i]];
__m128 x0y0_tex, x1y1_tex, x1y0_tex, x0y1_tex;
// Convert each pixel in the quad and store.
{
uint8_t const* pix_x0y0 = mipPtr + morton_x0y0[i];
__m128i const x0y0 = _mm_cvtsi32_si128(*(uint32_t*)pix_x0y0);
x0y0_tex = _mm_mul_ps(_mm_set1_ps(1.0f / 255.0f), _mm_cvtepi32_ps(_mm_cvtepu8_epi32(x0y0)));
}
{
uint8_t const* pix_x1y0 = mipPtr + morton_x1y0[i];
__m128i const x1y0 = _mm_cvtsi32_si128(*(uint32_t*)pix_x1y0);
x1y0_tex = _mm_mul_ps(_mm_set1_ps(1.0f / 255.0f), _mm_cvtepi32_ps(_mm_cvtepu8_epi32(x1y0)));
}
{
uint8_t const* pix_x1y1 = mipPtr + morton_x1y1[i];
__m128i const x1y1 = _mm_cvtsi32_si128(*(uint32_t*)pix_x1y1);
x1y1_tex = _mm_mul_ps(_mm_set1_ps(1.0f / 255.0f), _mm_cvtepi32_ps(_mm_cvtepu8_epi32(x1y1)));
}
{
uint8_t const* pix_x0y1 = mipPtr + morton_x0y1[i];
__m128i const x0y1 = _mm_cvtsi32_si128(*(uint32_t*)pix_x0y1);
x0y1_tex = _mm_mul_ps(_mm_set1_ps(1.0f / 255.0f), _mm_cvtepi32_ps(_mm_cvtepu8_epi32(x0y1)));
}
__m128 const interpU_broadcast = _mm_broadcast_ss(_interpU + i);
__m128 const interpV_broadcast = _mm_broadcast_ss(_interpV + i);
__m128 const left = simdutil::Lerp(x0y0_tex, x0y1_tex, interpV_broadcast);
__m128 const right = simdutil::Lerp(x1y0_tex, x1y1_tex, interpV_broadcast);
__m128 const finalInterp = simdutil::Lerp(left, right, interpU_broadcast);
// See above comment.
uint32_t const writeIdx = i >= 4 ? (i & 3) * 8 + 4 : i * 8;
_mm_store_ps(interpolatedTexels + writeIdx, finalInterp);
}
o_r = _mm256_load_ps(interpolatedTexels);
o_g = _mm256_load_ps(interpolatedTexels + 8);
o_b = _mm256_load_ps(interpolatedTexels + 16);
o_a = _mm256_load_ps(interpolatedTexels + 24);
simdutil::Transpose4x4SubMatricies(o_r, o_g, o_b, o_a);
}
void SampleWrap
(
TextureData const& _tex,
__m256 _u,
__m256 _v,
__m256 _dudx,
__m256 _dudy,
__m256 _dvdx,
__m256 _dvdy,
__m256& o_r,
__m256& o_g,
__m256& o_b,
__m256& o_a,
uint32_t _execMask
)
{
__m256i const mipFloor = CalcMipLevels(_tex, _dudx, _dudy, _dvdx, _dvdy);
__m256i const one = _mm256_set1_epi32(1);
__m256i const widthLog2 = _mm256_set1_epi32(_tex.m_widthLog2);
__m256i const heightLog2 = _mm256_set1_epi32(_tex.m_heightLog2);
// Calculate mip widths.
__m256i const width = _mm256_sllv_epi32(one, _mm256_sub_epi32(widthLog2, _mm256_min_epi32(widthLog2, mipFloor)));
__m256i const height = _mm256_sllv_epi32(one, _mm256_sub_epi32(heightLog2, _mm256_min_epi32(heightLog2, mipFloor)));
__m256 const signBit = SR_AVX_LOAD_CONST_FLOAT(simdutil::c_avxSignBit);
// Perform wrapping of uv coordinates and account for sign.
__m256 const uSign = _mm256_and_ps(signBit, _u);
__m256 const vSign = _mm256_and_ps(signBit, _v);
__m256 const absU = _mm256_xor_ps(uSign, _u);
__m256 const absV = _mm256_xor_ps(vSign, _v);
__m256 const fracU = _mm256_sub_ps(absU, _mm256_floor_ps(absU));
__m256 const fracV = _mm256_sub_ps(absV, _mm256_floor_ps(absV));
__m256 const fracU_wrap = _mm256_blendv_ps(fracU, _mm256_sub_ps(_mm256_set1_ps(1.0f), fracU), uSign);
__m256 const fracV_wrap = _mm256_blendv_ps(fracV, _mm256_sub_ps(_mm256_set1_ps(1.0f), fracV), vSign);
__m256 const widthF = _mm256_cvtepi32_ps(width);
__m256 const heightF = _mm256_cvtepi32_ps(height);
__m256 const u_texSpace = _mm256_mul_ps(widthF, fracU_wrap);
__m256 const v_texSpace = _mm256_mul_ps(heightF, fracV_wrap);
__m256 const u_texSpace_floor = _mm256_floor_ps(u_texSpace);
__m256 const v_texSpace_floor = _mm256_floor_ps(v_texSpace);
__m256 const u_interp = _mm256_sub_ps(u_texSpace, u_texSpace_floor);
__m256 const v_interp = _mm256_sub_ps(v_texSpace, v_texSpace_floor);
__m256i const x0 = BoundCoordsWrap(_mm256_cvtps_epi32(u_texSpace_floor), width);
__m256i const y0 = BoundCoordsWrap(_mm256_cvtps_epi32(v_texSpace_floor), height);
__m256i const x1 = BoundCoordsWrap(_mm256_add_epi32(x0, one), width);
__m256i const y1 = BoundCoordsWrap(_mm256_add_epi32(y0, one), height);
KT_ALIGNAS(32) uint32_t mips[8];
_mm256_store_si256((__m256i*)mips, mipFloor);
KT_ALIGNAS(32) float interpU[8];
KT_ALIGNAS(32) float interpV[8];
_mm256_store_ps(interpU, u_interp);
_mm256_store_ps(interpV, v_interp);
GatherQuadsAndInterpolate(_tex, mips, width, x0, y0, x1, y1, o_r, o_g, o_b, o_a, interpU, interpV, _execMask);
}
}
} | 35.793407 | 165 | 0.751811 | mathieuchartier |
8d3d6f8872e5ae389dac5b29543d4ed0a4f7c8ca | 12,977 | hpp | C++ | libraries/chain/include/eos/chain/record_functions.hpp | brendankirby/eos | 233ba4e54bd53a7cf6ac68898fd25c44345737fa | [
"MIT"
] | 2 | 2018-01-06T12:12:28.000Z | 2021-12-25T11:09:37.000Z | libraries/chain/include/eos/chain/record_functions.hpp | lijava2002/eos | 2cc40a4eed76b797ba1382ab461fe8b6d3f518c4 | [
"MIT"
] | null | null | null | libraries/chain/include/eos/chain/record_functions.hpp | lijava2002/eos | 2cc40a4eed76b797ba1382ab461fe8b6d3f518c4 | [
"MIT"
] | 1 | 2021-04-04T23:28:27.000Z | 2021-04-04T23:28:27.000Z | /**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eos/chain/key_value_object.hpp>
namespace eosio { namespace chain {
/// find_tuple helper
template <typename T>
struct find_tuple {};
template <>
struct find_tuple<key_value_object> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys);
}
};
template <>
struct find_tuple<keystr_value_object> {
inline static auto get(name scope, name code, name table, std::string* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
keys->data());
}
};
template <>
struct find_tuple<key128x128_value_object> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys, *(keys+1) );
}
};
template <>
struct find_tuple<key64x64x64_value_object> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys, *(keys+1), *(keys+2) );
}
};
/// key_helper helper
template <typename T>
struct key_helper {};
template <>
struct key_helper<key_value_object> {
inline static void set(key_value_object& object, uint64_t* keys) {
object.primary_key = *keys;
}
inline static void set(uint64_t* keys, const key_value_object& object) {
*keys = object.primary_key;
}
inline static bool compare(const key_value_object& object, uint64_t* keys) {
return object.primary_key == *keys;
}
};
template <>
struct key_helper<keystr_value_object> {
inline static void set(keystr_value_object& object, std::string* keys) {
object.primary_key.assign(keys->data(), keys->size());
}
inline static void set(std::string* keys, const keystr_value_object& object) {
keys->assign(object.primary_key.data(), object.primary_key.size());
}
inline static bool compare(const keystr_value_object& object, std::string* keys) {
return !keys->compare(object.primary_key.c_str());
}
};
template <>
struct key_helper<key128x128_value_object> {
inline static auto set(key128x128_value_object& object, uint128_t* keys) {
object.primary_key = *keys;
object.secondary_key = *(keys+1);
}
inline static auto set(uint128_t* keys, const key128x128_value_object& object) {
*keys = object.primary_key;
*(keys+1) = object.secondary_key;
}
inline static bool compare(const key128x128_value_object& object, uint128_t* keys) {
return object.primary_key == *keys &&
object.secondary_key == *(keys+1);
}
};
template <>
struct key_helper<key64x64x64_value_object> {
inline static auto set(key64x64x64_value_object& object, uint64_t* keys) {
object.primary_key = *keys;
object.secondary_key = *(keys+1);
object.tertiary_key = *(keys+2);
}
inline static auto set(uint64_t* keys, const key64x64x64_value_object& object) {
*keys = object.primary_key;
*(keys+1) = object.secondary_key;
*(keys+2) = object.tertiary_key;
}
inline static bool compare(const key64x64x64_value_object& object, uint64_t* keys) {
return object.primary_key == *keys &&
object.secondary_key == *(keys+1) &&
object.tertiary_key == *(keys+2);
}
};
/// load_record_tuple helper
template <typename T, typename Q>
struct load_record_tuple {};
template <>
struct load_record_tuple<key_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *keys);
}
};
template <>
struct load_record_tuple<keystr_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, std::string* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), keys->data());
}
};
template <>
struct load_record_tuple<key128x128_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *keys, uint128_t(0));
}
};
template <>
struct load_record_tuple<key128x128_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *(keys+1), uint128_t(0));
}
};
template <>
struct load_record_tuple<key64x64x64_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *keys, uint64_t(0), uint64_t(0));
}
};
template <>
struct load_record_tuple<key64x64x64_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *(keys+1), uint64_t(0));
}
};
template <>
struct load_record_tuple<key64x64x64_value_object, by_scope_tertiary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *(keys+2));
}
};
//load_record_compare
template <typename ObjectType, typename Scope>
struct load_record_compare {
inline static auto compare(const ObjectType& object, typename ObjectType::key_type* keys) {
return typename ObjectType::key_type(object.primary_key) == *keys;
}
};
template <>
struct load_record_compare<keystr_value_object, by_scope_primary> {
inline static auto compare(const keystr_value_object& object, std::string* keys) {
return !memcmp(object.primary_key.data(), keys->data(), keys->size());
}
};
template <>
struct load_record_compare<key128x128_value_object, by_scope_secondary> {
inline static auto compare(const key128x128_value_object& object, uint128_t* keys) {
return object.secondary_key == *(keys+1);
}
};
template <>
struct load_record_compare<key64x64x64_value_object, by_scope_primary> {
inline static auto compare(const key64x64x64_value_object& object, uint64_t* keys) {
return object.primary_key == *keys;
}
};
template <>
struct load_record_compare<key64x64x64_value_object, by_scope_secondary> {
inline static auto compare(const key64x64x64_value_object& object, uint64_t* keys) {
return object.secondary_key == *(keys+1);
}
};
template <>
struct load_record_compare<key64x64x64_value_object, by_scope_tertiary> {
inline static auto compare(const key64x64x64_value_object& object, uint64_t* keys) {
return object.tertiary_key == *(keys+2);
}
};
//front_record_tuple
template <typename ObjectType>
struct front_record_tuple {
inline static auto get(name scope, name code, name table) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
typename ObjectType::key_type(0), typename ObjectType::key_type(0), typename ObjectType::key_type(0));
}
};
template <>
struct front_record_tuple<key_value_object> {
inline static auto get(name scope, name code, name table) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), uint64_t(0));
}
};
template <>
struct front_record_tuple<keystr_value_object> {
inline static auto get(name scope, name code, name table) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table));
}
};
// //back_record_tuple
// template <typename ObjectType>
// struct back_record_tuple {
// inline static auto get(name scope, name code, name table) {
// return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
// typename ObjectType::key_type(-1), typename ObjectType::key_type(-1), typename ObjectType::key_type(-1));
// }
// };
//next_record_tuple (same for previous)
template <typename T>
struct next_record_tuple {};
template <>
struct next_record_tuple<key_value_object> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys);
}
};
template <>
struct next_record_tuple<keystr_value_object> {
inline static auto get(name scope, name code, name table, std::string* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
keys->data());
}
};
template <>
struct next_record_tuple<key128x128_value_object> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( uint64_t(scope), uint64_t(code), uint64_t(table),
*keys, *(keys+1));
}
};
template <>
struct next_record_tuple<key64x64x64_value_object> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( uint64_t(scope), uint64_t(code), uint64_t(table),
*keys, *(keys+1), *(keys+2));
}
};
//lower_bound_tuple
template <typename ObjectType, typename Scope>
struct lower_bound_tuple{};
template <typename ObjectType>
struct lower_bound_tuple<ObjectType, by_scope_primary> {
inline static auto get(name scope, name code, name table, typename ObjectType::key_type* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys, typename ObjectType::key_type(0), typename ObjectType::key_type(0) );
}
};
template <>
struct lower_bound_tuple<key_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), *keys);
}
};
template <>
struct lower_bound_tuple<keystr_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, std::string* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table), keys->data());
}
};
template <>
struct lower_bound_tuple<key128x128_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+1), uint128_t(0));
}
};
template <>
struct lower_bound_tuple<key64x64x64_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+1), uint64_t(0));
}
};
template <>
struct lower_bound_tuple<key64x64x64_value_object, by_scope_tertiary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+2));
}
};
//upper_bound_tuple
template <typename ObjectType, typename Scope>
struct upper_bound_tuple{};
template <typename ObjectType>
struct upper_bound_tuple<ObjectType, by_scope_primary> {
inline static auto get(name scope, name code, name table, typename ObjectType::key_type* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*keys, typename ObjectType::key_type(-1), typename ObjectType::key_type(-1) );
}
};
template <>
struct upper_bound_tuple<keystr_value_object, by_scope_primary> {
inline static auto get(name scope, name code, name table, std::string* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
keys->data());
}
};
template <>
struct upper_bound_tuple<key128x128_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint128_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+1), uint128_t(-1) );
}
};
template <>
struct upper_bound_tuple<key64x64x64_value_object, by_scope_secondary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+1), uint64_t(-1) );
}
};
template <>
struct upper_bound_tuple<key64x64x64_value_object, by_scope_tertiary> {
inline static auto get(name scope, name code, name table, uint64_t* keys) {
return boost::make_tuple( account_name(scope), account_name(code), account_name(table),
*(keys+2));
}
};
} } // eosio::chain | 38.055718 | 127 | 0.716421 | brendankirby |
8d41f4fd92fb2d95f5870b65d1b3ef7bc01004f1 | 560 | cpp | C++ | z/util/regex/rules/word.cpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | null | null | null | z/util/regex/rules/word.cpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | 12 | 2022-01-09T04:05:56.000Z | 2022-01-16T04:50:52.000Z | z/util/regex/rules/word.cpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | 1 | 2021-01-30T01:19:02.000Z | 2021-01-30T01:19:02.000Z | #include "word.hpp"
#include "../../../core/charFunctions.hpp"
namespace z
{
namespace util
{
namespace rgx
{
word::word(bool negate, int min, int max, bool greedy) noexcept :
rule(min,max,greedy), negate(negate) {}
bool word::match(uint32_t current) const noexcept
{
return negate ^ (('_' == current) || core::isAlphaNumeric(current));
}
# ifdef DEBUG
void word::print(core::outputStream& stream, int level) noexcept
{
(zstring(" ").repeat(level*2)+(negate?"\\W":"\\w")+meta()).writeln(stream);
}
# endif
}
}
}
| 21.538462 | 79 | 0.621429 | ZacharyWesterman |
8d42f0d2f27d8b70896042575e773980c5b415c0 | 389 | cpp | C++ | test/gbelib_tests/ops/logic_tests.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | test/gbelib_tests/ops/logic_tests.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | test/gbelib_tests/ops/logic_tests.cpp | johannes51/GBEmu | bb85debc8191d7eaa3917c2d441172f97731374c | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "location/location.h"
#include "location/rambyte.h"
#include "ops/logic.h"
#include "location/variablebyte.h"
TEST(LogicTest, Xor)
{
auto d = variableLocation(0x3C);
auto s = variableLocation(0xF1);
ops::xorF(d, s);
EXPECT_EQ(0xCD, d.get());
}
TEST(LogicTest, XorZ)
{
auto d = variableLocation(0x3C);
EXPECT_EQ(1, ops::xorF(d, d).z);
}
| 15.56 | 34 | 0.676093 | johannes51 |
1d2caac62e61d201987a9a6f970b781e4364ba0d | 2,350 | hpp | C++ | engine/include/Transform.hpp | Trypio/Aeyon3D | 6e630228fe8f8fe269ab1dfc835a7c7c5d314c2b | [
"MIT"
] | null | null | null | engine/include/Transform.hpp | Trypio/Aeyon3D | 6e630228fe8f8fe269ab1dfc835a7c7c5d314c2b | [
"MIT"
] | null | null | null | engine/include/Transform.hpp | Trypio/Aeyon3D | 6e630228fe8f8fe269ab1dfc835a7c7c5d314c2b | [
"MIT"
] | null | null | null | //
//
//
#ifndef AEYON3D_TRANSFORM_HPP
#define AEYON3D_TRANSFORM_HPP
#include "ECS/ComponentTypeIndex.hpp"
#include "Space.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <vector>
namespace aeyon
{
class Transform : public ComponentTypeIndex<Transform>
{
private:
glm::vec3 m_position;
glm::quat m_rotation;
glm::vec3 m_scale;
mutable glm::mat4x4 m_localToWorldMatrix;
mutable glm::mat4x4 m_worldToLocalMatrix;
mutable bool m_isLocalToWorldMatrixDirty;
mutable bool m_isWorldToLocalMatrixDirty;
Transform* m_parent;
std::vector<Transform*> m_children;
void markAsChanged();
public:
Transform();
Transform(const glm::vec3& position, const glm::vec3& rotationEuler, const glm::vec3& scale);
Transform(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale);
void setPosition(const glm::vec3& position);
void setLocalPosition(const glm::vec3& position);
void translate(const glm::vec3& translation);
void translate(const glm::vec3& translation, Space relativeTo);
void setRotation(const glm::quat& rotation);
void setRotationEuler(const glm::vec3& eulerAngles);
void setLocalRotation(const glm::quat& rotation);
void setLocalRotationEuler(const glm::vec3& eulerAngles);
void rotate(const glm::vec3& eulerAngles);
void rotate(const glm::vec3& eulerAngles, Space relativeTo);
void rotateAround(const glm::vec3& center, const glm::vec3& axis, float angle);
void setScale(const glm::vec3& scale);
void setLocalScale(const glm::vec3& scale);
void scale(const glm::vec3& scale);
void lookAt(const glm::vec3& target);
void lookAt(const glm::vec3& target, const glm::vec3& worldUp);
glm::vec3 getPosition() const;
glm::vec3 getLocalPosition() const;
glm::quat getRotation() const;
glm::quat getLocalRotation() const;
glm::vec3 getRotationEuler() const;
glm::vec3 getLocalRotationEuler() const;
glm::vec3 getScale() const;
glm::vec3 getLocalScale() const;
glm::vec3 getForward() const;
glm::vec3 getRight() const;
glm::vec3 getUp() const;
glm::mat4x4 getLocalToWorldMatrix() const;
glm::mat4x4 getWorldToLocalMatrix() const;
void setParent(Transform* parent);
Transform* getParent() const;
void detachChildren();
const std::vector<Transform*>& getChildren() const;
};
}
#endif //AEYON3D_TRANSFORM_HPP
| 27.647059 | 95 | 0.739149 | Trypio |
1d2daf60c5182772dee199804d234512ae42ec53 | 34,545 | hpp | C++ | include/foonathan/memory/joint_allocator.hpp | Bog999/memory | c1a06eb19992410e11e2fe20d8b2d076c1737804 | [
"Zlib"
] | 1 | 2021-03-07T09:33:39.000Z | 2021-03-07T09:33:39.000Z | include/foonathan/memory/joint_allocator.hpp | Bog999/memory | c1a06eb19992410e11e2fe20d8b2d076c1737804 | [
"Zlib"
] | 1 | 2020-12-18T13:37:01.000Z | 2020-12-18T13:37:01.000Z | include/foonathan/memory/joint_allocator.hpp | Bog999/memory | c1a06eb19992410e11e2fe20d8b2d076c1737804 | [
"Zlib"
] | null | null | null | // Copyright (C) 2015-2020 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED
#define FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED
/// \file
/// Class template \ref foonathan::memory::joint_ptr, \ref foonathan::memory::joint_allocator and related.
#include <initializer_list>
#include <new>
#include "detail/align.hpp"
#include "detail/memory_stack.hpp"
#include "detail/utility.hpp"
#include "allocator_storage.hpp"
#include "config.hpp"
#include "default_allocator.hpp"
#include "error.hpp"
namespace foonathan
{
namespace memory
{
template <typename T, class RawAllocator>
class joint_ptr;
template <typename T>
class joint_type;
namespace detail
{
// the stack that allocates the joint memory
class joint_stack
{
public:
joint_stack(void* mem, std::size_t cap) noexcept
: stack_(static_cast<char*>(mem)), end_(static_cast<char*>(mem) + cap)
{
}
void* allocate(std::size_t size, std::size_t alignment) noexcept
{
return stack_.allocate(end_, size, alignment, 0u);
}
bool bump(std::size_t offset) noexcept
{
if (offset > std::size_t(end_ - stack_.top()))
return false;
stack_.bump(offset);
return true;
}
char* top() noexcept
{
return stack_.top();
}
const char* top() const noexcept
{
return stack_.top();
}
void unwind(void* ptr) noexcept
{
stack_.unwind(static_cast<char*>(ptr));
}
std::size_t capacity(const char* mem) const noexcept
{
return std::size_t(end_ - mem);
}
std::size_t capacity_left() const noexcept
{
return std::size_t(end_ - top());
}
std::size_t capacity_used(const char* mem) const noexcept
{
return std::size_t(top() - mem);
}
private:
detail::fixed_memory_stack stack_;
char* end_;
};
template <typename T>
detail::joint_stack& get_stack(joint_type<T>& obj) noexcept;
template <typename T>
const detail::joint_stack& get_stack(const joint_type<T>& obj) noexcept;
} // namespace detail
/// Tag type that can't be created.
///
/// It isued by \ref joint_ptr.
/// \ingroup allocator
class joint
{
joint(std::size_t cap) noexcept : capacity(cap) {}
std::size_t capacity;
template <typename T, class RawAllocator>
friend class joint_ptr;
template <typename T>
friend class joint_type;
};
/// Tag type to make the joint size more explicit.
///
/// It is used by \ref joint_ptr.
/// \ingroup allocator
struct joint_size
{
std::size_t size;
explicit joint_size(std::size_t s) noexcept : size(s) {}
};
/// CRTP base class for all objects that want to use joint memory.
///
/// This will disable default copy/move operations
/// and inserts additional members for the joint memory management.
/// \ingroup allocator
template <typename T>
class joint_type
{
protected:
/// \effects Creates the base class,
/// the tag type cannot be created by the user.
/// \note This ensures that you cannot create joint types yourself.
joint_type(joint j) noexcept;
joint_type(const joint_type&) = delete;
joint_type(joint_type&&) = delete;
private:
detail::joint_stack stack_;
template <typename U>
friend detail::joint_stack& detail::get_stack(joint_type<U>& obj) noexcept;
template <typename U>
friend const detail::joint_stack& detail::get_stack(const joint_type<U>& obj) noexcept;
};
namespace detail
{
template <typename T>
detail::joint_stack& get_stack(joint_type<T>& obj) noexcept
{
return obj.stack_;
}
template <typename T>
const detail::joint_stack& get_stack(const joint_type<T>& obj) noexcept
{
return obj.stack_;
}
template <typename T>
char* get_memory(joint_type<T>& obj) noexcept
{
auto mem = static_cast<void*>(&obj);
return static_cast<char*>(mem) + sizeof(T);
}
template <typename T>
const char* get_memory(const joint_type<T>& obj) noexcept
{
auto mem = static_cast<const void*>(&obj);
return static_cast<const char*>(mem) + sizeof(T);
}
} // namespace detail
template <typename T>
joint_type<T>::joint_type(joint j) noexcept : stack_(detail::get_memory(*this), j.capacity)
{
FOONATHAN_MEMORY_ASSERT(stack_.top() == detail::get_memory(*this));
FOONATHAN_MEMORY_ASSERT(stack_.capacity_left() == j.capacity);
}
/// A pointer to an object where all allocations are joint.
///
/// It can either own an object or not (be `nullptr`).
/// When it owns an object, it points to a memory block.
/// This memory block contains both the actual object (of the type `T`)
/// and space for allocations of `T`s members.
///
/// The type `T` must be derived from \ref joint_type and every constructor must take \ref joint
/// as first parameter.
/// This prevents that you create joint objects yourself,
/// without the additional storage.
/// The default copy and move constructors are also deleted,
/// you need to write them yourself.
///
/// You can only access the object through the pointer,
/// use \ref joint_allocator or \ref joint_array as members of `T`,
/// to enable the memory sharing.
/// If you are using \ref joint_allocator inside STL containers,
/// make sure that you do not call their regular copy/move constructors,
/// but instead the version where you pass an allocator.
///
/// The memory block will be managed by the given \concept{concept_rawallocator,RawAllocator},
/// it is stored in an \ref allocator_reference and not owned by the pointer directly.
/// \ingroup allocator
template <typename T, class RawAllocator>
class joint_ptr : FOONATHAN_EBO(allocator_reference<RawAllocator>)
{
static_assert(std::is_base_of<joint_type<T>, T>::value,
"T must be derived of joint_type<T>");
public:
using element_type = T;
using allocator_type = typename allocator_reference<RawAllocator>::allocator_type;
//=== constructors/destructor/assignment ===//
/// @{
/// \effects Creates it with a \concept{concept_rawallocator,RawAllocator}, but does not own a new object.
explicit joint_ptr(allocator_type& alloc) noexcept
: allocator_reference<RawAllocator>(alloc), ptr_(nullptr)
{
}
explicit joint_ptr(const allocator_type& alloc) noexcept
: allocator_reference<RawAllocator>(alloc), ptr_(nullptr)
{
}
/// @}
/// @{
/// \effects Reserves memory for the object and the additional size,
/// and creates the object by forwarding the arguments to its constructor.
/// The \concept{concept_rawallocator,RawAllocator} will be used for the allocation.
template <typename... Args>
joint_ptr(allocator_type& alloc, joint_size additional_size, Args&&... args)
: joint_ptr(alloc)
{
create(additional_size.size, detail::forward<Args>(args)...);
}
template <typename... Args>
joint_ptr(const allocator_type& alloc, joint_size additional_size, Args&&... args)
: joint_ptr(alloc)
{
create(additional_size.size, detail::forward<Args>(args)...);
}
/// @}
/// \effects Move-constructs the pointer.
/// Ownership will be transferred from `other` to the new object.
joint_ptr(joint_ptr&& other) noexcept
: allocator_reference<RawAllocator>(detail::move(other)), ptr_(other.ptr_)
{
other.ptr_ = nullptr;
}
/// \effects Destroys the object and deallocates its storage.
~joint_ptr() noexcept
{
reset();
}
/// \effects Move-assings the pointer.
/// The previously owned object will be destroyed,
/// and ownership of `other` transferred.
joint_ptr& operator=(joint_ptr&& other) noexcept
{
joint_ptr tmp(detail::move(other));
swap(*this, tmp);
return *this;
}
/// \effects Same as `reset()`.
joint_ptr& operator=(std::nullptr_t) noexcept
{
reset();
return *this;
}
/// \effects Swaps to pointers and their ownership and allocator.
friend void swap(joint_ptr& a, joint_ptr& b) noexcept
{
detail::adl_swap(static_cast<allocator_reference<RawAllocator>&>(a),
static_cast<allocator_reference<RawAllocator>&>(b));
detail::adl_swap(a.ptr_, b.ptr_);
}
//=== modifiers ===//
/// \effects Destroys the object it refers to,
/// if there is any.
void reset() noexcept
{
if (ptr_)
{
(**this).~element_type();
this->deallocate_node(ptr_,
sizeof(element_type)
+ detail::get_stack(*ptr_).capacity(
detail::get_memory(*ptr_)),
alignof(element_type));
ptr_ = nullptr;
}
}
//=== accessors ===//
/// \returns `true` if the pointer does own an object,
/// `false` otherwise.
explicit operator bool() const noexcept
{
return ptr_ != nullptr;
}
/// \returns A reference to the object it owns.
/// \requires The pointer must own an object,
/// i.e. `operator bool()` must return `true`.
element_type& operator*() const noexcept
{
FOONATHAN_MEMORY_ASSERT(ptr_);
return *get();
}
/// \returns A pointer to the object it owns.
/// \requires The pointer must own an object,
/// i.e. `operator bool()` must return `true`.
element_type* operator->() const noexcept
{
FOONATHAN_MEMORY_ASSERT(ptr_);
return get();
}
/// \returns A pointer to the object it owns
/// or `nullptr`, if it does not own any object.
element_type* get() const noexcept
{
return static_cast<element_type*>(ptr_);
}
/// \returns A reference to the allocator it will use for the deallocation.
auto get_allocator() const noexcept
-> decltype(std::declval<allocator_reference<allocator_type>>().get_allocator())
{
return this->allocator_reference<allocator_type>::get_allocator();
}
private:
template <typename... Args>
void create(std::size_t additional_size, Args&&... args)
{
auto mem = this->allocate_node(sizeof(element_type) + additional_size,
alignof(element_type));
element_type* ptr = nullptr;
#if FOONATHAN_HAS_EXCEPTION_SUPPORT
try
{
ptr = ::new (mem)
element_type(joint(additional_size), detail::forward<Args>(args)...);
}
catch (...)
{
this->deallocate_node(mem, sizeof(element_type) + additional_size,
alignof(element_type));
throw;
}
#else
ptr = ::new (mem)
element_type(joint(additional_size), detail::forward<Args>(args)...);
#endif
ptr_ = ptr;
}
joint_type<T>* ptr_;
friend class joint_allocator;
};
/// @{
/// \returns `!ptr`,
/// i.e. if `ptr` does not own anything.
/// \relates joint_ptr
template <typename T, class RawAllocator>
bool operator==(const joint_ptr<T, RawAllocator>& ptr, std::nullptr_t)
{
return !ptr;
}
template <typename T, class RawAllocator>
bool operator==(std::nullptr_t, const joint_ptr<T, RawAllocator>& ptr)
{
return ptr == nullptr;
}
/// @}
/// @{
/// \returns `ptr.get() == p`,
/// i.e. if `ptr` ownws the object referred to by `p`.
/// \relates joint_ptr
template <typename T, class RawAllocator>
bool operator==(const joint_ptr<T, RawAllocator>& ptr, T* p)
{
return ptr.get() == p;
}
template <typename T, class RawAllocator>
bool operator==(T* p, const joint_ptr<T, RawAllocator>& ptr)
{
return ptr == p;
}
/// @}
/// @{
/// \returns `!(ptr == nullptr)`,
/// i.e. if `ptr` does own something.
/// \relates joint_ptr
template <typename T, class RawAllocator>
bool operator!=(const joint_ptr<T, RawAllocator>& ptr, std::nullptr_t)
{
return !(ptr == nullptr);
}
template <typename T, class RawAllocator>
bool operator!=(std::nullptr_t, const joint_ptr<T, RawAllocator>& ptr)
{
return ptr != nullptr;
}
/// @}
/// @{
/// \returns `!(ptr == p)`,
/// i.e. if `ptr` does not ownw the object referred to by `p`.
/// \relates joint_ptr
template <typename T, class RawAllocator>
bool operator!=(const joint_ptr<T, RawAllocator>& ptr, T* p)
{
return !(ptr == p);
}
template <typename T, class RawAllocator>
bool operator!=(T* p, const joint_ptr<T, RawAllocator>& ptr)
{
return ptr != p;
}
/// @}
/// @{
/// \returns A new \ref joint_ptr as if created with the same arguments passed to the constructor.
/// \relatesalso joint_ptr
/// \ingroup allocator
template <typename T, class RawAllocator, typename... Args>
auto allocate_joint(RawAllocator& alloc, joint_size additional_size, Args&&... args)
-> joint_ptr<T, RawAllocator>
{
return joint_ptr<T, RawAllocator>(alloc, additional_size,
detail::forward<Args>(args)...);
}
template <typename T, class RawAllocator, typename... Args>
auto allocate_joint(const RawAllocator& alloc, joint_size additional_size, Args&&... args)
-> joint_ptr<T, RawAllocator>
{
return joint_ptr<T, RawAllocator>(alloc, additional_size,
detail::forward<Args>(args)...);
}
/// @}
/// @{
/// \returns A new \ref joint_ptr that points to a copy of `joint`.
/// It will allocate as much memory as needed and forward to the copy constructor.
/// \ingroup allocator
template <class RawAllocator, typename T>
auto clone_joint(RawAllocator& alloc, const joint_type<T>& joint)
-> joint_ptr<T, RawAllocator>
{
return joint_ptr<T, RawAllocator>(alloc,
joint_size(detail::get_stack(joint).capacity_used(
detail::get_memory(joint))),
static_cast<const T&>(joint));
}
template <class RawAllocator, typename T>
auto clone_joint(const RawAllocator& alloc, const joint_type<T>& joint)
-> joint_ptr<T, RawAllocator>
{
return joint_ptr<T, RawAllocator>(alloc,
joint_size(detail::get_stack(joint).capacity_used(
detail::get_memory(joint))),
static_cast<const T&>(joint));
}
/// @}
/// A \concept{concept_rawallocator,RawAllocator} that uses the additional joint memory for its allocation.
///
/// It is somewhat limited and allows only allocation once.
/// All joint allocators for an object share the joint memory and must not be used in multiple threads.
/// The memory it returns is owned by a \ref joint_ptr and will be destroyed through it.
/// \ingroup allocator
class joint_allocator
{
public:
#if defined(__GNUC__) && (!defined(_GLIBCXX_USE_CXX11_ABI) || _GLIBCXX_USE_CXX11_ABI == 0)
// std::string requires default constructor for the small string optimization when using gcc's old ABI
// so add one, but it must never be used for allocation
joint_allocator() noexcept : stack_(nullptr) {}
#endif
/// \effects Creates it using the joint memory of the given object.
template <typename T>
joint_allocator(joint_type<T>& j) noexcept : stack_(&detail::get_stack(j))
{
}
joint_allocator(const joint_allocator& other) noexcept = default;
joint_allocator& operator=(const joint_allocator& other) noexcept = default;
/// \effects Allocates a node with given properties.
/// \returns A pointer to the new node.
/// \throws \ref out_of_fixed_memory exception if this function has been called for a second time
/// or the joint memory block is exhausted.
void* allocate_node(std::size_t size, std::size_t alignment)
{
FOONATHAN_MEMORY_ASSERT(stack_);
auto mem = stack_->allocate(size, alignment);
if (!mem)
FOONATHAN_THROW(out_of_fixed_memory(info(), size));
return mem;
}
/// \effects Deallocates the node, if possible.
/// \note It is only possible if it was the last allocation.
void deallocate_node(void* ptr, std::size_t size, std::size_t) noexcept
{
FOONATHAN_MEMORY_ASSERT(stack_);
auto end = static_cast<char*>(ptr) + size;
if (end == stack_->top())
stack_->unwind(ptr);
}
private:
allocator_info info() const noexcept
{
return allocator_info(FOONATHAN_MEMORY_LOG_PREFIX "::joint_allocator", this);
}
detail::joint_stack* stack_;
friend bool operator==(const joint_allocator& lhs, const joint_allocator& rhs) noexcept;
};
/// @{
/// \returns Whether `lhs` and `rhs` use the same joint memory for the allocation.
/// \relates joint_allocator
inline bool operator==(const joint_allocator& lhs, const joint_allocator& rhs) noexcept
{
return lhs.stack_ == rhs.stack_;
}
inline bool operator!=(const joint_allocator& lhs, const joint_allocator& rhs) noexcept
{
return !(lhs == rhs);
}
/// @}
/// Specialization of \ref is_shared_allocator to mark \ref joint_allocator as shared.
/// This allows using it as \ref allocator_reference directly.
/// \ingroup allocator
template <>
struct is_shared_allocator<joint_allocator> : std::true_type
{
};
/// Specialization of \ref is_thread_safe_allocator to mark \ref joint_allocator as thread safe.
/// This is an optimization to get rid of the mutex in \ref allocator_storage,
/// as joint allocator must not be shared between threads.
/// \note The allocator is *not* thread safe, it just must not be shared.
template <>
struct is_thread_safe_allocator<joint_allocator> : std::true_type
{
};
#if !defined(DOXYGEN)
template <class RawAllocator>
struct propagation_traits;
#endif
/// Specialization of the \ref propagation_traits for the \ref joint_allocator.
/// A joint allocator does not propagate on assignment
/// and it is not allowed to use the regular copy/move constructor of allocator aware containers,
/// instead it needs the copy/move constructor with allocator.
/// \note This is required because the container constructor will end up copying/moving the allocator.
/// But this is not allowed as you need the allocator with the correct joined memory.
/// Copying can be customized (i.e. forbidden), but sadly not move, so keep that in mind.
/// \ingroup allocator
template <>
struct propagation_traits<joint_allocator>
{
using propagate_on_container_swap = std::false_type;
using propagate_on_container_move_assignment = std::false_type;
using propagate_on_container_copy_assignment = std::false_type;
template <class AllocReference>
static AllocReference select_on_container_copy_construction(const AllocReference&)
{
static_assert(always_false<AllocReference>::value,
"you must not use the regular copy constructor");
}
private:
template <typename T>
struct always_false : std::false_type
{
};
};
/// A zero overhead dynamic array using joint memory.
///
/// If you use, e.g. `std::vector` with \ref joint_allocator,
/// this has a slight additional overhead.
/// This type is joint memory aware and has no overhead.
///
/// It has a dynamic, but fixed size,
/// it cannot grow after it has been created.
/// \ingroup allocator
template <typename T>
class joint_array
{
public:
using value_type = T;
using iterator = value_type*;
using const_iterator = const value_type*;
//=== constructors ===//
/// \effects Creates with `size` default-constructed objects using the specified joint memory.
/// \throws \ref out_of_fixed_memory if `size` is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename JointType>
joint_array(std::size_t size, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), size)
{
}
/// \effects Creates with `size` copies of `val` using the specified joint memory.
/// \throws \ref out_of_fixed_memory if `size` is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename JointType>
joint_array(std::size_t size, const value_type& val, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), size, val)
{
}
/// \effects Creates with the copies of the objects in the initializer list using the specified joint memory.
/// \throws \ref out_of_fixed_memory if the size is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename JointType>
joint_array(std::initializer_list<value_type> ilist, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), ilist)
{
}
/// \effects Creates it by forwarding each element of the range to `T`s constructor using the specified joint memory.
/// \throws \ref out_of_fixed_memory if the size is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename InIter, typename JointType,
typename = decltype(*std::declval<InIter&>()++)>
joint_array(InIter begin, InIter end, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), begin, end)
{
}
joint_array(const joint_array&) = delete;
/// \effects Copy constructs each element from `other` into the storage of the specified joint memory.
/// \throws \ref out_of_fixed_memory if the size is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename JointType>
joint_array(const joint_array& other, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), other)
{
}
joint_array(joint_array&&) = delete;
/// \effects Move constructs each element from `other` into the storage of the specified joint memory.
/// \throws \ref out_of_fixed_memory if the size is too big
/// and anything thrown by `T`s constructor.
/// If an allocation is thrown, the memory will be released directly.
template <typename JointType>
joint_array(joint_array&& other, joint_type<JointType>& j)
: joint_array(detail::get_stack(j), detail::move(other))
{
}
/// \effects Destroys all objects,
/// but does not release the storage.
~joint_array() noexcept
{
for (std::size_t i = 0u; i != size_; ++i)
ptr_[i].~T();
}
joint_array& operator=(const joint_array&) = delete;
joint_array& operator=(joint_array&&) = delete;
//=== accessors ===//
/// @{
/// \returns A reference to the `i`th object.
/// \requires `i < size()`.
value_type& operator[](std::size_t i) noexcept
{
FOONATHAN_MEMORY_ASSERT(i < size_);
return ptr_[i];
}
const value_type& operator[](std::size_t i) const noexcept
{
FOONATHAN_MEMORY_ASSERT(i < size_);
return ptr_[i];
}
/// @}
/// @{
/// \returns A pointer to the first object.
/// It points to contiguous memory and can be used to access the objects directly.
value_type* data() noexcept
{
return ptr_;
}
const value_type* data() const noexcept
{
return ptr_;
}
/// @}
/// @{
/// \returns A random access iterator to the first element.
iterator begin() noexcept
{
return ptr_;
}
const_iterator begin() const noexcept
{
return ptr_;
}
/// @}
/// @{
/// \returns A random access iterator one past the last element.
iterator end() noexcept
{
return ptr_ + size_;
}
const_iterator end() const noexcept
{
return ptr_ + size_;
}
/// @}
/// \returns The number of elements in the array.
std::size_t size() const noexcept
{
return size_;
}
/// \returns `true` if the array is empty, `false` otherwise.
bool empty() const noexcept
{
return size_ == 0u;
}
private:
// allocate only
struct allocate_only
{
};
joint_array(allocate_only, detail::joint_stack& stack, std::size_t size)
: ptr_(nullptr), size_(0u)
{
ptr_ = static_cast<T*>(stack.allocate(size * sizeof(T), alignof(T)));
if (!ptr_)
FOONATHAN_THROW(out_of_fixed_memory(info(), size * sizeof(T)));
}
class builder
{
public:
builder(detail::joint_stack& stack, T* ptr) noexcept
: stack_(&stack), objects_(ptr), size_(0u)
{
}
~builder() noexcept
{
for (std::size_t i = 0u; i != size_; ++i)
objects_[i].~T();
if (size_)
stack_->unwind(objects_);
}
builder(builder&&) = delete;
builder& operator=(builder&&) = delete;
template <typename... Args>
T* create(Args&&... args)
{
auto ptr = ::new (static_cast<void*>(&objects_[size_]))
T(detail::forward<Args>(args)...);
++size_;
return ptr;
}
std::size_t size() const noexcept
{
return size_;
}
std::size_t release() noexcept
{
auto res = size_;
size_ = 0u;
return res;
}
private:
detail::joint_stack* stack_;
T* objects_;
std::size_t size_;
};
joint_array(detail::joint_stack& stack, std::size_t size)
: joint_array(allocate_only{}, stack, size)
{
builder b(stack, ptr_);
for (auto i = 0u; i != size; ++i)
b.create();
size_ = b.release();
}
joint_array(detail::joint_stack& stack, std::size_t size, const value_type& value)
: joint_array(allocate_only{}, stack, size)
{
builder b(stack, ptr_);
for (auto i = 0u; i != size; ++i)
b.create(value);
size_ = b.release();
}
joint_array(detail::joint_stack& stack, std::initializer_list<value_type> ilist)
: joint_array(allocate_only{}, stack, ilist.size())
{
builder b(stack, ptr_);
for (auto& elem : ilist)
b.create(elem);
size_ = b.release();
}
joint_array(detail::joint_stack& stack, const joint_array& other)
: joint_array(allocate_only{}, stack, other.size())
{
builder b(stack, ptr_);
for (auto& elem : other)
b.create(elem);
size_ = b.release();
}
joint_array(detail::joint_stack& stack, joint_array&& other)
: joint_array(allocate_only{}, stack, other.size())
{
builder b(stack, ptr_);
for (auto& elem : other)
b.create(detail::move(elem));
size_ = b.release();
}
template <typename InIter>
joint_array(detail::joint_stack& stack, InIter begin, InIter end)
: ptr_(nullptr), size_(0u)
{
if (begin == end)
return;
ptr_ = static_cast<T*>(stack.allocate(sizeof(T), alignof(T)));
if (!ptr_)
FOONATHAN_THROW(out_of_fixed_memory(info(), sizeof(T)));
builder b(stack, ptr_);
b.create(*begin++);
for (auto last = ptr_; begin != end; ++begin)
{
// just bump stack to get more memory
if (!stack.bump(sizeof(T)))
FOONATHAN_THROW(out_of_fixed_memory(info(), b.size() * sizeof(T)));
auto cur = b.create(*begin);
FOONATHAN_MEMORY_ASSERT(last + 1 == cur);
last = cur;
}
size_ = b.release();
}
allocator_info info() const noexcept
{
return {FOONATHAN_MEMORY_LOG_PREFIX "::joint_array", this};
}
value_type* ptr_;
std::size_t size_;
};
} // namespace memory
} // namespace foonathan
#endif // FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED
| 37.225216 | 130 | 0.519873 | Bog999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.