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
0f7a3181e6e8633f29872134329182743762646a
5,267
cpp
C++
NetworkRelay/Remote.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
5
2016-03-15T20:14:10.000Z
2020-10-30T23:56:24.000Z
NetworkRelay/Remote.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
3
2018-12-19T19:12:44.000Z
2020-04-02T13:07:00.000Z
NetworkRelay/Remote.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
2
2016-04-11T19:29:28.000Z
2021-11-26T20:53:22.000Z
#include <cstring> #include "Remote.hh" #include "INetworkRelay.hh" #include "Unistd.hh" #include "TCPException.hh" #include "LockGuard.hpp" Remote::Remote(ISocketTCP &socket, unsigned int hash) : _temporary_tcp_buffer(4096) { this->_ready = false; this->_tcp = &socket; this->_ip = ""; this->_port = 0; this->_private_hash = hash; } Remote::~Remote() { if (this->_tcp) this->_tcp->close(); delete this->_tcp; } const ISocketTCP &Remote::getTCPSocket() const { return (*this->_tcp); } ISocketTCP &Remote::getTCPSocket() { return (*this->_tcp); } const std::string &Remote::getIP() const { return (this->_ip); } unsigned int Remote::getPrivateHash() const { return (this->_private_hash); } int Remote::getPort() const { return (this->_port); } void Remote::setIP(const std::string &ip) { this->_ip = ip; } void Remote::setPort(const int port) { this->_port = port; } void Remote::setPrivateHash(const unsigned int hash) { this->_private_hash = hash; } void Remote::sendTCP(IBuffer *buffer) { unsigned int size; size = buffer->getLength(); buffer->rewind(); *buffer << size; buffer->rewind(); auto guard = create_lock(this->_send_buffer_tcp); this->_send_buffer_tcp.push_back(buffer); } void Remote::sendUDP(IBuffer *buffer) { if (this->isReady() || buffer->getLength() == sizeof(unsigned int)) { buffer->rewind(); *buffer << this->_private_hash; buffer->rewind(); auto guard = create_lock(this->_send_buffer_udp); this->_send_buffer_udp.push_back(buffer); if (this->_send_buffer_udp.size() > 1000) this->_send_buffer_udp.erase(this->_send_buffer_udp.begin()); } } LockVector<IBuffer *> &Remote::getRecvBufferUDP() { return (this->_recv_buffer_udp); } LockVector<IBuffer *> &Remote::getRecvBufferTCP() { return (this->_recv_buffer_tcp); } const std::string &Remote::getRoom() const { return (this->_room); } void Remote::setRoom(const std::string &room) { this->_room = room; } void Remote::networkSendTCP(INetworkRelay &network) { IBuffer *buffer; auto guard = create_lock(this->_send_buffer_tcp); if (!this->_send_buffer_tcp.empty()) { buffer = this->_send_buffer_tcp.front(); if (this->_tcp->send(*buffer)) { network.disposeTCPBuffer(buffer); this->_send_buffer_tcp.erase(this->_send_buffer_tcp.begin()); } } } bool Remote::networkReceiveTCP(INetworkRelay &network) { unsigned int size_read; if (this->_recv_buffer_tcp.trylock()) { auto guard = create_lock(this->_recv_buffer_tcp, true); this->_temporary_tcp_buffer.gotoEnd(); try { size_read = this->_tcp->receive(this->_temporary_tcp_buffer); } catch (const TCPException &e) { std::cerr << e.what() << std::endl; return false; } while (this->extractTCPPacket(network)) ; memmove(this->_temporary_tcp_buffer.getBuffer(), this->_temporary_tcp_buffer.getBuffer() + this->_temporary_tcp_buffer.getPosition(), this->_temporary_tcp_buffer.getRemainingLength()); this->_temporary_tcp_buffer.setLength(this->_temporary_tcp_buffer.getRemainingLength()); this->_temporary_tcp_buffer.rewind(); return (size_read > 0); } return (true); } // Private function to get message from recv buffer bool Remote::extractTCPPacket(INetworkRelay &network) { unsigned int old_pos; unsigned int size; IBuffer *buffer; if (this->_temporary_tcp_buffer.getRemainingLength() >= sizeof(unsigned int)) { old_pos = this->_temporary_tcp_buffer.getPosition(); this->_temporary_tcp_buffer >> size; if (this->_temporary_tcp_buffer.getRemainingLength() + sizeof(size) >= size) { buffer = network.getTCPBuffer(); buffer->rewind(); memcpy(buffer->getBuffer(), this->_temporary_tcp_buffer.getBuffer() + this->_temporary_tcp_buffer.getPosition(), size - sizeof(size)); buffer->setLength(size - sizeof(size)); buffer->rewind(); if (this->_private_hash == 0) { *buffer >> this->_private_hash; std::cout << "Connexion established: " << this->_private_hash << std::endl; network.disposeTCPBuffer(buffer); } else { this->_recv_buffer_tcp.push_back(buffer); } this->_temporary_tcp_buffer.setPosition(this->_temporary_tcp_buffer.getPosition() + size - sizeof(size)); return (true); } else this->_temporary_tcp_buffer.setPosition(old_pos); } return (false); } void Remote::networkSendUDP(INetworkRelay &network, SocketUDP &udp) { IBuffer *buffer; auto guard = create_lock(this->_send_buffer_udp); if (!this->_send_buffer_udp.empty()) { buffer = this->_send_buffer_udp.front(); udp.send(*buffer, this->_ip, this->_port); network.disposeUDPBuffer(buffer); this->_send_buffer_udp.erase(this->_send_buffer_udp.begin()); } } bool Remote::canSendUDP() { auto guard = create_lock(this->_send_buffer_udp); return (!this->_send_buffer_udp.empty()); } bool Remote::canSendTCP() { auto guard = create_lock(this->_send_buffer_tcp); return (!this->_send_buffer_tcp.empty()); } void Remote::setReady(bool ready) { this->_ready = ready; } bool Remote::isReady() const { return (this->_ready); }
22.702586
94
0.675337
deb0ch
0f7d6adee67a4744c303e30def5d23e03704cd1e
544
hpp
C++
include/mizuiro/color/format/homogenous_dynamic_fwd.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/format/homogenous_dynamic_fwd.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/format/homogenous_dynamic_fwd.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 MIZUIRO_COLOR_FORMAT_HOMOGENOUS_DYNAMIC_FWD_HPP_INCLUDED #define MIZUIRO_COLOR_FORMAT_HOMOGENOUS_DYNAMIC_FWD_HPP_INCLUDED #include <mizuiro/size_type.hpp> namespace mizuiro::color::format { template <typename ChannelType, typename Channels, mizuiro::size_type ChannelCount> struct homogenous_dynamic; } #endif
27.2
83
0.783088
cpreh
0f803d969e3f3d126e4a940751d9a72cf966a1e7
592
cpp
C++
examples/Basics/Objects/CompositeObjects/Egg.cpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
12
2015-01-12T07:43:22.000Z
2022-03-08T06:43:20.000Z
examples/Basics/Objects/CompositeObjects/Egg.cpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
null
null
null
examples/Basics/Objects/CompositeObjects/Egg.cpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
7
2015-02-09T15:44:10.000Z
2019-07-07T11:48:10.000Z
#include <cprocessing/cprocessing.hpp> #include "Egg.hpp" Egg::Egg(float xpos, float ypos, float t, float s) { x = xpos; y = ypos; tilt = t; scalar = s / 100.0; } void Egg::wobble() { tilt = cos(angle) / 8; angle += 0.1; } void Egg::display() { noStroke(); fill(255); pushMatrix(); translate(x, y); rotate(tilt); scale(scalar); beginShape(); vertex(0, -100); bezierVertex(25, -100, 40, -65, 40, -40); bezierVertex(40, -15, 25, 0, 0, 0); bezierVertex(-25, 0, -40, -15, -40, -40); bezierVertex(-40, -65, -25, -100, 0, -100); endShape(); popMatrix(); }
19.096774
52
0.577703
RedErr404
abee2ba07c7554b960a9e06ead9bcec12aa58f3e
13,165
cpp
C++
src/X86Assembler_Avx.cpp
bigianb/Play--CodeGen
8aa3a4e63300b0bda680a8d73a63c8d5b0879967
[ "BSD-2-Clause" ]
45
2015-01-27T13:00:06.000Z
2022-03-10T20:24:58.000Z
src/X86Assembler_Avx.cpp
bigianb/Play--CodeGen
8aa3a4e63300b0bda680a8d73a63c8d5b0879967
[ "BSD-2-Clause" ]
21
2015-07-14T14:04:33.000Z
2021-11-06T22:54:19.000Z
src/X86Assembler_Avx.cpp
bigianb/Play--CodeGen
8aa3a4e63300b0bda680a8d73a63c8d5b0879967
[ "BSD-2-Clause" ]
39
2015-02-16T03:21:30.000Z
2022-01-08T08:30:12.000Z
#include <cassert> #include "X86Assembler.h" void CX86Assembler::WriteVex(VEX_OPCODE_MAP opMap, XMMREGISTER& dst, XMMREGISTER src1, const CAddress& src2) { assert(!src2.nIsExtendedSib); uint8 prefix = (opMap >> 4) & 0x0F; uint8 map = (opMap & 0x0F); assert(prefix < 4); assert(map < 4); bool isExtendedR = (dst > xMM7); if(isExtendedR) { dst = static_cast<XMMREGISTER>(dst & 7); } if(src2.nIsExtendedModRM || (map != 1)) { //Three byte VEX uint8 b1 = 0; b1 |= map; b1 |= (src2.nIsExtendedModRM ? 0 : 1) << 5; b1 |= (src2.nIsExtendedSib ? 0 : 1) << 6; b1 |= (isExtendedR ? 0 : 1) << 7; uint8 b2 = 0; b2 |= prefix; b2 |= (~static_cast<uint8>(src1) & 0xF) << 3; WriteByte(0xC4); WriteByte(b1); WriteByte(b2); } else { //Two byte VEX uint8 b1 = 0; b1 |= prefix; b1 |= (~static_cast<uint8>(src1) & 0xF) << 3; b1 |= (isExtendedR ? 0 : 1) << 7; WriteByte(0xC5); WriteByte(b1); } } void CX86Assembler::WriteVexVoOp(VEX_OPCODE_MAP opMap, uint8 op, XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVex(opMap, dst, src1, src2); WriteByte(op); CAddress newAddress(src2); newAddress.ModRm.nFnReg = dst; newAddress.Write(&m_tmpStream); //Check for rIP relative addressing if(src2.ModRm.nByte == 0x05) { assert(m_currentLabel); auto literalIterator = m_currentLabel->literal128Refs.find(src2.literal128Id); assert(literalIterator != std::end(m_currentLabel->literal128Refs)); auto& literal = literalIterator->second; assert(literal.offset == 0); literal.offset = static_cast<uint32>(m_tmpStream.Tell()); //Write placeholder m_tmpStream.Write32(0); } } void CX86Assembler::WriteVexShiftVoOp(uint8 op, uint8 subOp, XMMREGISTER dst, XMMREGISTER src, uint8 amount) { assert(subOp < 8); auto tmpReg = CX86Assembler::xMM0; auto address = MakeXmmRegisterAddress(src); address.ModRm.nFnReg = subOp; WriteVex(VEX_OPCODE_MAP_66, tmpReg, dst, address); WriteByte(op); address.Write(&m_tmpStream); WriteByte(amount); } void CX86Assembler::VmovdVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x6E, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VmovdVo(const CAddress& dst, XMMREGISTER src) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x7E, src, CX86Assembler::xMM0, dst); } void CX86Assembler::VmovssEd(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x10, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VmovssEd(const CAddress& dst, XMMREGISTER src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x11, src, CX86Assembler::xMM0, dst); } void CX86Assembler::VaddssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x58, dst, src1, src2); } void CX86Assembler::VsubssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x5C, dst, src1, src2); } void CX86Assembler::VmulssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x59, dst, src1, src2); } void CX86Assembler::VdivssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x5E, dst, src1, src2); } void CX86Assembler::VmaxssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x5F, dst, src1, src2); } void CX86Assembler::VminssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x5D, dst, src1, src2); } void CX86Assembler::VcmpssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2, SSE_CMP_TYPE condition) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0xC2, dst, src1, src2); WriteByte(static_cast<uint8>(condition)); } void CX86Assembler::VsqrtssEd(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x51, dst, src1, src2); } void CX86Assembler::Vcvtsi2ssEd(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x2A, dst, CX86Assembler::xMM0, src); } void CX86Assembler::Vcvttss2siEd(REGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x2C, static_cast<XMMREGISTER>(dst), CX86Assembler::xMM0, src); } void CX86Assembler::VmovdqaVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x6F, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VmovdqaVo(const CAddress& dst, XMMREGISTER src) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x7F, src, CX86Assembler::xMM0, dst); } void CX86Assembler::VmovdquVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x6F, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VmovapsVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x28, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VmovapsVo(const CAddress& dst, XMMREGISTER src) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x29, src, CX86Assembler::xMM0, dst); } void CX86Assembler::VpaddbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xFC, dst, src1, src2); } void CX86Assembler::VpaddwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xFD, dst, src1, src2); } void CX86Assembler::VpadddVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xFE, dst, src1, src2); } void CX86Assembler::VpaddsbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xEC, dst, src1, src2); } void CX86Assembler::VpaddswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xED, dst, src1, src2); } void CX86Assembler::VpaddusbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xDC, dst, src1, src2); } void CX86Assembler::VpadduswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xDD, dst, src1, src2); } void CX86Assembler::VpsubbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xF8, dst, src1, src2); } void CX86Assembler::VpsubwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xF9, dst, src1, src2); } void CX86Assembler::VpsubdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xFA, dst, src1, src2); } void CX86Assembler::VpsubswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xE9, dst, src1, src2); } void CX86Assembler::VpsubusbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xD8, dst, src1, src2); } void CX86Assembler::VpsubuswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xD9, dst, src1, src2); } void CX86Assembler::VpandVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xDB, dst, src1, src2); } void CX86Assembler::VporVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xEB, dst, src1, src2); } void CX86Assembler::VpxorVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xEF, dst, src1, src2); } void CX86Assembler::VpsllwVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x71, 0x06, dst, src, amount); } void CX86Assembler::VpsrlwVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x71, 0x02, dst, src, amount); } void CX86Assembler::VpsrawVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x71, 0x04, dst, src, amount); } void CX86Assembler::VpslldVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x72, 0x06, dst, src, amount); } void CX86Assembler::VpsrldVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x72, 0x02, dst, src, amount); } void CX86Assembler::VpsradVo(XMMREGISTER dst, XMMREGISTER src, uint8 amount) { WriteVexShiftVoOp(0x72, 0x04, dst, src, amount); } void CX86Assembler::VpcmpeqbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x74, dst, src1, src2); } void CX86Assembler::VpcmpeqwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x75, dst, src1, src2); } void CX86Assembler::VpcmpeqdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x76, dst, src1, src2); } void CX86Assembler::VpcmpgtbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x64, dst, src1, src2); } void CX86Assembler::VpcmpgtwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x65, dst, src1, src2); } void CX86Assembler::VpcmpgtdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x66, dst, src1, src2); } void CX86Assembler::VpmaxswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xEE, dst, src1, src2); } void CX86Assembler::VpmaxsdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66_38, 0x3D, dst, src1, src2); } void CX86Assembler::VpminswVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xEA, dst, src1, src2); } void CX86Assembler::VpminsdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66_38, 0x39, dst, src1, src2); } void CX86Assembler::VpackssdwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x6B, dst, src1, src2); } void CX86Assembler::VpackuswbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x67, dst, src1, src2); } void CX86Assembler::VpunpcklbwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x60, dst, src1, src2); } void CX86Assembler::VpunpcklwdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x61, dst, src1, src2); } void CX86Assembler::VpunpckldqVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x62, dst, src1, src2); } void CX86Assembler::VpunpckhbwVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x68, dst, src1, src2); } void CX86Assembler::VpunpckhwdVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x69, dst, src1, src2); } void CX86Assembler::VpunpckhdqVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0x6A, dst, src1, src2); } void CX86Assembler::VpshufbVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_66_38, 0x00, dst, src1, src2); } void CX86Assembler::VpmovmskbVo(REGISTER dst, XMMREGISTER src) { WriteVexVoOp(VEX_OPCODE_MAP_66, 0xD7, static_cast<XMMREGISTER>(dst), CX86Assembler::xMM0, CX86Assembler::MakeXmmRegisterAddress(src)); } void CX86Assembler::VaddpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x58, dst, src1, src2); } void CX86Assembler::VsubpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x5C, dst, src1, src2); } void CX86Assembler::VmulpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x59, dst, src1, src2); } void CX86Assembler::VdivpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x5E, dst, src1, src2); } void CX86Assembler::VcmpltpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { VcmppsVo(dst, src1, src2, SSE_CMP_LT); } void CX86Assembler::VcmpgtpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { VcmppsVo(dst, src1, src2, SSE_CMP_NLE); } void CX86Assembler::VminpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x5D, dst, src1, src2); } void CX86Assembler::VmaxpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x5F, dst, src1, src2); } void CX86Assembler::Vcvtdq2psVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0x5B, dst, CX86Assembler::xMM0, src); } void CX86Assembler::Vcvttps2dqVo(XMMREGISTER dst, const CAddress& src) { WriteVexVoOp(VEX_OPCODE_MAP_F3, 0x5B, dst, CX86Assembler::xMM0, src); } void CX86Assembler::VcmppsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2, SSE_CMP_TYPE condition) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0xC2, dst, src1, src2); WriteByte(static_cast<uint8>(condition)); } void CX86Assembler::VblendpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2, uint8 mask) { WriteVexVoOp(VEX_OPCODE_MAP_66_3A, 0x0C, dst, src1, src2); WriteByte(mask); } void CX86Assembler::VshufpsVo(XMMREGISTER dst, XMMREGISTER src1, const CAddress& src2, uint8 shuffleByte) { WriteVexVoOp(VEX_OPCODE_MAP_NONE, 0xC6, dst, src1, src2); WriteByte(shuffleByte); }
28.870614
135
0.764603
bigianb
abf1a981003d8c75ecd410813b82032e138a0437
789
cpp
C++
src/main.cpp
ToruNiina/haywire
73818ca211b64bbc4fab24367830a2f8cc471a83
[ "MIT" ]
null
null
null
src/main.cpp
ToruNiina/haywire
73818ca211b64bbc4fab24367830a2f8cc471a83
[ "MIT" ]
null
null
null
src/main.cpp
ToruNiina/haywire
73818ca211b64bbc4fab24367830a2f8cc471a83
[ "MIT" ]
null
null
null
#include <haywire/world.hpp> #include <haywire/gui.hpp> #include <extlib/wad/wad/default_archiver.hpp> int main(int argc, char **argv) { std::cerr << "Usage: ./haywire [data.toml]" << std::endl; std::cerr << "Space: toggle execution" << std::endl; std::cerr << "Enter: step-by-step update" << std::endl; haywire::window win; if(argc == 2) { const std::string fname(argv[1]); if(fname.substr(fname.size() - 5) == ".toml") { win.load_toml(argv[1]); } else if(fname.substr(fname.size() - 4) == ".msg") { wad::read_archiver src(fname); if(!wad::load(src, win)) { return 1; } } } while(win.update()) {} return 0; }
23.909091
61
0.498099
ToruNiina
abf63f7228c7322dd97814a57f22a1fc931e6ce3
3,272
cpp
C++
ArcGISRuntimeSDKQt_CppSamples/Analysis/ViewshedCamera/ViewshedCamera.cpp
markjdugger/arcgis-runtime-samples-qt
833b583d8f0a70b2dbbe4a8c28d8609c7e93dca3
[ "Apache-2.0" ]
1
2021-08-08T13:58:54.000Z
2021-08-08T13:58:54.000Z
ArcGISRuntimeSDKQt_CppSamples/Analysis/ViewshedCamera/ViewshedCamera.cpp
markjdugger/arcgis-runtime-samples-qt
833b583d8f0a70b2dbbe4a8c28d8609c7e93dca3
[ "Apache-2.0" ]
null
null
null
ArcGISRuntimeSDKQt_CppSamples/Analysis/ViewshedCamera/ViewshedCamera.cpp
markjdugger/arcgis-runtime-samples-qt
833b583d8f0a70b2dbbe4a8c28d8609c7e93dca3
[ "Apache-2.0" ]
null
null
null
// [WriteFile Name=ViewshedCamera, Category=Analysis] // [Legal] // Copyright 2017 Esri. // 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. // [Legal] #include "ViewshedCamera.h" #include "ArcGISTiledElevationSource.h" #include "Scene.h" #include "SceneQuickView.h" #include "ArcGISSceneLayer.h" #include "AnalysisOverlay.h" #include "Point.h" #include "Camera.h" #include "Viewpoint.h" #include "LocationViewshed.h" using namespace Esri::ArcGISRuntime; ViewshedCamera::ViewshedCamera(QQuickItem* parent /* = nullptr */): QQuickItem(parent) { } void ViewshedCamera::init() { // Register classes for QML qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView"); qmlRegisterType<ViewshedCamera>("Esri.Samples", 1, 0, "ViewshedCameraSample"); } void ViewshedCamera::componentComplete() { QQuickItem::componentComplete(); // Create a scene m_sceneView = findChild<SceneQuickView*>("sceneView"); m_scene = new Scene(Basemap::imagery(this), this); // Set a base surface Surface* surface = new Surface(this); surface->elevationSources()->append( new ArcGISTiledElevationSource( QUrl("https://scene.arcgis.com/arcgis/rest/services/BREST_DTM_1M/ImageServer"), this)); m_scene->setBaseSurface(surface); // Add a Scene Layer ArcGISSceneLayer* sceneLayer = new ArcGISSceneLayer(QUrl("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer/layers/0"), this); m_scene->operationalLayers()->append(sceneLayer); // Add an AnalysisOverlay m_analysisOverlay = new AnalysisOverlay(this); m_sceneView->analysisOverlays()->append(m_analysisOverlay); // Set initial viewpoint setInitialViewpoint(); // Add the Scene to the Sceneview m_sceneView->setArcGISScene(m_scene); } void ViewshedCamera::calculateViewshed() { if (!m_viewshed) { // Create the viewshed const double minDistance = 1; const double maxDistance = 1000; m_viewshed = new LocationViewshed(m_sceneView->currentViewpointCamera(), minDistance, maxDistance, this); // display the frustum m_viewshed->setFrustumOutlineVisible(true); // Add the viewshed to the overlay m_analysisOverlay->analyses()->append(m_viewshed); } else { m_viewshed->updateFromCamera(m_sceneView->currentViewpointCamera()); } } void ViewshedCamera::setInitialViewpoint() { // create a camera and set the initial viewpoint const double x = -4.49492; const double y = 48.3808; const double z = 48.2511; Point pt(x, y, z, SpatialReference(4326)); const double heading = 344.488; const double pitch = 74.1212; const double roll = 0; Camera camera(pt, heading, pitch, roll); Viewpoint initViewpoint(pt, camera); m_scene->setInitialViewpoint(initViewpoint); }
30.018349
175
0.735024
markjdugger
abf9f393670c29069eb8657f908355426a05ab81
1,857
cpp
C++
src/ace/ACE_wrappers/examples/Naming/test_open.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/examples/Naming/test_open.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/examples/Naming/test_open.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
#include "ace/OS_main.h" #include "ace/Naming_Context.h" #include "ace/Log_Msg.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_unistd.h" int ACE_TMAIN (int argc, ACE_TCHAR **argv) { const ACE_TCHAR *host = argc > 1 ? argv[1] : ACE_TEXT("-hlocalhost"); const ACE_TCHAR *port = argc > 2 ? argv[2] : ACE_TEXT("-p20012"); ACE_STATIC_SVC_REGISTER(ACE_Naming_Context); ACE_Naming_Context ns; ACE_Name_Options *name_options = ns.name_options (); const ACE_TCHAR *m_argv[] = { ACE_TEXT("MyName"), ACE_TEXT("-cNET_LOCAL"), host, port, 0 }; int m_argc = sizeof (m_argv) / sizeof (ACE_TCHAR *) -1; name_options->parse_args (m_argc, (ACE_TCHAR **) m_argv); int result = ns.open (ACE_Naming_Context::NET_LOCAL); ACE_DEBUG ((LM_DEBUG, "ACE_Naming_Context::open returned %d\n", result)); if (result != 0) return result; else { char key[128]; char val[32]; char type[2]; type[0] = '-'; type[1] = '\0'; int i = 0; for (int l = 1; l <= 1000 ; l++) { ACE_OS::sprintf (key, "K_%05d_%05d", (int) ACE_OS::getpid (), l); ACE_OS::sprintf (val, "Val%05d", l); i = ns.bind (key, val, type); ACE_DEBUG ((LM_DEBUG, "%d: bind of %s: %d\n", ACE_OS::getpid (), key, i)); if (i != 0) return -1; } result = ns.close (); ACE_DEBUG ((LM_DEBUG, "ACE_Naming_Context::close returned %d\n", result)); } return result; }
23.2125
71
0.466344
wfnex
abfa8ced6c61af45e5bdb7d2148a9d89f44c1c31
2,663
hpp
C++
src/marnav/nmea/gsa.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
src/marnav/nmea/gsa.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
src/marnav/nmea/gsa.hpp
ShadowTeolog/marnav
094dd06a2b9e52591bc9c3879ea4b5cf34a92192
[ "BSD-4-Clause" ]
null
null
null
#ifndef MARNAV__NMEA__GSA__HPP #define MARNAV__NMEA__GSA__HPP #include <array> #include "sentence.hpp" #include "../utils/optional.hpp" namespace marnav { namespace nmea { /// @brief GSA - GPS DOP and active satellites /// /// @code /// 1 2 3 14 15 16 17 /// | | | | | | | /// $--GSA,a,a,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x.x,x.x,x.x*hh<CR><LF> /// @endcode /// /// Field Number: /// 1. Selection mode: M=Manual, forced to operate in 2D or 3D, A=Automatic, 3D/2D /// 2. Mode (1 = no fix, 2 = 2D fix, 3 = 3D fix) /// 3. ID of 1st satellite used for fix /// 4. ID of 2nd satellite used for fix /// 5. ID of 3rd satellite used for fix /// 6. ID of 4th satellite used for fix /// 7. ID of 5th satellite used for fix /// 8. ID of 6th satellite used for fix /// 9. ID of 7th satellite used for fix /// 10. ID of 8th satellite used for fix /// 11. ID of 9th satellite used for fix /// 12. ID of 10th satellite used for fix /// 13. ID of 11th satellite used for fix /// 14. ID of 12th satellite used for fix /// 15. PDOP /// 16. HDOP /// 17. VDOP /// class gsa : public sentence { friend class detail::factory; public: constexpr static sentence_id ID = sentence_id::GSA; constexpr static const char * TAG = "GSA"; constexpr static int max_satellite_ids = 12; gsa(); gsa(const gsa &) = default; gsa & operator=(const gsa &) = default; gsa(gsa &&) = default; gsa & operator=(gsa &&) = default; protected: gsa(talker talk, fields::const_iterator first, fields::const_iterator last); virtual void append_data_to(std::string &) const override; private: utils::optional<selection_mode> sel_mode_; // A:automatic 2D/3D, M:manual utils::optional<uint32_t> mode_; // 1 = no fix, 2 = 2D fix, 3 = 3D fix, TODO: enum std::array<utils::optional<uint32_t>, max_satellite_ids> satellite_id_; utils::optional<double> pdop_; utils::optional<double> hdop_; utils::optional<double> vdop_; void check_index(int index) const; public: decltype(sel_mode_) get_sel_mode() const { return sel_mode_; } decltype(mode_) get_mode() const { return mode_; } utils::optional<uint32_t> get_satellite_id(int index) const; decltype(pdop_) get_pdop() const { return pdop_; } decltype(hdop_) get_hdop() const { return hdop_; } decltype(vdop_) get_vdop() const { return vdop_; } void set_sel_mode(selection_mode t) noexcept { sel_mode_ = t; } void set_mode(uint32_t t) noexcept { mode_ = t; } void set_satellite_id(int index, uint32_t t); void set_pdop(double t) noexcept { pdop_ = t; } void set_hdop(double t) noexcept { hdop_ = t; } void set_vdop(double t) noexcept { vdop_ = t; } }; } } #endif
30.261364
83
0.667668
ShadowTeolog
abfdf9798573f437ffe630ddd4bacda4d6f41a4d
626
cpp
C++
web/code/class-03/struct.cpp
CPC-UTEC/blog
30ab1e744088d0d3b3fb4136c96e4568be0b2741
[ "MIT" ]
2
2020-09-09T20:29:25.000Z
2021-02-09T14:17:45.000Z
web/code/class-03/struct.cpp
CPC-UTEC/blog
30ab1e744088d0d3b3fb4136c96e4568be0b2741
[ "MIT" ]
null
null
null
web/code/class-03/struct.cpp
CPC-UTEC/blog
30ab1e744088d0d3b3fb4136c96e4568be0b2741
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct MyStructure { // we can declare attributes of different types int var1; double var2; string var3; MyStructure (int var1, double var2, string _var3): var1(var1), var2(var2) { // we can initialize the variables in this way var3 = _var3; // ot in this way } void my_method () { cout << var1 << ' ' << var2 << ' ' << var3 << '\n'; } }; int main () { MyStructure structure(18, 20.7, "hello world!"); structure.my_method(); // cal a method structure.var1 = 19; // access an attribute cout << structure.var3 << '\n'; return (0); }
23.185185
63
0.611821
CPC-UTEC
abfeb2aed635e3cf44540dc89ea4d6d74640e7c9
15,898
hpp
C++
native/external-libraries/boost/boost/interprocess/sync/scoped_lock.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
47
2015-01-01T14:37:36.000Z
2021-04-25T07:38:07.000Z
native/external-libraries/boost/boost/interprocess/sync/scoped_lock.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
6
2016-01-11T05:20:05.000Z
2021-02-06T11:37:24.000Z
native/external-libraries/boost/boost/interprocess/sync/scoped_lock.hpp
l3dlp-sandbox/airkinect-2-core
49aecbd3c3fd9584434089dd2d9eef93567036e7
[ "Apache-2.0" ]
17
2015-01-05T15:10:43.000Z
2021-06-22T04:59:16.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// // // This interface is inspired by Howard Hinnant's lock proposal. // http://home.twcny.rr.com/hinnant/cpp_extensions/threads_move.html // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_SCOPED_LOCK_HPP #define BOOST_INTERPROCESS_SCOPED_LOCK_HPP #if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #include <boost/interprocess/interprocess_fwd.hpp> #include <boost/interprocess/sync/lock_options.hpp> #include <boost/interprocess/exceptions.hpp> #include <boost/interprocess/detail/mpl.hpp> #include <boost/interprocess/detail/type_traits.hpp> #include <boost/interprocess/detail/move.hpp> #include <boost/interprocess/detail/posix_time_types_wrk.hpp> //!\file //!Describes the scoped_lock class. namespace boost { namespace interprocess { //!scoped_lock is meant to carry out the tasks for locking, unlocking, try-locking //!and timed-locking (recursive or not) for the Mutex. The Mutex need not supply all //!of this functionality. If the client of scoped_lock<Mutex> does not use //!functionality which the Mutex does not supply, no harm is done. Mutex ownership //!transfer is supported through the syntax of move semantics. Ownership transfer //!is allowed both by construction and assignment. The scoped_lock does not support //!copy semantics. A compile time error results if copy construction or copy //!assignment is attempted. Mutex ownership can also be moved from an //!upgradable_lock and sharable_lock via constructor. In this role, scoped_lock //!shares the same functionality as a write_lock. template <class Mutex> class scoped_lock { /// @cond private: typedef scoped_lock<Mutex> this_type; BOOST_MOVABLE_BUT_NOT_COPYABLE(scoped_lock) typedef bool this_type::*unspecified_bool_type; /// @endcond public: typedef Mutex mutex_type; //!Effects: Default constructs a scoped_lock. //!Postconditions: owns() == false and mutex() == 0. scoped_lock() : mp_mutex(0), m_locked(false) {} //!Effects: m.lock(). //!Postconditions: owns() == true and mutex() == &m. //!Notes: The constructor will take ownership of the mutex. If another thread //! already owns the mutex, this thread will block until the mutex is released. //! Whether or not this constructor handles recursive locking depends upon the mutex. explicit scoped_lock(mutex_type& m) : mp_mutex(&m), m_locked(false) { mp_mutex->lock(); m_locked = true; } //!Postconditions: owns() == false, and mutex() == &m. //!Notes: The constructor will not take ownership of the mutex. There is no effect //! required on the referenced mutex. scoped_lock(mutex_type& m, defer_lock_type) : mp_mutex(&m), m_locked(false) {} //!Postconditions: owns() == true, and mutex() == &m. //!Notes: The constructor will suppose that the mutex is already locked. There //! is no effect required on the referenced mutex. scoped_lock(mutex_type& m, accept_ownership_type) : mp_mutex(&m), m_locked(true) {} //!Effects: m.try_lock(). //!Postconditions: mutex() == &m. owns() == the return value of the //! m.try_lock() executed within the constructor. //!Notes: The constructor will take ownership of the mutex if it can do //! so without waiting. Whether or not this constructor handles recursive //! locking depends upon the mutex. If the mutex_type does not support try_lock, //! this constructor will fail at compile time if instantiated, but otherwise //! have no effect. scoped_lock(mutex_type& m, try_to_lock_type) : mp_mutex(&m), m_locked(mp_mutex->try_lock()) {} //!Effects: m.timed_lock(abs_time). //!Postconditions: mutex() == &m. owns() == the return value of the //! m.timed_lock(abs_time) executed within the constructor. //!Notes: The constructor will take ownership of the mutex if it can do //! it until abs_time is reached. Whether or not this constructor //! handles recursive locking depends upon the mutex. If the mutex_type //! does not support try_lock, this constructor will fail at compile //! time if instantiated, but otherwise have no effect. scoped_lock(mutex_type& m, const boost::posix_time::ptime& abs_time) : mp_mutex(&m), m_locked(mp_mutex->timed_lock(abs_time)) {} //!Postconditions: mutex() == the value scop.mutex() had before the //! constructor executes. s1.mutex() == 0. owns() == the value of //! scop.owns() before the constructor executes. scop.owns(). //!Notes: If the scop scoped_lock owns the mutex, ownership is moved //! to thisscoped_lock with no blocking. If the scop scoped_lock does not //! own the mutex, then neither will this scoped_lock. Only a moved //! scoped_lock's will match this signature. An non-moved scoped_lock //! can be moved with the expression: "boost::interprocess::move(lock);". This //! constructor does not alter the state of the mutex, only potentially //! who owns it. scoped_lock(BOOST_RV_REF(scoped_lock) scop) : mp_mutex(0), m_locked(scop.owns()) { mp_mutex = scop.release(); } //!Effects: If upgr.owns() then calls unlock_upgradable_and_lock() on the //! referenced mutex. upgr.release() is called. //!Postconditions: mutex() == the value upgr.mutex() had before the construction. //! upgr.mutex() == 0. owns() == upgr.owns() before the construction. //! upgr.owns() == false after the construction. //!Notes: If upgr is locked, this constructor will lock this scoped_lock while //! unlocking upgr. If upgr is unlocked, then this scoped_lock will be //! unlocked as well. Only a moved upgradable_lock's will match this //! signature. An non-moved upgradable_lock can be moved with //! the expression: "boost::interprocess::move(lock);" This constructor may block if //! other threads hold a sharable_lock on this mutex (sharable_lock's can //! share ownership with an upgradable_lock). template<class T> explicit scoped_lock(BOOST_RV_REF(upgradable_lock<T>) upgr , typename ipcdetail::enable_if< ipcdetail::is_same<T, Mutex> >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock<mutex_type> &u_lock = upgr; if(u_lock.owns()){ u_lock.mutex()->unlock_upgradable_and_lock(); m_locked = true; } mp_mutex = u_lock.release(); } //!Effects: If upgr.owns() then calls try_unlock_upgradable_and_lock() on the //!referenced mutex: //! a)if try_unlock_upgradable_and_lock() returns true then mutex() obtains //! the value from upgr.release() and owns() is set to true. //! b)if try_unlock_upgradable_and_lock() returns false then upgr is //! unaffected and this scoped_lock construction as the same effects as //! a default construction. //! c)Else upgr.owns() is false. mutex() obtains the value from upgr.release() //! and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex //! ownership from upgr immediately, while changing the lock type from a //! "read lock" to a "write lock". If the "read lock" isn't held in the //! first place, the mutex merely changes type to an unlocked "write lock". //! If the "read lock" is held, then mutex transfer occurs only if it can //! do so in a non-blocking manner. template<class T> scoped_lock(BOOST_RV_REF(upgradable_lock<T>) upgr, try_to_lock_type , typename ipcdetail::enable_if< ipcdetail::is_same<T, Mutex> >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock<mutex_type> &u_lock = upgr; if(u_lock.owns()){ if((m_locked = u_lock.mutex()->try_unlock_upgradable_and_lock()) == true){ mp_mutex = u_lock.release(); } } else{ u_lock.release(); } } //!Effects: If upgr.owns() then calls timed_unlock_upgradable_and_lock(abs_time) //! on the referenced mutex: //! a)if timed_unlock_upgradable_and_lock(abs_time) returns true then mutex() //! obtains the value from upgr.release() and owns() is set to true. //! b)if timed_unlock_upgradable_and_lock(abs_time) returns false then upgr //! is unaffected and this scoped_lock construction as the same effects //! as a default construction. //! c)Else upgr.owns() is false. mutex() obtains the value from upgr.release() //! and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex ownership //! from upgr immediately, while changing the lock type from a "read lock" to a //! "write lock". If the "read lock" isn't held in the first place, the mutex //! merely changes type to an unlocked "write lock". If the "read lock" is held, //! then mutex transfer occurs only if it can do so in a non-blocking manner. template<class T> scoped_lock(BOOST_RV_REF(upgradable_lock<T>) upgr, boost::posix_time::ptime &abs_time , typename ipcdetail::enable_if< ipcdetail::is_same<T, Mutex> >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock<mutex_type> &u_lock = upgr; if(u_lock.owns()){ if((m_locked = u_lock.mutex()->timed_unlock_upgradable_and_lock(abs_time)) == true){ mp_mutex = u_lock.release(); } } else{ u_lock.release(); } } //!Effects: If shar.owns() then calls try_unlock_sharable_and_lock() on the //!referenced mutex. //! a)if try_unlock_sharable_and_lock() returns true then mutex() obtains //! the value from shar.release() and owns() is set to true. //! b)if try_unlock_sharable_and_lock() returns false then shar is //! unaffected and this scoped_lock construction has the same //! effects as a default construction. //! c)Else shar.owns() is false. mutex() obtains the value from //! shar.release() and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex //! ownership from shar immediately, while changing the lock type from a //! "read lock" to a "write lock". If the "read lock" isn't held in the //! first place, the mutex merely changes type to an unlocked "write lock". //! If the "read lock" is held, then mutex transfer occurs only if it can //! do so in a non-blocking manner. template<class T> scoped_lock(BOOST_RV_REF(sharable_lock<T>) shar, try_to_lock_type , typename ipcdetail::enable_if< ipcdetail::is_same<T, Mutex> >::type * = 0) : mp_mutex(0), m_locked(false) { sharable_lock<mutex_type> &s_lock = shar; if(s_lock.owns()){ if((m_locked = s_lock.mutex()->try_unlock_sharable_and_lock()) == true){ mp_mutex = s_lock.release(); } } else{ s_lock.release(); } } //!Effects: if (owns()) mp_mutex->unlock(). //!Notes: The destructor behavior ensures that the mutex lock is not leaked.*/ ~scoped_lock() { try{ if(m_locked && mp_mutex) mp_mutex->unlock(); } catch(...){} } //!Effects: If owns() before the call, then unlock() is called on mutex(). //! *this gets the state of scop and scop gets set to a default constructed state. //!Notes: With a recursive mutex it is possible that both this and scop own //! the same mutex before the assignment. In this case, this will own the //! mutex after the assignment (and scop will not), but the mutex's lock //! count will be decremented by one. scoped_lock &operator=(BOOST_RV_REF(scoped_lock) scop) { if(this->owns()) this->unlock(); m_locked = scop.owns(); mp_mutex = scop.release(); return *this; } //!Effects: If mutex() == 0 or if already locked, throws a lock_exception() //! exception. Calls lock() on the referenced mutex. //!Postconditions: owns() == true. //!Notes: The scoped_lock changes from a state of not owning the mutex, to //! owning the mutex, blocking if necessary. void lock() { if(!mp_mutex || m_locked) throw lock_exception(); mp_mutex->lock(); m_locked = true; } //!Effects: If mutex() == 0 or if already locked, throws a lock_exception() //! exception. Calls try_lock() on the referenced mutex. //!Postconditions: owns() == the value returned from mutex()->try_lock(). //!Notes: The scoped_lock changes from a state of not owning the mutex, to //! owning the mutex, but only if blocking was not required. If the //! mutex_type does not support try_lock(), this function will fail at //! compile time if instantiated, but otherwise have no effect.*/ bool try_lock() { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->try_lock(); return m_locked; } //!Effects: If mutex() == 0 or if already locked, throws a lock_exception() //! exception. Calls timed_lock(abs_time) on the referenced mutex. //!Postconditions: owns() == the value returned from mutex()-> timed_lock(abs_time). //!Notes: The scoped_lock changes from a state of not owning the mutex, to //! owning the mutex, but only if it can obtain ownership by the specified //! time. If the mutex_type does not support timed_lock (), this function //! will fail at compile time if instantiated, but otherwise have no effect.*/ bool timed_lock(const boost::posix_time::ptime& abs_time) { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->timed_lock(abs_time); return m_locked; } //!Effects: If mutex() == 0 or if not locked, throws a lock_exception() //! exception. Calls unlock() on the referenced mutex. //!Postconditions: owns() == false. //!Notes: The scoped_lock changes from a state of owning the mutex, to not //! owning the mutex.*/ void unlock() { if(!mp_mutex || !m_locked) throw lock_exception(); mp_mutex->unlock(); m_locked = false; } //!Effects: Returns true if this scoped_lock has acquired //!the referenced mutex. bool owns() const { return m_locked && mp_mutex; } //!Conversion to bool. //!Returns owns(). operator unspecified_bool_type() const { return m_locked? &this_type::m_locked : 0; } //!Effects: Returns a pointer to the referenced mutex, or 0 if //!there is no mutex to reference. mutex_type* mutex() const { return mp_mutex; } //!Effects: Returns a pointer to the referenced mutex, or 0 if there is no //! mutex to reference. //!Postconditions: mutex() == 0 and owns() == false. mutex_type* release() { mutex_type *mut = mp_mutex; mp_mutex = 0; m_locked = false; return mut; } //!Effects: Swaps state with moved lock. //!Throws: Nothing. void swap( scoped_lock<mutex_type> &other) { std::swap(mp_mutex, other.mp_mutex); std::swap(m_locked, other.m_locked); } /// @cond private: mutex_type *mp_mutex; bool m_locked; /// @endcond }; } // namespace interprocess } // namespace boost #include <boost/interprocess/detail/config_end.hpp> #endif // BOOST_INTERPROCESS_SCOPED_LOCK_HPP
42.621984
93
0.661718
l3dlp-sandbox
abff2ed8bf737d093bc878b08a00e445f9e2eb2d
734
cpp
C++
Interviewbit/Arrays/kth_row_of_pascal_triangle.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
Interviewbit/Arrays/kth_row_of_pascal_triangle.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
Interviewbit/Arrays/kth_row_of_pascal_triangle.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
/* https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/ */ #include <iostream> #include <vector> #include <algorithm> #include <list> #include <queue> using namespace std; void print_vector(vector<int> v) { for (int i = 0; i < v.size(); ++i) { cout<<v[i]<<" "; } cout<<"\n"; } vector<int> generate_kth_row(int k) { vector<int> ans; int elem = 1; int numerator = k; int denominator = 1; for(int i=0; i<=k; i++) { ans.push_back(elem); elem = (elem * numerator)/denominator; numerator--; denominator++; } return ans; } int main() { int k; cin>>k; vector<int> v = generate_kth_row(k); print_vector(v); return 0; }
15.956522
66
0.56267
sohilladhani
abff57875b24d4f78c0348129cfa7f6b7104f823
88
cpp
C++
tests/Issue386_2.cpp
devtbi/cppinsights
5a9a8d93435f3c516240d3a87ee36f0a4bce5d90
[ "MIT" ]
1,853
2018-05-13T21:49:17.000Z
2022-03-30T10:34:45.000Z
tests/Issue386_2.cpp
tiandaoafei/cppinsights
af78ac299121354101a5e506dafccaac95d27a77
[ "MIT" ]
398
2018-05-15T14:48:51.000Z
2022-03-24T12:14:33.000Z
tests/Issue386_2.cpp
SammyEnigma/cppinsights
c984b8e68139bbcc244c094fd2463eeced8fd997
[ "MIT" ]
104
2018-05-15T04:00:59.000Z
2022-03-17T02:04:15.000Z
int main() { if(true) []{}(); for(;false;) []{}(); while(false) []{}(); }
9.777778
24
0.352273
devtbi
280199d45f80d2d672d10dfdb63c0a2fbe6e2563
1,848
cc
C++
cc/timer.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
1
2021-12-02T11:24:08.000Z
2021-12-02T11:24:08.000Z
cc/timer.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
null
null
null
cc/timer.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include <chrono> #include <atomic> struct Timer { template<typename F> void setTimeout(F func, uint32_t milliseconds); template<typename F> void setInterval(F func, uint32_t milliseconds); template<typename F> void setTimeoutSec(F func, uint32_t seconds); template<typename F> void setIntervalSec(F func, uint32_t seconds); void stop(); private: std::atomic<bool> alive{ true }; }; template<typename F> void Timer::setTimeout(F func, uint32_t milliseconds) { alive = true; std::thread t([=]() { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); if (!alive.load()) return; func(); }); t.detach(); } template<typename F> void Timer::setInterval(F func, uint32_t milliseconds) { alive = true; std::thread t([=]() { while (alive.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); if (!alive.load()) return; func(); } }); t.detach(); } template<typename F> void Timer::setTimeoutSec(F func, uint32_t seconds) { alive = true; std::thread t([=]() { std::this_thread::sleep_for(std::chrono::seconds(seconds)); if (!alive.load()) return; func(); }); t.detach(); } template<typename F> void Timer::setIntervalSec(F func, uint32_t seconds) { alive = true; std::thread t([=]() { while (alive.load()) { std::this_thread::sleep_for(std::chrono::seconds(seconds)); if (!alive.load()) return; func(); } }); t.detach(); } void Timer::stop() { alive = false; } int main() { using namespace std; std::locale::global(std::locale("en_US.UTF8")); Timer t; int i = 0; bool run = true; t.setTimeout([&t, &run]() { cout << "经过6.18s" << endl; t.stop(); run = false; }, 6180); t.setInterval([&i]() { cout << "持续" << ++i << "秒" << endl; }, 1000); cout << "定时器开始!" << endl; while (run) this_thread::yield(); return 0; }
30.295082
77
0.653139
asciphx
2803dfae39ed45d9d4836c6f19c9431e915ad3d3
1,600
hpp
C++
src/libs/graphics/color.hpp
dv1/dv1-misc-code
22d38ae0c1c1d7afe3f32147dc102298d00fb7bb
[ "BSD-2-Clause-FreeBSD" ]
2
2020-05-16T19:33:03.000Z
2020-05-17T04:21:31.000Z
src/libs/graphics/color.hpp
dv1/dv1-misc-code
22d38ae0c1c1d7afe3f32147dc102298d00fb7bb
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/libs/graphics/color.hpp
dv1/dv1-misc-code
22d38ae0c1c1d7afe3f32147dc102298d00fb7bb
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef GRAPHICS_COLOR_HPP___________ #define GRAPHICS_COLOR_HPP___________ #include <cstddef> #include <array> #include <map> #include "base/progress_report.hpp" #include "pixmap_view.hpp" namespace graphics { struct color { std::array < int, 3 > m_rgb_values; color(); explicit color(int const p_red, int const p_green, int const p_blue); color& operator += (color const &p_other); color& operator -= (color const &p_other); color& operator *= (int const p_value); color& operator /= (int const p_value); int operator [](std::size_t const p_index) const { return m_rgb_values[p_index]; } int& operator [](std::size_t const p_index) { return m_rgb_values[p_index]; } }; color operator + (color const &p_first, color const &p_second); color operator - (color const &p_first, color const &p_second); color operator * (color const &p_color, int const p_value); color operator / (color const &p_color, int const p_value); bool operator < (color const &p_first, color const &p_second); bool operator == (color const &p_first, color const &p_second); bool operator != (color const &p_first, color const &p_second); std::string to_string(color const &p_color); long calculate_color_distance(color const &p_first, color const &p_second); typedef std::map < color, std::size_t > color_histogram; void compute_color_histogram( color_histogram &p_color_histogram, const_pixmap_view_t p_input_pixmap, base::progress_report_callback const &p_progress_report_callback = base::progress_report_callback() ); } // namespace graphics end #endif // GRAPHICS_COLOR_HPP___________
25
100
0.751875
dv1
280547ed5c2b0a6fcfa8ec670add5c760a6ad8ac
4,468
cpp
C++
openstudiocore/src/energyplus/Test/ZoneHVACLowTempRadiantElectric_GTest.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/energyplus/Test/ZoneHVACLowTempRadiantElectric_GTest.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/energyplus/Test/ZoneHVACLowTempRadiantElectric_GTest.cpp
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 **********************************************************************/ #include <gtest/gtest.h> #include <energyplus/Test/EnergyPlusFixture.hpp> #include <energyplus/ForwardTranslator.hpp> #include <energyplus/ReverseTranslator.hpp> #include <model/ZoneHVACLowTemperatureRadiantElectric.hpp> #include <model/ZoneHVACLowTemperatureRadiantElectric_Impl.hpp> #include <model/ConstructionWithInternalSource.hpp> #include <model/ConstructionWithInternalSource_Impl.hpp> #include <model/DefaultConstructionSet.hpp> #include <model/DefaultConstructionSet_Impl.hpp> #include <model/DefaultSurfaceConstructions.hpp> #include <model/DefaultSurfaceConstructions_Impl.hpp> #include <model/HVACComponent.hpp> #include <model/HVACComponent_Impl.hpp> #include <model/Model.hpp> #include <model/Node.hpp> #include <model/Node_Impl.hpp> #include <model/ScheduleConstant.hpp> #include <model/ScheduleConstant_Impl.hpp> #include <model/StandardOpaqueMaterial.hpp> #include <model/StandardOpaqueMaterial_Impl.hpp> #include <model/ThermalZone.hpp> #include <model/ThermalZone_Impl.hpp> #include <utilities/idd/ZoneHVAC_LowTemperatureRadiant_Electric_FieldEnums.hxx> #include <utilities/idf/IdfExtensibleGroup.hpp> #include <resources.hxx> #include <sstream> using namespace openstudio::energyplus; using namespace openstudio::model; using namespace openstudio; TEST_F(EnergyPlusFixture,ZoneHVACLowTempRadiantElectric_Set_Flow_Fractions) { //make the example model Model model = model::exampleModel(); //loop through all zones and add a radiant system to each one BOOST_FOREACH(ThermalZone thermalZone, model.getModelObjects<ThermalZone>()){ //make an electric radiant unit ScheduleConstant availabilitySched(model); ScheduleConstant heatingControlTemperatureSchedule(model); availabilitySched.setValue(1.0); heatingControlTemperatureSchedule.setValue(10.0); ZoneHVACLowTemperatureRadiantElectric testRad(model,availabilitySched,heatingControlTemperatureSchedule); //add it to the thermal zone testRad.addToThermalZone(thermalZone); //attach to ceilings testRad.setRadiantSurfaceType("Ceilings"); //test that "surfaces" method returns 0 since no //ceilings have an internal source construction EXPECT_EQ(0,testRad.surfaces().size()); } // Create some materials and make an internal source construction StandardOpaqueMaterial exterior(model); StandardOpaqueMaterial interior(model); OpaqueMaterialVector layers; layers.push_back(exterior); layers.push_back(interior); ConstructionWithInternalSource construction(layers); //set building's default ceiling construction to internal source construction DefaultConstructionSet defConSet = model.getModelObjects<DefaultConstructionSet>()[0]; defConSet.defaultExteriorSurfaceConstructions()->setRoofCeilingConstruction(construction); //translate the model to EnergyPlus ForwardTranslator trans; Workspace workspace = trans.translateModel(model); //loop through all zones and check the flow fraction for each surface in the surface group. it should be 0.25 BOOST_FOREACH(ThermalZone thermalZone, model.getModelObjects<ThermalZone>()){ //get the radiant zone equipment BOOST_FOREACH(ModelObject equipment, thermalZone.equipment()){ if (equipment.optionalCast<ZoneHVACLowTemperatureRadiantElectric>()){ ZoneHVACLowTemperatureRadiantElectric testRad = equipment.optionalCast<ZoneHVACLowTemperatureRadiantElectric>().get(); BOOST_FOREACH(IdfExtensibleGroup extGrp, testRad.extensibleGroups()){ EXPECT_EQ(0.25,extGrp.getDouble(1,false)); } } } } }
37.546218
122
0.77641
bobzabcik
2806f470c1fb46abafafba5641f306041749d127
1,683
hpp
C++
src/main/include/Robot.hpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
src/main/include/Robot.hpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
src/main/include/Robot.hpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2021 FRC Team 3512. All Rights Reserved. #pragma once #include <cameraserver/CameraServer.h> #include <cscore.h> #include <ctre/phoenix/motorcontrol/can/TalonSRX.h> #include <frc/DigitalInput.h> #include <frc/DoubleSolenoid.h> #include <frc/Joystick.h> #include <frc/Solenoid.h> #include <frc/TimedRobot.h> #include "AutonomousChooser.hpp" #include "Constants.hpp" #include "subsystems/Drivetrain.hpp" class Robot : public frc::TimedRobot { public: Robot(); void DisabledInit() override; void AutonomousInit() override; void TeleopInit() override; void TestInit() override; void RobotPeriodic() override; void DisabledPeriodic() override; void AutonomousPeriodic() override; void TeleopPeriodic() override; void AutoLeftGear(); void AutoCenterGear(); void AutoRightGear(); void AutoBaseLine(); void DS_PrintOut(); private: using WPI_TalonSRX = ctre::phoenix::motorcontrol::can::WPI_TalonSRX; Drivetrain robotDrive; frc::Solenoid claw{0}; frc::DoubleSolenoid arm{1, 2}; frc::DoubleSolenoid gearPunch{3, 4}; frc::Solenoid shifter{5}; WPI_TalonSRX grabberMotor{15}; frc::DigitalInput forwardGrabberLimit{1}; frc::DigitalInput reverseGrabberLimit{0}; WPI_TalonSRX winchMotor{3}; frc::Joystick driveStick1{kDriveStick1Port}; frc::Joystick driveStick2{kDriveStick2Port}; frc::Joystick grabberStick{kGrabberStickPort}; frc3512::AutonomousChooser m_autonChooser{"No-op", [] {}}; // Camera cs::UsbCamera camera1{"Camera 1", 0}; // cs::UsbCamera camera2{"Camera 2", 1}; cs::MjpegServer server{"Server", kMjpegServerPort}; };
24.75
72
0.708853
Team3512
28091d656c645093e1284223b53f30b03b6041a4
1,676
cpp
C++
kattis/set3/reduction.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
kattis/set3/reduction.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
kattis/set3/reduction.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
/** Words are like swords. If you use them the wrong way, they can turn into ugly weapons. */ #include <bits/stdc++.h> #define forn(i, l, r) for(int i=l;i<=r;i++) #define all(v) v.begin(),v.end() #define pb push_back #define nd second #define st first #define debug(x) cout<<#x<<" -> "<<x<< endl #define kakimasu(x) cout << x << '\n' #define sz(x) (int)x.size() #define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin()) //need to sort first b4 using unique using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<bool> vb; typedef vector<string> vs; typedef vector<double> vd; typedef vector<long long> vll; typedef vector<vector<int> > vvi; typedef vector<vll> vvll; typedef vector<pair<int, int> > vpi; typedef vector<vpi> vvpi; typedef pair<int, int> pi; typedef pair<ll, ll> pll; typedef vector<pll> vpll; const int INF = 1 << 30; /** Start coding from here */ struct State { int s,w,c; }; int main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL_PROJECT freopen("input.txt","r",stdin); #endif int tc; cin>>tc; int ct=1; while(tc--) { int n, m, c; cin>>n>>m>>c; vector<pair<int, string> > ans; forn(i, 1, c) { string s; cin>>s; string name=s.substr(0, s.find(":")); int a = stoi(s.substr(s.find(":") + 1, s.find(","))); int b = stoi(s.substr(s.find(",") + 1)); int res = INF; int cur = n; int cost = 0; while(cur>=m) { res = min(res, cost + (cur - m) * a); cur/=2; cost+=b; } ans.pb({res, name}); } sort(all(ans)); cout << "Case " << ct++ << '\n'; for(auto &aa : ans) cout << aa.nd << ' ' <<aa.st<<'\n'; } return 0; }
22.648649
94
0.599642
heiseish
280b7fb194500156f9c98d02399d79c99ad66b2f
1,855
cpp
C++
Double_List/Double_List.cpp
kungcn/Data_Structure
45db44d2f116b5ad316634399c0e246105e0f46e
[ "MIT" ]
null
null
null
Double_List/Double_List.cpp
kungcn/Data_Structure
45db44d2f116b5ad316634399c0e246105e0f46e
[ "MIT" ]
null
null
null
Double_List/Double_List.cpp
kungcn/Data_Structure
45db44d2f116b5ad316634399c0e246105e0f46e
[ "MIT" ]
null
null
null
#include "Double_List.h" template <class List_entry> Double_List<List_entry>::Double_List() { } template <class List_entry> Double_List<List_entry>::~Double_List() { } // 拷贝构造函数和赋值运算符重载,注意深拷贝与浅拷贝的差异 template <class List_entry> Double_List<List_entry>::Double_List(const Double_List<List_entry> &copy) { S } template <class List_entry> void Double_List<List_entry>::operator =(const Double_List<List_entry> &copy) { } // 清空list template <class List_entry> void Double_List<List_entry>::clear() { } // 判断list是否为空 template <class List_entry> bool Double_List<List_entry>::empty() const { } // 判断list是否已满 template <class List_entry> bool Double_List<List_entry>::full() const { } // 获取list的元素数量 template <class List_entry> int Double_List<List_entry>::size() const { } // 在第position个位置插入值为entry的元素,如果position为0则插入在链表头,依次类推 // 若position < 0 或者 position > count,则返回underflow template <class List_entry> Error_code Double_List<List_entry>::insert(int position, const List_entry &entry) { } // 删除第position个位置的元素,并将该元素的值保存在entry中 // 若position < 0 或者 position >= count,则返回underflow template <class List_entry> Error_code Double_List<List_entry>::remove(int position, List_entry &entry) { } // 获取第position个位置的元素,保存在entry中 // 若position < 0 或者 position >= count,则返回underflow template <class List_entry> Error_code Double_List<List_entry>::retrieve(int position, List_entry &entry) const { } // 将第position个位置的元素替换为entry // 若position < 0 或者 position >= count,则返回underflow template <class List_entry> Error_code Double_List<List_entry>::replace(int position, const List_entry &entry) { } // 用visit函数遍历list内所有的元素 template <class List_entry> void Double_List<List_entry>::traverse(void (*visit)(List_entry &)) { } // 设置current指针的位置,指向第position个位置 template <class List_entry> void Double_List<List_entry>::setPosition(int position) const { }
21.079545
85
0.769272
kungcn
280feedf02bae1f8bb7b233d733c8ca514c19ec3
11,977
cpp
C++
apps/AutoSmiley/AutoSmiley-v001/src/mpi/mpieyefinder/faceobject.cpp
yingshixiaohu/SmileFile
96641a104e4c9d5cac887aeef617bdc1f51557b3
[ "MIT" ]
1
2015-01-05T23:16:06.000Z
2015-01-05T23:16:06.000Z
apps/AutoSmiley/AutoSmiley-v001/src/mpi/mpieyefinder/faceobject.cpp
yingshixiaohu/SmileFile
96641a104e4c9d5cac887aeef617bdc1f51557b3
[ "MIT" ]
null
null
null
apps/AutoSmiley/AutoSmiley-v001/src/mpi/mpieyefinder/faceobject.cpp
yingshixiaohu/SmileFile
96641a104e4c9d5cac887aeef617bdc1f51557b3
[ "MIT" ]
null
null
null
/* * FACEOBJECT.cpp * * Created by Bret Fortenberry on Aug 27, 2003. * Fixes: * * Copyright (c) 2003 Machine Perception Laboratory * University of California San Diego. * * Please read the disclaimer and notes about redistribution * at the end of this file. * */ #include "faceobject.h" #include <iostream> //extern "C"{ #include <math.h> //} FaceObject::FaceObject(){ feature = e_face; leftEyes.reserve(EYEMEMSIZE); rightEyes.reserve(EYEMEMSIZE); } FaceObject::FaceObject(float x_in, float y_in, float xSize_in, float ySize_in, float scale_in){ x = x_in; y = y_in; xSize = xSize_in; ySize = ySize_in; scale = scale_in; feature = e_face; leftEyes.reserve(EYEMEMSIZE); rightEyes.reserve(EYEMEMSIZE); } FaceObject::FaceObject(FaceObject &thelist) { objects = thelist.objects; x = thelist.x; y = thelist.y; xSize = thelist.xSize; ySize = thelist.ySize; scale = thelist.scale; eyes = thelist.eyes; leftEyes = thelist.leftEyes; rightEyes = thelist.rightEyes; feature = thelist.feature; activation = thelist.activation; } FaceObject::FaceObject(TSquare<float> &square) { x = square.x; y = square.y; xSize = square.size; ySize = square.size; scale = square.scale; leftEyes.reserve(EYEMEMSIZE); rightEyes.reserve(EYEMEMSIZE); feature = e_face; } FaceObject::FaceObject(list<Square>::iterator face) { x = face->x; y = face->y; xSize = face->size; ySize = face->size; scale = face->scale; feature = e_face; } FaceObject::~FaceObject() { clear(); } void FaceObject::clear(){ if(objects.size()) { list< VisualObject* >::iterator it = objects.begin(); for(; it != objects.end(); ++it) { (*it)->clear(); delete (*it); } objects.clear(); } leftEyes.clear(); rightEyes.clear(); } void FaceObject::findMax() { double max = -1000000; if(leftEyes.size()){ //cout << "finding max left eye" << endl; eyes.leftEye = true; vector< EyeObject >::iterator it = leftEyes.begin(); for(; it != leftEyes.end(); ++it){ if(max < it->activation){ max = it->activation; //cout << "max: " << max; eyes.xLeft = it->x; eyes.yLeft = it->y; eyes.leftScale = it->scale; //cout << " at (" << it->x << "," << it->y << ")" << endl; } } } max = -1000000; if(rightEyes.size()){ eyes.rightEye = true; vector< EyeObject >::iterator it = rightEyes.begin(); for(; it != rightEyes.end(); ++it){ if(max < it->activation){ max = it->activation; eyes.xRight = it->x; eyes.yRight = it->y; eyes.rightScale = it->scale; } } } } void FaceObject::posterior(combine_mode mode) { switch(mode){ double maxAct; case mean_shift: case mpi_search: case maximum: // not currently used break; case face_only: eyes.xLeft = x + (xSize*0.7077f); eyes.yLeft = y + (xSize*0.3099f); eyes.leftScale = scale; eyes.xRight = x + (xSize*0.3149f); eyes.yRight = y + (xSize*0.3136f); eyes.rightScale = scale; break; case wt_max: case none: maxAct = -1000000; if(leftEyes.size()){ eyes.leftEye = true; vector< EyeObject >::iterator it = leftEyes.begin(); for(; it != leftEyes.end(); ++it){ if(maxAct < it->activation){ maxAct = it->activation; eyes.xLeft = it->x; eyes.yLeft = it->y; eyes.leftScale = it->scale; } } } maxAct = -1000000; if(rightEyes.size()){ eyes.rightEye = true; vector< EyeObject >::iterator it = rightEyes.begin(); for(; it != rightEyes.end(); ++it){ if(maxAct < it->activation){ maxAct = it->activation; eyes.xRight = it->x; eyes.yRight = it->y; eyes.rightScale = it->scale; } } } break; case wt_avg: case average: float xWt; float yWt; float scaleWt; float totalAct; vector< vector< float > > meanSub; vector< vector< float > > wtMeanSub; vector< vector< float > > invMtx; vector< vector< float > > covMtx; vector< EyeObject > *EyesPtr = 0; //cout << "leftEyes size = " << leftEyes.size() << endl; for(int cur_eye = 0; cur_eye < 2; cur_eye++){ bool run = false; if(leftEyes.size() && cur_eye == 0){ EyesPtr = &leftEyes; run = true; } else if(rightEyes.size() && cur_eye == 1){ EyesPtr = &rightEyes; run = true; } else cur_eye++; if (run){ vector< EyeObject > Eyes = *EyesPtr; float expo; bool outlier = true; float mean3d[3]; float determ; while(outlier){ totalAct = 0.0f; xWt = 0.0f; yWt = 0.0f; scaleWt = 0.0f; for (unsigned int i = 0; i < Eyes.size(); i++){ expo = exp(Eyes[i].activation); xWt += (expo * Eyes[i].x); yWt += (expo * Eyes[i].y); scaleWt += (expo * Eyes[i].scale); totalAct += expo; } mean3d[0] = xWt/totalAct; mean3d[1] = yWt/totalAct; mean3d[2] = scaleWt/totalAct; for(unsigned int pos = 0; pos < Eyes.size(); ++pos){ vector< float > v; vector< float > wt; expo = exp(Eyes[pos].activation); v.push_back(Eyes[pos].x - mean3d[0]); wt.push_back(v[0] * expo); v.push_back(Eyes[pos].y - mean3d[1]); wt.push_back(v[1] * expo); v.push_back(Eyes[pos].scale - mean3d[2]); wt.push_back(v[2] * expo); meanSub.push_back(v); wtMeanSub.push_back(wt); } float divTotAct = 1.0f/totalAct; if(mtxMult_2T(meanSub, wtMeanSub, covMtx, divTotAct) != 9){ meanSub.clear(); wtMeanSub.clear(); invMtx.clear(); covMtx.clear(); break; } if((determ = det3(covMtx))){ TransCof3(covMtx, invMtx, determ); } else { //later implement psudo inverse page 192 meanSub.clear(); wtMeanSub.clear(); invMtx.clear(); covMtx.clear(); break; //exit while loop } outlier = findOutliers(meanSub, invMtx, Eyes); meanSub.clear(); wtMeanSub.clear(); invMtx.clear(); covMtx.clear(); }//while loop if(mean3d[0] > x && mean3d[0] < (x+xSize) && mean3d[1] > y && mean3d[1] < (y+ySize)){ if(cur_eye == 0){ eyes.xLeft = mean3d[0]; eyes.yLeft = mean3d[1]; eyes.leftScale = mean3d[2]; eyes.leftEye = true; } if(cur_eye == 1){ eyes.xRight = mean3d[0]; eyes.yRight = mean3d[1]; eyes.rightScale = mean3d[2]; eyes.rightEye = true; } } } } break; }; } void FaceObject::TransCof3(vector< vector< float > > &inMtx, vector< vector< float > > &rtnMtx, float det){ float divDet = 1/det; vector< float > v; v.push_back((inMtx[1][1]*inMtx[2][2]-inMtx[1][2]*inMtx[2][1])*divDet); v.push_back(-(inMtx[0][1]*inMtx[2][2]-inMtx[0][2]*inMtx[2][1])*divDet); v.push_back((inMtx[0][1]*inMtx[1][2]-inMtx[0][2]*inMtx[1][1])*divDet); rtnMtx.push_back(v); vector< float > v2; v2.push_back(-(inMtx[1][0]*inMtx[2][2]-inMtx[1][2]*inMtx[2][0])*divDet); v2.push_back((inMtx[0][0]*inMtx[2][2]-inMtx[0][2]*inMtx[2][0])*divDet); v2.push_back(-(inMtx[0][0]*inMtx[1][2]-inMtx[0][2]*inMtx[1][0])*divDet); rtnMtx.push_back(v2); vector< float > v3; v3.push_back((inMtx[1][0]*inMtx[2][1]-inMtx[1][1]*inMtx[2][0])*divDet); v3.push_back(-(inMtx[0][0]*inMtx[2][1]-inMtx[0][1]*inMtx[2][0])*divDet); v3.push_back((inMtx[0][0]*inMtx[1][1]-inMtx[0][1]*inMtx[1][0])*divDet); rtnMtx.push_back(v3); } //http://astronomy.swin.edu.au/~pbourke/analysis/inverse/ float FaceObject::det3(vector< vector< float > > &matrix){ if ((matrix.size() != 3) || (matrix[0].size() != 3)) return (0.0f); return ((matrix[0][0] * (matrix[1][1]*matrix[2][2] - matrix[1][2]*matrix[2][1])) - (matrix[0][1] * (matrix[1][0]*matrix[2][2] - matrix[1][2]*matrix[2][0])) + (matrix[0][2] * (matrix[1][0]*matrix[2][1] - matrix[1][1]*matrix[2][0]))); } //http://www.mathworks.com/access/helpdesk/help/toolbox/aeroblks/determinantof3x3matrix.shtml int FaceObject::mtxMult(vector< vector< float > > &matrix1, vector< vector< float > > &matrix2, vector< vector< float > > &rtnMtx){ if(matrix1[0].size() != matrix2.size()){ return 0; } rtnMtx.clear(); float comb; int size = 0; for(unsigned int cur_row = 0; cur_row < matrix1.size(); ++cur_row){ vector< float > v; for(unsigned int cur_col = 0; cur_col < matrix2[0].size(); ++cur_col){ comb = 0; for(unsigned int cur_pos = 0; cur_pos < matrix1[0].size(); ++cur_pos){ comb += matrix1[cur_row][cur_pos] * matrix2[cur_pos][cur_col]; } v.push_back(comb); size++; } rtnMtx.push_back(v); } return size; } int FaceObject::mtxMult_2T(vector< vector< float > > &matrix1, vector< vector< float > > &matrix2, vector< vector< float > > &rtnMtx, float mult){ if(matrix1.size() != matrix2.size()) return 0; rtnMtx.clear(); float comb; int size = 0; for(unsigned int cur_row = 0; cur_row < matrix1[0].size(); ++cur_row){ vector< float > v; for(unsigned int cur_col = 0; cur_col < matrix2[0].size(); ++cur_col){ comb = 0; for(unsigned int cur_pos = 0; cur_pos < matrix1.size(); ++cur_pos){ comb += matrix1[cur_pos][cur_row] * matrix2[cur_pos][cur_col]; } v.push_back(comb*mult); size++; } rtnMtx.push_back(v); } return size; } bool FaceObject::findOutliers(vector< vector< float > > &meanSub, vector< vector< float > > &invMtx, vector< EyeObject > &Eyes){ vector< vector< float > > mnSubMtx; vector< vector< float > > tempMtx; vector< vector< float > > di; bool rtn = false; for (int i = (meanSub.size() - 1); i >= 0; --i){ mnSubMtx.push_back(meanSub[i]); mtxMult(mnSubMtx, invMtx, tempMtx); mtxMult_2T(tempMtx, mnSubMtx, di); //cout << "outlier di = " << di[0][0] << endl; if (di[0][0] > 1.0f){ //cout << "outlier di !!!!!!!= " << di[0][0] << endl; rtn = true; Eyes.erase(Eyes.begin() + i); } mnSubMtx.clear(); tempMtx.clear(); di.clear(); } return rtn; } #ifndef WIN32 int FaceObject::prtMtx(vector< vector< float > > &matrix){ for(unsigned int cur_row = 0; cur_row < matrix.size(); ++cur_row){ cout << "("; for(unsigned int cur_col = 0; cur_col < matrix[0].size(); ++cur_col){ cout << matrix[cur_row][cur_col] << ", "; } cout << ")\n"; } cout << endl; return 1; } #endif /* * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */
29.57284
707
0.595475
yingshixiaohu
2810203c4093d5a61ef28859b19ccf71c031ff55
1,889
hpp
C++
src/fly/task/task.hpp
lichuan/fly
7927f819f74997314fb526c5d8ab4d88ea593b91
[ "Apache-2.0" ]
60
2015-06-23T12:36:33.000Z
2022-03-09T01:27:14.000Z
src/fly/task/task.hpp
lichuan/fly
7927f819f74997314fb526c5d8ab4d88ea593b91
[ "Apache-2.0" ]
1
2021-12-21T11:23:04.000Z
2021-12-21T11:23:04.000Z
src/fly/task/task.hpp
lichuan/fly
7927f819f74997314fb526c5d8ab4d88ea593b91
[ "Apache-2.0" ]
30
2015-08-03T07:22:04.000Z
2022-01-13T08:49:48.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: 308831759@qq.com * * @github: https://github.com/lichuan/fly * * @date: 2015-06-21 18:45:20 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef FLY__TASK__TASK #define FLY__TASK__TASK #include "fly/base/common.hpp" namespace fly { namespace task { class Task { friend class Executor; public: Task(uint64 seq); virtual ~Task() = default; virtual void run() {} uint64 seq(); void set_executor_id(uint32 id); protected: uint32 m_executor_id; private: uint64 m_seq; bool m_stop_executor = false; }; } } #endif
35.641509
73
0.228163
lichuan
2810e8476f082b4b7c063f099eedbea4d9b4c56f
17,503
hpp
C++
src/MSR.hpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
src/MSR.hpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
src/MSR.hpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MSR_HPP_INCLUDE #define MSR_HPP_INCLUDE #include <stdint.h> #include <string> #include <vector> #include <map> namespace geopm { /// @brief Class describing all of the encoded values within a /// single MSR register. This class encodes how to access fields /// within an MSR, but does not hold the state of any registers. class IMSR { public: /// @brief Structure describing a bit field in an MSR. struct m_encode_s { int begin_bit; /// First bit of the field, inclusive. int end_bit; /// Last bit of the field, exclusive. int domain; /// Domain over which the MSR is shared (geopm_domain_type_e). int function; /// Function which converts the bit field into an integer to be scaled (m_function_e). int units; /// Scalar converts the integer output of function into units (m_units_e). double scalar; /// Scale factor to convert integer output of function to SI units. }; enum m_function_e { M_FUNCTION_SCALE, // Only apply scalar value (applied by all functions) M_FUNCTION_LOG_HALF, // 2.0 ^ -X M_FUNCTION_7_BIT_FLOAT, // 2 ^ Y * (1.0 + Z / 4.0) : Y in [0:5), Z in [5:7) M_FUNCTION_OVERFLOW, // Counter that may overflow }; enum m_units_e { M_UNITS_NONE, M_UNITS_SECONDS, M_UNITS_HZ, M_UNITS_WATTS, M_UNITS_JOULES, M_UNITS_CELSIUS, }; IMSR() = default; virtual ~IMSR() = default; /// @brief Query the name of the MSR. /// @param msr_name [out] The name of the MSR. virtual std::string name(void) const = 0; /// @brief The byte offset for the MSR. /// @return The 64-bit offset to the register. virtual uint64_t offset(void) const = 0; /// @brief The number of distinct signals encoded in the MSR. /// @return The number of contiguous bit fields in the MSR /// that encode signals. virtual int num_signal(void) const = 0; /// @brief The number of distinct controls encoded in the MSR. /// @return The number of contiguous bit fields in the MSR /// that encode controls. virtual int num_control(void) const = 0; /// @brief Query the name of a signal bit field. /// @param [in] signal_idx The index of the bit field in /// range from to 0 to num_signal() - 1. /// @param [out] name The name of a signal bit field. virtual std::string signal_name(int signal_idx) const = 0; /// @brief Query the name of a control bit field. /// @param [in] control_idx The index of the bit field in /// range from to 0 to num_control() - 1. /// @param [out] name The name of a control bit field. virtual std::string control_name(int control_idx) const = 0; /// @brief Query for the signal index given a name. /// @param [in] name The name of the signal bit field. /// @return Index of the signal queried unless signal name /// is not found, then -1 is returned. virtual int signal_index(const std::string &name) const = 0; /// @brief Query for the control index given a name. /// @param [in] name The name of the control bit field. /// @return Index of the control queried unless control name /// is not found, then -1 is returned. virtual int control_index(const std::string &name) const = 0; /// @brief Extract a signal from a raw MSR value. /// @param [in] signal_idx Index of the signal bit field. /// @param [in] field the 64-bit register value to decode. /// @param [in] last_field Previous value of the MSR. /// Only relevant if the decode function is /// M_FUNCTION_OVERFLOW. /// @return The decoded signal in SI units. virtual double signal(int signal_idx, uint64_t field, uint64_t &last_field, uint64_t &num_overflow) const = 0; /// @brief Set a control bit field in a raw MSR value. /// @param [in] control_idx Index of the control bit /// field. /// @param [in] value The value in SI units that will be /// encoded. /// @param [out] mask The write mask to be used when /// writing the field. /// @param [out] field The register value to write into /// the MSR. virtual void control(int control_idx, double value, uint64_t &field, uint64_t &mask) const = 0; /// @brief Get mask given a control index. /// @param [in] control_idx Index of the control bit /// field. /// @return The write mask to be used when writing the /// field. virtual uint64_t mask(int control_idx) const = 0; /// @brief The type of the domain that the MSR encodes. /// @return The domain type that the MSR pertains to as /// defined in the m_domain_e enum /// from the PlatformTopo.hpp header. virtual int domain_type(void) const = 0; /// @brief The function used to decode the MSR value as defined /// in the m_function_e enum. virtual int decode_function(int signal_idx) const = 0; }; class IMSRSignal { public: IMSRSignal() = default; virtual ~IMSRSignal() = default; /// @brief Get the signal parameter name. /// @return The name of the feature being measured. virtual std::string name(void) const = 0; /// @brief Get the type of the domain under measurement. /// @return One of the values from the IPlatformTopo::m_domain_e /// enum described in PlatformTopo.hpp. virtual int domain_type(void) const = 0; /// @brief Get the index of the cpu in the domain under measurement. /// @return The index of the domain within the set of /// domains of the same type on the platform. virtual int cpu_idx(void) const = 0; /// @brief Get the value of the signal. /// @return The value of the parameter measured in SI /// units. virtual double sample(void) = 0; /// @brief Gets the MSR offset for each of the MSRs that are /// combined to provide a signal. /// @param [out] offset The MSR offset values. virtual uint64_t offset(void) const = 0; /// @brief Map 64 bits of memory storing the raw value of /// an MSR that will be referenced when calculating /// the signal. /// @param [in] Pointer to the memory containing the raw /// MSR value. virtual void map_field(const uint64_t *field) = 0; }; class IMSRControl { public: IMSRControl() = default; virtual ~IMSRControl() = default; /// @brief Get the control parameter name. /// @return The name of the feature under control. virtual std::string name(void) const = 0; /// @brief Get the type of the domain under control. /// @return One of the values from the m_domain_e /// enum described in PlatformTopo.hpp. virtual int domain_type(void) const = 0; /// @brief Get the index of the cpu in the domain under control. /// @return The index of the domain within the set of /// domains of the same type on the platform. virtual int cpu_idx(void) const = 0; /// @brief Set the value for the control. /// @param [in] setting Value in SI units of the parameter /// controlled by the object. virtual void adjust(double setting) = 0; /// @brief Gets the MSR offset for each of the MSRs that are /// set by the control. /// @param [out] offset The MSR offset values. virtual uint64_t offset(void) const = 0; /// @brief Gets the mask for each of the MSRs that are /// written by the control. /// @param [out] mask The write mask values. virtual uint64_t mask(void) const = 0; /// @brief Map 64 bits of memory storing the raw value of /// an MSR that will be referenced when enforcing /// the control. /// @param [in] field Pointer to the memory containing the /// raw MSR value. /// @param [in] mask Pointer to mask that is applied when /// writing value. virtual void map_field(uint64_t *field, uint64_t *mask) = 0; }; class MSREncode; class MSR : public IMSR { public: /// @brief Constructor for the MSR class for fixed MSRs. /// @param [in] msr_name The name of the MSR. /// @param [in] offset The byte offset of the MSR. /// @param [in] signal Vector of signal name and encode /// struct pairs describing all signals embedded in /// the MSR. /// @param [in] control Vector of control name and encode /// struct pairs describing all controls embedded in the /// MSR. MSR(const std::string &msr_name, uint64_t offset, const std::vector<std::pair<std::string, struct IMSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct IMSR::m_encode_s> > &control); /// @brief MSR class destructor. virtual ~MSR(); std::string name(void) const override; uint64_t offset(void) const override; int num_signal(void) const override; int num_control(void) const override; std::string signal_name(int signal_idx) const override; std::string control_name(int control_idx) const override; int signal_index(const std::string &name) const override; int control_index(const std::string &name) const override; double signal(int signal_idx, uint64_t field, uint64_t &last_field, uint64_t &num_overflow) const override; void control(int control_idx, double value, uint64_t &field, uint64_t &mask) const override; uint64_t mask(int control_idx) const override; int domain_type(void) const override; int decode_function(int signal_idx) const override; private: void init(const std::vector<std::pair<std::string, struct IMSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct IMSR::m_encode_s> > &control); std::string m_name; uint64_t m_offset; std::vector<MSREncode *> m_signal_encode; std::vector<MSREncode *> m_control_encode; std::map<std::string, int> m_signal_map; std::map<std::string, int> m_control_map; int m_domain_type; const std::vector<const IMSR *> m_prog_msr; const std::vector<std::string> m_prog_field_name; const std::vector<double> m_prog_value; }; class MSRSignal : public IMSRSignal { public: /// @brief Constructor for the MSRSignal class used when the /// signal is determined by a single bit field in a /// single MSR. /// @param [in] msr_obj Pointer to the MSR object /// describing the MSR that contains the signal. /// @param [in] cpu_idx The logical Linux CPU index to /// query for the MSR. /// @param [in] signal_idx The index of the signal within /// the MSR that the class represents. MSRSignal(const IMSR &msr_obj, int domain_type, int cpu_idx, int signal_idx); /// @brief Constructor for an MSRSignal corresponding to the raw /// value of the entire MSR. MSRSignal(const IMSR &msr_obj, int domain_type, int cpu_idx); /// @brief Copy constructor. After copying, map field /// must be called again on the new MSRSignal. MSRSignal(const MSRSignal &other); MSRSignal &operator=(const MSRSignal &other) = delete; virtual ~MSRSignal() = default; virtual std::string name(void) const override; int domain_type(void) const override; int cpu_idx(void) const override; double sample(void) override; uint64_t offset(void) const override; void map_field(const uint64_t *field) override; private: const std::string m_name; const IMSR &m_msr_obj; const int m_domain_type; const int m_cpu_idx; const int m_signal_idx; const uint64_t *m_field_ptr; uint64_t m_field_last; uint64_t m_num_overflow; bool m_is_field_mapped; bool m_is_raw; }; class MSRControl : public IMSRControl { public: /// @brief Constructor for the MSRControl class used when the /// control is enforced with a single bit field in a /// single MSR. /// @param [in] msr_obj Pointer to the MSR object /// describing the MSR that contains the control. /// @param [in] cpu_idx The logical Linux CPU index to /// write the MSR. /// @param [in] control_idx The index of the control within /// the MSR that the class represents. MSRControl(const IMSR &msr_obj, int domain_type, int cpu_idx, int control_idx); MSRControl(const MSRControl &other) = default; MSRControl &operator=(const MSRControl &other) = default; virtual ~MSRControl(); virtual std::string name(void) const override; int domain_type(void) const override; int cpu_idx(void) const override; void adjust(double setting) override; uint64_t offset(void) const override; uint64_t mask(void) const override; void map_field(uint64_t *field, uint64_t *mask) override; private: const std::string m_name; const IMSR &m_msr_obj; const int m_domain_type; const int m_cpu_idx; const int m_control_idx; uint64_t *m_field_ptr; uint64_t *m_mask_ptr; bool m_is_field_mapped; }; } #endif
48.217631
118
0.560247
alawibaba
2811723e7793cb9ff266154c029a1849b4db5e26
10,993
cpp
C++
cpu/cpumd/Host.cpp
vakuras/moleculardynamics
f9c6b03db7df8e429f72fa17b5ccfd98d08ee272
[ "MIT" ]
null
null
null
cpu/cpumd/Host.cpp
vakuras/moleculardynamics
f9c6b03db7df8e429f72fa17b5ccfd98d08ee272
[ "MIT" ]
null
null
null
cpu/cpumd/Host.cpp
vakuras/moleculardynamics
f9c6b03db7df8e429f72fa17b5ccfd98d08ee272
[ "MIT" ]
null
null
null
/// /// CPU Host /// /// Molecular Dynamics Simulation on GPU /// /// Written by Vadim Kuras. 2009-2010. /// #include "Host.h" /// /// Simulation main host function /// int hostMain(configuration * config) { real4 * posArray; //positions real3 * velocityArray; //velocity real3 * forceArray; //force real3 * aAccArray; //acceleration real3 * bAccArray; //b-acceleration real3 * cAccArray; //c-acceleration int * ljList = NULL; //lennard jones list pointer int * mbList = NULL; //many body list pointer listSettings lj; //lennard jones list settings listSettings mb; //many body list settings real highestVelocity; //heighest velocity int timesteps; //timestep counter int ljNextBuild; //on which timestep to call the build of the lennard jones list int mbNextBuild; //on which timestep to call the build of the many body list real boxSize=pow((config->LennardJonesParticles + config->ManyBodyParticles),1.0/3.0)*52.8; //box size real boxSizeList; //box size for the neighbor lists int buckets; //bucket count for the neighbor list vector<results> resultVec; //results vector vector<float*> posVec; //position vector for animation vector<float*> velVec; //velocity vector for animation //time-measure events DWORD start, stop, elapsed; //allocate memory for data on host TC(posArray = new real4[(config->LennardJonesParticles + config->ManyBodyParticles)]); TC(velocityArray = new real3[(config->LennardJonesParticles + config->ManyBodyParticles)]); TC(aAccArray = new real3[(config->LennardJonesParticles + config->ManyBodyParticles)]); TC(forceArray = new real3[(config->LennardJonesParticles + config->ManyBodyParticles)]); TC(bAccArray = new real3[(config->LennardJonesParticles + config->ManyBodyParticles)]); TC(cAccArray = new real3[(config->LennardJonesParticles + config->ManyBodyParticles)]); //number of buckets for list hashs buckets = (config->LennardJonesParticles + config->ManyBodyParticles) * 3; lj.nlargestsize = mb.nlargestsize = 0; if (config->useLennardJones) //set lennard jones list settings { lj.maxnlmove = ((config->LennardJonesRS) - (config->LennardJonesRCUT)) * 0.5f; lj.maxnlmovesq = pow(lj.maxnlmove, 2); lj.rcutsq = pow(config->LennardJonesRCUT,2); lj.rcut = config->LennardJonesRCUT; lj.rs = config->LennardJonesRS; } if (config->useManyBody) //set many body list settings { mb.maxnlmove = ((config->ManyBodyRS) - (config->ManyBodyRCUT)) * 0.5f; mb.maxnlmovesq = pow(mb.maxnlmove, 2); mb.rcutsq = pow(config->ManyBodyRCUT,2); mb.rcut = config->ManyBodyRCUT; mb.rs = config->ManyBodyRS; } config->energyLoss = sqrt(config->energyLoss); //fix energy loss for(float vxcm=config->vxcmFrom; vxcm<=config->vxcmTo; vxcm+=config->vxcmStep) { //init timesteps = 0; ljNextBuild = mbNextBuild = 0; //information int printout = config->OutputTimesteps; //next debug output time step int animts = config->animts; //next animation save time step //set the allocated memory to 0 memset(aAccArray,0, sizeof(real3)*(config->LennardJonesParticles + config->ManyBodyParticles)); memset(bAccArray,0, sizeof(real3)*(config->LennardJonesParticles + config->ManyBodyParticles)); memset(cAccArray,0, sizeof(real3)*(config->LennardJonesParticles + config->ManyBodyParticles)); //read input file readInput(config, (real*) posArray, (real*) velocityArray); //push the particles outside the box into the box & vxcm for (int id=0; id< (config->LennardJonesParticles + config->ManyBodyParticles); id++) { if (fabs(posArray[id].x) > (boxSize/2)) posArray[id].x = (boxSize/2) * (posArray[id].x/fabs(posArray[id].x)); if (fabs(posArray[id].y) > (boxSize/2)) posArray[id].y = (boxSize/2) * (posArray[id].y/fabs(posArray[id].y)); if (fabs(posArray[id].z) > (boxSize/2)) posArray[id].z = (boxSize/2) * (posArray[id].z/fabs(posArray[id].z)); velocityArray[id].x += vxcm; } //before sim output cout << fixed << setprecision(6); //set maximal precision for output cout.setf(ios::fixed,ios::floatfield); //zero padding cout << "Before Simulation [VXCM = " << vxcm << "]:" << endl; //calculate highest velocity and boxSizeList readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList); if (config->useLennardJones) //build lennard jones list buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, 0, &ljList, config->DT); if (config->useManyBody) //build many body list buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, 0, &mbList, config->DT); //perform the output function performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, timesteps, config->DT, true); cout << endl; if (config->animts>-1) pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles)); //measure & perform start = GetTickCount(); if (config->useLennardJones) //calculate force for lennard jones lennardJonesForces(posArray, forceArray, (config->LennardJonesParticles + config->ManyBodyParticles), lj.nlargestsize, lj.nlistsize, ljList, lj.rcutsq); if (config->useManyBody) //calculate force for many body manyBodyForces(posArray, forceArray, config->ManyBodyParticles, mb.nlargestsize, mb.nlistsize, mbList, mb.rcutsq, config->useLennardJones); //calculate the accelerations after the force calculateAccelerations(posArray, aAccArray, forceArray, (config->LennardJonesParticles + config->ManyBodyParticles)); //while not reached the timestep goal while(timesteps<config->Timesteps) { if (ljNextBuild == timesteps || mbNextBuild == timesteps) //is is time to build any of the lists? { readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList); if (config->useLennardJones && ljNextBuild == timesteps) buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, timesteps, &ljList, config->DT); if (config->useManyBody && mbNextBuild == timesteps) buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, timesteps, &mbList, config->DT); } //predict predict(posArray, velocityArray, aAccArray, bAccArray, cAccArray, config->DT, (config->LennardJonesParticles + config->ManyBodyParticles)); if (config->useLennardJones) //force lj lennardJonesForces(posArray, forceArray, (config->LennardJonesParticles + config->ManyBodyParticles), lj.nlargestsize, lj.nlistsize, ljList, lj.rcutsq); if (config->useManyBody) //force mb manyBodyForces(posArray, forceArray, config->ManyBodyParticles, mb.nlargestsize, mb.nlistsize, mbList, mb.rcutsq, config->useLennardJones); bool flag = false; //correct correct(posArray, velocityArray, forceArray, aAccArray, bAccArray, cAccArray, config->DT, (config->LennardJonesParticles + config->ManyBodyParticles), boxSize, flag, config->energyLoss); if (flag) { if (config->useLennardJones) //force lj lennardJonesForces(posArray, forceArray, (config->LennardJonesParticles + config->ManyBodyParticles), lj.nlargestsize, lj.nlistsize, ljList, lj.rcutsq); if (config->useManyBody) //force mb manyBodyForces(posArray, forceArray, config->ManyBodyParticles, mb.nlargestsize, mb.nlistsize, mbList, mb.rcutsq, config->useLennardJones); //calculate the accelerations after the force calculateAccelerations(posArray, aAccArray, forceArray, (config->LennardJonesParticles + config->ManyBodyParticles)); } //results if (printout==timesteps) { performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, timesteps, config->DT, config->Debug); printout += config->OutputTimesteps; } //animation if (animts==timesteps) { pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles)); animts += config->animts; } timesteps++; } //stop measuring stop = GetTickCount(); //calculate the time took to simulate elapsed = stop - start; //after sim output cout << "\nAfter Simulation [VXCM = " << vxcm << "]:" << endl; performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, timesteps, config->DT, true); cout << "\nTime took: " << elapsed << "ms" << endl << endl; //write the output writeOutput(config, (real*) posArray, (real*) velocityArray); writeResults(resultVec, config, (float)elapsed, tailResults(posArray, config->ManyBodyParticles), vxcm); if (config->animts > -1) writeAnimationBinaryData(posVec, velVec, config, vxcm); flushVectors(resultVec, posVec, velVec); } //free memory delete [] posArray; delete [] velocityArray; delete [] aAccArray; delete [] forceArray; delete [] bAccArray; delete [] cAccArray; //release lists memory if (ljList) { delete [] ljList; ljList = NULL; } if (mbList) { delete [] mbList; mbList = NULL; } return EXIT_SUCCESS; } /// /// Get Highest Velocity & Box Size /// void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, real & highestVelocity, real & boxSize) { highestVelocity = 0; boxSize = 0; for(int i=0; i<NumberOfParticles; i++) { //calculate highest velocity real velocity = sqrt(velocityArray[i].x * velocityArray[i].x + velocityArray[i].y * velocityArray[i].y + velocityArray[i].z * velocityArray[i].z); if (velocity>highestVelocity) highestVelocity = velocity; //boxsize = (the particle that is far the most from 0,0,0) * 2 if (boxSize<abs(posArray[i].x)) boxSize = abs(posArray[i].x); if (boxSize<abs(posArray[i].y)) boxSize = abs(posArray[i].y); if (boxSize<abs(posArray[i].z)) boxSize = abs(posArray[i].z); } boxSize*=2; //final box size } /// /// Build Neighbor List /// void buildList(real4 * posArray, listSettings * listsettings, real boxSize, int buckets, real highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, real dt) { //free memory if needed if (*list) { delete [] *list; *list = NULL; } //build list *list = buildNeighborList(posArray, listsettings, boxSize, buckets, NumberOfParticles); //calculte next build time step nextBuild = (int) ((listsettings->maxnlmove / highestVelocity) / fabs(dt)); nextBuild += currentTimestep; }
37.776632
194
0.699627
vakuras
28157783daa7a0c6c273850c3d0aa94aa1007ab8
19,813
cpp
C++
llvm-5.0.1.src/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
60
2017-12-21T06:49:58.000Z
2022-02-24T09:43:52.000Z
llvm-5.0.1.src/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
null
null
null
llvm-5.0.1.src/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
17
2017-12-20T09:54:56.000Z
2021-06-24T05:39:36.000Z
//===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Correlated Value Propagation pass. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/LazyValueInfo.h" #include "llvm/IR/CFG.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" using namespace llvm; #define DEBUG_TYPE "correlated-value-propagation" STATISTIC(NumPhis, "Number of phis propagated"); STATISTIC(NumSelects, "Number of selects propagated"); STATISTIC(NumMemAccess, "Number of memory access targets propagated"); STATISTIC(NumCmps, "Number of comparisons propagated"); STATISTIC(NumReturns, "Number of return values propagated"); STATISTIC(NumDeadCases, "Number of switch cases removed"); STATISTIC(NumSDivs, "Number of sdiv converted to udiv"); STATISTIC(NumAShrs, "Number of ashr converted to lshr"); STATISTIC(NumSRems, "Number of srem converted to urem"); static cl::opt<bool> DontProcessAdds("cvp-dont-process-adds", cl::init(true)); namespace { class CorrelatedValuePropagation : public FunctionPass { public: static char ID; CorrelatedValuePropagation(): FunctionPass(ID) { initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function &F) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LazyValueInfoWrapperPass>(); AU.addPreserved<GlobalsAAWrapperPass>(); } }; } char CorrelatedValuePropagation::ID = 0; INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation", "Value Propagation", false, false) INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation", "Value Propagation", false, false) // Public interface to the Value Propagation pass Pass *llvm::createCorrelatedValuePropagationPass() { return new CorrelatedValuePropagation(); } static bool processSelect(SelectInst *S, LazyValueInfo *LVI) { if (S->getType()->isVectorTy()) return false; if (isa<Constant>(S->getOperand(0))) return false; Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S); if (!C) return false; ConstantInt *CI = dyn_cast<ConstantInt>(C); if (!CI) return false; Value *ReplaceWith = S->getOperand(1); Value *Other = S->getOperand(2); if (!CI->isOne()) std::swap(ReplaceWith, Other); if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType()); S->replaceAllUsesWith(ReplaceWith); S->eraseFromParent(); ++NumSelects; return true; } static bool processPHI(PHINode *P, LazyValueInfo *LVI, const SimplifyQuery &SQ) { bool Changed = false; BasicBlock *BB = P->getParent(); for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { Value *Incoming = P->getIncomingValue(i); if (isa<Constant>(Incoming)) continue; Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P); // Look if the incoming value is a select with a scalar condition for which // LVI can tells us the value. In that case replace the incoming value with // the appropriate value of the select. This often allows us to remove the // select later. if (!V) { SelectInst *SI = dyn_cast<SelectInst>(Incoming); if (!SI) continue; Value *Condition = SI->getCondition(); if (!Condition->getType()->isVectorTy()) { if (Constant *C = LVI->getConstantOnEdge( Condition, P->getIncomingBlock(i), BB, P)) { if (C->isOneValue()) { V = SI->getTrueValue(); } else if (C->isZeroValue()) { V = SI->getFalseValue(); } // Once LVI learns to handle vector types, we could also add support // for vector type constants that are not all zeroes or all ones. } } // Look if the select has a constant but LVI tells us that the incoming // value can never be that constant. In that case replace the incoming // value with the other value of the select. This often allows us to // remove the select later. if (!V) { Constant *C = dyn_cast<Constant>(SI->getFalseValue()); if (!C) continue; if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, P->getIncomingBlock(i), BB, P) != LazyValueInfo::False) continue; V = SI->getTrueValue(); } DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n'); } P->setIncomingValue(i, V); Changed = true; } if (Value *V = SimplifyInstruction(P, SQ)) { P->replaceAllUsesWith(V); P->eraseFromParent(); Changed = true; } if (Changed) ++NumPhis; return Changed; } static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) { Value *Pointer = nullptr; if (LoadInst *L = dyn_cast<LoadInst>(I)) Pointer = L->getPointerOperand(); else Pointer = cast<StoreInst>(I)->getPointerOperand(); if (isa<Constant>(Pointer)) return false; Constant *C = LVI->getConstant(Pointer, I->getParent(), I); if (!C) return false; ++NumMemAccess; I->replaceUsesOfWith(Pointer, C); return true; } /// See if LazyValueInfo's ability to exploit edge conditions or range /// information is sufficient to prove this comparison. Even for local /// conditions, this can sometimes prove conditions instcombine can't by /// exploiting range information. static bool processCmp(CmpInst *C, LazyValueInfo *LVI) { Value *Op0 = C->getOperand(0); Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); if (!Op1) return false; // As a policy choice, we choose not to waste compile time on anything where // the comparison is testing local values. While LVI can sometimes reason // about such cases, it's not its primary purpose. We do make sure to do // the block local query for uses from terminator instructions, but that's // handled in the code for each terminator. auto *I = dyn_cast<Instruction>(Op0); if (I && I->getParent() == C->getParent()) return false; LazyValueInfo::Tristate Result = LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C); if (Result == LazyValueInfo::Unknown) return false; ++NumCmps; if (Result == LazyValueInfo::True) C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); else C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); C->eraseFromParent(); return true; } /// Simplify a switch instruction by removing cases which can never fire. If the /// uselessness of a case could be determined locally then constant propagation /// would already have figured it out. Instead, walk the predecessors and /// statically evaluate cases based on information available on that edge. Cases /// that cannot fire no matter what the incoming edge can safely be removed. If /// a case fires on every incoming edge then the entire switch can be removed /// and replaced with a branch to the case destination. static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) { Value *Cond = SI->getCondition(); BasicBlock *BB = SI->getParent(); // If the condition was defined in same block as the switch then LazyValueInfo // currently won't say anything useful about it, though in theory it could. if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB) return false; // If the switch is unreachable then trying to improve it is a waste of time. pred_iterator PB = pred_begin(BB), PE = pred_end(BB); if (PB == PE) return false; // Analyse each switch case in turn. bool Changed = false; for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) { ConstantInt *Case = CI->getCaseValue(); // Check to see if the switch condition is equal to/not equal to the case // value on every incoming edge, equal/not equal being the same each time. LazyValueInfo::Tristate State = LazyValueInfo::Unknown; for (pred_iterator PI = PB; PI != PE; ++PI) { // Is the switch condition equal to the case value? LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ, Cond, Case, *PI, BB, SI); // Give up on this case if nothing is known. if (Value == LazyValueInfo::Unknown) { State = LazyValueInfo::Unknown; break; } // If this was the first edge to be visited, record that all other edges // need to give the same result. if (PI == PB) { State = Value; continue; } // If this case is known to fire for some edges and known not to fire for // others then there is nothing we can do - give up. if (Value != State) { State = LazyValueInfo::Unknown; break; } } if (State == LazyValueInfo::False) { // This case never fires - remove it. CI->getCaseSuccessor()->removePredecessor(BB); CI = SI->removeCase(CI); CE = SI->case_end(); // The condition can be modified by removePredecessor's PHI simplification // logic. Cond = SI->getCondition(); ++NumDeadCases; Changed = true; continue; } if (State == LazyValueInfo::True) { // This case always fires. Arrange for the switch to be turned into an // unconditional branch by replacing the switch condition with the case // value. SI->setCondition(Case); NumDeadCases += SI->getNumCases(); Changed = true; break; } // Increment the case iterator since we didn't delete it. ++CI; } if (Changed) // If the switch has been simplified to the point where it can be replaced // by a branch then do so now. ConstantFoldTerminator(BB); return Changed; } /// Infer nonnull attributes for the arguments at the specified callsite. static bool processCallSite(CallSite CS, LazyValueInfo *LVI) { SmallVector<unsigned, 4> ArgNos; unsigned ArgNo = 0; for (Value *V : CS.args()) { PointerType *Type = dyn_cast<PointerType>(V->getType()); // Try to mark pointer typed parameters as non-null. We skip the // relatively expensive analysis for constants which are obviously either // null or non-null to start with. if (Type && !CS.paramHasAttr(ArgNo, Attribute::NonNull) && !isa<Constant>(V) && LVI->getPredicateAt(ICmpInst::ICMP_EQ, V, ConstantPointerNull::get(Type), CS.getInstruction()) == LazyValueInfo::False) ArgNos.push_back(ArgNo); ArgNo++; } assert(ArgNo == CS.arg_size() && "sanity check"); if (ArgNos.empty()) return false; AttributeList AS = CS.getAttributes(); LLVMContext &Ctx = CS.getInstruction()->getContext(); AS = AS.addParamAttribute(Ctx, ArgNos, Attribute::get(Ctx, Attribute::NonNull)); CS.setAttributes(AS); return true; } // Helper function to rewrite srem and sdiv. As a policy choice, we choose not // to waste compile time on anything where the operands are local defs. While // LVI can sometimes reason about such cases, it's not its primary purpose. static bool hasLocalDefs(BinaryOperator *SDI) { for (Value *O : SDI->operands()) { auto *I = dyn_cast<Instruction>(O); if (I && I->getParent() == SDI->getParent()) return true; } return false; } static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) { Constant *Zero = ConstantInt::get(SDI->getType(), 0); for (Value *O : SDI->operands()) { auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI); if (Result != LazyValueInfo::True) return false; } return true; } static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) { if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) || !hasPositiveOperands(SDI, LVI)) return false; ++NumSRems; auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1), SDI->getName(), SDI); SDI->replaceAllUsesWith(BO); SDI->eraseFromParent(); return true; } /// See if LazyValueInfo's ability to exploit edge conditions or range /// information is sufficient to prove the both operands of this SDiv are /// positive. If this is the case, replace the SDiv with a UDiv. Even for local /// conditions, this can sometimes prove conditions instcombine can't by /// exploiting range information. static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) { if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) || !hasPositiveOperands(SDI, LVI)) return false; ++NumSDivs; auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1), SDI->getName(), SDI); BO->setIsExact(SDI->isExact()); SDI->replaceAllUsesWith(BO); SDI->eraseFromParent(); return true; } static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) { if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI)) return false; Constant *Zero = ConstantInt::get(SDI->getType(), 0); if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) != LazyValueInfo::True) return false; ++NumAShrs; auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1), SDI->getName(), SDI); BO->setIsExact(SDI->isExact()); SDI->replaceAllUsesWith(BO); SDI->eraseFromParent(); return true; } static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) { typedef OverflowingBinaryOperator OBO; if (DontProcessAdds) return false; if (AddOp->getType()->isVectorTy() || hasLocalDefs(AddOp)) return false; bool NSW = AddOp->hasNoSignedWrap(); bool NUW = AddOp->hasNoUnsignedWrap(); if (NSW && NUW) return false; BasicBlock *BB = AddOp->getParent(); Value *LHS = AddOp->getOperand(0); Value *RHS = AddOp->getOperand(1); ConstantRange LRange = LVI->getConstantRange(LHS, BB, AddOp); // Initialize RRange only if we need it. If we know that guaranteed no wrap // range for the given LHS range is empty don't spend time calculating the // range for the RHS. Optional<ConstantRange> RRange; auto LazyRRange = [&] () { if (!RRange) RRange = LVI->getConstantRange(RHS, BB, AddOp); return RRange.getValue(); }; bool Changed = false; if (!NUW) { ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion( BinaryOperator::Add, LRange, OBO::NoUnsignedWrap); if (!NUWRange.isEmptySet()) { bool NewNUW = NUWRange.contains(LazyRRange()); AddOp->setHasNoUnsignedWrap(NewNUW); Changed |= NewNUW; } } if (!NSW) { ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion( BinaryOperator::Add, LRange, OBO::NoSignedWrap); if (!NSWRange.isEmptySet()) { bool NewNSW = NSWRange.contains(LazyRRange()); AddOp->setHasNoSignedWrap(NewNSW); Changed |= NewNSW; } } return Changed; } static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) { if (Constant *C = LVI->getConstant(V, At->getParent(), At)) return C; // TODO: The following really should be sunk inside LVI's core algorithm, or // at least the outer shims around such. auto *C = dyn_cast<CmpInst>(V); if (!C) return nullptr; Value *Op0 = C->getOperand(0); Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); if (!Op1) return nullptr; LazyValueInfo::Tristate Result = LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At); if (Result == LazyValueInfo::Unknown) return nullptr; return (Result == LazyValueInfo::True) ? ConstantInt::getTrue(C->getContext()) : ConstantInt::getFalse(C->getContext()); } static bool runImpl(Function &F, LazyValueInfo *LVI, const SimplifyQuery &SQ) { bool FnChanged = false; // Visiting in a pre-order depth-first traversal causes us to simplify early // blocks before querying later blocks (which require us to analyze early // blocks). Eagerly simplifying shallow blocks means there is strictly less // work to do for deep blocks. This also means we don't visit unreachable // blocks. for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { bool BBChanged = false; for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { Instruction *II = &*BI++; switch (II->getOpcode()) { case Instruction::Select: BBChanged |= processSelect(cast<SelectInst>(II), LVI); break; case Instruction::PHI: BBChanged |= processPHI(cast<PHINode>(II), LVI, SQ); break; case Instruction::ICmp: case Instruction::FCmp: BBChanged |= processCmp(cast<CmpInst>(II), LVI); break; case Instruction::Load: case Instruction::Store: BBChanged |= processMemAccess(II, LVI); break; case Instruction::Call: case Instruction::Invoke: BBChanged |= processCallSite(CallSite(II), LVI); break; case Instruction::SRem: BBChanged |= processSRem(cast<BinaryOperator>(II), LVI); break; case Instruction::SDiv: BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI); break; case Instruction::AShr: BBChanged |= processAShr(cast<BinaryOperator>(II), LVI); break; case Instruction::Add: BBChanged |= processAdd(cast<BinaryOperator>(II), LVI); break; } } Instruction *Term = BB->getTerminator(); switch (Term->getOpcode()) { case Instruction::Switch: BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI); break; case Instruction::Ret: { auto *RI = cast<ReturnInst>(Term); // Try to determine the return value if we can. This is mainly here to // simplify the writing of unit tests, but also helps to enable IPO by // constant folding the return values of callees. auto *RetVal = RI->getReturnValue(); if (!RetVal) break; // handle "ret void" if (isa<Constant>(RetVal)) break; // nothing to do if (auto *C = getConstantAt(RetVal, RI, LVI)) { ++NumReturns; RI->replaceUsesOfWith(RetVal, C); BBChanged = true; } } } FnChanged |= BBChanged; } return FnChanged; } bool CorrelatedValuePropagation::runOnFunction(Function &F) { if (skipFunction(F)) return false; LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); return runImpl(F, LVI, getBestSimplifyQuery(*this, F)); } PreservedAnalyses CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) { LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F); bool Changed = runImpl(F, LVI, getBestSimplifyQuery(AM, F)); if (!Changed) return PreservedAnalyses::all(); PreservedAnalyses PA; PA.preserve<GlobalsAA>(); return PA; }
34.101549
80
0.655378
ShawnLess
281578d214212272e9583b050285d79efdcb44d1
932
hpp
C++
include/Exceptions/ENetInitializationFailedException.hpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
1
2021-04-28T20:32:57.000Z
2021-04-28T20:32:57.000Z
include/Exceptions/ENetInitializationFailedException.hpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
7
2021-08-24T14:09:33.000Z
2021-08-30T12:47:40.000Z
include/Exceptions/ENetInitializationFailedException.hpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
null
null
null
#pragma once #include <stdexcept> #include <string> /// <summary> /// Whack-A-Stoodent server namespace /// </summary> namespace WhackAStoodentServer { /// <summary> /// A class that describes an ENet intialization failed exception /// </summary> class ENetInitializationFailedException : public std::runtime_error { public: ENetInitializationFailedException() = delete; /// <summary> /// Constructs an ENet intialization failed exception /// </summary> /// <param name="errorCode">Error code</param> ENetInitializationFailedException(int errorCode); /// <summary> /// Destroys ENet intialization failed exception /// </summary> virtual ~ENetInitializationFailedException() override; /// <summary> /// Gets the error code /// </summary> /// <returns>Error code</returns> virtual int GetErrorCode() const; private: /// <summary> /// Error code /// </summary> int errorCode; }; }
20.711111
68
0.688841
BigETI
2818a93391e57c0d038fc2f263475b23a88b845e
2,174
cpp
C++
native/tests/seal/publickey.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
17
2019-12-02T09:26:24.000Z
2022-02-03T03:59:25.000Z
native/tests/seal/publickey.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
1
2020-09-14T06:19:36.000Z
2020-09-14T06:19:36.000Z
native/tests/seal/publickey.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
11
2019-12-02T22:02:39.000Z
2021-12-10T02:17:06.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "gtest/gtest.h" #include "seal/publickey.h" #include "seal/context.h" #include "seal/modulus.h" #include "seal/keygenerator.h" using namespace seal; using namespace std; namespace SEALTest { TEST(PublicKeyTest, SaveLoadPublicKey) { stringstream stream; { EncryptionParameters parms(scheme_type::BFV); parms.set_poly_modulus_degree(64); parms.set_plain_modulus(1 << 6); parms.set_coeff_modulus(CoeffModulus::Create(64, { 60 })); auto context = SEALContext::Create(parms, false, sec_level_type::none); KeyGenerator keygen(context); PublicKey pk = keygen.public_key(); ASSERT_TRUE(pk.parms_id() == context->key_parms_id()); pk.save(stream); PublicKey pk2; pk2.load(context, stream); ASSERT_EQ(pk.data().int_array().size(), pk2.data().int_array().size()); for (size_t i = 0; i < pk.data().int_array().size(); i++) { ASSERT_EQ(pk.data().data()[i], pk2.data().data()[i]); } ASSERT_TRUE(pk.parms_id() == pk2.parms_id()); } { EncryptionParameters parms(scheme_type::BFV); parms.set_poly_modulus_degree(256); parms.set_plain_modulus(1 << 20); parms.set_coeff_modulus(CoeffModulus::Create(256, { 30, 40 })); auto context = SEALContext::Create(parms, false, sec_level_type::none); KeyGenerator keygen(context); PublicKey pk = keygen.public_key(); ASSERT_TRUE(pk.parms_id() == context->key_parms_id()); pk.save(stream); PublicKey pk2; pk2.load(context, stream); ASSERT_EQ(pk.data().int_array().size(), pk2.data().int_array().size()); for (size_t i = 0; i < pk.data().int_array().size(); i++) { ASSERT_EQ(pk.data().data()[i], pk2.data().data()[i]); } ASSERT_TRUE(pk.parms_id() == pk2.parms_id()); } } }
32.939394
83
0.565317
nitrieu
2819bd8af889af9925282eb172478b2344c99fc0
1,587
cpp
C++
src/clientMain.cpp
kn0t3k/kyrys
142bcdd1bc34fe7b8d01e4666668f97c26aa297d
[ "MIT" ]
null
null
null
src/clientMain.cpp
kn0t3k/kyrys
142bcdd1bc34fe7b8d01e4666668f97c26aa297d
[ "MIT" ]
33
2017-03-07T13:45:52.000Z
2017-05-07T21:17:28.000Z
src/clientMain.cpp
kn0t3k/kyrys
142bcdd1bc34fe7b8d01e4666668f97c26aa297d
[ "MIT" ]
null
null
null
#include <reference.hpp> #include <client.hpp> int main(int argc, char **argv) { int portNo = Kyrys::Enums::Defaults::DefaultPortNumber::DEFAULT_PORT; QString hostName = "127.0.0.1"; QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Test helper"); parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({ { "h", QCoreApplication::translate("main", "set hostname."), QCoreApplication::translate("main", "server hostname") }, { "p", QCoreApplication::translate("main", "Server port"), QCoreApplication::translate("main", "port number") }, }); parser.process(a); if (parser.isSet("p")) { portNo = parser.value("p").toInt(); } QThread *clientThread = new QThread; Kyrys::Client *client = new Kyrys::Client(hostName, static_cast<quint16>(portNo)); client->moveToThread(clientThread); QObject::connect(clientThread, SIGNAL(finished()), client, SLOT(deleteLater())); QObject::connect(clientThread, SIGNAL(started()), client, SLOT(secureConnect())); QObject::connect(client, SIGNAL(clientFinished()), client, SLOT(deleteLater())); clientThread->start(); return a.exec(); }
33.765957
92
0.522369
kn0t3k
281b2e0e48a50ea7b4763b0c484571a2ddbcee59
268
cpp
C++
A - Team.cpp
lionrocker/codeforces-solutions
02703ff02dab98d30ef01e52b5a1acc1d8596862
[ "MIT" ]
null
null
null
A - Team.cpp
lionrocker/codeforces-solutions
02703ff02dab98d30ef01e52b5a1acc1d8596862
[ "MIT" ]
null
null
null
A - Team.cpp
lionrocker/codeforces-solutions
02703ff02dab98d30ef01e52b5a1acc1d8596862
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int n; cin >> n; int ans = 0; for (int i =0; i < n; i++) { int a, b, c; cin >> a >> b >> c; if (a + b + c >=2) ans++; } cout << ans << "\n"; }
13.4
33
0.350746
lionrocker
281c6a44165537c10a049045888d6932ecfb8e6e
717
cpp
C++
Programy/klasy/ios3/progr.cpp
efiku/ZadaniaCpp
8c316214f4f3add12eeec9bcd0cf74fe125c6c68
[ "MIT" ]
null
null
null
Programy/klasy/ios3/progr.cpp
efiku/ZadaniaCpp
8c316214f4f3add12eeec9bcd0cf74fe125c6c68
[ "MIT" ]
null
null
null
Programy/klasy/ios3/progr.cpp
efiku/ZadaniaCpp
8c316214f4f3add12eeec9bcd0cf74fe125c6c68
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////// // plik progr.cpp //// ////////////////////////////////////////////////////////////// #include <iostream> using namespace std; #include "osoba.h" // void prezentacja(osoba); // /*************************************************************/ int main() { osoba kompozytor, autor; // kompozytor.zapamietaj("Fryderyk Chopin", 36); autor.zapamietaj("Marcel Proust", 34); // wywołujemy funkcje, wysyłając obiekty prezentacja(kompozytor); // prezentacja(autor); system("pause"); // } /*************************************************************/
28.68
64
0.348675
efiku
281c8579ef5b36daec3662ae4b633bd1284ce69a
2,208
cpp
C++
tle.cpp
komasaru/iss_sgp4_teme
5474ab1acdc5076e12d90c1dcd2d259e36fbd18d
[ "MIT" ]
null
null
null
tle.cpp
komasaru/iss_sgp4_teme
5474ab1acdc5076e12d90c1dcd2d259e36fbd18d
[ "MIT" ]
null
null
null
tle.cpp
komasaru/iss_sgp4_teme
5474ab1acdc5076e12d90c1dcd2d259e36fbd18d
[ "MIT" ]
null
null
null
#include "tle.hpp" namespace iss_sgp4_teme { // 定数 static constexpr char kFTle[] = "tle.txt"; static constexpr unsigned int kSecDay = 86400; // Seconds in a day /* * @brief コンストラクタ * * @param[in] UT1 (timespec) */ Tle::Tle(struct timespec ut1) { this->ut1 = ut1; } /* * @brief TLE 読み込み * * @param <none> * @return TLE(2行) (vector<string>) */ std::vector<std::string> Tle::get_tle() { std::string f(kFTle); // ファイル名 std::vector<std::string> data; // TLE 一覧(全データ) struct tm t; // 時刻構造体 std::string buf; // 1行分バッファ std::vector<std::string> tle_p(2); // TLE(退避用) unsigned int y; // year double d; // day struct timespec utc; // UTC unsigned int i; // loop index std::vector<std::string> tle(2, ""); // TLE try { // ファイル OPEN std::ifstream ifs(f); if (!ifs) throw; // 読み込み失敗 // ファイル READ(一旦、全て読み込む) while (getline(ifs, buf)) { std::istringstream iss(buf); // 文字列ストリーム if (buf[0] != '1' && buf[0] != '2') { continue; } data.push_back(buf); } // 最新 TLE 検索 for (auto l: data) { if (l[0] == '1') { y = 2000 + stoi(l.substr(18, 2)); d = stod(l.substr(20, 12)); // y 年の 01-01 00:00:00 std::stringstream ss; ss << std::setfill('0') << std::setw(4) << y << std::setw(2) << 1 << std::setw(2) << 1 << std::setw(2) << 0 << std::setw(2) << 0 << std::setw(2) << 0; std::istringstream is(ss.str()); is >> std::get_time(&t, "%Y%m%d%H%M%S"); utc.tv_sec = mktime(&t); utc.tv_nsec = 0; // utc = y 年の 01-01 00:00:00 に経過日数 d を加算した日時 utc = ts_add(utc, d * kSecDay); if (utc.tv_sec > ut1.tv_sec) { tle = tle_p; break; } } tle_p[stoi(l.substr(0, 1)) - 1] = l; } // 上記の処理で該当レコードが得られなかった場合は、最初の2行 if (tle[0] == "") { for (i = 0; i < 2; ++i) { tle[i] = data[i]; } } } catch (...) { throw; } return tle; } } // namespace iss_sgp4_teme
24.808989
69
0.462409
komasaru
281c9fe418e1c4833bb87f82f74f1cc4d722d57c
2,544
cpp
C++
webkit/WebCore/html/FormDataList.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/html/FormDataList.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/html/FormDataList.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "FormDataList.h" namespace WebCore { FormDataList::FormDataList(const TextEncoding& c) : m_encoding(c) { } void FormDataList::appendString(const CString& s) { m_list.append(s); } // Change plain CR and plain LF to CRLF pairs. static CString fixLineBreaks(const CString& s) { // Compute the length. unsigned newLen = 0; const char* p = s.data(); while (char c = *p++) { if (c == '\r') { // Safe to look ahead because of trailing '\0'. if (*p != '\n') { // Turn CR into CRLF. newLen += 2; } } else if (c == '\n') { // Turn LF into CRLF. newLen += 2; } else { // Leave other characters alone. newLen += 1; } } if (newLen == s.length()) { return s; } // Make a copy of the string. p = s.data(); char* q; CString result = CString::newUninitialized(newLen, q); while (char c = *p++) { if (c == '\r') { // Safe to look ahead because of trailing '\0'. if (*p != '\n') { // Turn CR into CRLF. *q++ = '\r'; *q++ = '\n'; } } else if (c == '\n') { // Turn LF into CRLF. *q++ = '\r'; *q++ = '\n'; } else { // Leave other characters alone. *q++ = c; } } return result; } void FormDataList::appendString(const String& s) { CString cstr = fixLineBreaks(m_encoding.encode(s.characters(), s.length(), EntitiesForUnencodables)); m_list.append(cstr); } } // namespace
27.652174
105
0.560535
s1rcheese
281d1fd480485b0cadb7c95f1d6d1b72d1dcad4b
6,555
cc
C++
src/algorithms/base_algorithm.cc
edoardopalli/bayesmix
2253d97b58e9d5fe9bd769944ae46cab0d938819
[ "BSD-3-Clause" ]
null
null
null
src/algorithms/base_algorithm.cc
edoardopalli/bayesmix
2253d97b58e9d5fe9bd769944ae46cab0d938819
[ "BSD-3-Clause" ]
null
null
null
src/algorithms/base_algorithm.cc
edoardopalli/bayesmix
2253d97b58e9d5fe9bd769944ae46cab0d938819
[ "BSD-3-Clause" ]
null
null
null
#include "base_algorithm.h" #include <Eigen/Dense> #include <memory> #include <vector> #include "algorithm_params.pb.h" #include "algorithm_state.pb.h" #include "lib/progressbar/progressbar.h" #include "mixing_state.pb.h" #include "src/algorithms/neal8_algorithm.h" #include "src/collectors/base_collector.h" #include "src/utils/eigen_utils.h" #include "src/utils/rng.h" Eigen::MatrixXd BaseAlgorithm::eval_lpdf( BaseCollector *const collector, const Eigen::MatrixXd &grid, const Eigen::RowVectorXd &hier_covariate /*= Eigen::RowVectorXd(0)*/, const Eigen::RowVectorXd &mix_covariate /*= Eigen::RowVectorXd(0)*/) { std::deque<Eigen::VectorXd> lpdf; bool keep = true; progresscpp::ProgressBar *bar = nullptr; if (verbose) { bar = new progresscpp::ProgressBar(collector->get_size(), 60); } while (keep) { keep = update_state_from_collector(collector); if (!keep) { break; } lpdf.push_back(lpdf_from_state(grid, hier_covariate, mix_covariate)); if (verbose) { ++(*bar); bar->display(); } } collector->reset(); if (verbose) { bar->done(); delete bar; print_ending_message(); } return bayesmix::stack_vectors(lpdf); } void BaseAlgorithm::read_params_from_proto( const bayesmix::AlgorithmParams &params) { // Generic parameters maxiter = params.iterations(); burnin = params.burnin(); init_num_clusters = params.init_num_clusters(); auto &rng = bayesmix::Rng::Instance().get(); rng.seed(params.rng_seed()); } void BaseAlgorithm::initialize() { if (verbose) { std::cout << "Initializing... " << std::flush; } // Perform checks if (data.rows() == 0) { throw std::invalid_argument("Data was not provided to algorithm"); } // Hierarchy checks if (unique_values.size() == 0) { throw std::invalid_argument("Hierarchy was not provided to algorithm"); } if (unique_values[0]->is_conjugate() == false and requires_conjugate_hierarchy()) { std::string msg = "Algorithm \"" + bayesmix::AlgorithmId_Name(get_id()) + "\" only supports conjugate hierarchies"; throw std::invalid_argument(msg); } if (unique_values[0]->is_multivariate() == false && data.cols() > 1) { throw std::invalid_argument( "Multivariate data supplied to univariate hierarchy"); } if (hier_covariates.rows() != 0) { if (unique_values[0]->is_dependent() == false) { throw std::invalid_argument( "Covariates supplied to non-dependent hierarchy"); } if (data.rows() != hier_covariates.rows()) { throw std::invalid_argument( "Sizes of data and hierarchy covariates do not match"); } } else { // Create empty covariates vector hier_covariates = Eigen::MatrixXd::Zero(data.rows(), 0); } // Mixing checks if (mixing == nullptr) { throw std::invalid_argument("Mixing was not provided to algorithm"); } if (this->is_conditional() != mixing->is_conditional()) { throw std::invalid_argument( "Algorithm and mixing must be either both " "marginal or both conditional"); } if (mix_covariates.rows() != 0) { if (mixing->is_dependent() == false) { throw std::invalid_argument( "Covariates supplied to non-dependent mixing"); } if (data.rows() != mix_covariates.rows()) { throw std::invalid_argument( "Sizes of data and mixing covariates do not match"); } } else { // Create empty covariates vector mix_covariates = Eigen::MatrixXd::Zero(data.rows(), 0); } mixing->set_covariates(&mix_covariates); // Initialize mixing mixing->set_num_components(init_num_clusters); mixing->initialize(); // Interpet default number of clusters if (mixing->get_num_components() == 0) { mixing->set_num_components(data.rows()); } // Initialize hierarchies unique_values[0]->initialize(); unsigned int num_components = mixing->get_num_components(); for (size_t i = 0; i < num_components - 1; i++) { unique_values.push_back(unique_values[0]->clone()); unique_values[i]->sample_prior(); } // Build uniform probability on clusters, given their initial number std::default_random_engine generator; std::uniform_int_distribution<int> distro(0, num_components - 1); // Allocate one datum per cluster first, and update cardinalities allocations.clear(); for (size_t i = 0; i < num_components; i++) { allocations.push_back(i); unique_values[i]->add_datum(i, data.row(i), update_hierarchy_params(), hier_covariates.row(i)); } // Randomly allocate all remaining data, and update cardinalities for (size_t i = num_components; i < data.rows(); i++) { unsigned int clust = distro(generator); allocations.push_back(clust); unique_values[clust]->add_datum(i, data.row(i), update_hierarchy_params(), hier_covariates.row(i)); } if (verbose) { std::cout << "Done" << std::endl; } } void BaseAlgorithm::update_hierarchy_hypers() { bayesmix::AlgorithmState::ClusterState clust; std::vector<bayesmix::AlgorithmState::ClusterState> states; // Build vector of states associated to non-empty clusters for (auto &un : unique_values) { if (un->get_card() > 0) { un->write_state_to_proto(&clust); states.push_back(clust); } } unique_values[0]->update_hypers(states); } bayesmix::AlgorithmState BaseAlgorithm::get_state_as_proto(unsigned int iter) { bayesmix::AlgorithmState iter_out; // Transcribe iteration number, allocations, and cardinalities iter_out.set_iteration_num(iter); *iter_out.mutable_cluster_allocs() = {allocations.begin(), allocations.end()}; // Transcribe unique values vector for (size_t i = 0; i < unique_values.size(); i++) { bayesmix::AlgorithmState::ClusterState clusval; unique_values[i]->write_state_to_proto(&clusval); iter_out.add_cluster_states()->CopyFrom(clusval); } // Transcribe the hyperparameters of the hyerarchy bayesmix::AlgorithmState::HierarchyHypers hyper_state; unique_values[0]->write_hypers_to_proto(&hyper_state); iter_out.mutable_hierarchy_hypers()->CopyFrom(hyper_state); // Transcribe mixing state bayesmix::MixingState mixstate; mixing->write_state_to_proto(&mixstate); iter_out.mutable_mixing_state()->CopyFrom(mixstate); return iter_out; } bool BaseAlgorithm::update_state_from_collector(BaseCollector *coll) { bool success = coll->get_next_state(&curr_state); return success; }
33.443878
79
0.679481
edoardopalli
28203e55a6bbf2f7aed045f150f6f63a22945172
8,124
cpp
C++
Source/Urho3D/Resource/PListFile.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
Source/Urho3D/Resource/PListFile.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
1
2021-04-17T22:38:25.000Z
2021-04-18T00:43:15.000Z
Source/Urho3D/Resource/PListFile.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2021 the Urho3D project // Copyright (c) 2021 проект Dviglo // Лицензия: MIT #include "../Precompiled.h" #include "../Core/Context.h" #include "../IO/Deserializer.h" #include "../IO/Log.h" #include "../Resource/PListFile.h" #include "../Resource/XMLFile.h" #include <cstdio> #include "../DebugNew.h" namespace Dviglo { static PListValue EMPTY_VALUE; static PListValueMap EMPTY_VALUEMAP; static PListValueVector EMPTY_VALUEVECTOR; PListValue::PListValue() : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { } PListValue::PListValue(int value) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetInt(value); } PListValue::PListValue(bool value) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetBool(value); } PListValue::PListValue(float value) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetFloat(value); } PListValue::PListValue(const String& value) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetString(value); } PListValue::PListValue(PListValueMap& valueMap) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetValueMap(valueMap); } PListValue::PListValue(PListValueVector& valueVector) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { SetValueVector(valueVector); } PListValue::PListValue(const PListValue& value) : // NOLINT(hicpp-member-init) type_(PLVT_NONE) { *this = value; } PListValue::~PListValue() { Reset(); } PListValue& PListValue::operator =(const PListValue& rhs) { switch (rhs.type_) { case PLVT_NONE: Reset(); break; case PLVT_INT: SetInt(rhs.int_); break; case PLVT_BOOL: SetBool(rhs.bool_); break; case PLVT_FLOAT: SetFloat(rhs.float_); break; case PLVT_STRING: SetString(*rhs.string_); break; case PLVT_VALUEMAP: SetValueMap(*rhs.valueMap_); break; case PLVT_VALUEVECTOR: SetValueVector(*rhs.valueVector_); break; } return *this; } void PListValue::SetInt(int value) { if (type_ != PLVT_INT) { Reset(); type_ = PLVT_INT; } int_ = value; } void PListValue::SetBool(bool value) { if (type_ != PLVT_BOOL) { Reset(); type_ = PLVT_BOOL; } bool_ = value; } void PListValue::SetFloat(float value) { if (type_ != PLVT_FLOAT) { Reset(); type_ = PLVT_FLOAT; } float_ = value; } void PListValue::SetString(const String& value) { if (type_ != PLVT_STRING) { Reset(); type_ = PLVT_STRING; string_ = new String(); } *string_ = value; } void PListValue::SetValueMap(const PListValueMap& valueMap) { if (type_ != PLVT_VALUEMAP) { Reset(); type_ = PLVT_VALUEMAP; valueMap_ = new PListValueMap(); } *valueMap_ = valueMap; } void PListValue::SetValueVector(const PListValueVector& valueVector) { if (type_ != PLVT_VALUEVECTOR) { Reset(); type_ = PLVT_VALUEVECTOR; valueVector_ = new PListValueVector(); } *valueVector_ = valueVector; } int PListValue::GetInt() const { return type_ == PLVT_INT ? int_ : 0; } bool PListValue::GetBool() const { return type_ == PLVT_BOOL ? bool_ : false; } float PListValue::GetFloat() const { return type_ == PLVT_FLOAT ? float_ : 0.0f; } const String& PListValue::GetString() const { return type_ == PLVT_STRING ? *string_ : String::EMPTY; } IntRect PListValue::GetIntRect() const { if (type_ != PLVT_STRING) return IntRect::ZERO; int x, y, w, h; sscanf(string_->CString(), "{{%d,%d},{%d,%d}}", &x, &y, &w, &h); // NOLINT(cert-err34-c) return {x, y, x + w, y + h}; } IntVector2 PListValue::GetIntVector2() const { if (type_ != PLVT_STRING) return IntVector2::ZERO; int x, y; sscanf(string_->CString(), "{%d,%d}", &x, &y); // NOLINT(cert-err34-c) return IntVector2(x, y); } IntVector3 PListValue::GetIntVector3() const { if (type_ != PLVT_STRING) return IntVector3::ZERO; int x, y, z; sscanf(string_->CString(), "{%d,%d,%d}", &x, &y, &z); // NOLINT(cert-err34-c) return IntVector3(x, y, z); } const PListValueMap& PListValue::GetValueMap() const { return type_ == PLVT_VALUEMAP ? *valueMap_ : EMPTY_VALUEMAP; } const PListValueVector& PListValue::GetValueVector() const { return type_ == PLVT_VALUEVECTOR ? *valueVector_ : EMPTY_VALUEVECTOR; } PListValueMap& PListValue::ConvertToValueMap() { if (type_ != PLVT_VALUEMAP) { Reset(); type_ = PLVT_VALUEMAP; valueMap_ = new PListValueMap(); } return *valueMap_; } PListValueVector& PListValue::ConvertToValueVector() { if (type_ != PLVT_VALUEVECTOR) { Reset(); type_ = PLVT_VALUEVECTOR; valueVector_ = new PListValueVector(); } return *valueVector_; } void PListValue::Reset() { if (type_ == PLVT_NONE) return; switch (type_) { case PLVT_STRING: delete string_; break; case PLVT_VALUEMAP: delete valueMap_; break; case PLVT_VALUEVECTOR: delete valueVector_; break; default: break; } type_ = PLVT_NONE; } PListFile::PListFile(Context* context) : Resource(context) { } PListFile::~PListFile() = default; void PListFile::RegisterObject(Context* context) { context->RegisterFactory<PListFile>(); } bool PListFile::BeginLoad(Deserializer& source) { if (GetName().Empty()) SetName(source.GetName()); XMLFile xmlFile(context_); if (!xmlFile.Load(source)) { URHO3D_LOGERROR("Could not load property list"); return false; } XMLElement plistElem = xmlFile.GetRoot("plist"); if (!plistElem) { URHO3D_LOGERROR("Invalid property list file"); return false; } root_.Clear(); XMLElement dictElem = plistElem.GetChild("dict"); if (!LoadDict(root_, dictElem)) return false; SetMemoryUse(source.GetSize()); return true; } bool PListFile::LoadDict(PListValueMap& dict, const XMLElement& dictElem) { if (!dictElem) return false; XMLElement keyElem = dictElem.GetChild("key"); XMLElement valueElem = keyElem.GetNext(); while (keyElem && valueElem) { String key = keyElem.GetValue(); valueElem = keyElem.GetNext(); PListValue value; if (!LoadValue(value, valueElem)) return false; dict[key] = value; keyElem = valueElem.GetNext("key"); valueElem = keyElem.GetNext(); } return true; } bool PListFile::LoadArray(PListValueVector& array, const XMLElement& arrayElem) { if (!arrayElem) return false; for (XMLElement valueElem = arrayElem.GetChild(); valueElem; valueElem = valueElem.GetNext()) { PListValue value; if (!LoadValue(value, valueElem)) return false; array.Push(value); } return true; } bool PListFile::LoadValue(PListValue& value, const XMLElement& valueElem) { String valueType = valueElem.GetName(); if (valueType == "string") value.SetString(valueElem.GetValue()); else if (valueType == "real") value.SetFloat(ToFloat(valueElem.GetValue())); else if (valueType == "integer") value.SetInt(ToInt(valueElem.GetValue())); else if (valueType == "true") value.SetBool(true); else if (valueType == "false") value.SetBool(false); else if (valueType == "dict") { if (!LoadDict(value.ConvertToValueMap(), valueElem)) return false; } else if (valueType == "array") { if (!LoadArray(value.ConvertToValueVector(), valueElem)) return false; } else { URHO3D_LOGERROR("Supported value type"); return false; } return true; } }
20.259352
97
0.604259
1vanK
282070978209257ff9f11efe537bde064d01f1f2
445
cpp
C++
stl/lambda.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
1
2020-04-14T05:44:50.000Z
2020-04-14T05:44:50.000Z
stl/lambda.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
null
null
null
stl/lambda.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
2
2020-09-02T08:56:31.000Z
2021-06-22T11:20:58.000Z
#include <iostream> using namespace std; //1.[capture list](params list) -> return type{ function body } //2.[capture list](params list) {function body} //3.[capture list] {function body} // "=","&","," outer variable descriptor // varlist limits: no default value/must have a name/no changable variable supported int main() { int x = 1; auto functor = [=](int k) mutable ->int {x++; return x + k; }; cout << functor(3) << endl; return 0; }
29.666667
84
0.660674
FrancsXiang
2826bbdb16be6f7791643bcdef0fe82d4f1f2c62
3,190
cpp
C++
game/state/rules/battle/damage.cpp
Jarskih/OpenApoc
16f13f1d5eb5ea5639cdc0ee488d71b70c5a8cc3
[ "MIT" ]
null
null
null
game/state/rules/battle/damage.cpp
Jarskih/OpenApoc
16f13f1d5eb5ea5639cdc0ee488d71b70c5a8cc3
[ "MIT" ]
null
null
null
game/state/rules/battle/damage.cpp
Jarskih/OpenApoc
16f13f1d5eb5ea5639cdc0ee488d71b70c5a8cc3
[ "MIT" ]
null
null
null
#include "game/state/rules/battle/damage.h" #include "game/state/gamestate.h" #include "game/state/rules/doodadtype.h" namespace OpenApoc { template <> const UString &StateObject<HazardType>::getPrefix() { static UString prefix = "HAZARD_"; return prefix; } template <> const UString &StateObject<HazardType>::getTypeName() { static UString name = "HazardType"; return name; } template <> sp<HazardType> StateObject<HazardType>::get(const GameState &state, const UString &id) { auto it = state.hazard_types.find(id); if (it == state.hazard_types.end()) { LogError("No hazard type matching ID \"%s\"", id); return nullptr; } return it->second; } template <> const UString &StateObject<DamageModifier>::getPrefix() { static UString prefix = "DAMAGEMODIFIER_"; return prefix; } template <> const UString &StateObject<DamageModifier>::getTypeName() { static UString name = "DamageModifier"; return name; } template <> sp<DamageModifier> StateObject<DamageModifier>::get(const GameState &state, const UString &id) { auto it = state.damage_modifiers.find(id); if (it == state.damage_modifiers.end()) { LogError("No damage modifier type matching ID \"%s\"", id); return nullptr; } return it->second; } template <> const UString &StateObject<DamageType>::getPrefix() { static UString prefix = "DAMAGETYPE_"; return prefix; } template <> const UString &StateObject<DamageType>::getTypeName() { static UString name = "DamageType"; return name; } template <> sp<DamageType> StateObject<DamageType>::get(const GameState &state, const UString &id) { auto it = state.damage_types.find(id); if (it == state.damage_types.end()) { LogError("No damage type type matching ID \"%s\"", id); return nullptr; } return it->second; } int DamageType::dealDamage(int damage, StateRef<DamageModifier> modifier) const { if (modifiers.find(modifier) == modifiers.end()) { LogError("Do not know how to deal damage type to modifier %s!", modifier.id); return damage; } else return damage * modifiers.at(modifier) / 100; } sp<Image> HazardType::getFrame(unsigned age, int offset) { if (fire) { // Explanation how fire frames work is at the end of battlehazard.h // Round stage to nearest 0,5 int stage = (age + 2) / 5 * 5; // Get min and max frames for this stage int minFrame = clamp((stage - 5) / 10, 0, 11); int maxFrame = clamp((stage + 5 + 5) / 10, 0, 11); // Trunc offset if it's too big if (minFrame + offset > maxFrame) { offset = 0; } int frame = minFrame + offset; // Scale to the actual frames of the doodad (crude support for more/less frames) return doodadType->frames[frame * doodadType->frames.size() / 12].image; } else { if (age >= 2 * maxLifetime) { LogError("Age must be lower than max lifetime"); return nullptr; } int frame = age * doodadType->frames.size() / (2 * maxLifetime); while (frame + offset >= (int)doodadType->frames.size()) offset -= (doodadType->frames.size() - frame); return doodadType->frames[frame + offset].image; } } int HazardType::getLifetime(GameState &state) { return randBoundsInclusive(state.rng, 2 * minLifetime, 2 * maxLifetime); } } // namespace OpenApoc
25.11811
98
0.695925
Jarskih
28294054faf82d7b7ed036dcceddd4e29b67ab6a
2,316
cpp
C++
src/scenes/mengfeiWhitney/mengfeiWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
12
2019-10-28T19:07:59.000Z
2021-08-21T22:00:52.000Z
src/scenes/mengfeiWhitney/mengfeiWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
1
2019-10-28T19:20:05.000Z
2019-10-28T20:14:24.000Z
src/scenes/mengfeiWhitney/mengfeiWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
8
2019-10-28T19:11:30.000Z
2020-01-12T05:18:31.000Z
#include "mengfeiWhitney.h" void mengfeiWhitney::setup(){ // setup parameters // if your original code use an ofxPanel instance dont use it here, instead // add your parameters to the "parameters" instance as follows. // param was declared in mengfeiWhitney.h // parameters.add(param.set("param", 5, 0, 100)); setAuthor("Mengfei Wang"); setOriginalArtist("John Whitney"); parameters.add(n.set("n", 7, 2, 20)); parameters.add(radiusX.set("radiusX", 200, 100, 300)); parameters.add(radiusY.set("radiusY", 200, 100, 300)); parameters.add(number.set("number", 15, 5, 100)); loadCode("scenes/mengfeiWhitney/exampleCode.cpp"); } void mengfeiWhitney::update(){ } void mengfeiWhitney::draw(){ ofBackground(0); ofSetColor(238, 168, 231); ofNoFill(); float time = ofGetElapsedTimef(); //get the center point of the window float centerX = dimensions.getWidth() * 0.5; float centerY = dimensions.getHeight() * 0.5; ////n affects the length of each side of the triangle //float n = 7; ////set the radius of the circular trajectory for triangles //float radiusX = 200; //float radiusY = 200; ////set the total number of triangles //int number = 15; //draw a group of triangles moving couter-clockwise for (int i = 0; i < number; i++) { //get the center point coordinates of triangles where the point moves counter-clockwise. float x0 = centerX + radiusX * sin(time+i); float y0 = centerY + radiusY * cos(time+i); //draw a triangle by giving the coordinates of three vertexes ofDrawTriangle(x0 - 1.732 * i*n, y0 - i*n, x0 + 1.732*i*n, y0 - i*n, x0, y0 + 2 * i*n); } ofSetColor(101, 25, 68); ofNoFill(); //draw a group of triangles moving clockwise for (int j = 0; j < number; j++) { //get the center point coordinates of triangles where the point moves clockwise. float x0 = centerX + radiusX * sin(time + j+180); float y0 = centerY + radiusY * cos(time + j+180) * (-1); //draw a triangle by giving the coordinates of three vertexes ofDrawTriangle(x0 - 1.732 * j*n, y0 - j * n, x0 + 1.732*j*n, y0 - j * n, x0, y0 + 2 * j*n); } }
30.88
99
0.60924
yxcde
282a28e3865aebb11fac0419d8f4100d10826c12
5,833
hpp
C++
include/lexy/dsl/context_identifier.hpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
include/lexy/dsl/context_identifier.hpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
include/lexy/dsl/context_identifier.hpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020-2022 Jonathan Müller and lexy contributors // SPDX-License-Identifier: BSL-1.0 #ifndef LEXY_DSL_CONTEXT_IDENTIFIER_HPP_INCLUDED #define LEXY_DSL_CONTEXT_IDENTIFIER_HPP_INCLUDED #include <lexy/dsl/base.hpp> #include <lexy/dsl/capture.hpp> #include <lexy/dsl/identifier.hpp> namespace lexy { struct different_identifier { static LEXY_CONSTEVAL auto name() { return "different identifier"; } }; } // namespace lexy namespace lexyd { template <typename Id, typename Reader> using _ctx_id = lexy::_detail::parse_context_var<Id, lexy::lexeme<Reader>>; template <typename Id> struct _ctx_icreate : rule_base { template <typename NextParser> struct p { template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { _ctx_id<Id, Reader> var({}); var.link(context); auto result = NextParser::parse(context, reader, LEXY_FWD(args)...); var.unlink(context); return result; } }; }; template <typename Id, typename Identifier> struct _ctx_icap : branch_base { template <typename NextParser> struct _pc { template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { // The last argument will be a lexeme. _ctx_id<Id, Reader>::get(context.control_block) = (args, ...); return NextParser::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Reader> using bp = lexy::continuation_branch_parser<Identifier, Reader, _pc>; template <typename NextParser> using p = lexy::parser_for<Identifier, _pc<NextParser>>; }; template <typename Id, typename Identifier, typename Tag> struct _ctx_irem : branch_base { // We only need the pattern: // We don't want a value and don't need to check for reserved identifiers, // as it needs to match a previously parsed identifier, which wasn't reserved. using _pattern = decltype(Identifier{}.pattern()); template <typename Reader> struct bp { typename Reader::iterator end; template <typename ControlBlock> constexpr bool try_parse(const ControlBlock* cb, const Reader& reader) { // Parse the pattern. lexy::token_parser_for<_pattern, Reader> parser(reader); if (!parser.try_parse(reader)) return false; end = parser.end; // The two lexemes need to be equal. auto lexeme = lexy::lexeme<Reader>(reader.position(), end); return lexy::_detail::equal_lexemes(_ctx_id<Id, Reader>::get(cb), lexeme); } template <typename Context> constexpr void cancel(Context&) {} template <typename NextParser, typename Context, typename... Args> LEXY_PARSER_FUNC bool finish(Context& context, Reader& reader, Args&&... args) { // Finish parsing the token. context.on(_ev::token{}, lexy::identifier_token_kind, reader.position(), end); reader.set_position(end); return lexy::whitespace_parser<Context, NextParser>::parse(context, reader, LEXY_FWD(args)...); } }; template <typename NextParser> struct p { template <typename... PrevArgs> struct _cont { template <typename Context, typename Reader> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, PrevArgs&&... args, lexy::lexeme<Reader> lexeme) { if (!lexy::_detail::equal_lexemes(_ctx_id<Id, Reader>::get(context.control_block), lexeme)) { // The lexemes weren't equal. using tag = lexy::_detail::type_or<Tag, lexy::different_identifier>; auto err = lexy::error<Reader, tag>(lexeme.begin(), lexeme.end()); context.on(_ev::error{}, err); // But we can trivially recover. } // Continue parsing with the symbol value. return NextParser::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { // Capture the pattern and continue with special continuation. return lexy::parser_for<_cap<_pattern>, _cont<Args...>>::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Error> static constexpr _ctx_irem<Id, Identifier, Error> error = {}; }; } // namespace lexyd namespace lexyd { template <typename Id, typename Identifier> struct _ctx_id_dsl { constexpr auto create() const { return _ctx_icreate<Id>{}; } constexpr auto capture() const { return _ctx_icap<Id, Identifier>{}; } constexpr auto rematch() const { return _ctx_irem<Id, Identifier, void>{}; } }; /// Declares a context variable that stores one instance of the given identifier. template <typename Id, typename Leading, typename Trailing, typename... Reserved> constexpr auto context_identifier(_id<Leading, Trailing, Reserved...>) { return _ctx_id_dsl<Id, _id<Leading, Trailing, Reserved...>>{}; } } // namespace lexyd #endif // LEXY_DSL_CONTEXT_IDENTIFIER_HPP_INCLUDED
32.769663
100
0.603292
gkgoat1
282d1f6f3424dc00cce24823c4dee035559d076a
2,586
hpp
C++
granite/vulkan/sampler.hpp
bsdunx/Granite
0bbb29717f2bc1e20ba922c7e4120f289e8f752e
[ "MIT" ]
null
null
null
granite/vulkan/sampler.hpp
bsdunx/Granite
0bbb29717f2bc1e20ba922c7e4120f289e8f752e
[ "MIT" ]
null
null
null
granite/vulkan/sampler.hpp
bsdunx/Granite
0bbb29717f2bc1e20ba922c7e4120f289e8f752e
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "vulkan/cookie.hpp" #include "vulkan/vulkan_common.hpp" #include "vulkan/vulkan_headers.hpp" namespace Vulkan { enum class StockSampler { NearestClamp, LinearClamp, TrilinearClamp, NearestWrap, LinearWrap, TrilinearWrap, NearestShadow, LinearShadow, LinearYUV420P, LinearYUV422P, LinearYUV444P, Count }; struct SamplerCreateInfo { VkFilter mag_filter; VkFilter min_filter; VkSamplerMipmapMode mipmap_mode; VkSamplerAddressMode address_mode_u; VkSamplerAddressMode address_mode_v; VkSamplerAddressMode address_mode_w; float mip_lod_bias; VkBool32 anisotropy_enable; float max_anisotropy; VkBool32 compare_enable; VkCompareOp compare_op; float min_lod; float max_lod; VkBorderColor border_color; VkBool32 unnormalized_coordinates; }; class Sampler; struct SamplerDeleter { void operator()(Sampler *sampler); }; class Sampler : public Util::IntrusivePtrEnabled<Sampler, SamplerDeleter, HandleCounter>, public Cookie, public InternalSyncEnabled { public: friend struct SamplerDeleter; ~Sampler(); VkSampler get_sampler() const { return sampler; } const SamplerCreateInfo &get_create_info() const { return create_info; } private: friend class Util::ObjectPool<Sampler>; Sampler(Device *device, VkSampler sampler, const SamplerCreateInfo &info); Device *device; VkSampler sampler; SamplerCreateInfo create_info; }; using SamplerHandle = Util::IntrusivePtr<Sampler>; }
26.121212
89
0.776875
bsdunx
282e352a13b173021f5dea70488e8527964df4b7
909
cpp
C++
src/c/imap/CIMAPNamespace.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
3
2019-07-16T13:19:50.000Z
2020-01-06T10:42:23.000Z
src/c/imap/CIMAPNamespace.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
15
2018-12-11T14:00:48.000Z
2021-12-21T17:42:42.000Z
src/c/imap/CIMAPNamespace.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
2
2015-05-26T18:07:22.000Z
2017-04-04T10:01:17.000Z
#include <MailCore/MCAsync.h> #include "CIMAPNamespace.h" #include "CBase+Private.h" #include <MailCore/MCCore.h> #define nativeType mailcore::IMAPNamespace #define structName CIMAPNamespace C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() CIMAPNamespace CIMAPNamespace_namespaceWithPrefix(MailCoreString prefix, char delimiter) { return CIMAPNamespace_new(mailcore::IMAPNamespace::namespaceWithPrefix(prefix.instance, delimiter)); } C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, mainPrefix) C_SYNTHESIZE_FUNC_WITH_SCALAR(char, mainDelimiter) C_SYNTHESIZE_FUNC_WITH_OBJ(CArray, prefixes) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, pathForComponents, CArray) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, pathForComponentsAndPrefix, CArray, MailCoreString) C_SYNTHESIZE_FUNC_WITH_OBJ(CArray, componentsFromPath, MailCoreString) C_SYNTHESIZE_FUNC_WITH_SCALAR(bool, containsFolderPath, MailCoreString)
36.36
104
0.863586
readdle
28344129a66c05830dcf68333449fe58cce37029
14,506
cpp
C++
engine/src/backends/video_backend_ffmpeg.cpp
kuujoo/pxl
67f68cf7baf3e64847c6c578ebb29efaae1aceb7
[ "MIT" ]
3
2021-05-19T07:42:56.000Z
2021-12-10T12:18:13.000Z
engine/src/backends/video_backend_ffmpeg.cpp
kuujoo/pxl
67f68cf7baf3e64847c6c578ebb29efaae1aceb7
[ "MIT" ]
1
2022-03-17T13:21:26.000Z
2022-03-17T13:21:26.000Z
engine/src/backends/video_backend_ffmpeg.cpp
kuujoo/pxl
67f68cf7baf3e64847c6c578ebb29efaae1aceb7
[ "MIT" ]
2
2021-05-19T07:42:58.000Z
2022-03-17T13:16:59.000Z
#ifdef PXL_VIDEO_FFMPEG #include <pxl/backends/video_backend.h> #include <pxl/backends/platform_backend.h> #include <pxl/containers/map.h> extern "C" { #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <libavcodec/avcodec.h> #include <libavutil/imgutils.h> #include <libavutil/avstring.h> #include <libavutil/time.h> #include <libavutil/opt.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libswresample/swresample.h> } namespace { bool s_ffmpeg_inited = false; struct FrameInfo { pxl::i64 pts; pxl::i64 dts; int frameNumber; }; AVCodecID pxlToFFmpeg(pxl::video::Codec codec) { switch (codec) { case pxl::video::Codec::MPEG4: return AV_CODEC_ID_MPEG4; case pxl::video::Codec::H264: return AV_CODEC_ID_H264; } assert(0); return AV_CODEC_ID_MPEG4; } pxl::video::Codec ffmpegToPxl(AVCodecID codec) { if (codec == AV_CODEC_ID_MPEG4) return pxl::video::Codec::MPEG4; else if (codec == AV_CODEC_ID_H264) return pxl::video::Codec::H264; assert(0); return pxl::video::Codec::MPEG4; } } class Encoder_ffmpeg : public pxl::video::Encoder { public: Encoder_ffmpeg(const pxl::video::EncoderInfo& info); ~Encoder_ffmpeg(); void add(const pxl::Image& image) override; void save() override; private: pxl::video::EncoderInfo info; AVFrame* getYuv(const pxl::Image& image); AVCodecContext* codecCtx; AVFrame* frame; AVFrame* frameRgba; AVFrame* frameYuv; AVOutputFormat* format; AVFormatContext* formatContext; AVStream* stream; pxl::u8* buffer; pxl::i64 pts; }; Encoder_ffmpeg::Encoder_ffmpeg(const pxl::video::EncoderInfo& info) : info(info) { if (!s_ffmpeg_inited) { av_register_all(); avcodec_register_all(); av_log_set_level(AV_LOG_QUIET); s_ffmpeg_inited = true; } codecCtx = nullptr; frame = nullptr; frameRgba = nullptr; frame = av_frame_alloc(); frameRgba = av_frame_alloc(); frameYuv = av_frame_alloc(); buffer = nullptr; // format = av_guess_format(nullptr, info.file.data(), nullptr); if (format == nullptr) { assert(0); } if (avformat_alloc_output_context2(&formatContext, format, nullptr, info.file.data()) < 0) { assert(0); } AVCodec* codec = avcodec_find_encoder(pxlToFFmpeg(info.codec)); if (!codec) { assert(0); } stream = avformat_new_stream(formatContext, codec); if (!stream) { assert(0); } codecCtx = avcodec_alloc_context3(codec); stream->codecpar->codec_id = pxlToFFmpeg(info.codec); stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; stream->codecpar->width = info.width; stream->codecpar->height = info.height; stream->codecpar->format = AV_PIX_FMT_YUV420P; stream->codecpar->bit_rate = info.bitrate; stream->avg_frame_rate = av_d2q(info.framerate, 100); avcodec_parameters_to_context(codecCtx, stream->codecpar); codecCtx->time_base = av_inv_q( av_d2q(info.framerate, 100) ); codecCtx->max_b_frames = info.b_frames; codecCtx->gop_size = info.gop_size; codecCtx->framerate = av_d2q(info.framerate, 100); auto cpus = pxl::platform::cpuCount(); if (cpus > -1) { codecCtx->thread_count = cpus; } if (stream->codecpar->codec_id == AV_CODEC_ID_H264) { codecCtx->profile = FF_PROFILE_H264_MAIN; } else if(stream->codecpar->codec_id == AV_CODEC_ID_MPEG4) { codecCtx->mb_decision = FF_MB_DECISION_RD; // -mbd rd codecCtx->flags |= AV_CODEC_FLAG_4MV; // -flags +mv4 ??? codecCtx->flags |= AV_CODEC_FLAG_PASS1; // -pass 1, PASS2 ei toimi codecCtx->trellis = 2; // -trellis 2 codecCtx->mv0_threshold = 2; // -cmp 2 // -cmp <string or int> : Full pel motion estimation compare function. codecCtx->me_subpel_quality = 2; // -subcmp 2 codecCtx->gop_size = info.gop_size; // -g 300 } avcodec_parameters_from_context(stream->codecpar, codecCtx); if (avcodec_open2(codecCtx, codec, nullptr) < 0) { assert(0); } if (!(format->flags & AVFMT_NOFILE)) { if ((avio_open(&formatContext->pb, info.file.data(), AVIO_FLAG_WRITE)) < 0) { assert(0); } } if (avformat_write_header(formatContext, nullptr) < 0) { assert(0); } pts = 0; frameYuv->width = codecCtx->width; frameYuv->height = codecCtx->height; frameYuv->format = codecCtx->pix_fmt; if (av_frame_get_buffer(frameYuv, 32) < 0) { assert(0); } } Encoder_ffmpeg::~Encoder_ffmpeg() { av_frame_free(&frame); av_free(frame); av_frame_free(&frameRgba); av_free(frameRgba); av_frame_free(&frameYuv); av_free(frameYuv); av_free(buffer); avformat_free_context(formatContext); avcodec_close(codecCtx); buffer = nullptr; frameRgba = nullptr; frameYuv = nullptr; frame = nullptr; codecCtx = nullptr; } void Encoder_ffmpeg::add(const pxl::Image& image) { auto yuvFrame = getYuv(image); yuvFrame->pts = pts * (pxl::i64)stream->time_base.den / (stream->time_base.num * info.framerate); auto ret = avcodec_send_frame(codecCtx, yuvFrame); if (ret < 0) { assert(0); } AVPacket packet; av_init_packet(&packet); packet.data = nullptr; packet.size = 0; while (ret >= 0) { ret = avcodec_receive_packet(codecCtx, &packet); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { assert(0); } if(codecCtx->coded_frame->key_frame) { packet.flags |= AV_PKT_FLAG_KEY; } av_interleaved_write_frame(formatContext, &packet); } av_packet_unref(&packet); pts++; } AVFrame* Encoder_ffmpeg::getYuv(const pxl::Image& image) { if (av_frame_make_writable(frameYuv) < 0) { assert(0); } frameRgba->format = AV_PIX_FMT_RGBA; frameRgba->width = image.width(); frameRgba->height = image.height(); frameRgba->data[0] = &image.pixels()->r; frameRgba->linesize[0] = image.width() * 4; if (buffer == nullptr) { int numBytes = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, codecCtx->width, codecCtx->height, 32); buffer = (pxl::u8*)av_malloc(numBytes * sizeof(pxl::u8)); } av_image_fill_arrays( frameYuv->data, frameYuv->linesize, buffer, AV_PIX_FMT_YUV420P, codecCtx->width, codecCtx->height, 32 ); struct SwsContext* sws_ctx = nullptr; sws_ctx = sws_getContext( image.width(), image.height(), AV_PIX_FMT_RGBA, codecCtx->width, codecCtx->height, codecCtx->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL ); sws_scale( sws_ctx, (uint8_t const* const*)frameRgba->data, frameRgba->linesize, 0, codecCtx->height, frameYuv->data, frameYuv->linesize ); sws_freeContext(sws_ctx); return frameYuv; } void Encoder_ffmpeg::save() { AVPacket packet; av_init_packet(&packet); packet.data = nullptr; packet.size = 0; auto ret = avcodec_send_frame(codecCtx, nullptr); if (ret < 0) { assert(0); } while (ret >= 0) { ret = avcodec_receive_packet(codecCtx, &packet); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { assert(0); } if (codecCtx->coded_frame->key_frame) { packet.flags |= AV_PKT_FLAG_KEY; } av_interleaved_write_frame(formatContext, &packet); } av_packet_unref(&packet); av_write_trailer(formatContext); if (!(format->flags & AVFMT_NOFILE)) { int err = avio_close(formatContext->pb); if (err < 0) { assert(0); } } } pxl::video::EncoderRef pxl::video::createEncoder(const EncoderInfo &info) { return std::make_shared<Encoder_ffmpeg>(info); } class Decoder_ffmpeg : public pxl::video::Decoder { public: Decoder_ffmpeg(); ~Decoder_ffmpeg(); void open(const pxl::String &file) override; void close() override; void calculateFrames(pxl::video::Progress &progress) override; pxl::Image currentFrameImage() override; pxl::i64 currentFrameNumber() const override; void flushDecoder() override; bool seek(int seekFrame) override; bool decode() override; pxl::video::FileInfo info() const override; private: bool decode(FrameInfo* fillInfo); pxl::i64 seekTarget; pxl::i64 seekTargetFrame; AVFormatContext* formatCtx;; AVCodecContext* codecCtxOrig; AVCodecContext* codecCtx; AVFrame* frame; AVFrame* frameRgba; pxl::u8* buffer; pxl::Vector<int> videoStreamIds; pxl::Vector<int> audioStreamIds; int videoStreamId; pxl::i64 currentFrame; FrameInfo currentFrameInfo; pxl::Map<pxl::i64, pxl::i64> dtsToTime; pxl::String file; }; Decoder_ffmpeg::Decoder_ffmpeg() : seekTarget(-1), seekTargetFrame(0), formatCtx(nullptr), codecCtxOrig(nullptr), codecCtx(nullptr), frame(nullptr), frameRgba(nullptr), buffer(nullptr), videoStreamId(-1), currentFrame(0) { if (!s_ffmpeg_inited) { av_register_all(); avcodec_register_all(); av_log_set_level(AV_LOG_QUIET); s_ffmpeg_inited = true; } } Decoder_ffmpeg::~Decoder_ffmpeg() { close(); } void Decoder_ffmpeg::open(const pxl::String& file) { this->file = file; frame = av_frame_alloc(); frameRgba = av_frame_alloc(); if (avformat_open_input(&formatCtx, file.data(), nullptr, nullptr) < 0) { assert(0); } if (avformat_find_stream_info(formatCtx, nullptr) < 0) { assert(0); } for (unsigned i = 0; i < formatCtx->nb_streams; i++) { if (formatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { videoStreamIds.push_back(i); break; } else if (formatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { audioStreamIds.push_back(i); break; } } videoStreamId = videoStreamIds.front(); if (videoStreamId == -1) { assert(0); } AVCodec* codec = nullptr; codec = avcodec_find_decoder(formatCtx->streams[videoStreamId]->codecpar->codec_id); if (codec == nullptr) { assert(0); } codecCtxOrig = avcodec_alloc_context3(codec); if (avcodec_parameters_to_context(codecCtxOrig, formatCtx->streams[videoStreamId]->codecpar) != 0) { assert(0); } codecCtx = avcodec_alloc_context3(codec); if (avcodec_parameters_to_context(codecCtx, formatCtx->streams[videoStreamId]->codecpar) != 0) { assert(0); } auto cpus = pxl::platform::cpuCount(); if (cpus > -1) { codecCtx->thread_count = cpus; } if (avcodec_open2(codecCtx, codec, nullptr) < 0) { assert(0); } buffer = nullptr; int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGBA, codecCtx->width, codecCtx->height, 32); buffer = (pxl::u8*)av_malloc(numBytes * sizeof(pxl::u8)); av_image_fill_arrays( frameRgba->data, frameRgba->linesize, buffer, AV_PIX_FMT_RGBA, codecCtx->width, codecCtx->height, 32 ); } void Decoder_ffmpeg::close() { av_free(buffer); av_frame_free(&frameRgba); av_free(frameRgba); av_frame_free(&frame); av_free(frame); avcodec_close(codecCtx); avcodec_close(codecCtxOrig); avformat_close_input(&formatCtx); buffer = nullptr; frameRgba = nullptr; frame = nullptr; codecCtx = nullptr; codecCtxOrig = nullptr; formatCtx = nullptr; } pxl::Image Decoder_ffmpeg::currentFrameImage() { struct SwsContext* sws_ctx = nullptr; sws_ctx = sws_getContext( codecCtx->width, codecCtx->height, codecCtx->pix_fmt, codecCtx->width, codecCtx->height, AV_PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL ); sws_scale( sws_ctx, (uint8_t const* const*)frame->data, frame->linesize, 0, codecCtx->height, frameRgba->data, frameRgba->linesize ); pxl::Image img(codecCtx->width, codecCtx->height); auto pxlPtr = img.pixels(); const uint8_t* srcData[] = { frameRgba->data[0], frameRgba->data[1], frameRgba->data[2], frameRgba->data[3] }; pxl::u8* dst[] = { &pxlPtr->r, nullptr, nullptr, nullptr }; int linesizes[] = { img.width() * 4, 0,0,0 }; av_image_copy(dst, linesizes, srcData, frameRgba->linesize, AV_PIX_FMT_RGBA, codecCtx->width, codecCtx->height); sws_freeContext(sws_ctx); return img; } pxl::i64 Decoder_ffmpeg::currentFrameNumber() const { return currentFrame; } void Decoder_ffmpeg::flushDecoder() { //flush codec auto ret = avcodec_send_packet(codecCtx, nullptr); if (ret < 0) { assert(0); } while (ret >= 0) { ret = avcodec_receive_frame(codecCtx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { // EOF exit loop break; } else if (ret < 0) { assert(0); } } avcodec_flush_buffers(codecCtx); currentFrame = 0; } bool Decoder_ffmpeg::seek(int seekFrame) { if (seekFrame < 1) return false; auto fileInfo = info(); if (seekFrame > fileInfo.frames) { return false; } flushDecoder(); pxl::i64 targetTime = dtsToTime[seekFrame]; if (av_seek_frame(formatCtx, videoStreamId, targetTime, AVSEEK_FLAG_BACKWARD) < 0) { assert(0); return false; } seekTarget = targetTime; seekTargetFrame = seekFrame; return true; } pxl::video::FileInfo Decoder_ffmpeg::info() const { pxl::video::FileInfo info; info.duration = formatCtx->duration / AV_TIME_BASE; info.frames = formatCtx->streams[videoStreamId]->nb_frames; info.framerate = av_q2d(formatCtx->streams[videoStreamId]->r_frame_rate); info.width = codecCtx->width; info.height = codecCtx->height; info.bitrate = codecCtx->bit_rate; info.gop_size = codecCtx->gop_size; info.file = file; info.codec = ffmpegToPxl( formatCtx->streams[videoStreamId]->codecpar->codec_id); return info; } bool Decoder_ffmpeg::decode() { return decode(nullptr); } bool Decoder_ffmpeg::decode(FrameInfo* fillInfo) { AVPacket packet; bool done = false; av_frame_unref(frame); while (av_read_frame(formatCtx, &packet) >= 0) { if (packet.stream_index == videoStreamId) { auto ret = avcodec_send_packet(codecCtx, &packet); if (ret < 0) { assert(0); } while (ret >= 0) { ret = avcodec_receive_frame(codecCtx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { // EOF exit loop break; } else if (ret < 0) { assert(0); } if (seekTarget != -1 && seekTarget != frame->pkt_dts) continue; if (seekTarget != -1) { seekTarget = -1; currentFrame = seekTargetFrame; seekTargetFrame = -1; } else { currentFrame++; } if (fillInfo != nullptr) { fillInfo->dts = frame->pkt_dts; fillInfo->pts = frame->pts; } done = true; break; } } av_packet_unref(&packet); if (done) { break; } } return done; } void Decoder_ffmpeg::calculateFrames(pxl::video::Progress &progress) { progress.max = formatCtx->streams[videoStreamId]->nb_frames; FrameInfo info; info.pts = 0; info.dts = 0; info.frameNumber = 0; while (decode(&info)) { info.frameNumber++; dtsToTime[info.frameNumber] = info.dts; progress.current = info.frameNumber; if(progress.update != nullptr) { progress.update(); } } seek(1); } pxl::video::DecoderRef pxl::video::createDecoder() { return std::make_shared<Decoder_ffmpeg>(); } #endif
20.459803
151
0.693713
kuujoo
283767e5c2fe85e0b676e9553bc2f06ea4615952
7,357
cpp
C++
UXToolsGame/Source/UXToolsTests/Tests/UxtTestHandTracker.cpp
xuelongmu/MixedReality-UXTools-Unreal
be2c5336115906853de42056f65735c406b91c34
[ "MIT" ]
213
2020-05-05T23:37:50.000Z
2022-03-25T15:36:00.000Z
UXToolsGame/Source/UXToolsTests/Tests/UxtTestHandTracker.cpp
xuelongmu/MixedReality-UXTools-Unreal
be2c5336115906853de42056f65735c406b91c34
[ "MIT" ]
50
2020-05-26T23:57:38.000Z
2022-03-31T15:06:27.000Z
UXToolsGame/Source/UXToolsTests/Tests/UxtTestHandTracker.cpp
xuelongmu/MixedReality-UXTools-Unreal
be2c5336115906853de42056f65735c406b91c34
[ "MIT" ]
65
2020-05-07T08:31:47.000Z
2022-03-26T09:59:28.000Z
// Copyright (c) 2020 Microsoft Corporation. // Licensed under the MIT License. #include "UxtTestHandTracker.h" FUxtTestHandData::FUxtTestHandData() { JointOrientation.SetNum(EHandKeypointCount); JointPosition.SetNum(EHandKeypointCount); JointRadius.SetNum(EHandKeypointCount); for (uint8 i = 0; i < EHandKeypointCount; ++i) { JointOrientation[i] = FQuat::Identity; JointPosition[i] = FVector::ZeroVector; JointRadius[i] = 1.0f; } } ETrackingStatus FUxtTestHandTracker::GetTrackingStatus(EControllerHand Hand) const { const FUxtTestHandData& HandState = GetHandState(Hand); return HandState.bIsTracked ? ETrackingStatus::Tracked : ETrackingStatus::NotTracked; } bool FUxtTestHandTracker::IsHandController(EControllerHand Hand) const { const FUxtTestHandData& HandState = GetHandState(Hand); return HandState.bIsTracked; } bool FUxtTestHandTracker::GetJointState( EControllerHand Hand, EHandKeypoint Joint, FQuat& OutOrientation, FVector& OutPosition, float& OutRadius) const { const FUxtTestHandData& HandState = GetHandState(Hand); if (HandState.bIsTracked) { OutOrientation = HandState.JointOrientation[(uint8)Joint]; OutPosition = HandState.JointPosition[(uint8)Joint]; OutRadius = HandState.JointRadius[(uint8)Joint]; return true; } return false; } bool FUxtTestHandTracker::GetPointerPose(EControllerHand Hand, FQuat& OutOrientation, FVector& OutPosition) const { const FUxtTestHandData& HandState = GetHandState(Hand); if (HandState.bIsTracked) { OutOrientation = HandState.JointOrientation[(uint8)EHandKeypoint::IndexProximal]; OutPosition = HandState.JointPosition[(uint8)EHandKeypoint::IndexProximal]; return true; } return false; } bool FUxtTestHandTracker::GetGripPose(EControllerHand Hand, FQuat& OutOrientation, FVector& OutPosition) const { const FUxtTestHandData& HandState = GetHandState(Hand); if (HandState.bIsTracked) { OutOrientation = HandState.JointOrientation[(uint8)EHandKeypoint::IndexProximal]; OutPosition = HandState.JointPosition[(uint8)EHandKeypoint::IndexProximal]; return true; } return false; } bool FUxtTestHandTracker::GetIsGrabbing(EControllerHand Hand, bool& OutIsGrabbing) const { const FUxtTestHandData& HandState = GetHandState(Hand); if (HandState.bIsTracked) { OutIsGrabbing = HandState.bIsGrabbing; return true; } return false; } bool FUxtTestHandTracker::GetIsSelectPressed(EControllerHand Hand, bool& OutIsSelectPressed) const { const FUxtTestHandData& HandState = GetHandState(Hand); if (HandState.bIsTracked) { OutIsSelectPressed = HandState.bIsSelectPressed; return true; } return false; } const FUxtTestHandData& FUxtTestHandTracker::GetHandState(EControllerHand Hand) const { switch (Hand) { default: case EControllerHand::Left: return LeftHandData; case EControllerHand::Right: return RightHandData; } } void FUxtTestHandTracker::SetTracked(bool bIsTracked, EControllerHand Hand) { switch (Hand) { case EControllerHand::Left: LeftHandData.bIsTracked = bIsTracked; break; case EControllerHand::Right: RightHandData.bIsTracked = bIsTracked; break; case EControllerHand::AnyHand: LeftHandData.bIsTracked = bIsTracked; RightHandData.bIsTracked = bIsTracked; break; } } void FUxtTestHandTracker::SetGrabbing(bool bIsGrabbing, EControllerHand Hand) { switch (Hand) { case EControllerHand::Left: LeftHandData.bIsGrabbing = bIsGrabbing; break; case EControllerHand::Right: RightHandData.bIsGrabbing = bIsGrabbing; break; case EControllerHand::AnyHand: LeftHandData.bIsGrabbing = bIsGrabbing; RightHandData.bIsGrabbing = bIsGrabbing; break; } } void FUxtTestHandTracker::SetSelectPressed(bool bIsSelectPressed, EControllerHand Hand) { switch (Hand) { case EControllerHand::Left: LeftHandData.bIsSelectPressed = bIsSelectPressed; break; case EControllerHand::Right: RightHandData.bIsSelectPressed = bIsSelectPressed; break; case EControllerHand::AnyHand: LeftHandData.bIsSelectPressed = bIsSelectPressed; RightHandData.bIsSelectPressed = bIsSelectPressed; break; } } void FUxtTestHandTracker::SetJointPosition(const FVector& Position, EControllerHand Hand, EHandKeypoint Joint) { switch (Hand) { case EControllerHand::Left: LeftHandData.JointPosition[(uint8)Joint] = Position; break; case EControllerHand::Right: RightHandData.JointPosition[(uint8)Joint] = Position; break; case EControllerHand::AnyHand: LeftHandData.JointPosition[(uint8)Joint] = Position; RightHandData.JointPosition[(uint8)Joint] = Position; break; } } void FUxtTestHandTracker::SetAllJointPositions(const FVector& Position, EControllerHand Hand) { const int32 NumKeypoints = EHandKeypointCount; switch (Hand) { case EControllerHand::Left: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointPosition[i] = Position; } break; case EControllerHand::Right: for (uint8 i = 0; i < NumKeypoints; ++i) { RightHandData.JointPosition[i] = Position; } break; case EControllerHand::AnyHand: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointPosition[i] = Position; RightHandData.JointPosition[i] = Position; } break; } } void FUxtTestHandTracker::SetJointOrientation(const FQuat& Orientation, EControllerHand Hand, EHandKeypoint Joint) { switch (Hand) { case EControllerHand::Left: LeftHandData.JointOrientation[(uint8)Joint] = Orientation; break; case EControllerHand::Right: RightHandData.JointOrientation[(uint8)Joint] = Orientation; break; case EControllerHand::AnyHand: LeftHandData.JointOrientation[(uint8)Joint] = Orientation; RightHandData.JointOrientation[(uint8)Joint] = Orientation; break; } } void FUxtTestHandTracker::SetAllJointOrientations(const FQuat& Orientation, EControllerHand Hand) { const int32 NumKeypoints = EHandKeypointCount; switch (Hand) { case EControllerHand::Left: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointOrientation[i] = Orientation; } break; case EControllerHand::Right: for (uint8 i = 0; i < NumKeypoints; ++i) { RightHandData.JointOrientation[i] = Orientation; } break; case EControllerHand::AnyHand: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointOrientation[i] = Orientation; RightHandData.JointOrientation[i] = Orientation; } break; } } void FUxtTestHandTracker::SetJointRadius(float Radius, EControllerHand Hand, EHandKeypoint Joint) { switch (Hand) { case EControllerHand::Left: LeftHandData.JointRadius[(uint8)Joint] = Radius; break; case EControllerHand::Right: RightHandData.JointRadius[(uint8)Joint] = Radius; break; case EControllerHand::AnyHand: LeftHandData.JointRadius[(uint8)Joint] = Radius; RightHandData.JointRadius[(uint8)Joint] = Radius; break; } } void FUxtTestHandTracker::SetAllJointRadii(float Radius, EControllerHand Hand) { const int32 NumKeypoints = EHandKeypointCount; switch (Hand) { case EControllerHand::Left: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointRadius[i] = Radius; } break; case EControllerHand::Right: for (uint8 i = 0; i < NumKeypoints; ++i) { RightHandData.JointRadius[i] = Radius; } break; case EControllerHand::AnyHand: for (uint8 i = 0; i < NumKeypoints; ++i) { LeftHandData.JointRadius[i] = Radius; RightHandData.JointRadius[i] = Radius; } break; } }
25.281787
114
0.759413
xuelongmu
283a1446b153a4bd256f1ce744f439b2d7a580dd
574
cpp
C++
lcx/lv/LCR_last_visited.cpp
WAFI-CNR/glcr
772d3a022d398401577d47e4fbc474b47dbd44b0
[ "BSD-3-Clause" ]
null
null
null
lcx/lv/LCR_last_visited.cpp
WAFI-CNR/glcr
772d3a022d398401577d47e4fbc474b47dbd44b0
[ "BSD-3-Clause" ]
1
2019-01-28T12:57:24.000Z
2019-01-28T13:02:50.000Z
lcx/lv/LCR_last_visited.cpp
WAFI-CNR/glcr
772d3a022d398401577d47e4fbc474b47dbd44b0
[ "BSD-3-Clause" ]
null
null
null
#include "LCR_last_visited.hpp" #include "util/LV_list_lcr.hpp" LCR_last_visited::LCR_last_visited(GSA *gsa, Result_saver* rs) : LCR(rs) { this->gsa = gsa; } LCR_last_visited::~LCR_last_visited() { } void LCR_last_visited::get_lcr(int x_repeats) { LV_list_lcr wl = LV_list_lcr(gsa->num_words, x_repeats, rs); for (int i=0; i<gsa->len; i++) { int lcp = gsa->lcp[i]; int text = gsa->text(i); int front_lcp = wl.get_front_lcp(); if (lcp <= front_lcp) { wl.lcp_update(lcp, i); } wl.list_update(text, lcp, i); } wl.lcp_update(0, gsa->len); }
20.5
74
0.656794
WAFI-CNR
283cdb5c4519f2c17487b4db513aa25ec2ef4cd5
2,158
cpp
C++
framegraph/Vulkan/CommandBuffer/VSubmitted.cpp
ayberkgerey5/FrameGraphx
cefc587529305ffdba35a4faa06a9e7c10accbe2
[ "BSD-2-Clause" ]
362
2018-10-14T04:03:50.000Z
2022-03-26T23:45:06.000Z
framegraph/Vulkan/CommandBuffer/VSubmitted.cpp
loopunit/FrameGraph
1359143284a135542ace8b851db78521f2800cc3
[ "BSD-2-Clause" ]
18
2019-05-25T13:43:53.000Z
2021-03-22T18:12:18.000Z
framegraph/Vulkan/CommandBuffer/VSubmitted.cpp
loopunit/FrameGraph
1359143284a135542ace8b851db78521f2800cc3
[ "BSD-2-Clause" ]
39
2019-03-04T05:47:11.000Z
2022-02-04T14:32:39.000Z
// Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE' #include "VSubmitted.h" #include "VDevice.h" #include "VResourceManager.h" namespace FG { /* ================================================= constructor ================================================= */ VSubmitted::VSubmitted (uint indexInPool) : _indexInPool{ indexInPool }, _fence{ VK_NULL_HANDLE }, _queueType{ Default } { } /* ================================================= destructor ================================================= */ VSubmitted::~VSubmitted () { ASSERT( not _fence ); ASSERT( _semaphores.empty() ); ASSERT( _batches.empty() ); } /* ================================================= Initialize ================================================= */ void VSubmitted::Initialize (const VDevice &dev, EQueueType queue, ArrayView<VCmdBatchPtr> batches, ArrayView<VkSemaphore> semaphores) { EXLOCK( _drCheck ); if ( not _fence ) { VkFenceCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; info.flags = 0; VK_CALL( dev.vkCreateFence( dev.GetVkDevice(), &info, null, OUT &_fence )); } else VK_CALL( dev.vkResetFences( dev.GetVkDevice(), 1, &_fence )); _batches = batches; _semaphores = semaphores; _queueType = queue; } /* ================================================= Release ================================================= */ void VSubmitted::Release (const VDevice &dev, VDebugger &debugger, const IFrameGraph::ShaderDebugCallback_t &shaderDbgCallback, INOUT Statistic_t &outStatistic) { EXLOCK( _drCheck ); for (auto& sem : _semaphores) { dev.vkDestroySemaphore( dev.GetVkDevice(), sem, null ); } _semaphores.clear(); for (auto& batch : _batches) { batch->OnComplete( debugger, shaderDbgCallback, INOUT outStatistic ); } _batches.clear(); } /* ================================================= Destroy ================================================= */ void VSubmitted::Destroy (const VDevice &dev) { EXLOCK( _drCheck ); dev.vkDestroyFence( dev.GetVkDevice(), _fence, null ); _fence = VK_NULL_HANDLE; } } // FG
22.715789
162
0.527804
ayberkgerey5
283f50c7d4b74949e5220936386a8ebc7279b112
3,192
cpp
C++
innative-test/test_assemblyscript.cpp
innative-sdk/innative
7c4733a390ace01900e914b1b03cc6bc96e879c8
[ "Apache-2.0" ]
381
2018-12-13T19:53:48.000Z
2022-03-21T07:33:39.000Z
innative-test/test_assemblyscript.cpp
Black-Sphere-Studios/innative
7c4733a390ace01900e914b1b03cc6bc96e879c8
[ "Apache-2.0" ]
62
2018-10-16T15:42:25.000Z
2021-03-29T23:55:56.000Z
innative-test/test_assemblyscript.cpp
Black-Sphere-Studios/innative
7c4733a390ace01900e914b1b03cc6bc96e879c8
[ "Apache-2.0" ]
13
2018-12-13T17:43:49.000Z
2020-06-13T15:10:38.000Z
// Copyright (c)2021 Fundament Software // For conditions of distribution and use, see copyright notice in innative.h #include "test.h" #include "../innative/utility.h" #include <signal.h> #include <setjmp.h> using namespace innative; #ifdef IN_DEBUG #define TEST_EMBEDDING "innative-assemblyscript-d" IN_STATIC_EXTENSION #else #define TEST_EMBEDDING "innative-assemblyscript" IN_STATIC_EXTENSION #endif #ifdef IN_PLATFORM_POSIX #define LONGJMP(x, i) siglongjmp(x, i) #define SETJMP(x) sigsetjmp(x, 1) #else #define LONGJMP(x, i) longjmp(x, i) #define SETJMP(x) setjmp(x) #include "../innative/win32.h" #endif jmp_buf jump_location; void TestCrashHandler(int sig) { LONGJMP(jump_location, 1); } bool isolate_call(IN_Entrypoint start, IN_Entrypoint cleanup) { bool caught = false; signal(SIGILL, TestCrashHandler); if(SETJMP(jump_location) != 0) caught = true; else { #ifdef IN_COMPILER_MSC // On windows, signals can sometimes get promoted to SEH exceptions across DLL bounderies. __try { #endif (*start)(); #ifdef IN_COMPILER_MSC } __except(GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION) // Only catch an illegal instruction { caught = true; } #endif } if(cleanup) (*cleanup)(); signal(SIGILL, SIG_DFL); return caught; } void TestHarness::test_assemblyscript() { auto fn = [this](const char* embed, size_t sz) { constexpr int i = 4; constexpr int j = 2; path dll_path = _folder / "astest" IN_LIBRARY_EXTENSION; constexpr const char wasm_path[] = "../scripts/assemblyscript.wasm"; Environment* env = (*_exports.CreateEnvironment)(1, 0, 0); env->flags |= ENV_LIBRARY | ENV_NO_INIT; env->system = "env"; #ifdef IN_DEBUG env->optimize = ENV_OPTIMIZE_O0; env->flags |= ENV_DEBUG; #endif int err = (*_exports.AddWhitelist)(env, "env", "trace"); err = (*_exports.AddWhitelist)(env, "env", "abort"); TESTERR(err, ERR_SUCCESS); err = (*_exports.AddEmbedding)(env, 0, embed, sz, 0); TESTERR(err, ERR_SUCCESS); err = (*_exports.AddEmbedding)(env, 0, (void*)(*_exports.GetDefaultEmbedding)(TestHarness::Debug), 0, 0); TESTERR(err, ERR_SUCCESS); (*_exports.AddModule)(env, wasm_path, 0, "astest", &err); TESTERR(err, ERR_SUCCESS); if(err < 0) return; err = (*_exports.FinalizeEnvironment)(env); TESTERR(err, ERR_SUCCESS); err = (*_exports.Compile)(env, dll_path.u8string().c_str()); TESTERR(err, ERR_SUCCESS); (*_exports.DestroyEnvironment)(env); void* assembly = LoadAssembly(dll_path); IN_Entrypoint start = (*_exports.LoadFunction)(assembly, 0, IN_INIT_FUNCTION); IN_Entrypoint cleanup = (*_exports.LoadFunction)(assembly, 0, IN_EXIT_FUNCTION); TEST(start); if(start) { auto caught = isolate_call(start, cleanup); TEST(caught); } if(assembly) (*_exports.FreeAssembly)(assembly); remove(dll_path); }; fn(TEST_EMBEDDING, 0); size_t embedsz = 0; auto embedfile = utility::LoadFile(TEST_EMBEDDING, embedsz); fn((const char*)embedfile.get(), embedsz); }
26.163934
109
0.6651
innative-sdk
2841ed4c83f26fd7a4458d58fd8c64681664d9d6
4,635
hpp
C++
libraries/chain/include/graphene/chain/account_evaluator.hpp
JWOCC/core
590c3cc7156a37494a501bb3852fbdb17fc56655
[ "MIT" ]
1
2020-11-19T03:37:07.000Z
2020-11-19T03:37:07.000Z
libraries/chain/include/graphene/chain/account_evaluator.hpp
dfdchain/dfd2.0_project
8824355a370026965987cbad9cbb4536ee1d9acf
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/account_evaluator.hpp
dfdchain/dfd2.0_project
8824355a370026965987cbad9cbb4536ee1d9acf
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/evaluator.hpp> #include <graphene/chain/account_object.hpp> namespace graphene { namespace chain { class account_create_evaluator : public evaluator<account_create_evaluator> { public: typedef account_create_operation operation_type; void_result do_evaluate( const account_create_operation& o ); object_id_type do_apply( const account_create_operation& o ) ; }; class account_update_evaluator : public evaluator<account_update_evaluator> { public: typedef account_update_operation operation_type; void_result do_evaluate( const account_update_operation& o ); void_result do_apply( const account_update_operation& o ); bool if_evluate(); const account_object* acnt; }; class account_upgrade_evaluator : public evaluator<account_upgrade_evaluator> { public: typedef account_upgrade_operation operation_type; void_result do_evaluate(const operation_type& o); void_result do_apply(const operation_type& o); bool if_evluate() { return true; } const account_object* account; }; class account_whitelist_evaluator : public evaluator<account_whitelist_evaluator> { public: typedef account_whitelist_operation operation_type; void_result do_evaluate( const account_whitelist_operation& o); void_result do_apply( const account_whitelist_operation& o); bool if_evluate() { return true; } const account_object* listed_account; }; class account_create_multisignature_address_evaluator : public evaluator<account_create_multisignature_address_evaluator> { public: typedef account_create_multisignature_address_operation operation_type; void_result do_evaluate(const account_create_multisignature_address_operation& o); void_result do_apply(const account_create_multisignature_address_operation& o); }; class block_address_evaluator :public evaluator<block_address_evaluator> { public: typedef block_address_operation operation_type; void_result do_evaluate(const block_address_operation& o); void_result do_apply(const block_address_operation& o); }; class cancel_address_block_evaluator : public evaluator<cancel_address_block_evaluator> { public: typedef cancel_address_block_operation operation_type; void_result do_evaluate(const cancel_address_block_operation& o); void_result do_apply(const cancel_address_block_operation& o); }; class add_whiteOperation_list_evaluator : public evaluator<add_whiteOperation_list_evaluator> { public: typedef add_whiteOperation_list_operation operation_type; void_result do_evaluate(const add_whiteOperation_list_operation& o); void_result do_apply(const add_whiteOperation_list_operation& o); }; class cancel_whiteOperation_list_evaluator : public evaluator<cancel_whiteOperation_list_evaluator> { public: typedef cancel_whiteOperation_list_operation operation_type; void_result do_evaluate(const cancel_whiteOperation_list_operation& o); void_result do_apply(const cancel_whiteOperation_list_operation& o); }; class undertaker_evaluator : public evaluator<undertaker_evaluator> { public: typedef undertaker_operation operation_type; void_result do_evaluate(const undertaker_operation& o); void_result do_apply(const undertaker_operation& o); }; class name_transfer_evaluator : public evaluator<name_transfer_evaluator> { public: typedef name_transfer_operation operation_type; void_result do_evaluate(const name_transfer_operation& o); void_result do_apply(const name_transfer_operation& o); }; } } // graphene::chain
36.496063
121
0.817691
JWOCC
2844c5630b6cf2f5653f84733384f611ead0b848
106
cpp
C++
src/3rdPartyLib/GainputInputDevicePad.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
2
2020-02-03T04:58:17.000Z
2021-03-13T06:03:52.000Z
src/3rdPartyLib/GainputInputDevicePad.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
src/3rdPartyLib/GainputInputDevicePad.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
#include "define.h" #define GAINPUT_LIB_DYNAMIC 1 #include <gainput/gainput/pad/GainputInputDevicePad.cpp>
35.333333
56
0.830189
SapphireEngine
28466899026082666ee9d044377e0d86cae92fc2
2,494
cpp
C++
plugins/opengl/src/texture/volume_context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/texture/volume_context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/texture/volume_context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/opengl/common.hpp> #include <sge/opengl/deref_fun_ptr.hpp> #include <sge/opengl/context/base.hpp> #include <sge/opengl/context/id.hpp> #include <sge/opengl/context/make_id.hpp> #include <sge/opengl/convert/to_gl_enum.hpp> #include <sge/opengl/info/cast_function.hpp> #include <sge/opengl/info/context.hpp> #include <sge/opengl/info/major_version.hpp> #include <sge/opengl/info/minor_version.hpp> #include <sge/opengl/info/version_at_least.hpp> #include <sge/opengl/texture/optional_volume_config.hpp> #include <sge/opengl/texture/volume_config.hpp> #include <sge/opengl/texture/volume_context.hpp> #include <sge/opengl/texture/convert/make_type.hpp> #include <fcppt/preprocessor/disable_clang_warning.hpp> #include <fcppt/preprocessor/pop_warning.hpp> #include <fcppt/preprocessor/push_warning.hpp> sge::opengl::texture::volume_context::volume_context(sge::opengl::info::context const &_info) : sge::opengl::context::base(), config_( sge::opengl::info::version_at_least( _info.version(), sge::opengl::info::major_version{1U}, sge::opengl::info::minor_version{3U}) ? sge::opengl::texture::optional_volume_config(sge::opengl::texture::volume_config( sge::opengl::texture::convert::make_type(GL_TEXTURE_3D), sge::opengl::deref_fun_ptr( sge::opengl::info::cast_function<PFNGLTEXIMAGE3DPROC>( _info.load_function("glTexImage3D"))), sge::opengl::deref_fun_ptr( sge::opengl::info::cast_function<PFNGLTEXSUBIMAGE3DPROC>( _info.load_function("glTexSubImage3D"))), sge::opengl::convert::to_gl_enum<GL_MAX_3D_TEXTURE_SIZE>())) : sge::opengl::texture::optional_volume_config()) { } sge::opengl::texture::volume_context::~volume_context() = default; sge::opengl::texture::optional_volume_config const & sge::opengl::texture::volume_context::config() const { return config_; } FCPPT_PP_PUSH_WARNING FCPPT_PP_DISABLE_CLANG_WARNING(-Wglobal-constructors) sge::opengl::context::id const sge::opengl::texture::volume_context::static_id(sge::opengl::context::make_id()); FCPPT_PP_POP_WARNING
41.566667
97
0.690858
cpreh
284c93e64f33b04453081861f71ff089c3bc72ea
3,750
cpp
C++
BUPT 2021 Winter Training #8/g.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
1
2022-03-04T15:11:33.000Z
2022-03-04T15:11:33.000Z
BUPT 2021 Winter Training #8/g.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
BUPT 2021 Winter Training #8/g.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define pb push_back #define all(x) (x).begin(), (x).end() #define um unordered_map #define pq priority_queue #define sz(x) ((int)(x).size()) #define fi first #define se second #define endl '\n' typedef vector<int> vi; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; mt19937 mrand(random_device{}()); const ll mod = 1000000007; int rnd(int x) { return mrand() % x;} ll mulmod(ll a, ll b) {ll res = 0; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = (res + a) % mod; a = 2 * a % mod;} return res;} ll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;} ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;} //head const int maxn = 107; int mp[maxn][maxn]; int a[maxn], n, m, s[maxn], h[maxn], vis[maxn], id[maxn]; int ans[maxn], cnt; void init() { //n^2预处理每个英雄能移动的范围 for (int i = 1; i <= m; i++) { mp[s[i]][s[i]] = h[i]; int tmp = h[i]; for (int j = s[i]; j >= 1; j--) { if (tmp < 0) mp[s[i]][j] = -1; else { tmp += a[j]; mp[s[i]][j] = max(-1, tmp); } } tmp = h[i]; for (int j = s[i]; j <= n; j++) { if (tmp < 0) mp[s[i]][j] = -1; else { tmp += a[j]; mp[s[i]][j] = max(-1, tmp); } } } } void print(int x) { //打印答案 printf("%d\n", x); for (int i = 1; i <= m; i++) { if (!vis[i]) ans[++cnt] = i; } for (int i = 1; i < cnt; i++) printf("%d ", ans[i]); printf("%d\n", ans[cnt]); } bool check(int x, int y) { // 查找剩余区间是否有英雄 for (int i = x; i <= y; i++) { if (id[i]) return 0; } return 1; } void solve() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; i++) { scanf("%d%d", &s[i], &h[i]); id[s[i]] = i; } for (int i = 1; i <= n; i++) scanf("%d", &a[i]); init(); a[0] = a[n + 1] = 0; for (int i = 1; i <= n; i++) { //枚举集结点 // 将集结点归在左区间 memset(vis, 0, sizeof vis); int tmp = i; //目前走到的位置 cnt = 0; bool f = 0; //标记集结点是否走过 for (int j = i; j >= 1; j--) { if (id[j] && mp[j][tmp] >= 0) { vis[id[j]] = 1; ans[++cnt] = id[j]; tmp = j - 1; f = 1; } } if (check(0, tmp)) { if (f == 0) tmp = i; else tmp = i + 1; for (int j = tmp; j <= n; j++) { if (id[j] && mp[j][tmp] >= 0) { vis[id[j]] = 1; ans[++cnt] = id[j]; tmp = j + 1; } } if (check(tmp, n + 1)) { print(i); return; } } memset(vis, 0, sizeof vis); cnt = 0; tmp = i; f = 0; for (int j = i; j <= n; j++) { if (id[j] && mp[j][tmp] >= 0) { vis[id[j]] = 1; ans[++cnt] = id[j]; tmp = j + 1; f = 1; } } if (check(tmp, n + 1)) { if (f == 0) tmp = i; else tmp = i - 1; for (int j = tmp; j >= 1; j--) { if (id[j] && mp[j][tmp] >= 0) { vis[id[j]] = 1; ans[++cnt] = id[j]; tmp = j - 1; } } if (check(0, tmp)) { print(i); return; } } } printf("-1\n"); } int main() { int t = 1; // cin >> t; while (t --) solve(); return 0; }
26.785714
144
0.361067
rakty
284f16dd34b55aec400d663164627c30539140ae
3,145
cpp
C++
Sources/Engine/Graphics/Animation/BoneAnimationTrack.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Graphics/Animation/BoneAnimationTrack.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Graphics/Animation/BoneAnimationTrack.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= BoneAnimationTrack.cpp Project: Sonata Engine Author: Julien Delezenne =============================================================================*/ #include "BoneAnimationTrack.h" namespace SonataEngine { BoneAnimationTrack::BoneAnimationTrack() : AnimationTrack(), _bone(NULL) { } BoneAnimationTrack::~BoneAnimationTrack() { } TransformKeyFrame* BoneAnimationTrack::GetBoneKeyFrame(int index) const { return (TransformKeyFrame*)GetKeyFrameByIndex(index); } void BoneAnimationTrack::GetTranslationKeys(BaseArray<KeyVector3>& translationKeys) { KeyFrameList::Iterator it = _keyFrames.GetIterator(); while (it.Next()) { TransformKeyFrame* keyFrame = (TransformKeyFrame*)it.Current(); if ((keyFrame->GetTransformType() & TransformKeyFrameType_Translation) != 0) { translationKeys.Add(KeyVector3(keyFrame->GetTime(), keyFrame->GetTranslation())); } } } void BoneAnimationTrack::GetRotationKeys(BaseArray<KeyQuaternion>& rotationKeys) { KeyFrameList::Iterator it = _keyFrames.GetIterator(); while (it.Next()) { TransformKeyFrame* keyFrame = (TransformKeyFrame*)it.Current(); if ((keyFrame->GetTransformType() & TransformKeyFrameType_Rotation) != 0) { rotationKeys.Add(KeyQuaternion(keyFrame->GetTime(), keyFrame->GetRotation())); } } } void BoneAnimationTrack::GetScaleKeys(BaseArray<KeyVector3>& scaleKeys) { KeyFrameList::Iterator it = _keyFrames.GetIterator(); while (it.Next()) { TransformKeyFrame* keyFrame = (TransformKeyFrame*)it.Current(); if ((keyFrame->GetTransformType() & TransformKeyFrameType_Scale) != 0) { scaleKeys.Add(KeyVector3(keyFrame->GetTime(), keyFrame->GetScale())); } } } KeyFrame* BoneAnimationTrack::_CreateKeyFrame(const TimeValue& timeValue) { return new TransformKeyFrame(timeValue); } void BoneAnimationTrack::Update(const TimeValue& timeValue) { if (_bone == NULL) { return; } KeyFrame* keyA = NULL; KeyFrame* keyB = NULL; TimeValue delta = GetKeyFramesAtTime(timeValue, &keyA, &keyB); if (keyA == NULL || keyB == NULL) { return; } real64 t = 0.0; if (timeValue != keyA->GetTime()) { t = (real64)(delta / (timeValue - keyA->GetTime())); } TransformKeyFrame* key1 = (TransformKeyFrame*)keyA; TransformKeyFrame* key2 = (TransformKeyFrame*)keyB; if ((key1->GetTransformType() & TransformKeyFrameType_Translation) != 0 && (key2->GetTransformType() & TransformKeyFrameType_Translation) != 0) { Vector3 translation = Vector3::Lerp(key1->GetTranslation(), key2->GetTranslation(), t); _bone->SetLocalPosition(translation); } if ((key1->GetTransformType() & TransformKeyFrameType_Rotation) != 0 && (key2->GetTransformType() & TransformKeyFrameType_Rotation) != 0) { Quaternion rotation = Quaternion::Slerp(key1->GetRotation(), key2->GetRotation(), t); _bone->SetLocalOrientation(rotation); } if ((key1->GetTransformType() & TransformKeyFrameType_Scale) != 0 && (key2->GetTransformType() & TransformKeyFrameType_Scale) != 0) { Vector3 scale = Vector3::Lerp(key1->GetScale(), key2->GetScale(), t); _bone->SetLocalScale(scale); } } }
26.880342
89
0.693482
jdelezenne
285082af97ca0675bcb91be02292f414112c6b5a
19,427
cpp
C++
3rdParty/fuerte/src/VstConnection.cpp
William533036/arangodb
e939a72607aec46fc93f4ea5f1149a9d15a3da9d
[ "Apache-2.0" ]
1
2020-01-16T06:16:53.000Z
2020-01-16T06:16:53.000Z
3rdParty/fuerte/src/VstConnection.cpp
William533036/arangodb
e939a72607aec46fc93f4ea5f1149a9d15a3da9d
[ "Apache-2.0" ]
null
null
null
3rdParty/fuerte/src/VstConnection.cpp
William533036/arangodb
e939a72607aec46fc93f4ea5f1149a9d15a3da9d
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016-2018 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Christoph Uhde /// @author Ewout Prangsma /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include "VstConnection.h" #include "Basics/cpu-relax.h" #include <fuerte/FuerteLogger.h> #include <fuerte/helper.h> #include <fuerte/loop.h> #include <fuerte/message.h> #include <fuerte/types.h> #include <velocypack/velocypack-aliases.h> namespace arangodb { namespace fuerte { inline namespace v1 { namespace vst { namespace fu = arangodb::fuerte::v1; using arangodb::fuerte::v1::SocketType; template <SocketType ST> VstConnection<ST>::VstConnection( EventLoopService& loop, fu::detail::ConnectionConfiguration const& config) : fuerte::GeneralConnection<ST>(loop, config), _writeQueue(), _vstVersion(config._vstVersion), _reading(false), _writing(false) {} template <SocketType ST> VstConnection<ST>::~VstConnection() try { this->shutdownConnection(Error::Canceled); drainQueue(Error::Canceled); } catch(...) {} static std::atomic<MessageID> vstMessageId(1); // sendRequest prepares a RequestItem for the given parameters // and adds it to the send queue. template <SocketType ST> MessageID VstConnection<ST>::sendRequest(std::unique_ptr<Request> req, RequestCallback cb) { // it does not matter if IDs are reused on different connections uint64_t mid = vstMessageId.fetch_add(1, std::memory_order_relaxed); // Create RequestItem from parameters auto item = std::make_unique<RequestItem>(); item->_messageID = mid; item->_request = std::move(req); item->_callback = cb; item->_expires = std::chrono::steady_clock::time_point::max(); // Add item to send queue if (!_writeQueue.push(item.get())) { FUERTE_LOG_ERROR << "connection queue capacity exceeded\n"; item->invokeOnError(Error::QueueCapacityExceeded); return 0; } item.release(); // queue owns this now this->_numQueued.fetch_add(1, std::memory_order_relaxed); FUERTE_LOG_VSTTRACE << "queued item: this=" << this << "\n"; // _state.load() after queuing request, to prevent race with connect Connection::State state = this->_state.load(std::memory_order_acquire); if (state == Connection::State::Connected) { FUERTE_LOG_VSTTRACE << "sendRequest (vst): start sending & reading\n"; startWriting(); // try to start write loop } else if (state == Connection::State::Disconnected) { FUERTE_LOG_VSTTRACE << "sendRequest (vst): not connected\n"; this->startConnection(); } else if (state == Connection::State::Failed) { FUERTE_LOG_ERROR << "queued request on failed connection\n"; drainQueue(fuerte::Error::ConnectionClosed); } return mid; } template <SocketType ST> std::size_t VstConnection<ST>::requestsLeft() const { uint32_t qd = this->_numQueued.load(std::memory_order_relaxed); if (_reading.load() || _writing.load()) { qd++; } return qd; } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- // socket connection is up (with optional SSL), now initiate the VST protocol. template <SocketType ST> void VstConnection<ST>::finishConnect() { FUERTE_LOG_VSTTRACE << "finishInitialization (vst)\n"; const char* vstHeader; switch (_vstVersion) { case VST1_0: vstHeader = "VST/1.0\r\n\r\n"; break; case VST1_1: vstHeader = "VST/1.1\r\n\r\n"; break; default: throw std::logic_error("Unknown VST version"); } auto self = Connection::shared_from_this(); asio_ns::async_write( this->_proto.socket, asio_ns::buffer(vstHeader, strlen(vstHeader)), [self](asio_ns::error_code const& ec, std::size_t nsend) { auto* thisPtr = static_cast<VstConnection<ST>*>(self.get()); if (ec) { FUERTE_LOG_ERROR << ec.message() << "\n"; thisPtr->shutdownConnection(Error::CouldNotConnect, "unable to connect: " + ec.message()); thisPtr->drainQueue(Error::CouldNotConnect); return; } FUERTE_LOG_VSTTRACE << "VST connection established\n"; if (thisPtr->_config._authenticationType != AuthenticationType::None) { // send the auth, then set _state == connected thisPtr->sendAuthenticationRequest(); } else { thisPtr->_state.store(Connection::State::Connected, std::memory_order_release); thisPtr->startWriting(); // start writing if something is queued } }); } // Send out the authentication message on this connection template <SocketType ST> void VstConnection<ST>::sendAuthenticationRequest() { assert(this->_config._authenticationType != AuthenticationType::None); // Part 1: Build ArangoDB VST auth message (1000) auto item = std::make_shared<RequestItem>(); item->_messageID = vstMessageId.fetch_add(1, std::memory_order_relaxed); item->_expires = std::chrono::steady_clock::now() + Request::defaultTimeout; auto self = Connection::shared_from_this(); item->_callback = [self](Error error, std::unique_ptr<Request>, std::unique_ptr<Response> resp) { auto* thisPtr = static_cast<VstConnection<ST>*>(self.get()); if (error != Error::NoError || resp->statusCode() != StatusOK) { thisPtr->_state.store(Connection::State::Failed, std::memory_order_release); thisPtr->shutdownConnection(Error::VstUnauthorized, "could not authenticate"); thisPtr->drainQueue(Error::VstUnauthorized); } else { thisPtr->_state.store(Connection::State::Connected); thisPtr->startWriting(); } }; _messageStore.add(item); // add message to store if (this->_config._authenticationType == AuthenticationType::Basic) { vst::message::authBasic(this->_config._user, this->_config._password, item->_buffer); } else if (this->_config._authenticationType == AuthenticationType::Jwt) { vst::message::authJWT(this->_config._jwtToken, item->_buffer); } assert(item->_buffer.size() < defaultMaxChunkSize); // actually send auth request auto cb = [this, self, item](asio_ns::error_code const& ec, std::size_t nsend) { if (ec) { this->_state.store(Connection::State::Failed); this-> shutdownConnection(Error::CouldNotConnect, "authorization message failed"); this->drainQueue(Error::CouldNotConnect); } else { asyncWriteCallback(ec, item, nsend); } }; std::vector<asio_ns::const_buffer> buffers; vst::message::prepareForNetwork(_vstVersion, item->messageID(), item->_buffer, /*payload*/ asio_ns::const_buffer(), buffers); asio_ns::async_write(this->_proto.socket, buffers, std::move(cb)); setTimeout(); } // ------------------------------------ // Writing data // ------------------------------------ // Thread-Safe: activate the writer loop (if off and items are queud) template <SocketType ST> void VstConnection<ST>::startWriting() { assert(this->_state.load(std::memory_order_acquire) == Connection::State::Connected); FUERTE_LOG_VSTTRACE << "startWriting: this=" << this << "\n"; if (_writing.load() || _writing.exchange(true)) { return; // There is already a write loop, do nothing } // we are the only ones here now FUERTE_LOG_HTTPTRACE << "startWriting: active=true, this=" << this << "\n"; asio_ns::post(*this->_io_context, [self = Connection::shared_from_this(), this] { // we have been in a race with shutdownConnection() Connection::State state = this->_state.load(); if (state != Connection::State::Connected) { this->_writing.store(false); if (state == Connection::State::Disconnected) { this->startConnection(); } } else { this->asyncWriteNextRequest(); } }); } // writes data from task queue to network using asio_ns::async_write template <SocketType ST> void VstConnection<ST>::asyncWriteNextRequest() { FUERTE_LOG_VSTTRACE << "asyncWrite: preparing to send next\n"; while(true) { // loop instead of recursion RequestItem* ptr = nullptr; if (!_writeQueue.pop(ptr)) { FUERTE_LOG_VSTTRACE << "asyncWriteNextRequest (vst): write queue empty\n"; // careful now, we need to consider that someone queues // a new request item _writing.store(false); if (_writeQueue.empty()) { FUERTE_LOG_VSTTRACE << "asyncWriteNextRequest (vst): write stopped\n"; break; // done, someone else may restart } bool expected = false; // may fail in a race if (_writing.compare_exchange_strong(expected, true)) { continue; // we re-start writing } assert(expected == true); break; // someone else restarted writing } this->_numQueued.fetch_sub(1, std::memory_order_relaxed); std::shared_ptr<RequestItem> item(ptr); // set the point-in-time when this request expires if (item->_request && item->_request->timeout().count() > 0) { item->_expires = std::chrono::steady_clock::now() + item->_request->timeout(); } _messageStore.add(item); // Add item to message store setTimeout(); // prepare request / connection timeouts asio_ns::async_write(this->_proto.socket, item->prepareForNetwork(_vstVersion), [self = Connection::shared_from_this(), req(item)] (asio_ns::error_code const& ec, std::size_t nwrite) mutable { auto& thisPtr = static_cast<VstConnection<ST>&>(*self); thisPtr.asyncWriteCallback(ec, std::move(req), nwrite); }); break; // done } FUERTE_LOG_VSTTRACE << "asyncWrite: done\n"; } // callback of async_write function that is called in sendNextRequest. template <SocketType ST> void VstConnection<ST>::asyncWriteCallback(asio_ns::error_code const& ec, std::shared_ptr<RequestItem> item, std::size_t nwrite) { // auto pendingAsyncCalls = --_connection->_async_calls; if (ec) { // Send failed FUERTE_LOG_VSTTRACE << "asyncWriteCallback: error " << ec.message() << "\n"; // Item has failed, remove from message store _messageStore.removeByID(item->_messageID); auto err = translateError(ec, Error::WriteError); try { // let user know that this request caused the error item->_callback(err, std::move(item->_request), nullptr); } catch(...) {} // Stop current connection and try to restart a new one. this->restartConnection(err); return; } // Send succeeded FUERTE_LOG_VSTTRACE << "asyncWriteCallback: send succeeded, " << nwrite << " bytes send\n"; // request is written we no longer need data for that item->resetSendData(); startReading(); // Make sure we're listening for a response // Continue with next request (if any) asyncWriteNextRequest(); // continue writing } // ------------------------------------ // Reading data // ------------------------------------ // Thread-Safe: activate the read loop (if needed) template <SocketType ST> void VstConnection<ST>::startReading() { FUERTE_LOG_VSTTRACE << "startReading: this=" << this << "\n"; if (_reading.load() || _reading.exchange(true)) { return; // There is already a read loop, do nothing } FUERTE_LOG_VSTTRACE << "startReading: active=true, this=" << this << "\n"; this->asyncReadSome(); } // asyncReadCallback is called when asyncReadSome is resulting in some data. template <SocketType ST> void VstConnection<ST>::asyncReadCallback(asio_ns::error_code const& ec) { if (ec) { FUERTE_LOG_VSTTRACE << "asyncReadCallback: Error while reading form socket: " << ec.message(); this->restartConnection(translateError(ec, Error::ReadError)); return; } // Inspect the data we've received so far. auto recvBuffs = this->_receiveBuffer.data(); // no copy auto cursor = asio_ns::buffer_cast<const uint8_t*>(recvBuffs); auto available = asio_ns::buffer_size(recvBuffs); // TODO technically buffer_cast is deprecated size_t parsedBytes = 0; while (true) { Chunk chunk; parser::ChunkState state = parser::ChunkState::Invalid; if (_vstVersion == VST1_1) { state = vst::parser::readChunkVST1_1(chunk, cursor, available); } else if (_vstVersion == VST1_0) { state = vst::parser::readChunkVST1_0(chunk, cursor, available); } if (parser::ChunkState::Incomplete == state) { break; } else if (parser::ChunkState::Invalid == state) { this->shutdownConnection(Error::ProtocolError, "Invalid VST chunk"); return; } // move cursors cursor += chunk.header.chunkLength(); available -= chunk.header.chunkLength(); parsedBytes += chunk.header.chunkLength(); // Process chunk processChunk(chunk); } // Remove consumed data from receive buffer. this->_receiveBuffer.consume(parsedBytes); // check for more messages that could arrive if (_messageStore.empty()/* && !_writing.load()*/) { FUERTE_LOG_VSTTRACE << "shouldStopReading: no more pending " "messages/requests, stopping read"; _reading.store(false); return; // write-loop restarts read-loop if necessary } assert(_reading.load()); this->asyncReadSome(); // Continue read loop } // Process the given incoming chunk. template <SocketType ST> void VstConnection<ST>::processChunk(Chunk const& chunk) { auto msgID = chunk.header.messageID(); FUERTE_LOG_VSTTRACE << "processChunk: messageID=" << msgID << "\n"; // Find requestItem for this chunk. auto item = _messageStore.findByID(chunk.header.messageID()); if (!item) { FUERTE_LOG_ERROR << "got chunk with unknown message ID: " << msgID << "\n"; return; } // We've found the matching RequestItem. item->addChunk(chunk); // Try to assembly chunks in RequestItem to complete response. auto completeBuffer = item->assemble(); if (completeBuffer) { FUERTE_LOG_VSTTRACE << "processChunk: complete response received\n"; this->_timeout.cancel(); // Message is complete // Remove message from store _messageStore.removeByID(item->_messageID); try { // Create response auto resp = createResponse(*item, completeBuffer); auto err = resp != nullptr ? Error::NoError : Error::ProtocolError; item->_callback(err, std::move(item->_request), std::move(resp)); } catch(...) { FUERTE_LOG_ERROR << "unhandled exception in fuerte callback\n"; } setTimeout(); // readjust timeout } } // Create a response object for given RequestItem & received response buffer. template <SocketType ST> std::unique_ptr<fu::Response> VstConnection<ST>::createResponse( RequestItem& item, std::unique_ptr<VPackBuffer<uint8_t>>& responseBuffer) { FUERTE_LOG_VSTTRACE << "creating response for item with messageid: " << item._messageID << "\n"; auto itemCursor = responseBuffer->data(); auto itemLength = responseBuffer->byteSize(); // first part of the buffer contains the response buffer std::size_t headerLength; MessageType type = parser::validateAndExtractMessageType( itemCursor, itemLength, headerLength); if (type != MessageType::Response) { FUERTE_LOG_ERROR << "received unsupported vst message from server"; return nullptr; } ResponseHeader header = parser::responseHeaderFromSlice(VPackSlice(itemCursor)); auto response = std::make_unique<Response>(std::move(header)); response->setPayload(std::move(*responseBuffer), /*offset*/ headerLength); return response; } // adjust the timeouts (only call from IO-Thread) template <SocketType ST> void VstConnection<ST>::setTimeout() { // set to smallest point in time auto expires = std::chrono::steady_clock::time_point::max(); size_t waiting = _messageStore.invokeOnAll([&](RequestItem* item) { if (expires > item->_expires) { expires = item->_expires; } return true; }); if (waiting == 0) { // use default connection timeout expires = std::chrono::steady_clock::now() + this->_config._idleTimeout; } this->_timeout.expires_at(expires); this->_timeout.async_wait([self = Connection::weak_from_this()](asio_ns::error_code const& ec) { std::shared_ptr<Connection> s; if (ec || !(s = self.lock())) { // was canceled / deallocated return; } auto* thisPtr = static_cast<VstConnection<ST>*>(s.get()); // cancel expired requests auto now = std::chrono::steady_clock::now(); size_t waiting = thisPtr->_messageStore.invokeOnAll([&](RequestItem* item) { if (item->_expires < now) { FUERTE_LOG_DEBUG << "VST-Request timeout\n"; item->invokeOnError(Error::Timeout); return false; // remove } return true; }); if (waiting == 0) { // no more messages to wait on FUERTE_LOG_DEBUG << "VST-Connection timeout\n"; thisPtr->shutdownConnection(Error::Timeout); } else { thisPtr->setTimeout(); } }); } /// abort ongoing / unfinished requests template <SocketType ST> void VstConnection<ST>::abortOngoingRequests(const fuerte::Error err) { FUERTE_LOG_VSTTRACE << "aborting ongoing requests"; // Reset the read & write loop // Cancel all items and remove them from the message store. if (err != Error::VstUnauthorized) { // prevents stack overflow _messageStore.cancelAll(err); } _reading.store(false); _writing.store(false); } /// abort all requests lingering in the queue template <SocketType ST> void VstConnection<ST>::drainQueue(const fuerte::Error ec) { RequestItem* item = nullptr; while (_writeQueue.pop(item)) { std::unique_ptr<RequestItem> guard(item); this->_numQueued.fetch_sub(1, std::memory_order_relaxed); guard->invokeOnError(ec); } } template class arangodb::fuerte::v1::vst::VstConnection<SocketType::Tcp>; template class arangodb::fuerte::v1::vst::VstConnection<SocketType::Ssl>; #ifdef ASIO_HAS_LOCAL_SOCKETS template class arangodb::fuerte::v1::vst::VstConnection<SocketType::Unix>; #endif }}}} // namespace arangodb::fuerte::v1::vst
35.45073
98
0.643126
William533036
285cd60c93534323ea5591c57277389fa8ba8d0b
3,371
cpp
C++
Code/Engine/Renderer/Material/RenderState.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Renderer/Material/RenderState.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Renderer/Material/RenderState.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#include "Engine/Renderer/Material/RenderState.hpp" #include "Engine/Renderer/Renderer/BeirusRenderer.hpp" STATIC const RenderState RenderState::RENDER_STATE_DEFAULT( DEPTH_MODE_ON, BLEND_MODE_OPAQUE, CULL_FACE_FRONT, WRITES_DEPTH_ON, WRITES_COLOR_ON, CASTS_SHADOWS_ON); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //ENABLE DISABLE ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- void RenderState::EnableRenderState() { ///////////////////////////////////////////////////////////// //--------------------------------- //DEPTH MODE /** eDepthMode mode = m_depthMode; if (m_depthMode == DEPTH_MODE_DEFAULT) { mode = DEFAULT_DEPTH_MODE; } switch (mode) { case DEPTH_MODE_OFF: { BeirusRenderer::DisableDepthTesting(); break; } case DEPTH_MODE_ON: { BeirusRenderer::EnableDepthTesting(); break; } case DEPTH_MODE_DUAL: { //TODO: IMPLEMENT DUAL DEPTH TEST MODE (Requires two passes) break; } default: { break; } } */ ///////////////////////////////////////////////////////////// //--------------------------------- //BLEND MODE - Opaque is checked in render passes eBlendMode blendMode = m_blendMode; if (blendMode == BLEND_MODE_DEFAULT) { blendMode = DEFAULT_BLEND_MODE; } switch (blendMode) { case BLEND_MODE_TRANSPARENT_ADDITIVE: { BeirusRenderer::EnableBlending(); BeirusRenderer::BlendMode(GL_SRC_ALPHA, GL_ONE); break; } case BLEND_MODE_TRANSPARENT_DEFAULT: { BeirusRenderer::EnableBlending(); BeirusRenderer::BlendMode(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } case BLEND_MODE_OPAQUE: { BeirusRenderer::DisableBlending(); } //TODO: IMPLEMENT THE OTHER BLEND MODES default: { break; } } /* ///////////////////////////////////////////////////////////// //--------------------------------- //CULL FACE eCullFace cullFace = m_cullFace; if (cullFace == CULL_FACE_DEFAULT) { cullFace = DEFAULT_CULL_FACE; } switch (cullFace) { case CULL_FACE_FRONT: { BeirusRenderer::SetCullFace(true); break; } case CULL_FACE_BACK: { BeirusRenderer::SetCullFace(false); break; } default: { break; } } ///////////////////////////////////////////////////////////// //--------------------------------- //WRITES DEPTH eWritesDepth writesDepth = m_writesDepth; if (writesDepth == WRITES_DEPTH_DEFAULT) { writesDepth = DEFAULT_WRITES_DEPTH; } switch (writesDepth) { case WRITES_DEPTH_ON: { BeirusRenderer::EnableDepthWriting(); break; } case WRITES_DEPTH_OFF: { BeirusRenderer::DisableDepthWriting(); break; } default: { break; } } ///////////////////////////////////////////////////////////// //--------------------------------- //WRITES COLORS eWritesColor writesColor = m_writesColor; if (writesColor == WRITES_COLOR_DEFAULT) { writesColor = DEFAULT_WRITES_COLOR; } switch (writesColor) { case WRITES_COLOR_ON: { BeirusRenderer::EnableColorWriting(); break; } case WRITES_COLOR_OFF: { BeirusRenderer::DisableColorWriting(); break; } default: { break; } } */ //Casts shadows is a check when rendering depth }
23.248276
125
0.53367
ntaylorbishop
285e4fdd377a76451175d18029ae85b0060da577
6,701
cpp
C++
src/transactions/OperationFrame.cpp
iotbda/iotchain-core
74094a7853d2591cdfa79aa4a9459f6036008b2d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/transactions/OperationFrame.cpp
iotbda/iotchain-core
74094a7853d2591cdfa79aa4a9459f6036008b2d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/transactions/OperationFrame.cpp
iotbda/iotchain-core
74094a7853d2591cdfa79aa4a9459f6036008b2d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "transactions/OperationFrame.h" #include "transactions/AllowTrustOpFrame.h" #include "transactions/BumpSequenceOpFrame.h" #include "transactions/ChangeTrustOpFrame.h" #include "transactions/CreateAccountOpFrame.h" #include "transactions/CreatePassiveSellOfferOpFrame.h" #include "transactions/InflationOpFrame.h" #include "transactions/ManageBuyOfferOpFrame.h" #include "transactions/ManageDataOpFrame.h" #include "transactions/ManageSellOfferOpFrame.h" #include "transactions/MergeOpFrame.h" #include "transactions/PathPaymentOpFrame.h" #include "transactions/PaymentOpFrame.h" #include "transactions/SetOptionsOpFrame.h" #include "transactions/TransactionFrame.h" #include "util/Logging.h" #include <xdrpp/printer.h> namespace iotchain { using namespace std; static int32_t getNeededThreshold(LedgerTxnEntry const& account, ThresholdLevel const level) { auto const& acc = account.current().data.account(); switch (level) { case ThresholdLevel::LOW: return acc.thresholds[THRESHOLD_LOW]; case ThresholdLevel::MEDIUM: return acc.thresholds[THRESHOLD_MED]; case ThresholdLevel::HIGH: return acc.thresholds[THRESHOLD_HIGH]; default: abort(); } } shared_ptr<OperationFrame> OperationFrame::makeHelper(Operation const& op, OperationResult& res, TransactionFrame& tx) { switch (op.body.type()) { case CREATE_ACCOUNT: return std::make_shared<CreateAccountOpFrame>(op, res, tx); case PAYMENT: return std::make_shared<PaymentOpFrame>(op, res, tx); case PATH_PAYMENT: return std::make_shared<PathPaymentOpFrame>(op, res, tx); case MANAGE_SELL_OFFER: return std::make_shared<ManageSellOfferOpFrame>(op, res, tx); case CREATE_PASSIVE_SELL_OFFER: return std::make_shared<CreatePassiveSellOfferOpFrame>(op, res, tx); case SET_OPTIONS: return std::make_shared<SetOptionsOpFrame>(op, res, tx); case CHANGE_TRUST: return std::make_shared<ChangeTrustOpFrame>(op, res, tx); case ALLOW_TRUST: return std::make_shared<AllowTrustOpFrame>(op, res, tx); case ACCOUNT_MERGE: return std::make_shared<MergeOpFrame>(op, res, tx); case INFLATION: return std::make_shared<InflationOpFrame>(op, res, tx); case MANAGE_DATA: return std::make_shared<ManageDataOpFrame>(op, res, tx); case BUMP_SEQUENCE: return std::make_shared<BumpSequenceOpFrame>(op, res, tx); case MANAGE_BUY_OFFER: return std::make_shared<ManageBuyOfferOpFrame>(op, res, tx); default: ostringstream err; err << "Unknown Tx type: " << op.body.type(); throw std::invalid_argument(err.str()); } } OperationFrame::OperationFrame(Operation const& op, OperationResult& res, TransactionFrame& parentTx) : mOperation(op), mParentTx(parentTx), mResult(res) { } bool OperationFrame::apply(SignatureChecker& signatureChecker, AbstractLedgerTxn& ltx) { bool res; if (Logging::logTrace("Tx")) { CLOG(TRACE, "Tx") << "Operation: " << xdr::xdr_to_string(mOperation); } res = checkValid(signatureChecker, ltx, true); if (res) { res = doApply(ltx); if (Logging::logTrace("Tx")) { CLOG(TRACE, "Tx") << "Operation result: " << xdr::xdr_to_string(mResult); } } return res; } ThresholdLevel OperationFrame::getThresholdLevel() const { return ThresholdLevel::MEDIUM; } bool OperationFrame::isVersionSupported(uint32_t) const { return true; } bool OperationFrame::checkSignature(SignatureChecker& signatureChecker, AbstractLedgerTxn& ltx, bool forApply) { auto header = ltx.loadHeader(); auto sourceAccount = loadSourceAccount(ltx, header); if (sourceAccount) { auto neededThreshold = getNeededThreshold(sourceAccount, getThresholdLevel()); if (!mParentTx.checkSignature(signatureChecker, sourceAccount, neededThreshold)) { mResult.code(opBAD_AUTH); return false; } } else { if (forApply || !mOperation.sourceAccount) { mResult.code(opNO_ACCOUNT); return false; } if (!mParentTx.checkSignatureNoAccount(signatureChecker, *mOperation.sourceAccount)) { mResult.code(opBAD_AUTH); return false; } } return true; } AccountID const& OperationFrame::getSourceID() const { return mOperation.sourceAccount ? *mOperation.sourceAccount : mParentTx.getEnvelope().tx.sourceAccount; } OperationResultCode OperationFrame::getResultCode() const { return mResult.code(); } // called when determining if we should accept this operation. // called when determining if we should flood // make sure sig is correct // verifies that the operation is well formed (operation specific) bool OperationFrame::checkValid(SignatureChecker& signatureChecker, AbstractLedgerTxn& ltxOuter, bool forApply) { // Note: ltx is always rolled back so checkValid never modifies the ledger LedgerTxn ltx(ltxOuter); auto ledgerVersion = ltx.loadHeader().current().ledgerVersion; if (!isVersionSupported(ledgerVersion)) { mResult.code(opNOT_SUPPORTED); return false; } if (!forApply || ledgerVersion < 10) { if (!checkSignature(signatureChecker, ltx, forApply)) { return false; } } else { // for ledger versions >= 10 we need to load account here, as for // previous versions it is done in checkSignature call if (!loadSourceAccount(ltx, ltx.loadHeader())) { mResult.code(opNO_ACCOUNT); return false; } } mResult.code(opINNER); mResult.tr().type(mOperation.body.type()); return doCheckValid(ledgerVersion); } LedgerTxnEntry OperationFrame::loadSourceAccount(AbstractLedgerTxn& ltx, LedgerTxnHeader const& header) { return mParentTx.loadAccount(ltx, header, getSourceID()); } void OperationFrame::insertLedgerKeysToPrefetch( std::unordered_set<LedgerKey>& keys) const { // Do nothing by default return; } }
29.134783
79
0.659155
iotbda
285e88a80a5c8f52c1a1420d50cc2fec918e435b
17,837
cpp
C++
electroslag/serialize/database.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
1
2018-08-19T11:06:17.000Z
2018-08-19T11:06:17.000Z
electroslag/serialize/database.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
electroslag/serialize/database.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
// Electroslag Interactive Graphics System // Copyright 2018 Joshua Buckman // // 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 "electroslag/precomp.hpp" #include "electroslag/file_stream.hpp" #include "electroslag/systems.hpp" #include "electroslag/logger.hpp" #include "electroslag/resource.hpp" #include "electroslag/resource_id.hpp" #include "electroslag/buffer_stream.hpp" #include "electroslag/serialize/serializable_type_registration.hpp" #include "electroslag/serialize/serializable_name_table.hpp" #include "electroslag/serialize/binary_archive.hpp" #if !defined(ELECTROSLAG_BUILD_SHIP) #include "electroslag/serialize/json_archive.hpp" #endif #include "electroslag/serialize/importer_interface.hpp" namespace electroslag { namespace serialize { database* get_database() { return (get_systems()->get_database()); } database::database() : m_mutex(ELECTROSLAG_STRING_AND_HASH("m:database")) {} database::~database() {} void database::register_serializable_type( unsigned long long name_hash, serializable_type_registration* const type ) { threading::lock_guard object_db_lock(&m_mutex); m_serializable_type_table.insert(std::make_pair(name_hash, type)); } load_record::ref database::create_load_record() { // Create an empty load record to be populated and then used / saved. load_record::ref load = load_record::create(); { threading::lock_guard object_db_lock(&m_mutex); m_load_records.emplace_back(load); } return (load); } load_record::ref database::load_objects(std::string const& file_name) { ELECTROSLAG_LOG_SERIALIZE("Loading objects from binary %s.", file_name.c_str()); file_stream db; db.open(file_name, file_stream_access_mode_read); std::filesystem::path dir(file_name); dir = std::filesystem::canonical(dir); dir = dir.remove_filename(); // Use the directory containing the archive file as the base directory. return (load_objects(&db, dir.string())); } load_record::ref database::load_objects(std::string const& file_name, std::string const& base_directory) { ELECTROSLAG_LOG_SERIALIZE("Loading objects from binary %s.", file_name.c_str()); file_stream db; db.open(file_name, file_stream_access_mode_read); return (load_objects(&db, base_directory)); } load_record::ref database::load_objects(stream_interface* s, std::string const& base_directory) { binary_archive_reader ar(s); ar.set_base_directory(base_directory); return (load_from_archive(&ar)); } load_record::ref database::load_objects( referenced_buffer_interface::ref const& buffer_ref, std::string const& base_directory ) { buffer_stream b(buffer_ref); return (load_objects(&b, base_directory)); } #if !defined(ELECTROSLAG_BUILD_SHIP) load_record::ref database::load_objects_json(std::string const& file_name) { ELECTROSLAG_LOG_SERIALIZE("Loading objects from json %s.", file_name.c_str()); file_stream db; db.open(file_name, file_stream_access_mode_read); std::filesystem::path dir(file_name); dir = std::filesystem::canonical(dir); dir = dir.remove_filename(); // Use the directory containing the archive file as the base directory. return (load_objects_json(&db, dir.string())); } load_record::ref database::load_objects_json( std::string const& file_name, std::string const& base_directory ) { ELECTROSLAG_LOG_SERIALIZE("Loading objects from json %s.", file_name.c_str()); file_stream db; db.open(file_name, file_stream_access_mode_read); return (load_objects_json(&db, base_directory)); } load_record::ref database::load_objects_json( stream_interface* s, std::string const& base_directory ) { json_archive_reader ar(s); ar.set_base_directory(base_directory); return (load_from_archive(&ar)); } load_record::ref database::load_objects_json( referenced_buffer_interface::ref const& buffer_ref, std::string const& base_directory ) { buffer_stream b(buffer_ref); return (load_objects_json(&b, base_directory)); } void database::save_objects(std::string const& file_name, load_record::ref& record) { ELECTROSLAG_LOG_SERIALIZE("Saving objects to binary %s.", file_name.c_str()); file_stream db; db.create_new(file_name, file_stream_access_mode_write); save_objects(&db, record); } void database::save_objects(stream_interface* s, load_record::ref& record) { binary_archive_writer ar(s); save_to_archive(&ar, record); } void database::save_objects( referenced_buffer_interface::ref const& buffer_ref, load_record::ref& record ) { buffer_stream b(buffer_ref); return (save_objects(&b, record)); } void database::save_objects_json(std::string const& file_name, load_record::ref& record) { ELECTROSLAG_LOG_SERIALIZE("Saving objects to json %s.", file_name.c_str()); file_stream db; db.create_new(file_name, file_stream_access_mode_write); save_objects_json(&db, record); } void database::save_objects_json(stream_interface* s, load_record::ref& record) { json_archive_writer ar(s); save_to_archive(&ar, record); } void database::save_objects_json( referenced_buffer_interface::ref const& buffer_ref, load_record::ref& record ) { buffer_stream b(buffer_ref); return (save_objects_json(&b, record)); } #endif serializable_object_interface* database::find_object(unsigned long long name_hash) const { threading::lock_guard object_db_lock(&m_mutex); return (m_object_table.at(name_hash)); } serializable_object_interface* database::locate_object(unsigned long long name_hash) const { threading::lock_guard object_db_lock(&m_mutex); object_table::const_iterator found_object = m_object_table.find(name_hash); if (found_object != m_object_table.end()) { return (found_object->second); } else { return (0); } } void database::clear_objects(load_record::ref& record) { threading::lock_guard object_db_lock(&m_mutex); if (record.is_valid()) { serializable_object_interface* obj = record->get_loaded_object_head(); while (obj != 0) { m_object_table.erase(obj->get_hash()); obj = obj->get_next_loaded_object(); } m_load_records.erase(std::remove(m_load_records.begin(), m_load_records.end(), record), m_load_records.end()); record.reset(); } else { m_object_table.clear(); m_load_records.clear(); } } void database::iterate_objects(iterate_object_delegate* iterator) { threading::lock_guard object_db_lock(&m_mutex); object_table::iterator o(m_object_table.begin()); while (o != m_object_table.end()) { if (!iterator->invoke(o->second)) { break; } ++o; } } load_record::ref database::load_from_archive(archive_reader_interface* ar) { load_record::ref load = load_record::create(); // Prepare the archive reader. ELECTROSLAG_CHECK(!ar->get_base_directory().empty()); ar->set_load_record(load); // Read the archive; create objects into the load record. unsigned long long type_hash = 0; unsigned long long name_hash = 0; while (ar->next_object(&type_hash, &name_hash)) { serializable_type_registration const* type = find_type(type_hash); ELECTROSLAG_CHECK(type); ELECTROSLAG_LOG_SERIALIZE("Loading [0x%016llX], Type %s [0x%016llX]", name_hash, type->get_name().c_str(), type_hash ); serializable_object_interface* new_obj = type->get_create_delegate()->invoke(ar); if (type != serializable_name_table::get_type_registration()) { new_obj->set_hash(name_hash); load->insert_object( new_obj, type->is_referenced() ? load_record::loaded_object_is_referenced_yes : load_record::loaded_object_is_referenced_no ); } else { // The name table object is special; we only care about the persistent // side-effects of creation; not the object itself. delete new_obj; } } ar->clear_load_record(); // Save a reference to the load_record. { threading::lock_guard object_db_lock(&m_mutex); m_load_records.emplace_back(load); } return (load); } #if !defined(ELECTROSLAG_BUILD_SHIP) void database::save_to_archive(archive_writer_interface* ar, load_record::ref& record) { // Locate all importers in the objects to be saved. These must all finish // before saving can occur. typedef std::vector<importer_interface::ref> importer_pointer_vector; importer_pointer_vector importers; { threading::lock_guard object_db_lock(&m_mutex); if (record.is_valid()) { serializable_object_interface* obj = record->get_loaded_object_head(); while (obj != 0) { if (is_importer(obj)) { importers.emplace_back(dynamic_cast<importer_interface*>(obj)); } obj = obj->get_next_loaded_object(); } } else { object_table::iterator o(m_object_table.begin()); while (o != m_object_table.end()) { if (is_importer(o->second)) { importers.emplace_back(dynamic_cast<importer_interface*>(o->second)); } ++o; } } } // The db lock is now dropped to allow importers to finish. importer_pointer_vector::iterator i(importers.begin()); while (i != importers.end()) { (*i)->finish_importing(); ++i; } importers.clear(); // Prepare the archive reader. ar->set_load_record(record); // Reacquire the database lock to save all of the objects. { threading::lock_guard object_db_lock(&m_mutex); if (record.is_valid()) { serializable_object_interface* obj = record->get_loaded_object_head(); while (obj != 0) { save_object(obj, ar); obj = obj->get_next_loaded_object(); } } else { object_table::iterator o(m_object_table.begin()); while (o != m_object_table.end()) { save_object(o->second, ar); ++o; } } // Now, write the string form of the names of the objects. serializable_name_table* name_table = new serializable_name_table(); ELECTROSLAG_CHECK(name_table); // Temporarily insert the name table into the load record to save. record->insert_object(name_table); save_object(name_table, ar); record->remove_object(name_table); // deletes the object too. } // Cleanup to finish. ar->clear_load_record(); } bool database::is_importer(serializable_object_interface const* obj) const { unsigned long long type_hash = obj->get_type_hash(); serializable_type_registration const* type = find_type(type_hash); ELECTROSLAG_CHECK(type); return (type->is_importer()); } void database::save_object(serializable_object_interface* obj, archive_writer_interface* ar) const { unsigned long long type_hash = obj->get_type_hash(); serializable_type_registration const* type = find_type(type_hash); ELECTROSLAG_CHECK(type); ELECTROSLAG_LOG_SERIALIZE("Saving %s [0x%016llX], Type %s [0x%016llX]", (obj->has_name_string() ? obj->get_name().c_str() : "<unnamed>"), obj->get_hash(), type->get_name().c_str(), type_hash ); obj->save_to_archive(ar); } #endif void database::import_object(serializable_object_interface* obj) { threading::lock_guard object_db_lock(&m_mutex); m_object_table.insert_or_assign(obj->get_hash(), obj); } void database::remove_object(serializable_object_interface* obj) { threading::lock_guard object_db_lock(&m_mutex); m_object_table.erase(obj->get_hash()); } #if !defined(ELECTROSLAG_BUILD_SHIP) void database::dump_types() const { threading::lock_guard object_db_lock(&m_mutex); ELECTROSLAG_LOG_MESSAGE("Serializable Type Table Dump"); ELECTROSLAG_LOG_MESSAGE("Type Hash | Ref | Name"); ELECTROSLAG_LOG_MESSAGE("-------------------|------|-----------------------------------------------"); serializable_type_table::const_iterator i(m_serializable_type_table.begin()); while (i != m_serializable_type_table.end()) { ELECTROSLAG_LOG_MESSAGE( "0x%016llX | %4s | %s", i->first, i->second->is_referenced() ? "yes" : "no", i->second->get_name().c_str() ); ++i; } } void database::dump_objects(load_record::ref const& record) const { threading::lock_guard object_db_lock(&m_mutex); ELECTROSLAG_LOG_MESSAGE("Database Object Table Dump"); ELECTROSLAG_LOG_MESSAGE("Object Hash | Type Hash | RefCount | Name"); ELECTROSLAG_LOG_MESSAGE("-------------------|--------------------|----------|-----------------------------------------------"); if (record.is_valid()) { serializable_object_interface const* obj = record->get_loaded_object_head(); while (obj != 0) { dump_object(obj); obj = obj->get_next_loaded_object(); } } else { object_table::const_iterator o(m_object_table.begin()); while (o != m_object_table.end()) { dump_object(o->second); ++o; } } } void database::dump_object(serializable_object_interface const* obj) const { int ref_count = 0; unsigned long long type_hash = obj->get_type_hash(); serializable_type_registration const* type = find_type(type_hash); if (type) { if (type->is_referenced()) { ref_count = dynamic_cast<referenced_object const*>(obj)->get_ref_count(); } } std::string object_name; if (obj->has_name_string()) { object_name = obj->get_name(); } else { object_name = "<unnamed>"; } ELECTROSLAG_LOG_MESSAGE( "0x%016llX | 0x%016llX | %8d | %s", obj->get_hash(), type_hash, ref_count, object_name.c_str() ); } #endif } }
37.39413
139
0.552111
jwb1
286229d4d7352f8f469494babe3e5a8a273b2a21
3,477
cpp
C++
CSGOSimple/render.cpp
mikemikko/mike-internal-public-version
77dafb13047580e38013ba42bf66b70a9b942604
[ "MIT" ]
null
null
null
CSGOSimple/render.cpp
mikemikko/mike-internal-public-version
77dafb13047580e38013ba42bf66b70a9b942604
[ "MIT" ]
null
null
null
CSGOSimple/render.cpp
mikemikko/mike-internal-public-version
77dafb13047580e38013ba42bf66b70a9b942604
[ "MIT" ]
null
null
null
#include "render.hpp" #include <mutex> #include "features/visuals.hpp" #include "valve_sdk/csgostructs.hpp" #include "helpers/input.hpp" #include "menu.hpp" #include "options.hpp" #include "fonts/fonts.hpp" #include "helpers/math.hpp" ImFont* g_pDefaultFont; ImFont* g_pSecondFont; ImDrawListSharedData _data; std::mutex render_mutex; void Render::Initialize() { ImGui::CreateContext(); ImGui_ImplWin32_Init(InputSys::Get().GetMainWindow()); ImGui_ImplDX9_Init(g_D3DDevice9); draw_list = new ImDrawList(ImGui::GetDrawListSharedData()); draw_list_act = new ImDrawList(ImGui::GetDrawListSharedData()); draw_list_rendering = new ImDrawList(ImGui::GetDrawListSharedData()); GetFonts(); } void Render::GetFonts() { // menu font ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF( Fonts::Droid_compressed_data, Fonts::Droid_compressed_size, 14.f); // esp font g_pDefaultFont = ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF( Fonts::Droid_compressed_data, Fonts::Droid_compressed_size, 18.f); // font for watermark; just example g_pSecondFont = ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF( Fonts::Cousine_compressed_data, Fonts::Cousine_compressed_size, 18.f); } void Render::ClearDrawList() { render_mutex.lock(); draw_list_act->Clear(); render_mutex.unlock(); } void Render::BeginScene() { draw_list->Clear(); draw_list->PushClipRectFullScreen(); if (g_Options.misc_watermark) //lol Render::Get().RenderText("Mikehook owns you and all", 10, 5, 18.f, g_Options.color_watermark, false, true, g_pSecondFont); if (g_EngineClient->IsInGame() && g_LocalPlayer && g_Options.esp_enabled) Visuals::Get().AddToDrawList(); render_mutex.lock(); *draw_list_act = *draw_list; render_mutex.unlock(); } ImDrawList* Render::RenderScene() { if (render_mutex.try_lock()) { *draw_list_rendering = *draw_list_act; render_mutex.unlock(); } return draw_list_rendering; } float Render::RenderText(const std::string& text, ImVec2 pos, float size, Color color, bool center, bool outline, ImFont* pFont) { ImVec2 textSize = pFont->CalcTextSizeA(size, FLT_MAX, 0.0f, text.c_str()); if (!pFont->ContainerAtlas) return 0.f; draw_list->PushTextureID(pFont->ContainerAtlas->TexID); if (center) pos.x -= textSize.x / 2.0f; if (outline) { draw_list->AddText(pFont, size, ImVec2(pos.x + 1, pos.y + 1), GetU32(Color(0, 0, 0, color.a())), text.c_str()); draw_list->AddText(pFont, size, ImVec2(pos.x - 1, pos.y - 1), GetU32(Color(0, 0, 0, color.a())), text.c_str()); draw_list->AddText(pFont, size, ImVec2(pos.x + 1, pos.y - 1), GetU32(Color(0, 0, 0, color.a())), text.c_str()); draw_list->AddText(pFont, size, ImVec2(pos.x - 1, pos.y + 1), GetU32(Color(0, 0, 0, color.a())), text.c_str()); } draw_list->AddText(pFont, size, pos, GetU32(color), text.c_str()); draw_list->PopTextureID(); return pos.y + textSize.y; } void Render::RenderCircle3D(Vector position, float points, float radius, Color color) { float step = (float)M_PI * 2.0f / points; for (float a = 0; a < (M_PI * 2.0f); a += step) { Vector start(radius * cosf(a) + position.x, radius * sinf(a) + position.y, position.z); Vector end(radius * cosf(a + step) + position.x, radius * sinf(a + step) + position.y, position.z); Vector start2d, end2d; if (g_DebugOverlay->ScreenPosition(start, start2d) || g_DebugOverlay->ScreenPosition(end, end2d)) return; RenderLine(start2d.x, start2d.y, end2d.x, end2d.y, color); } }
26.746154
128
0.71067
mikemikko
28644a5509f7d705a7e6c70cb2a7292352601e34
295
cpp
C++
cycle_counter.cpp
jaoleonardo01/STE29008_ATV4
377111fa252c3c88209d229966aefadddedb0eb0
[ "MIT" ]
null
null
null
cycle_counter.cpp
jaoleonardo01/STE29008_ATV4
377111fa252c3c88209d229966aefadddedb0eb0
[ "MIT" ]
null
null
null
cycle_counter.cpp
jaoleonardo01/STE29008_ATV4
377111fa252c3c88209d229966aefadddedb0eb0
[ "MIT" ]
null
null
null
#include "cycle_counter.h" Cycle_Counter::Cycle_Counter(/* args */) { asm ( "clr r1\n\t" "clr r0\n\t" "inc r0\n\t" "ldi r30, 0xb0\r\n" "ldi r31, 0x00\r\n" "st Z+, r1\r\n" "st Z, r0\r\n" ); } Cycle_Counter::~Cycle_Counter() { }
15.526316
40
0.471186
jaoleonardo01
2866200e00b445a04f0c24a4ab997aa81e344d3a
4,561
inl
C++
Impt/glm/gtx/rotate_vector.inl
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
76
2015-01-08T12:19:17.000Z
2021-03-27T03:31:12.000Z
Impt/glm/gtx/rotate_vector.inl
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
10
2015-08-09T21:10:55.000Z
2015-08-10T02:50:07.000Z
Impt/glm/gtx/rotate_vector.inl
StavrosBizelis/NetworkDistributedDeferredShading
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
[ "MIT" ]
17
2015-01-17T07:23:21.000Z
2020-12-15T02:44:19.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-11-02 // Updated : 2009-02-19 // Licence : This source is under MIT License // File : glm/gtx/rotate_vector.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm { template <typename T> GLM_FUNC_QUALIFIER detail::tvec2<T> rotate ( detail::tvec2<T> const & v, T const & angle ) { detail::tvec2<T> Result; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos = cos(radians(angle)); T const Sin = sin(radians(angle)); #endif Result.x = v.x * Cos - v.y * Sin; Result.y = v.x * Sin + v.y * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotate ( detail::tvec3<T> const & v, T const & angle, detail::tvec3<T> const & normal ) { return detail::tmat3x3<T>(glm::rotate(angle, normal)) * v; } /* template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotateGTX( const detail::tvec3<T>& x, T angle, const detail::tvec3<T>& normal) { const T Cos = cos(radians(angle)); const T Sin = sin(radians(angle)); return x * Cos + ((x * normal) * (T(1) - Cos)) * normal + cross(x, normal) * Sin; } */ template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> rotate ( detail::tvec4<T> const & v, T const & angle, detail::tvec3<T> const & normal ) { return rotate(angle, normal) * v; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotateX ( detail::tvec3<T> const & v, T const & angle ) { detail::tvec3<T> Result(v); #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos = cos(radians(angle)); T const Sin = sin(radians(angle)); #endif Result.y = v.y * Cos - v.z * Sin; Result.z = v.y * Sin + v.z * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotateY ( detail::tvec3<T> const & v, T const & angle ) { detail::tvec3<T> Result = v; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos(cos(radians(angle))); T const Sin(sin(radians(angle))); #endif Result.x = v.x * Cos + v.z * Sin; Result.z = -v.x * Sin + v.z * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotateZ ( detail::tvec3<T> const & v, T const & angle ) { detail::tvec3<T> Result = v; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos(cos(radians(angle))); T const Sin(sin(radians(angle))); #endif Result.x = v.x * Cos - v.y * Sin; Result.y = v.x * Sin + v.y * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> rotateX ( detail::tvec4<T> const & v, T const & angle ) { detail::tvec4<T> Result = v; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos(cos(radians(angle))); T const Sin(sin(radians(angle))); #endif Result.y = v.y * Cos - v.z * Sin; Result.z = v.y * Sin + v.z * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> rotateY ( detail::tvec4<T> const & v, T const & angle ) { detail::tvec4<T> Result = v; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos(cos(radians(angle))); T const Sin(sin(radians(angle))); #endif Result.x = v.x * Cos + v.z * Sin; Result.z = -v.x * Sin + v.z * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> rotateZ ( detail::tvec4<T> const & v, T const & angle ) { detail::tvec4<T> Result = v; #ifdef GLM_FORCE_RADIANS T const Cos(cos(angle)); T const Sin(sin(angle)); #else T const Cos(cos(radians(angle))); T const Sin(sin(radians(angle))); #endif Result.x = v.x * Cos - v.y * Sin; Result.y = v.x * Sin + v.y * Cos; return Result; } template <typename T> GLM_FUNC_QUALIFIER detail::tmat4x4<T> orientation ( detail::tvec3<T> const & Normal, detail::tvec3<T> const & Up ) { if(all(equal(Normal, Up))) return detail::tmat4x4<T>(T(1)); detail::tvec3<T> RotationAxis = cross(Up, Normal); T Angle = degrees(acos(dot(Normal, Up))); return rotate(Angle, RotationAxis); } }//namespace glm
21.514151
99
0.592633
StavrosBizelis
2866b43f16d5d285ca908d5f6782dd2be759bb88
654
cpp
C++
Uri-Online-Judge/cpp/1196 - WERTYU.cpp
ThiagoInocencio/Competitive-Programming-Solutions
efcabdd48d8c103ca619fff53db50aef0ea873d4
[ "MIT" ]
1
2020-06-07T22:08:42.000Z
2020-06-07T22:08:42.000Z
Uri-Online-Judge/cpp/1196 - WERTYU.cpp
ThiagoInocencio/Competitive-Programming-Solutions
efcabdd48d8c103ca619fff53db50aef0ea873d4
[ "MIT" ]
null
null
null
Uri-Online-Judge/cpp/1196 - WERTYU.cpp
ThiagoInocencio/Competitive-Programming-Solutions
efcabdd48d8c103ca619fff53db50aef0ea873d4
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <stdlib.h> using namespace std; int main() { string QWERT = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./"; int i, index, length; char LETTER; string text; while(getline(cin, text)) { length = text.length(); for(i = 0; i < length; i++){ LETTER = text[i]; if(LETTER == ' ') { cout << " "; } else{ index = QWERT.find(LETTER); cout << QWERT[index-1]; } } cout << "\n"; } return 0; }
16.35
70
0.454128
ThiagoInocencio
2866f3235ec91780a35ca29a0945406b12fa2b8b
4,058
cpp
C++
sc-kpm/ui/uiTranslators.cpp
rusalexd/sc-machine
d92afee12fd22a7d2c5cb0c3014a280f7de5b42f
[ "MIT" ]
null
null
null
sc-kpm/ui/uiTranslators.cpp
rusalexd/sc-machine
d92afee12fd22a7d2c5cb0c3014a280f7de5b42f
[ "MIT" ]
null
null
null
sc-kpm/ui/uiTranslators.cpp
rusalexd/sc-machine
d92afee12fd22a7d2c5cb0c3014a280f7de5b42f
[ "MIT" ]
null
null
null
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "uiPrecompiled.h" #include "uiTranslators.h" #include "uiKeynodes.h" #include "translators/uiSc2ScsJsonTranslator.h" #include "translators/uiSc2SCgJsonTranslator.h" #include "translators/uiSc2SCnJsonTranslator.h" sc_event *ui_translator_sc2scs_event = (sc_event*)null_ptr; sc_event *ui_translator_sc2scg_json_event = (sc_event*)null_ptr; sc_event *ui_translator_sc2scn_json_event = (sc_event*)null_ptr; void ui_initialize_translators() { ui_translator_sc2scs_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2ScsTranslator::ui_translate_sc2scs, 0); ui_translator_sc2scg_json_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2SCgJsonTranslator::ui_translate_sc2scg_json, 0); ui_translator_sc2scn_json_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2SCnJsonTranslator::ui_translate_sc2scn, 0); } void ui_shutdown_translators() { if (ui_translator_sc2scs_event) sc_event_destroy(ui_translator_sc2scs_event); if (ui_translator_sc2scg_json_event) sc_event_destroy(ui_translator_sc2scg_json_event); if (ui_translator_sc2scn_json_event) sc_event_destroy(ui_translator_sc2scn_json_event); } sc_result ui_translate_command_resolve_arguments(sc_addr cmd_addr, sc_addr *output_fmt_addr, sc_addr *source_addr) { sc_iterator5 *it = (sc_iterator5*)null_ptr; sc_bool fmt_found = SC_FALSE; sc_bool source_found = SC_FALSE; // resolve output format it = sc_iterator5_f_a_a_a_f_new(s_default_ctx, cmd_addr, sc_type_arc_pos_const_perm, sc_type_node | sc_type_const, sc_type_arc_pos_const_perm, keynode_rrel_output_format); while (sc_iterator5_next(it) == SC_TRUE) { *output_fmt_addr = sc_iterator5_value(it, 2); fmt_found = SC_TRUE; } sc_iterator5_free(it); if (fmt_found == SC_FALSE) return SC_RESULT_ERROR; // resolve input construction it = sc_iterator5_f_a_a_a_f_new(s_default_ctx, cmd_addr, sc_type_arc_pos_const_perm, sc_type_node | sc_type_const, sc_type_arc_pos_const_perm, keynode_rrel_source_sc_construction); while (sc_iterator5_next(it) == SC_TRUE) { *source_addr = sc_iterator5_value(it, 2); source_found = SC_TRUE; } sc_iterator5_free(it); if (source_found == SC_FALSE) return SC_RESULT_ERROR; return SC_RESULT_OK; } sc_bool ui_translate_resolve_system_identifier(sc_addr el, String &sys_idtf) { sc_addr sys_idtf_addr; sc_stream *idtf_stream = 0; sc_uint32 idtf_length = 0; sc_uint32 read_bytes = 0; sc_bool result = SC_FALSE; sc_char buffer[32]; sys_idtf = ""; if (sc_helper_get_system_identifier_link(s_default_ctx, el, &sys_idtf_addr) == SC_RESULT_OK) { if (sc_memory_get_link_content(s_default_ctx, sys_idtf_addr, &idtf_stream) == SC_RESULT_OK) { sc_stream_get_length(idtf_stream, &idtf_length); while (sc_stream_eof(idtf_stream) == SC_FALSE) { sc_stream_read_data(idtf_stream, buffer, 32, &read_bytes); sys_idtf.append(buffer, read_bytes); } sc_stream_free(idtf_stream); result = SC_TRUE; } } if (result == SC_FALSE) { StringStream ss; ss << el.seg << "_" << el.offset; sys_idtf = ss.str(); return SC_FALSE; } return result; }
33.816667
174
0.666092
rusalexd
28677a9fdf67c593f8d09b9002d1f097ff4ee992
1,396
hpp
C++
game/common_defs.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
game/common_defs.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
game/common_defs.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
#ifndef COMMON_DEFS_HPP #define COMMON_DEFS_HPP #include "vaslib/vas_math.hpp" #include "vaslib/vas_time.hpp" #include "vaslib/vas_types.hpp" namespace GameConst { // physical radiuses const float hsz_supply = 0.5; ///< Supplies const float hsz_supply_big = 0.8; ///< Powerups etc const float hsz_proj = 0.3; ///< Normal projectile const float hsz_proj_big = 0.45; ///< Big projectile const float hsz_rat = 0.7; ///< PC const float hsz_box_small = 0.85; const float hsz_drone = 0.6; const float hsz_drone_big = 0.8; const float hsz_drone_hunter = 1.4; const float hsz_cell_tmp = 1.5; ///< temporary const float hsz_interact = 1.3; const float hsz_termfin = 2; const vec2fp hsz_pshl = {0.7, 1.2}; ///< Projected shield // other consts constexpr float cell_size = 3; const size_t total_key_count = 6; } enum : size_t { TEAM_ENVIRON = 0, ///< Environment TEAM_BOTS = 1, TEAM_PLAYER = 2 }; struct EntityIndex { using Int = uint32_t; EntityIndex() = default; bool operator ==(const EntityIndex& ei) const {return i == ei.i;} bool operator !=(const EntityIndex& ei) const {return i != ei.i;} explicit operator bool() const {return i != std::numeric_limits<Int>::max();} [[nodiscard]] static EntityIndex from_int(Int i) {EntityIndex ei; ei.i = i; return ei;} Int to_int() const {return i;} private: Int i = std::numeric_limits<Int>::max(); }; #endif // COMMON_DEFS_HPP
21.8125
88
0.702006
vasukas
28693840f63785da9d1e1ee9f087807bd60af890
6,501
cpp
C++
Tests/test1.cpp
nikhilYadala/Python_to_cpp
2a1637851c5395a6742a3f8711e8490e491e54fa
[ "BSD-3-Clause" ]
1
2016-04-28T12:55:48.000Z
2016-04-28T12:55:48.000Z
Tests/test1.cpp
coderabhishek/Glue
d522608798c1c050baafe077d5599dce359bd7da
[ "BSD-3-Clause" ]
1
2017-06-16T16:12:55.000Z
2017-06-16T16:12:55.000Z
Tests/test1.cpp
nikhilYadala/Python_to_cpp
2a1637851c5395a6742a3f8711e8490e491e54fa
[ "BSD-3-Clause" ]
null
null
null
/** @file test1.cpp * @brief Test the artificial string library function * We are testing the artificial string functions on some trivial and corner cases strings and comparing it with expected output * @bug No known bugs. */ #include <limits.h> #include "../Source/Header/supporting_libs/supporting_libs.h" #include "gtest/gtest.h" #include<string> /** @brief This is a Test function to check * if capitalize function works. * * It defines a class of source code and runs the capitalize string function * @param Nil. * @return If the testcase is passed or not. */ TEST (capitialize, trivialnull) { artificial_string abc= artificial_string("@8.41#$"); abc.capitalize(); EXPECT_STREQ("@8.41#$",abc.str.c_str()); abc.str=""; EXPECT_STREQ("",abc.str.c_str()); } TEST (capitialize, various_strings) { artificial_string abc= artificial_string("abhishek"); abc.capitalize(); ASSERT_STREQ("Abhishek",abc.str.c_str()); //To Test the function capitalize abc.str="We like CS242"; ASSERT_STREQ("We like CS242",abc.str.c_str()); } //================================================================================================== /** @brief This is a Test function to check * if len function works. * * It defines a class of source code and runs the len string function * @param Nil. * @return If the testcase is passed or not. */ TEST (len, trivialnull){ artificial_string abc= artificial_string(""); EXPECT_EQ(0,abc.len()); } TEST (len, otherlengths){ //To Test the function len artificial_string abc= artificial_string("123456789"); ASSERT_EQ(9,abc.len()); abc.str="This is Python to C++ translator"; ASSERT_EQ(32,abc.len()); abc.str="!@#$^&("; ASSERT_EQ(7,abc.len()); } //=================================================================================================== /** @brief This is a Test function to check * if upper function works. * * It defines a class of source code and runs the upper string function * @param Nil. * @return If the testcase is passed or not. */ TEST (upper, trivialnull){ artificial_string abc= artificial_string(""); abc.upper(); EXPECT_STREQ("",abc.str.c_str()); abc.str="@8.41#$"; abc.upper(); EXPECT_STREQ("@8.41#$",abc.str.c_str()); } TEST (upper, various_strings) { artificial_string abc= artificial_string("abhishek"); abc.upper(); ASSERT_STREQ("ABHISHEK",abc.str.c_str()); //To Test the function upper abc.str="We like CS242"; abc.upper(); ASSERT_STREQ("WE LIKE CS242",abc.str.c_str()); } //=================================================================================================== /** @brief This is a Test function to check * if max function works. * * It defines a class of source code and runs the max string function * @param Nil. * @return If the testcase is passed or not. */ TEST (max, trivialnull){ artificial_string abc= artificial_string("@!@#443243646"); EXPECT_EQ(' ',abc.max()); abc.str=""; EXPECT_EQ(' ',abc.max()); } TEST (max, diffstrings) { //To Test the max function artificial_string abc= artificial_string("a2312300AZ"); EXPECT_EQ('a',abc.max()); abc.str="zZaA@!"; ASSERT_EQ('z',abc.max()); abc.str="iamms"; ASSERT_EQ('s',abc.max()); abc.str="2837!&25JGU"; ASSERT_EQ(' ',abc.max()); abc.str="AGILEMETHOD"; ASSERT_EQ(' ',abc.max()); } //==================================================================================================== /** @brief This is a Test function to check * if lower function works. * * It defines a class of source code and runs the lower string function * @param Nil. * @return If the testcase is passed or not. */ TEST (lower, trivialnull){ artificial_string abc= artificial_string(""); abc.lower(); EXPECT_STREQ("",abc.str.c_str()); abc.str="@8.41#$"; abc.lower(); EXPECT_STREQ("@8.41#$",abc.str.c_str()); } TEST (lower, various_strings) { artificial_string abc= artificial_string("abhishek"); abc.lower(); ASSERT_STREQ("abhishek",abc.str.c_str()); //To Test the function lower abc.str="INDIA_IS_MY_COUNTRY"; abc.lower(); ASSERT_STREQ("india_is_my_country",abc.str.c_str()); abc.str="We Like CS242"; abc.lower(); ASSERT_STREQ("we like cs242",abc.str.c_str()); } //==================================================================================================== /** @brief This is a Test function to check * if min function works. * * It defines a class of source code and runs the min string function * @param Nil. * @return If the testcase is passed or not. */ TEST (min, trivialnull){ artificial_string abc= artificial_string("@!@#443243646"); EXPECT_EQ(' ',abc.min()); abc.str=""; EXPECT_EQ(' ',abc.min()); } TEST (min, diffstrings){ //To Test the min function artificial_string abc= artificial_string("a2312300AZ"); ASSERT_EQ('a',abc.min()); abc.str="zZaA@!"; ASSERT_EQ('a',abc.min()); abc.str="iamms"; ASSERT_EQ('a',abc.min()); abc.str="2837!&25JGU"; ASSERT_EQ(' ',abc.min()); abc.str="AGILEMETHOD"; ASSERT_EQ(' ',abc.min()); } //==================================================================================================== /** @brief This is a Test function to check * if swapcase function works. * * It defines a class of source code and runs the swapcase string function * @param Nil. * @return If the testcase is passed or not. */ TEST (swapcase, trivialnull){ artificial_string abc= artificial_string(""); abc.swapcase(); EXPECT_STREQ("",abc.str.c_str()); } TEST (swapcase, diffstrings){ artificial_string abc = artificial_string("tHIS iS gREAT"); abc.swapcase(); EXPECT_STREQ("This Is Great",abc.str.c_str()); //To test the swapcase function //artificial_string abc = artificial_string("ABCDEFGHIjklmn"); abc.str="ABCDEFGHIjklm"; abc.swapcase(); ASSERT_STREQ("abcdefghiJKLM",abc.str.c_str()); abc.str="!@# 456 ASD qwe"; //artificial_string abc = artificial_string("!@# 456 ASD qwe"); abc.swapcase(); ASSERT_STREQ("!@# 456 asd QWE",abc.str.c_str()); } //===================================================================================================
33.168367
130
0.565913
nikhilYadala
286afe57eea3df6f0e6a7509b86b4ea16dcf1889
7,510
hpp
C++
libvast/include/vast/detail/generator.hpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
63
2016-04-22T01:50:03.000Z
2019-07-31T15:50:36.000Z
libvast/include/vast/detail/generator.hpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
216
2017-01-24T16:25:43.000Z
2019-08-01T19:37:00.000Z
libvast/include/vast/detail/generator.hpp
rdettai/vast
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
[ "BSD-3-Clause" ]
28
2016-05-19T13:09:19.000Z
2019-04-12T15:11:42.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2021 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause // cppcoro, adapted for libvast. // // Original Author: Lewis Baker // Original License: MIT // Original Revision: a87e97fe5b6091ca9f6de4637736b8e0d8b109cf // Includes code from https://github.com/lewissbaker/cppcoro #pragma once #include "vast/fwd.hpp" #include <exception> #include <functional> #include <iterator> #include <type_traits> #include <utility> #if __has_include(<coroutine>) # include <coroutine> namespace stdcoro = std; #else # include <experimental/coroutine> namespace stdcoro = std::experimental; #endif namespace vast::detail { /// A generator represents a coroutine type that produces a sequence of values /// of type, T, where values are produced lazily and synchronously. /// /// The coroutine body is able to yield values of type T using the co_yield /// keyword. Note, however, that the coroutine body is not able to use the /// co_await keyword; values must be produced synchronously. /// /// When a coroutine function returning a generator<T> is called the coroutine /// is created initially suspended. Execution of the coroutine enters the /// coroutine body when the generator<T>::begin() method is called and continues /// until either the first co_yield statement is reached or the coroutine runs /// to completion. If the returned iterator is not equal to the end() iterator /// then dereferencing the iterator will return a reference to the value passed /// to the co_yield statement. Calling operator++() on the iterator will resume /// execution of the coroutine and continue until either the next co_yield point /// is reached or the coroutine runs to completion(). Any unhandled exceptions /// thrown by the coroutine will propagate out of the begin() or operator++() /// calls to the caller. template <typename T> class generator; namespace internal { template <typename T> class generator_promise { public: using value_type = std::remove_reference_t<T>; using reference_type = T&&; using pointer_type = value_type*; generator_promise() = default; generator<T> get_return_object() noexcept; constexpr stdcoro::suspend_always initial_suspend() const noexcept { return {}; } constexpr stdcoro::suspend_always final_suspend() const noexcept { return {}; } // This overload copies v to a temporary, then yields a pointer to that. // This allows passing an lvalue to co_yield for a generator<NotReference>. // Looks crazy, but taken from the reference implementation in P2529R0. auto yield_value(const T& v) requires( !std::is_reference_v<T> && std::copy_constructible<T>) { struct Owner : stdcoro::suspend_always { Owner(const T& val, pointer_type& out) : v(val) { out = &v; } Owner(Owner&&) = delete; T v; }; return Owner(v, m_value); } stdcoro::suspend_always yield_value(std::remove_reference_t<T>&& value) noexcept { m_value = std::addressof(value); return {}; } void unhandled_exception() { m_exception = std::current_exception(); } void return_void() { } reference_type value() const noexcept { return static_cast<reference_type>(*m_value); } // Don't allow any use of 'co_await' inside the generator coroutine. template <typename U> stdcoro::suspend_never await_transform(U&& value) = delete; void rethrow_if_exception() { if (m_exception) { std::rethrow_exception(m_exception); } } private: pointer_type m_value; std::exception_ptr m_exception; }; struct generator_sentinel {}; template <typename T> class generator_iterator { using coroutine_handle = stdcoro::coroutine_handle<generator_promise<T>>; public: using iterator_category = std::input_iterator_tag; // What type should we use for counting elements of a potentially infinite // sequence? using difference_type = std::ptrdiff_t; using value_type = typename generator_promise<T>::value_type; using reference = typename generator_promise<T>::reference_type; using pointer = typename generator_promise<T>::pointer_type; // Iterator needs to be default-constructible to satisfy the Range concept. generator_iterator() noexcept : m_coroutine(nullptr) { } explicit generator_iterator(coroutine_handle coroutine) noexcept : m_coroutine(coroutine) { } friend bool operator==(const generator_iterator& it, generator_sentinel) noexcept { return !it.m_coroutine || it.m_coroutine.done(); } friend bool operator!=(const generator_iterator& it, generator_sentinel s) noexcept { return !(it == s); } friend bool operator==(generator_sentinel s, const generator_iterator& it) noexcept { return (it == s); } friend bool operator!=(generator_sentinel s, const generator_iterator& it) noexcept { return it != s; } generator_iterator& operator++() { m_coroutine.resume(); if (m_coroutine.done()) { m_coroutine.promise().rethrow_if_exception(); } return *this; } // Need to provide post-increment operator to implement the 'Range' concept. void operator++(int) { (void)operator++(); } reference operator*() const noexcept { return m_coroutine.promise().value(); } private: coroutine_handle m_coroutine; }; } // namespace internal template <typename T> class [[nodiscard]] generator { public: using promise_type = internal::generator_promise<T>; using iterator = internal::generator_iterator<T>; generator() noexcept : m_coroutine(nullptr) { } generator(generator&& other) noexcept : m_coroutine(other.m_coroutine) { other.m_coroutine = nullptr; } generator(const generator& other) = delete; ~generator() { if (m_coroutine) m_coroutine.destroy(); } generator& operator=(generator other) noexcept { swap(other); return *this; } generator& operator=(generator&& other) noexcept { if (m_coroutine) m_coroutine.destroy(); m_coroutine = other.m_coroutine; other.m_coroutine = nullptr; return *this; } iterator begin() { if (m_coroutine) { m_coroutine.resume(); if (m_coroutine.done()) { m_coroutine.promise().rethrow_if_exception(); } } return iterator{m_coroutine}; } internal::generator_sentinel end() noexcept { return internal::generator_sentinel{}; } void swap(generator& other) noexcept { std::swap(m_coroutine, other.m_coroutine); } private: friend class internal::generator_promise<T>; explicit generator(stdcoro::coroutine_handle<promise_type> coroutine) noexcept : m_coroutine(coroutine) { } stdcoro::coroutine_handle<promise_type> m_coroutine; }; template <typename T> void swap(generator<T>& a, generator<T>& b) { a.swap(b); } namespace internal { template <typename T> generator<T> generator_promise<T>::get_return_object() noexcept { using coroutine_handle = stdcoro::coroutine_handle<generator_promise<T>>; return generator<T>{coroutine_handle::from_promise(*this)}; } } // namespace internal template <typename FUNC, typename T> generator<std::invoke_result_t<FUNC&, typename generator<T>::iterator::reference>> fmap(FUNC func, generator<T> source) { for (auto&& value : source) { co_yield std::invoke(func, static_cast<decltype(value)>(value)); } } } // namespace vast::detail
26.725979
82
0.709055
rdettai
286e237de1ead0a48c194098da0b43243c2f7f93
22,240
cpp
C++
llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp
davidungar/llvm-project
dd6b6bfe304864c6c898511fceece0279621c5c3
[ "Apache-2.0" ]
null
null
null
llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp
davidungar/llvm-project
dd6b6bfe304864c6c898511fceece0279621c5c3
[ "Apache-2.0" ]
null
null
null
llvm/lib/Transforms/Scalar/CallSiteSplitting.cpp
davidungar/llvm-project
dd6b6bfe304864c6c898511fceece0279621c5c3
[ "Apache-2.0" ]
null
null
null
//===- CallSiteSplitting.cpp ----------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file implements a transformation that tries to split a call-site to pass // more constrained arguments if its argument is predicated in the control flow // so that we can expose better context to the later passes (e.g, inliner, jump // threading, or IPA-CP based function cloning, etc.). // As of now we support two cases : // // 1) Try to a split call-site with constrained arguments, if any constraints // on any argument can be found by following the single predecessors of the // all site's predecessors. Currently this pass only handles call-sites with 2 // predecessors. For example, in the code below, we try to split the call-site // since we can predicate the argument(ptr) based on the OR condition. // // Split from : // if (!ptr || c) // callee(ptr); // to : // if (!ptr) // callee(null) // set the known constant value // else if (c) // callee(nonnull ptr) // set non-null attribute in the argument // // 2) We can also split a call-site based on constant incoming values of a PHI // For example, // from : // Header: // %c = icmp eq i32 %i1, %i2 // br i1 %c, label %Tail, label %TBB // TBB: // br label Tail% // Tail: // %p = phi i32 [ 0, %Header], [ 1, %TBB] // call void @bar(i32 %p) // to // Header: // %c = icmp eq i32 %i1, %i2 // br i1 %c, label %Tail-split0, label %TBB // TBB: // br label %Tail-split1 // Tail-split0: // call void @bar(i32 0) // br label %Tail // Tail-split1: // call void @bar(i32 1) // br label %Tail // Tail: // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ] // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/CallSiteSplitting.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/PatternMatch.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/Local.h" using namespace llvm; using namespace PatternMatch; #define DEBUG_TYPE "callsite-splitting" STATISTIC(NumCallSiteSplit, "Number of call-site split"); /// Only allow instructions before a call, if their CodeSize cost is below /// DuplicationThreshold. Those instructions need to be duplicated in all /// split blocks. static cl::opt<unsigned> DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden, cl::desc("Only allow instructions before a call, if " "their cost is below DuplicationThreshold"), cl::init(5)); static void addNonNullAttribute(CallSite CS, Value *Op) { unsigned ArgNo = 0; for (auto &I : CS.args()) { if (&*I == Op) CS.addParamAttr(ArgNo, Attribute::NonNull); ++ArgNo; } } static void setConstantInArgument(CallSite CS, Value *Op, Constant *ConstValue) { unsigned ArgNo = 0; for (auto &I : CS.args()) { if (&*I == Op) { // It is possible we have already added the non-null attribute to the // parameter by using an earlier constraining condition. CS.removeParamAttr(ArgNo, Attribute::NonNull); CS.setArgument(ArgNo, ConstValue); } ++ArgNo; } } static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS) { assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand."); Value *Op0 = Cmp->getOperand(0); unsigned ArgNo = 0; for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I, ++ArgNo) { // Don't consider constant or arguments that are already known non-null. if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull)) continue; if (*I == Op0) return true; } return false; } typedef std::pair<ICmpInst *, unsigned> ConditionTy; typedef SmallVector<ConditionTy, 2> ConditionsTy; /// If From has a conditional jump to To, add the condition to Conditions, /// if it is relevant to any argument at CS. static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To, ConditionsTy &Conditions) { auto *BI = dyn_cast<BranchInst>(From->getTerminator()); if (!BI || !BI->isConditional()) return; CmpInst::Predicate Pred; Value *Cond = BI->getCondition(); if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant()))) return; ICmpInst *Cmp = cast<ICmpInst>(Cond); if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) if (isCondRelevantToAnyCallArgument(Cmp, CS)) Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To ? Pred : Cmp->getInversePredicate()}); } /// Record ICmp conditions relevant to any argument in CS following Pred's /// single predecessors. If there are conflicting conditions along a path, like /// x == 1 and x == 0, the first condition will be used. We stop once we reach /// an edge to StopAt. static void recordConditions(CallSite CS, BasicBlock *Pred, ConditionsTy &Conditions, BasicBlock *StopAt) { BasicBlock *From = Pred; BasicBlock *To = Pred; SmallPtrSet<BasicBlock *, 4> Visited; while (To != StopAt && !Visited.count(From->getSinglePredecessor()) && (From = From->getSinglePredecessor())) { recordCondition(CS, From, To, Conditions); Visited.insert(From); To = From; } } static void addConditions(CallSite CS, const ConditionsTy &Conditions) { for (auto &Cond : Conditions) { Value *Arg = Cond.first->getOperand(0); Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1)); if (Cond.second == ICmpInst::ICMP_EQ) setConstantInArgument(CS, Arg, ConstVal); else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) { assert(Cond.second == ICmpInst::ICMP_NE); addNonNullAttribute(CS, Arg); } } } static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) { SmallVector<BasicBlock *, 2> Preds(predecessors((BB))); assert(Preds.size() == 2 && "Expected exactly 2 predecessors!"); return Preds; } static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI) { if (CS.isConvergent() || CS.cannotDuplicate()) return false; // FIXME: As of now we handle only CallInst. InvokeInst could be handled // without too much effort. Instruction *Instr = CS.getInstruction(); if (!isa<CallInst>(Instr)) return false; BasicBlock *CallSiteBB = Instr->getParent(); // Need 2 predecessors and cannot split an edge from an IndirectBrInst. SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB)); if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) || isa<IndirectBrInst>(Preds[1]->getTerminator())) return false; // BasicBlock::canSplitPredecessors is more aggressive, so checking for // BasicBlock::isEHPad as well. if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad()) return false; // Allow splitting a call-site only when the CodeSize cost of the // instructions before the call is less then DuplicationThreshold. The // instructions before the call will be duplicated in the split blocks and // corresponding uses will be updated. unsigned Cost = 0; for (auto &InstBeforeCall : llvm::make_range(CallSiteBB->begin(), Instr->getIterator())) { Cost += TTI.getInstructionCost(&InstBeforeCall, TargetTransformInfo::TCK_CodeSize); if (Cost >= DuplicationThreshold) return false; } return true; } static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before, Value *V) { Instruction *Copy = I->clone(); Copy->setName(I->getName()); Copy->insertBefore(Before); if (V) Copy->setOperand(0, V); return Copy; } /// Copy mandatory `musttail` return sequence that follows original `CI`, and /// link it up to `NewCI` value instead: /// /// * (optional) `bitcast NewCI to ...` /// * `ret bitcast or NewCI` /// /// Insert this sequence right before `SplitBB`'s terminator, which will be /// cleaned up later in `splitCallSite` below. static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI, Instruction *NewCI) { bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy(); auto II = std::next(CI->getIterator()); BitCastInst* BCI = dyn_cast<BitCastInst>(&*II); if (BCI) ++II; ReturnInst* RI = dyn_cast<ReturnInst>(&*II); assert(RI && "`musttail` call must be followed by `ret` instruction"); Instruction *TI = SplitBB->getTerminator(); Value *V = NewCI; if (BCI) V = cloneInstForMustTail(BCI, TI, V); cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V); // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug // that prevents doing this now. } /// For each (predecessor, conditions from predecessors) pair, it will split the /// basic block containing the call site, hook it up to the predecessor and /// replace the call instruction with new call instructions, which contain /// constraints based on the conditions from their predecessors. /// For example, in the IR below with an OR condition, the call-site can /// be split. In this case, Preds for Tail is [(Header, a == null), /// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing /// CallInst1, which has constraints based on the conditions from Head and /// CallInst2, which has constraints based on the conditions coming from TBB. /// /// From : /// /// Header: /// %c = icmp eq i32* %a, null /// br i1 %c %Tail, %TBB /// TBB: /// %c2 = icmp eq i32* %b, null /// br i1 %c %Tail, %End /// Tail: /// %ca = call i1 @callee (i32* %a, i32* %b) /// /// to : /// /// Header: // PredBB1 is Header /// %c = icmp eq i32* %a, null /// br i1 %c %Tail-split1, %TBB /// TBB: // PredBB2 is TBB /// %c2 = icmp eq i32* %b, null /// br i1 %c %Tail-split2, %End /// Tail-split1: /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1 /// br %Tail /// Tail-split2: /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2 /// br %Tail /// Tail: /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2] /// /// Note that in case any arguments at the call-site are constrained by its /// predecessors, new call-sites with more constrained arguments will be /// created in createCallSitesOnPredicatedArgument(). static void splitCallSite( CallSite CS, const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds, DomTreeUpdater &DTU) { Instruction *Instr = CS.getInstruction(); BasicBlock *TailBB = Instr->getParent(); bool IsMustTailCall = CS.isMustTailCall(); PHINode *CallPN = nullptr; // `musttail` calls must be followed by optional `bitcast`, and `ret`. The // split blocks will be terminated right after that so there're no users for // this phi in a `TailBB`. if (!IsMustTailCall && !Instr->use_empty()) { CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call"); CallPN->setDebugLoc(Instr->getDebugLoc()); } LLVM_DEBUG(dbgs() << "split call-site : " << *Instr << " into \n"); assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2."); // ValueToValueMapTy is neither copy nor moveable, so we use a simple array // here. ValueToValueMapTy ValueToValueMaps[2]; for (unsigned i = 0; i < Preds.size(); i++) { BasicBlock *PredBB = Preds[i].first; BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween( TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i], DTU); assert(SplitBlock && "Unexpected new basic block split."); Instruction *NewCI = &*std::prev(SplitBlock->getTerminator()->getIterator()); CallSite NewCS(NewCI); addConditions(NewCS, Preds[i].second); // Handle PHIs used as arguments in the call-site. for (PHINode &PN : TailBB->phis()) { unsigned ArgNo = 0; for (auto &CI : CS.args()) { if (&*CI == &PN) { NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock)); } ++ArgNo; } } LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName() << "\n"); if (CallPN) CallPN->addIncoming(NewCI, SplitBlock); // Clone and place bitcast and return instructions before `TI` if (IsMustTailCall) copyMustTailReturn(SplitBlock, Instr, NewCI); } NumCallSiteSplit++; // FIXME: remove TI in `copyMustTailReturn` if (IsMustTailCall) { // Remove superfluous `br` terminators from the end of the Split blocks // NOTE: Removing terminator removes the SplitBlock from the TailBB's // predecessors. Therefore we must get complete list of Splits before // attempting removal. SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB))); assert(Splits.size() == 2 && "Expected exactly 2 splits!"); for (unsigned i = 0; i < Splits.size(); i++) { Splits[i]->getTerminator()->eraseFromParent(); DTU.applyUpdatesPermissive({{DominatorTree::Delete, Splits[i], TailBB}}); } // Erase the tail block once done with musttail patching DTU.deleteBB(TailBB); return; } auto *OriginalBegin = &*TailBB->begin(); // Replace users of the original call with a PHI mering call-sites split. if (CallPN) { CallPN->insertBefore(OriginalBegin); Instr->replaceAllUsesWith(CallPN); } // Remove instructions moved to split blocks from TailBB, from the duplicated // call instruction to the beginning of the basic block. If an instruction // has any uses, add a new PHI node to combine the values coming from the // split blocks. The new PHI nodes are placed before the first original // instruction, so we do not end up deleting them. By using reverse-order, we // do not introduce unnecessary PHI nodes for def-use chains from the call // instruction to the beginning of the block. auto I = Instr->getReverseIterator(); while (I != TailBB->rend()) { Instruction *CurrentI = &*I++; if (!CurrentI->use_empty()) { // If an existing PHI has users after the call, there is no need to create // a new one. if (isa<PHINode>(CurrentI)) continue; PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size()); NewPN->setDebugLoc(CurrentI->getDebugLoc()); for (auto &Mapping : ValueToValueMaps) NewPN->addIncoming(Mapping[CurrentI], cast<Instruction>(Mapping[CurrentI])->getParent()); NewPN->insertBefore(&*TailBB->begin()); CurrentI->replaceAllUsesWith(NewPN); } CurrentI->eraseFromParent(); // We are done once we handled the first original instruction in TailBB. if (CurrentI == OriginalBegin) break; } } // Return true if the call-site has an argument which is a PHI with only // constant incoming values. static bool isPredicatedOnPHI(CallSite CS) { Instruction *Instr = CS.getInstruction(); BasicBlock *Parent = Instr->getParent(); if (Instr != Parent->getFirstNonPHIOrDbg()) return false; for (auto &PN : Parent->phis()) { for (auto &Arg : CS.args()) { if (&*Arg != &PN) continue; assert(PN.getNumIncomingValues() == 2 && "Unexpected number of incoming values"); if (PN.getIncomingBlock(0) == PN.getIncomingBlock(1)) return false; if (PN.getIncomingValue(0) == PN.getIncomingValue(1)) continue; if (isa<Constant>(PN.getIncomingValue(0)) && isa<Constant>(PN.getIncomingValue(1))) return true; } } return false; } using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>; // Check if any of the arguments in CS are predicated on a PHI node and return // the set of predecessors we should use for splitting. static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallSite CS) { if (!isPredicatedOnPHI(CS)) return {}; auto Preds = getTwoPredecessors(CS.getInstruction()->getParent()); return {{Preds[0], {}}, {Preds[1], {}}}; } // Checks if any of the arguments in CS are predicated in a predecessor and // returns a list of predecessors with the conditions that hold on their edges // to CS. static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallSite CS, DomTreeUpdater &DTU) { auto Preds = getTwoPredecessors(CS.getInstruction()->getParent()); if (Preds[0] == Preds[1]) return {}; // We can stop recording conditions once we reached the immediate dominator // for the block containing the call site. Conditions in predecessors of the // that node will be the same for all paths to the call site and splitting // is not beneficial. assert(DTU.hasDomTree() && "We need a DTU with a valid DT!"); auto *CSDTNode = DTU.getDomTree().getNode(CS.getInstruction()->getParent()); BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr; SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS; for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) { ConditionsTy Conditions; // Record condition on edge BB(CS) <- Pred recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions); // Record conditions following Pred's single predecessors. recordConditions(CS, Pred, Conditions, StopAt); PredsCS.push_back({Pred, Conditions}); } if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) { return P.second.empty(); })) return {}; return PredsCS; } static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI, DomTreeUpdater &DTU) { // Check if we can split the call site. if (!CS.arg_size() || !canSplitCallSite(CS, TTI)) return false; auto PredsWithConds = shouldSplitOnPredicatedArgument(CS, DTU); if (PredsWithConds.empty()) PredsWithConds = shouldSplitOnPHIPredicatedArgument(CS); if (PredsWithConds.empty()) return false; splitCallSite(CS, PredsWithConds, DTU); return true; } static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT) { DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy); bool Changed = false; for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) { BasicBlock &BB = *BI++; auto II = BB.getFirstNonPHIOrDbg()->getIterator(); auto IE = BB.getTerminator()->getIterator(); // Iterate until we reach the terminator instruction. tryToSplitCallSite // can replace BB's terminator in case BB is a successor of itself. In that // case, IE will be invalidated and we also have to check the current // terminator. while (II != IE && &*II != BB.getTerminator()) { Instruction *I = &*II++; CallSite CS(cast<Value>(I)); if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI)) continue; Function *Callee = CS.getCalledFunction(); if (!Callee || Callee->isDeclaration()) continue; // Successful musttail call-site splits result in erased CI and erased BB. // Check if such path is possible before attempting the splitting. bool IsMustTail = CS.isMustTailCall(); Changed |= tryToSplitCallSite(CS, TTI, DTU); // There're no interesting instructions after this. The call site // itself might have been erased on splitting. if (IsMustTail) break; } } return Changed; } namespace { struct CallSiteSplittingLegacyPass : public FunctionPass { static char ID; CallSiteSplittingLegacyPass() : FunctionPass(ID) { initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<TargetLibraryInfoWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); AU.addRequired<DominatorTreeWrapperPass>(); AU.addPreserved<DominatorTreeWrapperPass>(); FunctionPass::getAnalysisUsage(AU); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); return doCallSiteSplitting(F, TLI, TTI, DT); } }; } // namespace char CallSiteSplittingLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting", "Call-site splitting", false, false) INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting", "Call-site splitting", false, false) FunctionPass *llvm::createCallSiteSplittingPass() { return new CallSiteSplittingLegacyPass(); } PreservedAnalyses CallSiteSplittingPass::run(Function &F, FunctionAnalysisManager &AM) { auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); auto &TTI = AM.getResult<TargetIRAnalysis>(F); auto &DT = AM.getResult<DominatorTreeAnalysis>(F); if (!doCallSiteSplitting(F, TLI, TTI, DT)) return PreservedAnalyses::all(); PreservedAnalyses PA; PA.preserve<DominatorTreeAnalysis>(); return PA; }
37.252931
80
0.657239
davidungar
28730493d07b19a4b43e3bed1e8f4bbeca41fddc
71,569
cpp
C++
tests/vklayertests_arm_best_practices.cpp
youkim02/Vulkan-ValidationLayers
09227446c8d3a6bc1f7814adee401573cdcc8c0f
[ "Apache-2.0" ]
null
null
null
tests/vklayertests_arm_best_practices.cpp
youkim02/Vulkan-ValidationLayers
09227446c8d3a6bc1f7814adee401573cdcc8c0f
[ "Apache-2.0" ]
null
null
null
tests/vklayertests_arm_best_practices.cpp
youkim02/Vulkan-ValidationLayers
09227446c8d3a6bc1f7814adee401573cdcc8c0f
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2015-2022 The Khronos Group Inc. * Copyright (c) 2015-2022 Valve Corporation * Copyright (c) 2015-2022 LunarG, Inc. * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Author: Nathaniel Cesario <nathaniel@lunarg.com> * Author: Nadav Geva <nadav.geva@amd.com> */ #include "cast_utils.h" #include "layer_validation_tests.h" const char *kEnableArmValidation = "VALIDATION_CHECK_ENABLE_VENDOR_SPECIFIC_ARM"; // Tests for Arm-specific best practices TEST_F(VkArmBestPracticesLayerTest, TooManySamples) { TEST_DESCRIPTION("Test for multisampled images with too many samples"); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateImage-too-large-sample-count"); VkImageCreateInfo image_info{}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.extent = {1920, 1080, 1}; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; image_info.samples = VK_SAMPLE_COUNT_8_BIT; image_info.arrayLayers = 1; image_info.mipLevels = 1; VkImage image = VK_NULL_HANDLE; vk::CreateImage(m_device->device(), &image_info, nullptr, &image); m_errorMonitor->VerifyFound(); if (image) { vk::DestroyImage(m_device->device(), image, nullptr); } } TEST_F(VkArmBestPracticesLayerTest, NonTransientMSImage) { TEST_DESCRIPTION("Test for non-transient multisampled images"); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateImage-non-transient-ms-image"); VkImageCreateInfo image_info{}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.extent = {1920, 1080, 1}; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; image_info.samples = VK_SAMPLE_COUNT_4_BIT; image_info.arrayLayers = 1; image_info.mipLevels = 1; VkImage image; vk::CreateImage(m_device->device(), &image_info, nullptr, &image); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, SamplerCreation) { TEST_DESCRIPTION("Test for various checks during sampler creation"); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-different-wrapping-modes"); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping"); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-lod-bias"); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-border-clamp-color"); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-unnormalized-coordinates"); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSampler-anisotropy"); VkSamplerCreateInfo sampler_info{}; sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; sampler_info.minLod = 0.0f; sampler_info.maxLod = 4.0f; sampler_info.mipLodBias = 1.0f; sampler_info.unnormalizedCoordinates = VK_TRUE; sampler_info.anisotropyEnable = VK_TRUE; sampler_info.maxAnisotropy = 4.0f; VkSampler sampler = VK_NULL_HANDLE; vk::CreateSampler(m_device->device(), &sampler_info, nullptr, &sampler); m_errorMonitor->VerifyFound(); if (sampler) { vk::DestroySampler(m_device->device(), sampler, nullptr); } } TEST_F(VkArmBestPracticesLayerTest, MultisampledBlending) { TEST_DESCRIPTION("Test for multisampled blending"); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreatePipelines-multisampled-blending"); VkAttachmentDescription attachment{}; attachment.samples = VK_SAMPLE_COUNT_4_BIT; attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachment.format = VK_FORMAT_R16G16B16A16_SFLOAT; VkAttachmentReference color_ref{}; color_ref.attachment = 0; color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &color_ref; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; VkRenderPassCreateInfo rp_info{}; rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; rp_info.attachmentCount = 1; rp_info.pAttachments = &attachment; rp_info.subpassCount = 1; rp_info.pSubpasses = &subpass; vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &m_renderPass); m_renderPass_info = rp_info; VkPipelineMultisampleStateCreateInfo pipe_ms_state_ci = {}; pipe_ms_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; pipe_ms_state_ci.rasterizationSamples = VK_SAMPLE_COUNT_4_BIT; VkPipelineColorBlendAttachmentState blend_att = {}; blend_att.blendEnable = VK_TRUE; blend_att.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo pipe_cb_state_ci = {}; pipe_cb_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; pipe_cb_state_ci.attachmentCount = 1; pipe_cb_state_ci.pAttachments = &blend_att; CreatePipelineHelper pipe(*this); pipe.InitInfo(); pipe.pipe_ms_state_ci_ = pipe_ms_state_ci; pipe.cb_ci_ = pipe_cb_state_ci; pipe.InitState(); pipe.CreateGraphicsPipeline(); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, AttachmentNeedsReadback) { TEST_DESCRIPTION("Test for attachments that need readback"); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_clear_via_load_op = false; // Force LOAD_OP_LOAD ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback"); m_commandBuffer->begin(); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, ManySmallIndexedDrawcalls) { InitBestPracticesFramework(kEnableArmValidation); InitState(); if (IsPlatform(kNexusPlayer) || IsPlatform(kShieldTV) || IsPlatform(kShieldTVb)) { return; } m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdDrawIndexed-many-small-indexed-drawcalls"); // This test may also trigger other warnings m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation"); ASSERT_NO_FATAL_FAILURE(InitViewport()); ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); VkPipelineMultisampleStateCreateInfo pipe_ms_state_ci = {}; pipe_ms_state_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; pipe_ms_state_ci.pNext = NULL; pipe_ms_state_ci.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; pipe_ms_state_ci.sampleShadingEnable = 0; pipe_ms_state_ci.minSampleShading = 1.0; pipe_ms_state_ci.pSampleMask = NULL; CreatePipelineHelper pipe(*this); pipe.InitInfo(); pipe.pipe_ms_state_ci_ = pipe_ms_state_ci; pipe.InitState(); pipe.CreateGraphicsPipeline(); m_commandBuffer->begin(); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_); for (int i = 0; i < 10; i++) { m_commandBuffer->DrawIndexed(3, 1, 0, 0, 0); } m_errorMonitor->VerifyFound(); m_commandBuffer->EndRenderPass(); m_commandBuffer->end(); } TEST_F(VkArmBestPracticesLayerTest, SuboptimalDescriptorReuseTest) { TEST_DESCRIPTION("Test for validation warnings of potentially suboptimal re-use of descriptor set allocations"); InitBestPracticesFramework(kEnableArmValidation); InitState(); ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); VkDescriptorPoolSize ds_type_count = {}; ds_type_count.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; ds_type_count.descriptorCount = 3; VkDescriptorPoolCreateInfo ds_pool_ci = {}; ds_pool_ci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; ds_pool_ci.pNext = NULL; ds_pool_ci.maxSets = 6; ds_pool_ci.poolSizeCount = 1; ds_pool_ci.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; ds_pool_ci.pPoolSizes = &ds_type_count; VkDescriptorPool ds_pool; VkResult err = vk::CreateDescriptorPool(m_device->device(), &ds_pool_ci, NULL, &ds_pool); ASSERT_VK_SUCCESS(err); VkDescriptorSetLayoutBinding ds_binding = {}; ds_binding.binding = 0; ds_binding.descriptorCount = 1; ds_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; VkDescriptorSetLayoutCreateInfo ds_layout_info = {}; ds_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; ds_layout_info.bindingCount = 1; ds_layout_info.pBindings = &ds_binding; VkDescriptorSetLayout ds_layout; err = vk::CreateDescriptorSetLayout(m_device->device(), &ds_layout_info, nullptr, &ds_layout); ASSERT_VK_SUCCESS(err); auto ds_layouts = std::vector<VkDescriptorSetLayout>(ds_pool_ci.maxSets, ds_layout); std::vector<VkDescriptorSet> descriptor_sets = {}; descriptor_sets.resize(ds_layouts.size()); // allocate N/2 descriptor sets VkDescriptorSetAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.descriptorPool = ds_pool; alloc_info.descriptorSetCount = descriptor_sets.size() / 2; alloc_info.pSetLayouts = ds_layouts.data(); err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, descriptor_sets.data()); ASSERT_VK_SUCCESS(err); // free one descriptor set VkDescriptorSet* ds = descriptor_sets.data(); err = vk::FreeDescriptorSets(m_device->device(), ds_pool, 1, ds); // the previous allocate and free should not cause any warning ASSERT_VK_SUCCESS(err); m_errorMonitor->VerifyNotFound(); // allocate the previously freed descriptor set alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.descriptorPool = ds_pool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = ds_layouts.data(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkAllocateDescriptorSets-suboptimal-reuse"); err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, ds); // this should create a validation warning, in addition to the appropriate warning message m_errorMonitor->VerifyFound(); // allocate the remaining descriptor sets (N - (N/2)) alloc_info.descriptorSetCount = descriptor_sets.size() - (descriptor_sets.size() / 2); err = vk::AllocateDescriptorSets(m_device->device(), &alloc_info, ds); // this should create no validation warnings m_errorMonitor->VerifyNotFound(); } TEST_F(VkArmBestPracticesLayerTest, SparseIndexBufferTest) { TEST_DESCRIPTION( "Test for appropriate warnings to be thrown when recording an indexed draw call with sparse/non-sparse index buffers."); InitBestPracticesFramework(kEnableArmValidation); InitState(); ASSERT_NO_FATAL_FAILURE(InitViewport()); ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); if (IsPlatform(kMockICD) || DeviceSimulation()) { printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix); return; } // create a non-sparse index buffer std::vector<uint16_t> nonsparse_indices; nonsparse_indices.resize(128); for (unsigned i = 0; i < nonsparse_indices.size(); i++) { nonsparse_indices[i] = i; } // another example of non-sparsity where the number of indices is also very small std::vector<uint16_t> nonsparse_indices_2 = {0, 1, 2, 3, 4, 5, 6, 7}; // smallest possible meaningful index buffer std::vector<uint16_t> nonsparse_indices_3 = {0}; // another example of non-sparsity, all the indices are the same value (42) std::vector<uint16_t> nonsparse_indices_4 = {}; nonsparse_indices_4.resize(128); std::fill(nonsparse_indices_4.begin(), nonsparse_indices_4.end(), 42); std::vector<uint16_t> sparse_indices = nonsparse_indices; // The buffer (0, 1, 2, ..., n) is completely un-sparse. However, if n < 0xFFFF, by adding 0xFFFF at the end, we // should trigger a warning due to loading all the indices in the range 0 to 0xFFFF, despite indices in the range // (n+1) to (0xFFFF - 1) not being used. sparse_indices[sparse_indices.size() - 1] = 0xFFFF; VkConstantBufferObj nonsparse_ibo(m_device, nonsparse_indices.size() * sizeof(uint16_t), nonsparse_indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); VkConstantBufferObj nonsparse_ibo_2(m_device, nonsparse_indices_2.size() * sizeof(uint16_t), nonsparse_indices_2.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); VkConstantBufferObj nonsparse_ibo_3(m_device, nonsparse_indices_3.size() * sizeof(uint16_t), nonsparse_indices_3.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); VkConstantBufferObj nonsparse_ibo_4(m_device, nonsparse_indices_4.size() * sizeof(uint16_t), nonsparse_indices_4.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); VkConstantBufferObj sparse_ibo(m_device, sparse_indices.size() * sizeof(uint16_t), sparse_indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); auto test_pipelines = [&](VkConstantBufferObj& ibo, size_t index_count, bool expect_error) -> void { CreatePipelineHelper pipe(*this); pipe.InitInfo(); pipe.InitState(); pipe.ia_ci_.primitiveRestartEnable = VK_FALSE; pipe.CreateGraphicsPipeline(); // pipeline with primitive restarts enabled CreatePipelineHelper pr_pipe(*this); pr_pipe.InitInfo(); pr_pipe.InitState(); pr_pipe.ia_ci_.primitiveRestartEnable = VK_TRUE; pr_pipe.CreateGraphicsPipeline(); m_commandBuffer->reset(); m_commandBuffer->begin(); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_); m_commandBuffer->BindIndexBuffer(&ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16); m_errorMonitor->VerifyNotFound(); // the validation layer will only be able to analyse mapped memory, it's too expensive otherwise to do in the layer itself ibo.memory().map(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdDrawIndexed-sparse-index-buffer"); m_commandBuffer->DrawIndexed(index_count, 0, 0, 0, 0); if (expect_error) { m_errorMonitor->VerifyFound(); } else { m_errorMonitor->VerifyNotFound(); } ibo.memory().unmap(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdDrawIndexed-sparse-index-buffer"); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pr_pipe.pipeline_); m_commandBuffer->BindIndexBuffer(&ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16); m_errorMonitor->VerifyNotFound(); ibo.memory().map(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdDrawIndexed-sparse-index-buffer"); m_commandBuffer->DrawIndexed(index_count, 0, 0, 0, 0); if (expect_error) { m_errorMonitor->VerifyFound(); } else { m_errorMonitor->VerifyNotFound(); } ibo.memory().unmap(); m_errorMonitor->Reset(); }; // our non-sparse indices should not trigger a warning for either pipeline in this case test_pipelines(nonsparse_ibo, nonsparse_indices.size(), false); test_pipelines(nonsparse_ibo_2, nonsparse_indices_2.size(), false); test_pipelines(nonsparse_ibo_3, nonsparse_indices_3.size(), false); test_pipelines(nonsparse_ibo_4, nonsparse_indices_4.size(), false); // our sparse indices should trigger warnings for both pipelines in this case test_pipelines(sparse_ibo, sparse_indices.size(), true); } TEST_F(VkArmBestPracticesLayerTest, PostTransformVertexCacheThrashingIndicesTest) { TEST_DESCRIPTION( "Test for appropriate warnings to be thrown when recording an indexed draw call where the indices thrash the " "post-transform vertex cache."); InitBestPracticesFramework(kEnableArmValidation); InitState(); ASSERT_NO_FATAL_FAILURE(InitViewport()); ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); if (IsPlatform(kMockICD) || DeviceSimulation()) { printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix); return; } CreatePipelineHelper pipe(*this); pipe.InitInfo(); pipe.InitState(); pipe.CreateGraphicsPipeline(); m_commandBuffer->begin(); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe.pipeline_); std::vector<uint16_t> worst_indices; worst_indices.resize(128 * 16); for (size_t i = 0; i < 16; i++) { for (size_t j = 0; j < 128; j++) { // worst case index buffer sequence for re-use // (0, 1, 2, 3, ..., 127, 0, 1, 2, 3, ..., 127, 0, 1, 2, ...<x16>) worst_indices[j + i * 128] = j; } } std::vector<uint16_t> best_indices; best_indices.resize(128 * 16); for (size_t i = 0; i < 16; i++) { for (size_t j = 0; j < 128; j++) { // best case index buffer sequence for re-use // (0, 0, 0, ...<x16>, 1, 1, 1, ...<x16>, 2, 2, 2, ...<x16> , ..., 127) best_indices[i + j * 16] = j; } } // make sure the worst-case indices throw a warning VkConstantBufferObj worst_ibo(m_device, worst_indices.size() * sizeof(uint16_t), worst_indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); m_commandBuffer->BindIndexBuffer(&worst_ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16); m_errorMonitor->VerifyNotFound(); // the validation layer will only be able to analyse mapped memory, it's too expensive otherwise to do in the layer itself worst_ibo.memory().map(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdDrawIndexed-post-transform-cache-thrashing"); m_commandBuffer->DrawIndexed(worst_indices.size(), 0, 0, 0, 0); m_errorMonitor->VerifyFound(); worst_ibo.memory().unmap(); // make sure that the best-case indices don't throw a warning VkConstantBufferObj best_ibo(m_device, best_indices.size() * sizeof(uint16_t), best_indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); m_commandBuffer->BindIndexBuffer(&best_ibo, static_cast<VkDeviceSize>(0), VK_INDEX_TYPE_UINT16); m_errorMonitor->VerifyNotFound(); best_ibo.memory().map(); m_commandBuffer->DrawIndexed(best_indices.size(), 0, 0, 0, 0); m_errorMonitor->VerifyNotFound(); best_ibo.memory().unmap(); } TEST_F(VkArmBestPracticesLayerTest, PresentModeTest) { TEST_DESCRIPTION("Test for usage of Presentation Modes"); AddSurfaceInstanceExtension(); InitBestPracticesFramework(kEnableArmValidation); AddSwapchainDeviceExtension(); InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo"); if (!InitSurface()) { printf("%s Cannot create surface, skipping test\n", kSkipPrefix); return; } InitSwapchainInfo(); VkBool32 supported; vk::GetPhysicalDeviceSurfaceSupportKHR(gpu(), m_device->graphics_queue_node_index_, m_surface, &supported); if (!supported) { printf("%s Graphics queue does not support present, skipping test\n", kSkipPrefix); return; } VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; VkSwapchainCreateInfoKHR swapchain_create_info = {}; swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchain_create_info.pNext = 0; swapchain_create_info.surface = m_surface; swapchain_create_info.minImageCount = m_surface_capabilities.minImageCount; swapchain_create_info.imageFormat = m_surface_formats[0].format; swapchain_create_info.imageColorSpace = m_surface_formats[0].colorSpace; swapchain_create_info.imageExtent = {m_surface_capabilities.minImageExtent.width, m_surface_capabilities.minImageExtent.height}; swapchain_create_info.imageArrayLayers = 1; swapchain_create_info.imageUsage = imageUsage; swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_create_info.preTransform = preTransform; swapchain_create_info.clipped = VK_FALSE; swapchain_create_info.oldSwapchain = 0; swapchain_create_info.compositeAlpha = m_surface_composite_alpha; if (m_surface_present_modes.size() <= 1) { printf("TEST SKIPPED: Only %i presentation mode is available!", int(m_surface_present_modes.size())); return; } for (size_t i = 0; i < m_surface_present_modes.size(); i++) { if (m_surface_present_modes[i] != VK_PRESENT_MODE_FIFO_KHR) { swapchain_create_info.presentMode = m_surface_present_modes[i]; break; } } VkResult err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain); m_errorMonitor->VerifyFound(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo"); swapchain_create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR; err = vk::CreateSwapchainKHR(device(), &swapchain_create_info, nullptr, &m_swapchain); m_errorMonitor->VerifyNotFound(); ASSERT_VK_SUCCESS(err) DestroySwapchain(); } TEST_F(VkArmBestPracticesLayerTest, PipelineDepthBiasZeroTest) { TEST_DESCRIPTION("Test for unnecessary rasterization due to using 0 for depthBiasConstantFactor and depthBiasSlopeFactor"); InitBestPracticesFramework(kEnableArmValidation); InitState(); ASSERT_NO_FATAL_FAILURE(InitViewport()); ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); CreatePipelineHelper pipe(*this); pipe.InitInfo(); pipe.rs_state_ci_.depthBiasEnable = VK_TRUE; pipe.rs_state_ci_.depthBiasConstantFactor = 0.0f; pipe.rs_state_ci_.depthBiasSlopeFactor = 0.0f; pipe.InitState(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreatePipelines-depthbias-zero"); pipe.CreateGraphicsPipeline(); m_errorMonitor->VerifyFound(); pipe.rs_state_ci_.depthBiasEnable = VK_FALSE; m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreatePipelines-depthbias-zero"); pipe.CreateGraphicsPipeline(); m_errorMonitor->VerifyNotFound(); } TEST_F(VkArmBestPracticesLayerTest, RobustBufferAccessTest) { TEST_DESCRIPTION("Test for appropriate warnings to be thrown when robustBufferAccess is enabled."); InitBestPracticesFramework(kEnableArmValidation); VkDevice local_device; VkDeviceQueueCreateInfo queue_info = {}; queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info.pNext = nullptr; queue_info.queueFamilyIndex = 0; queue_info.queueCount = 1; queue_info.pQueuePriorities = nullptr; VkDeviceCreateInfo dev_info = {}; dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; dev_info.pNext = nullptr; dev_info.queueCreateInfoCount = 1; dev_info.pQueueCreateInfos = &queue_info; dev_info.enabledLayerCount = 0; dev_info.ppEnabledLayerNames = nullptr; dev_info.enabledExtensionCount = m_device_extension_names.size(); dev_info.ppEnabledExtensionNames = m_device_extension_names.data(); VkPhysicalDeviceFeatures supported_features; vk::GetPhysicalDeviceFeatures(this->gpu(), &supported_features); if (supported_features.robustBufferAccess) { m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateDevice-RobustBufferAccess"); VkPhysicalDeviceFeatures device_features = {}; device_features.robustBufferAccess = VK_TRUE; dev_info.pEnabledFeatures = &device_features; vk::CreateDevice(this->gpu(), &dev_info, nullptr, &local_device); m_errorMonitor->VerifyFound(); } else { printf("%s robustBufferAccess is not available, skipping test\n", kSkipPrefix); return; } } TEST_F(VkArmBestPracticesLayerTest, DepthPrePassUsage) { InitBestPracticesFramework(kEnableArmValidation); InitState(); if (IsPlatform(kNexusPlayer)) { printf("%s This test crashes on the NexusPlayer platform\n", kSkipPrefix); return; } m_depth_stencil_fmt = FindSupportedDepthStencilFormat(gpu()); ASSERT_TRUE(m_depth_stencil_fmt != 0); m_depthStencil->Init(m_device, static_cast<int32_t>(m_width), static_cast<int32_t>(m_height), m_depth_stencil_fmt); InitRenderTarget(m_depthStencil->BindInfo()); VkAttachmentDescription attachment{}; attachment.samples = VK_SAMPLE_COUNT_4_BIT; attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkRenderPassCreateInfo rp_info{}; rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; rp_info.attachmentCount = 1; rp_info.pAttachments = &attachment; rp_info.pNext = nullptr; VkRenderPass rp = VK_NULL_HANDLE; vk::CreateRenderPass(m_device->device(), &rp_info, nullptr, &rp); // set up pipelines VkPipelineColorBlendAttachmentState color_write_off = {}; VkPipelineColorBlendAttachmentState color_write_on = {}; color_write_on.colorWriteMask = 0xF; VkPipelineColorBlendStateCreateInfo cb_depth_only_ci = {}; cb_depth_only_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cb_depth_only_ci.attachmentCount = 1; cb_depth_only_ci.pAttachments = &color_write_off; VkPipelineColorBlendStateCreateInfo cb_depth_equal_ci = {}; cb_depth_equal_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cb_depth_equal_ci.attachmentCount = 1; cb_depth_equal_ci.pAttachments = &color_write_on; VkPipelineDepthStencilStateCreateInfo ds_depth_only_ci = {}; ds_depth_only_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; ds_depth_only_ci.depthTestEnable = VK_TRUE; ds_depth_only_ci.depthWriteEnable = VK_TRUE; ds_depth_only_ci.depthCompareOp = VK_COMPARE_OP_LESS; VkPipelineDepthStencilStateCreateInfo ds_depth_equal_ci = {}; ds_depth_equal_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; ds_depth_equal_ci.depthTestEnable = VK_TRUE; ds_depth_equal_ci.depthWriteEnable = VK_FALSE; ds_depth_equal_ci.depthCompareOp = VK_COMPARE_OP_EQUAL; CreatePipelineHelper pipe_depth_only(*this); pipe_depth_only.InitInfo(); pipe_depth_only.gp_ci_.pColorBlendState = &cb_depth_only_ci; pipe_depth_only.gp_ci_.pDepthStencilState = &ds_depth_only_ci; pipe_depth_only.InitState(); pipe_depth_only.CreateGraphicsPipeline(); CreatePipelineHelper pipe_depth_equal(*this); pipe_depth_equal.InitInfo(); pipe_depth_equal.gp_ci_.pColorBlendState = &cb_depth_equal_ci; pipe_depth_equal.gp_ci_.pDepthStencilState = &ds_depth_equal_ci; pipe_depth_equal.InitState(); pipe_depth_equal.CreateGraphicsPipeline(); // create a simple index buffer std::vector<uint32_t> indices = {}; indices.resize(3); VkConstantBufferObj ibo(m_device, sizeof(uint32_t) * indices.size(), indices.data(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT); m_commandBuffer->begin(); m_commandBuffer->BindIndexBuffer(&ibo, 0, VK_INDEX_TYPE_UINT32); // record a command buffer which doesn't use enough depth pre-passes or geometry to matter m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_only.pipeline_); for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 10, 0, 0, 0); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_equal.pipeline_); for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 10, 0, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyNotFound(); // record a command buffer which records a significant number of depth pre-passes m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-vkCmdEndRenderPass-depth-pre-pass-usage"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_only.pipeline_); for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 1000, 0, 0, 0); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth_equal.pipeline_); for (size_t i = 0; i < 30; i++) m_commandBuffer->DrawIndexed(indices.size(), 1000, 0, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyFound(); m_commandBuffer->end(); } TEST_F(VkArmBestPracticesLayerTest, ComputeShaderBadWorkGroupThreadAlignmentTest) { TEST_DESCRIPTION( "Testing for cases where compute shaders will be dispatched in an inefficient way, due to work group dispatch counts on " "Arm Mali architectures."); InitBestPracticesFramework(kEnableArmValidation); InitState(); VkShaderObj compute_4_1_1(this, "#version 320 es\n" "\n" "layout(local_size_x = 4, local_size_y = 1, local_size_z = 1) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_4_1_3(this, "#version 320 es\n" "\n" "layout(local_size_x = 4, local_size_y = 1, local_size_z = 3) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_16_8_1(this, "#version 320 es\n" "\n" "layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); CreateComputePipelineHelper pipe(*this); auto makePipelineWithShader = [=](CreateComputePipelineHelper& pipe, const VkPipelineShaderStageCreateInfo& stage) { pipe.InitInfo(); pipe.InitState(); pipe.cp_ci_.stage = stage; pipe.dsl_bindings_ = {}; pipe.cp_ci_.layout = pipe.pipeline_layout_.handle(); pipe.CreateComputePipeline(true, false); }; // these two pipelines should not cause any warning m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-thread-group-alignment"); makePipelineWithShader(pipe, compute_4_1_1.GetStageCreateInfo()); m_errorMonitor->VerifyNotFound(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-thread-group-alignment"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size"); makePipelineWithShader(pipe, compute_16_8_1.GetStageCreateInfo()); m_errorMonitor->VerifyNotFound(); // this pipeline should cause a warning due to bad work group alignment m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-thread-group-alignment"); makePipelineWithShader(pipe, compute_4_1_3.GetStageCreateInfo()); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, ComputeShaderBadWorkGroupThreadCountTest) { TEST_DESCRIPTION( "Testing for cases where the number of work groups spawned is greater than advised for Arm Mali architectures."); InitBestPracticesFramework(kEnableArmValidation); InitState(); VkShaderObj compute_4_1_1(this, "#version 320 es\n" "\n" "layout(local_size_x = 4, local_size_y = 1, local_size_z = 1) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_4_1_3(this, "#version 320 es\n" "\n" "layout(local_size_x = 4, local_size_y = 1, local_size_z = 3) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_16_8_1(this, "#version 320 es\n" "\n" "layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in;\n\n" "void main() {}\n", VK_SHADER_STAGE_COMPUTE_BIT); CreateComputePipelineHelper pipe(*this); auto make_pipeline_with_shader = [=](CreateComputePipelineHelper& pipe, const VkPipelineShaderStageCreateInfo& stage) { pipe.InitInfo(); pipe.InitState(); pipe.cp_ci_.stage = stage; pipe.dsl_bindings_ = {}; pipe.cp_ci_.layout = pipe.pipeline_layout_.handle(); pipe.CreateComputePipeline(true, false); }; // these two pipelines should not cause any warning m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size"); make_pipeline_with_shader(pipe, compute_4_1_1.GetStageCreateInfo()); m_errorMonitor->VerifyNotFound(); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-thread-group-alignment"); make_pipeline_with_shader(pipe, compute_4_1_3.GetStageCreateInfo()); m_errorMonitor->VerifyNotFound(); // this pipeline should cause a warning due to the total workgroup count m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size"); make_pipeline_with_shader(pipe, compute_16_8_1.GetStageCreateInfo()); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, ComputeShaderBadSpatialLocalityTest) { TEST_DESCRIPTION( "Testing for cases where a compute shader's configuration makes poor use of spatial locality, on Arm Mali architectures, " "for one or more of its resources."); InitBestPracticesFramework(kEnableArmValidation); InitState(); VkShaderObj compute_sampler_2d_8_8_1(this, "#version 450\n" "layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;\n\n" "layout(set = 0, binding = 0) uniform sampler2D uSampler;\n" "void main() {\n" " vec4 value = textureLod(uSampler, vec2(0.5), 0.0);\n" "}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_sampler_1d_64_1_1(this, "#version 450\n" "layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;\n\n" "layout(set = 0, binding = 0) uniform sampler1D uSampler;\n" "void main() {\n" " vec4 value = textureLod(uSampler, 0.5, 0.0);\n" "}\n", VK_SHADER_STAGE_COMPUTE_BIT); VkShaderObj compute_sampler_2d_64_1_1(this, "#version 450\n" "layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;\n\n" "layout(set = 0, binding = 0) uniform sampler2D uSampler;\n" "void main() {\n" " vec4 value = textureLod(uSampler, vec2(0.5), 0.0);\n" "}\n", VK_SHADER_STAGE_COMPUTE_BIT); CreateComputePipelineHelper pipe(*this); auto make_pipeline_with_shader = [this](CreateComputePipelineHelper& pipe, const VkPipelineShaderStageCreateInfo& stage) { VkDescriptorSetLayoutBinding sampler_binding = {}; sampler_binding.binding = 0; sampler_binding.descriptorCount = 1; sampler_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; sampler_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; pipe.InitInfo(); pipe.InitState(); auto ds_layout = std::unique_ptr<VkDescriptorSetLayoutObj>(new VkDescriptorSetLayoutObj(m_device, {sampler_binding})); auto pipe_layout = std::unique_ptr<VkPipelineLayoutObj>(new VkPipelineLayoutObj(m_device, {ds_layout.get()})); pipe.cp_ci_.stage = stage; pipe.cp_ci_.layout = pipe_layout->handle(); pipe.CreateComputePipeline(true, false); }; auto* this_ptr = this; // Required for older compilers with c++20 compatibility auto test_spatial_locality = [=](CreateComputePipelineHelper& pipe, const VkPipelineShaderStageCreateInfo& stage, bool positive_test, const std::vector<std::string>& allowed = {}) { this_ptr->m_errorMonitor->SetDesiredFailureMsg( VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-spatial-locality"); make_pipeline_with_shader(pipe, stage); if (positive_test) { this_ptr->m_errorMonitor->VerifyFound(); } else { this_ptr->m_errorMonitor->VerifyNotFound(); } }; test_spatial_locality(pipe, compute_sampler_2d_8_8_1.GetStageCreateInfo(), false); test_spatial_locality(pipe, compute_sampler_1d_64_1_1.GetStageCreateInfo(), false); test_spatial_locality(pipe, compute_sampler_2d_64_1_1.GetStageCreateInfo(), true); } TEST_F(VkArmBestPracticesLayerTest, RedundantRenderPassStore) { TEST_DESCRIPTION("Test for appropriate warnings to be thrown when a redundant store is used."); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-RenderPass-redundant-store"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); const VkFormat FMT = VK_FORMAT_R8G8B8A8_UNORM; const uint32_t WIDTH = 512, HEIGHT = 512; std::vector<std::unique_ptr<VkImageObj>> images; std::vector<VkRenderPass> renderpasses; std::vector<VkFramebuffer> framebuffers; images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); renderpasses.push_back(CreateRenderPass(FMT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE)); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[0]->targetView(FMT), renderpasses[0])); images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); renderpasses.push_back(CreateRenderPass(FMT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE)); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[1]->targetView(FMT), renderpasses[1])); CreatePipelineHelper graphics_pipeline(*this); graphics_pipeline.vs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT)); graphics_pipeline.fs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateFragSamplerShaderText, VK_SHADER_STAGE_FRAGMENT_BIT)); graphics_pipeline.InitInfo(); graphics_pipeline.dsl_bindings_[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; graphics_pipeline.InitState(); graphics_pipeline.gp_ci_.renderPass = renderpasses[1]; graphics_pipeline.gp_ci_.flags = 0; graphics_pipeline.CreateGraphicsPipeline(); VkClearValue clear_values[3]; memset(clear_values, 0, sizeof(clear_values)); VkRenderPassBeginInfo render_pass_begin_info = {}; render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; render_pass_begin_info.renderPass = renderpasses[0]; render_pass_begin_info.framebuffer = framebuffers[0]; render_pass_begin_info.clearValueCount = 3; render_pass_begin_info.pClearValues = clear_values; const auto execute_work = [&](const std::function<void(VkCommandBufferObj & command_buffer)>& work) { m_commandBuffer->begin(); work(*m_commandBuffer); m_commandBuffer->end(); VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &m_commandBuffer->handle(); vk::QueueSubmit(m_device->m_queue, 1, &submit, VK_NULL_HANDLE); vk::QueueWaitIdle(m_device->m_queue); }; const auto start_and_end_renderpass = [&](VkCommandBufferObj& command_buffer) { command_buffer.BeginRenderPass(render_pass_begin_info); command_buffer.EndRenderPass(); }; execute_work(start_and_end_renderpass); // Use the image somehow. execute_work([&](VkCommandBufferObj& command_buffer) { VkRenderPassBeginInfo rpbi = {}; rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rpbi.renderPass = renderpasses[1]; rpbi.framebuffer = framebuffers[1]; rpbi.clearValueCount = 3; rpbi.pClearValues = clear_values; command_buffer.BeginRenderPass(rpbi); vk::CmdBindPipeline(command_buffer.handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(WIDTH); viewport.height = static_cast<float>(HEIGHT); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; command_buffer.SetViewport(0, 1, &viewport); command_buffer.Draw(3, 1, 0, 0); command_buffer.EndRenderPass(); }); execute_work(start_and_end_renderpass); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, RedundantRenderPassClear) { TEST_DESCRIPTION("Test for appropriate warnings to be thrown when a redundant clear is used."); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-RenderPass-redundant-clear"); const VkFormat FMT = VK_FORMAT_R8G8B8A8_UNORM; const uint32_t WIDTH = 512, HEIGHT = 512; std::vector<std::unique_ptr<VkImageObj>> images; std::vector<VkRenderPass> renderpasses; std::vector<VkFramebuffer> framebuffers; images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); renderpasses.push_back(CreateRenderPass(FMT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE)); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[0]->targetView(FMT), renderpasses[0])); CreatePipelineHelper graphics_pipeline(*this); graphics_pipeline.vs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT)); graphics_pipeline.fs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateFragShaderText, VK_SHADER_STAGE_FRAGMENT_BIT)); graphics_pipeline.InitInfo(); graphics_pipeline.dsl_bindings_[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; graphics_pipeline.cb_attachments_.colorWriteMask = 0xf; graphics_pipeline.cb_ci_.attachmentCount = 1; graphics_pipeline.cb_ci_.pAttachments = &graphics_pipeline.cb_attachments_; graphics_pipeline.InitState(); graphics_pipeline.gp_ci_.renderPass = renderpasses[0]; graphics_pipeline.gp_ci_.flags = 0; graphics_pipeline.CreateGraphicsPipeline(); VkClearValue clear_values[3]; memset(clear_values, 0, sizeof(clear_values)); VkRenderPassBeginInfo render_pass_begin_info = {}; render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; render_pass_begin_info.renderPass = renderpasses[0]; render_pass_begin_info.framebuffer = framebuffers[0]; render_pass_begin_info.clearValueCount = 3; render_pass_begin_info.pClearValues = clear_values; m_commandBuffer->begin(); VkClearColorValue clear_color_value = {}; VkImageSubresourceRange subresource_range = {}; subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresource_range.layerCount = VK_REMAINING_ARRAY_LAYERS; subresource_range.levelCount = VK_REMAINING_MIP_LEVELS; m_commandBuffer->ClearColorImage(images[0]->image(), VK_IMAGE_LAYOUT_GENERAL, &clear_color_value, 1, &subresource_range); m_commandBuffer->BeginRenderPass(render_pass_begin_info); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(WIDTH); viewport.height = static_cast<float>(HEIGHT); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; m_commandBuffer->SetViewport(0, 1, &viewport); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_); m_commandBuffer->Draw(3, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_commandBuffer->end(); VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &m_commandBuffer->handle(); vk::QueueSubmit(m_device->m_queue, 1, &submit, VK_NULL_HANDLE); vk::QueueWaitIdle(m_device->m_queue); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, InefficientRenderPassClear) { TEST_DESCRIPTION("Test for appropriate warnings to be thrown when a redundant clear is used on a LOAD_OP_LOAD attachment."); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-RenderPass-inefficient-clear"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback"); const VkFormat FMT = VK_FORMAT_R8G8B8A8_UNORM; const uint32_t WIDTH = 512, HEIGHT = 512; std::vector<std::unique_ptr<VkImageObj>> images; std::vector<VkRenderPass> renderpasses; std::vector<VkFramebuffer> framebuffers; images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); renderpasses.push_back(CreateRenderPass(FMT, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE)); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[0]->targetView(FMT), renderpasses[0])); CreatePipelineHelper graphics_pipeline(*this); graphics_pipeline.vs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT)); graphics_pipeline.fs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateFragShaderText, VK_SHADER_STAGE_FRAGMENT_BIT)); graphics_pipeline.InitInfo(); graphics_pipeline.dsl_bindings_[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; graphics_pipeline.cb_attachments_.colorWriteMask = 0xf; graphics_pipeline.cb_ci_.attachmentCount = 1; graphics_pipeline.cb_ci_.pAttachments = &graphics_pipeline.cb_attachments_; graphics_pipeline.InitState(); graphics_pipeline.gp_ci_.renderPass = renderpasses[0]; graphics_pipeline.gp_ci_.flags = 0; graphics_pipeline.CreateGraphicsPipeline(); VkClearValue clear_values[3]; memset(clear_values, 0, sizeof(clear_values)); VkRenderPassBeginInfo render_pass_begin_info = {}; render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; render_pass_begin_info.renderPass = renderpasses[0]; render_pass_begin_info.framebuffer = framebuffers[0]; render_pass_begin_info.clearValueCount = 3; render_pass_begin_info.pClearValues = clear_values; m_commandBuffer->begin(); VkClearColorValue clear_color_value = {}; VkImageSubresourceRange subresource_range = {}; subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresource_range.layerCount = VK_REMAINING_ARRAY_LAYERS; subresource_range.levelCount = VK_REMAINING_MIP_LEVELS; m_commandBuffer->ClearColorImage(images[0]->image(), VK_IMAGE_LAYOUT_GENERAL, &clear_color_value, 1, &subresource_range); m_commandBuffer->BeginRenderPass(render_pass_begin_info); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(WIDTH); viewport.height = static_cast<float>(HEIGHT); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; m_commandBuffer->SetViewport(0, 1, &viewport); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_); m_commandBuffer->Draw(3, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_commandBuffer->end(); VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &m_commandBuffer->handle(); vk::QueueSubmit(m_device->m_queue, 1, &submit, VK_NULL_HANDLE); vk::QueueWaitIdle(m_device->m_queue); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, DescriptorTracking) { TEST_DESCRIPTION("Tests that we track descriptors, which means we should not trigger warnings."); InitBestPracticesFramework(kEnableArmValidation); InitState(); m_errorMonitor->SetDesiredFailureMsg(kPerformanceWarningBit, "UNASSIGNED-BestPractices-RenderPass-inefficient-clear"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback"); const VkFormat FMT = VK_FORMAT_R8G8B8A8_UNORM; const uint32_t WIDTH = 512, HEIGHT = 512; std::vector<std::unique_ptr<VkImageObj>> images; std::vector<VkRenderPass> renderpasses; std::vector<VkFramebuffer> framebuffers; images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); renderpasses.push_back(CreateRenderPass(FMT, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE)); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[0]->targetView(FMT), renderpasses[0])); framebuffers.push_back(CreateFramebuffer(WIDTH, HEIGHT, images[1]->targetView(FMT), renderpasses[0])); CreatePipelineHelper graphics_pipeline(*this); graphics_pipeline.vs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT)); graphics_pipeline.fs_ = std::unique_ptr<VkShaderObj>(new VkShaderObj(this, bindStateFragShaderText, VK_SHADER_STAGE_FRAGMENT_BIT)); graphics_pipeline.InitInfo(); graphics_pipeline.dsl_bindings_.resize(2); graphics_pipeline.dsl_bindings_[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // Tests that we correctly handle weird binding layouts. graphics_pipeline.dsl_bindings_[0].binding = 20; graphics_pipeline.dsl_bindings_[0].descriptorCount = 1; graphics_pipeline.dsl_bindings_[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; graphics_pipeline.dsl_bindings_[1].binding = 10; graphics_pipeline.dsl_bindings_[1].descriptorCount = 4; graphics_pipeline.cb_ci_.attachmentCount = 1; graphics_pipeline.cb_ci_.pAttachments = &graphics_pipeline.cb_attachments_; graphics_pipeline.cb_attachments_.colorWriteMask = 0xf; graphics_pipeline.InitState(); graphics_pipeline.gp_ci_.renderPass = renderpasses[0]; graphics_pipeline.gp_ci_.flags = 0; graphics_pipeline.CreateGraphicsPipeline(); VkDescriptorPoolSize pool_sizes[2] = {}; pool_sizes[0].descriptorCount = 1; pool_sizes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; pool_sizes[1].descriptorCount = 4; pool_sizes[1].type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; VkDescriptorPool pool; VkDescriptorPoolCreateInfo descriptor_pool_create_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; descriptor_pool_create_info.maxSets = 1; descriptor_pool_create_info.poolSizeCount = 2; descriptor_pool_create_info.pPoolSizes = pool_sizes; vk::CreateDescriptorPool(m_device->handle(), &descriptor_pool_create_info, nullptr, &pool); VkDescriptorSet descriptor_set{VK_NULL_HANDLE}; VkDescriptorSetAllocateInfo descriptor_set_allocate_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; descriptor_set_allocate_info.descriptorPool = pool; descriptor_set_allocate_info.descriptorSetCount = 1; descriptor_set_allocate_info.pSetLayouts = &graphics_pipeline.descriptor_set_->layout_.handle(); vk::AllocateDescriptorSets(m_device->handle(), &descriptor_set_allocate_info, &descriptor_set); VkDescriptorImageInfo image_info = {}; image_info.imageView = images[1]->targetView(FMT); image_info.sampler = VK_NULL_HANDLE; image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkWriteDescriptorSet write = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; write.descriptorCount = 1; write.dstBinding = 10; write.dstArrayElement = 1; write.dstSet = descriptor_set; write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; write.pImageInfo = &image_info; vk::UpdateDescriptorSets(m_device->handle(), 1, &write, 0, nullptr); VkClearValue clear_values[3]; memset(clear_values, 0, sizeof(clear_values)); VkRenderPassBeginInfo render_pass_begin_info = {}; render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; render_pass_begin_info.renderPass = renderpasses[0]; render_pass_begin_info.framebuffer = framebuffers[0]; render_pass_begin_info.clearValueCount = 3; render_pass_begin_info.pClearValues = clear_values; m_commandBuffer->begin(); VkClearColorValue clear_color_value = {}; VkImageSubresourceRange subresource_range = {}; subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresource_range.layerCount = VK_REMAINING_ARRAY_LAYERS; subresource_range.levelCount = VK_REMAINING_MIP_LEVELS; m_commandBuffer->ClearColorImage(images[1]->image(), VK_IMAGE_LAYOUT_GENERAL, &clear_color_value, 1, &subresource_range); // Trigger a read on the image. m_commandBuffer->BeginRenderPass(render_pass_begin_info); { vk::CmdBindDescriptorSets(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_layout_.handle(), 0, 1, &descriptor_set, 0, nullptr); VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(WIDTH); viewport.height = static_cast<float>(HEIGHT); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; m_commandBuffer->SetViewport(0, 1, &viewport); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_); m_commandBuffer->Draw(3, 1, 0, 0); } m_commandBuffer->EndRenderPass(); // Now, LOAD_OP_LOAD, which should not trigger since we already read the image. render_pass_begin_info.framebuffer = framebuffers[1]; m_commandBuffer->BeginRenderPass(render_pass_begin_info); { VkViewport viewport; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(WIDTH); viewport.height = static_cast<float>(HEIGHT); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; m_commandBuffer->SetViewport(0, 1, &viewport); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline.pipeline_); m_commandBuffer->Draw(3, 1, 0, 0); } m_commandBuffer->EndRenderPass(); m_commandBuffer->end(); VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &m_commandBuffer->handle(); vk::QueueSubmit(m_device->m_queue, 1, &submit, VK_NULL_HANDLE); vk::QueueWaitIdle(m_device->m_queue); m_errorMonitor->VerifyNotFound(); } TEST_F(VkArmBestPracticesLayerTest, BlitImageLoadOpLoad) { TEST_DESCRIPTION("Test for vkBlitImage followed by a LoadOpLoad renderpass"); ASSERT_NO_FATAL_FAILURE(InitBestPracticesFramework(kEnableArmValidation)); InitState(); m_clear_via_load_op = false; // Force LOAD_OP_LOAD ASSERT_NO_FATAL_FAILURE(InitRenderTarget()); m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-RenderPass-blitimage-loadopload"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkAllocateMemory-small-allocation"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkBindMemory-small-dedicated-allocation"); // On tiled renderers, this can also trigger a warning about LOAD_OP_LOAD causing a readback m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdBeginRenderPass-attachment-needs-readback"); m_errorMonitor->SetAllowedFailureMsg("UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); m_commandBuffer->begin(); const VkFormat FMT = VK_FORMAT_R8G8B8A8_UNORM; const uint32_t WIDTH = 512, HEIGHT = 512; std::vector<std::unique_ptr<VkImageObj>> images; images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); images.push_back(CreateImage(FMT, WIDTH, HEIGHT)); VkImageMemoryBarrier image_barriers[2] = { {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, 0, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, images[0]->image(), { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }}, {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, images[1]->image(), { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }}, }; m_commandBuffer->PipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 2, image_barriers); VkOffset3D blit_size{WIDTH, HEIGHT, 1}; VkImageBlit blit_region{}; blit_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit_region.srcSubresource.layerCount = 1; blit_region.srcOffsets[1] = blit_size; blit_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit_region.dstSubresource.layerCount = 1; blit_region.dstOffsets[1] = blit_size; vk::CmdBlitImage(m_commandBuffer->handle(), images[0]->image(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images[1]->image(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_region, VK_FILTER_LINEAR); VkImageMemoryBarrier pre_render_pass_barrier{ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, images[0]->image(), { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } }; m_commandBuffer->PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &pre_render_pass_barrier); // A renderpass with two subpasses, both writing the same attachment. VkAttachmentDescription attach[] = { {0, FMT, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, }; VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; VkSubpassDescription subpass = { 0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, nullptr, 1, &ref, nullptr, nullptr, 0, nullptr, }; VkRenderPassCreateInfo rpci = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, nullptr, 0, 1, attach, 1, &subpass, 0, nullptr}; VkRenderPass rp; VkResult err = vk::CreateRenderPass(m_device->device(), &rpci, nullptr, &rp); ASSERT_VK_SUCCESS(err); auto imageView = images[1]->targetView(FMT); VkFramebufferCreateInfo fbci = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, nullptr, 0, rp, 1, &imageView, WIDTH, HEIGHT, 1}; VkFramebuffer fb; err = vk::CreateFramebuffer(m_device->device(), &fbci, nullptr, &fb); ASSERT_VK_SUCCESS(err); VkRenderPassBeginInfo rpbi = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, nullptr, rp, fb, {{0, 0}, {WIDTH, HEIGHT}}, 0, nullptr }; // subtest 1: bind in the wrong subpass m_commandBuffer->BeginRenderPass(rpbi); m_commandBuffer->EndRenderPass(); m_commandBuffer->end(); VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &m_commandBuffer->handle(); vk::QueueSubmit(m_device->m_queue, 1, &submit, VK_NULL_HANDLE); vk::QueueWaitIdle(m_device->m_queue); m_errorMonitor->VerifyFound(); } TEST_F(VkArmBestPracticesLayerTest, RedundantAttachment) { TEST_DESCRIPTION("Test for redundant renderpasses which consume bandwidth"); ASSERT_NO_FATAL_FAILURE(InitBestPracticesFramework(kEnableArmValidation)); InitState(); // One of these formats must be supported. VkFormat ds_format = VK_FORMAT_D24_UNORM_S8_UINT; VkFormatProperties format_props; vk::GetPhysicalDeviceFormatProperties(gpu(), ds_format, &format_props); if ((format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) == 0) { ds_format = VK_FORMAT_D32_SFLOAT_S8_UINT; vk::GetPhysicalDeviceFormatProperties(gpu(), ds_format, &format_props); ASSERT_TRUE((format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0); } auto ds = CreateImage(ds_format, 64, 64, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); m_clear_via_load_op = true; m_depth_stencil_fmt = ds_format; auto ds_view = ds->targetView(ds_format, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); ASSERT_NO_FATAL_FAILURE(InitRenderTarget(1, &ds_view)); CreatePipelineHelper pipe_all(*this); pipe_all.InitInfo(); pipe_all.InitState(); pipe_all.cb_attachments_.colorWriteMask = 0xf; pipe_all.ds_ci_ = {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; pipe_all.gp_ci_.pDepthStencilState = &pipe_all.ds_ci_; pipe_all.ds_ci_.depthTestEnable = VK_TRUE; pipe_all.ds_ci_.stencilTestEnable = VK_TRUE; pipe_all.CreateGraphicsPipeline(); CreatePipelineHelper pipe_color(*this); pipe_color.InitInfo(); pipe_color.InitState(); pipe_color.cb_attachments_.colorWriteMask = 0xf; pipe_color.ds_ci_ = {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; pipe_color.gp_ci_.pDepthStencilState = &pipe_color.ds_ci_; pipe_color.CreateGraphicsPipeline(); CreatePipelineHelper pipe_depth(*this); pipe_depth.InitInfo(); pipe_depth.InitState(); pipe_depth.cb_attachments_.colorWriteMask = 0; pipe_depth.ds_ci_ = {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; pipe_depth.gp_ci_.pDepthStencilState = &pipe_depth.ds_ci_; pipe_depth.ds_ci_.depthTestEnable = VK_TRUE; pipe_depth.CreateGraphicsPipeline(); CreatePipelineHelper pipe_stencil(*this); pipe_stencil.InitInfo(); pipe_stencil.InitState(); pipe_stencil.cb_attachments_.colorWriteMask = 0; pipe_stencil.ds_ci_ = {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; pipe_stencil.gp_ci_.pDepthStencilState = &pipe_stencil.ds_ci_; pipe_stencil.ds_ci_.stencilTestEnable = VK_TRUE; pipe_stencil.CreateGraphicsPipeline(); m_commandBuffer->begin(); // Nothing is redundant. { m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_all.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyNotFound(); } // Only color is redundant. { m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_stencil.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyFound(); } // Only depth is redundant. { m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_color.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_stencil.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyFound(); } // Only stencil is redundant. { m_errorMonitor->SetDesiredFailureMsg(VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, "UNASSIGNED-BestPractices-vkCmdEndRenderPass-redundant-attachment-on-tile"); m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo); // Test that clear attachments counts as an access. VkClearAttachment clear_att = {}; VkClearRect clear_rect = {}; clear_att.colorAttachment = 0; clear_att.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; clear_rect.layerCount = 1; clear_rect.rect = { { 0, 0 }, { 1, 1 } }; vk::CmdClearAttachments(m_commandBuffer->handle(), 1, &clear_att, 1, &clear_rect); vk::CmdBindPipeline(m_commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipe_depth.pipeline_); m_commandBuffer->Draw(1, 1, 0, 0); m_commandBuffer->EndRenderPass(); m_errorMonitor->VerifyFound(); } m_commandBuffer->end(); }
44.983658
155
0.717028
youkim02
287439a8bb92e4fa3ddb6fdc22349b4858b45e83
472
hpp
C++
apps/opencs/model/doc/state.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/model/doc/state.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/model/doc/state.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef CSM_DOC_STATE_H #define CSM_DOC_STATE_H namespace CSMDoc { enum State { State_Modified = 1, State_Locked = 2, State_Operation = 4, State_Running = 8, State_Saving = 16, State_Verifying = 32, State_Compiling = 64, // not implemented yet State_Searching = 128, // not implemented yet State_Loading = 256 // pseudo-state; can not be encountered in a loaded document }; } #endif
21.454545
90
0.618644
Bodillium
2874909b149507fe5d25479569ef20303fc1a0fd
3,115
cc
C++
UX/plugins/Style/Materialist/src/MaterialistPlugin.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
UX/plugins/Style/Materialist/src/MaterialistPlugin.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/plugins/Style/Materialist/src/MaterialistPlugin.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2020 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/MaterialistPlugin> #include <cc/FontManager> #include <cc/MaterialLight> #include <cc/GlyphVisual> #include <cc/File> #include <cc/Dir> #include <cc/Bundle> #include <cc/Registration> #include <cc/DEBUG> namespace cc { struct MaterialistPlugin::State: public StylePlugin::State { State(): StylePlugin::State{"Industrial"} { theme_ = MaterialLight{}; } void activate() override { if (File::exists("/usr/share/fonts/TTF/Roboto-Regular.ttf")) { // Arch FontManager{}.addPath("/usr/share/fonts/TTF", "Roboto"); defaultFont_ = Font{"Roboto", sp(16)}; defaultFixedFont_ = Font{"Roboto Mono", sp(16)}; } if (File::exists("/usr/share/fonts/TTF/DejaVuSans.ttf")) { // Arch FontManager{}.addPath("/usr/share/fonts/TTF", "DejaVu"); if (!defaultFont_) defaultFont_ = Font{"DejaVu Sans", sp(16)}; defaultFixedFont_ = Font{"DejaVu Sans Mono", sp(16)}; } else if (File::exists("/usr/share/fonts/truetype/dejavu")) { // Debian String dejavuPath = "/usr/share/fonts/truetype/dejavu"; if (Dir::exists(dejavuPath)) { FontManager{}.addPath(dejavuPath); defaultFont_ = Font{"DejaVu Sans", sp(16)}; defaultFixedFont_ = Font{"DejaVu Sans Mono", sp(16)}; } } if (!defaultFont_) { const char *notoPaths[] = { "/usr/share/fonts/noto", // Arch "/usr/share/fonts/truetype/noto" // Debian }; for (auto path: notoPaths) { if (Dir::exists(path)) { FontManager{}.addPath(path); defaultFont_ = Font{"Noto Sans", sp(16)}; // defaultFixedFont_ = Font{"Noto Mono", sp(16)}; break; } } const char *notoCjkPaths[] = { "/usr/share/fonts/noto-cjk", // Arch "/usr/share/fonts/opentype/noto" // Debian }; for (auto path: notoCjkPaths) { if (Dir::exists(path)) FontManager{}.addPath(path); } } if (!defaultFont_) CC_DEBUG << "Failed to locate default font"; String iconsPath = CC_BUNDLE_LOOKUP("icons"); if (iconsPath != "") FontManager{}.addPath(iconsPath); else CC_DEBUG << "Failed to locate icons directory"; } Visual ideograph(Ideographic ch, double size) const override { if (size <= 0) return GlyphVisual{+ch, iconFont_}; Font font = iconFont_; font.size(size); return GlyphVisual{+ch, font}; } Font iconFont_{"Icons", sp(24)}; }; MaterialistPlugin::MaterialistPlugin(): StylePlugin{new State} {} CC_REGISTRATION(MaterialistPlugin); } // namespace cc
28.577982
74
0.539005
frankencode
287b7e337d78f2f4ac0a11fc0334a79c53680eee
1,592
cpp
C++
core/general-client/src/pybind_general_model.cpp
guru4elephant/Serving
18ee0af3465487e47a90d0581c6785bc69cc5b78
[ "Apache-2.0" ]
null
null
null
core/general-client/src/pybind_general_model.cpp
guru4elephant/Serving
18ee0af3465487e47a90d0581c6785bc69cc5b78
[ "Apache-2.0" ]
null
null
null
core/general-client/src/pybind_general_model.cpp
guru4elephant/Serving
18ee0af3465487e47a90d0581c6785bc69cc5b78
[ "Apache-2.0" ]
null
null
null
#include <Python.h> #include <pybind11/pybind11.h> #include <unordered_map> #include "core/general-client/include/general_model.h" #include <pybind11/stl.h> namespace py = pybind11; using baidu::paddle_serving::general_model::FetchedMap; namespace baidu { namespace paddle_serving { namespace general_model { PYBIND11_MODULE(serving_client, m) { m.doc() = R"pddoc(this is a practice )pddoc"; py::class_<PredictorClient>(m, "PredictorClient", py::buffer_protocol()) .def(py::init()) .def("init", [](PredictorClient &self, const std::string & conf) { self.init(conf); }) .def("set_predictor_conf", [](PredictorClient &self, const std::string & conf_path, const std::string & conf_file) { self.set_predictor_conf(conf_path, conf_file); }) .def("create_predictor", [](PredictorClient & self) { self.create_predictor(); }) .def("predict", [](PredictorClient &self, const std::vector<std::vector<float> > & float_feed, const std::vector<std::string> & float_feed_name, const std::vector<std::vector<int64_t> > & int_feed, const std::vector<std::string> & int_feed_name, const std::vector<std::string> & fetch_name) { return self.predict(float_feed, float_feed_name, int_feed, int_feed_name, fetch_name); }); } } // namespace general_model } // namespace paddle_serving } // namespace baidu
31.84
74
0.600503
guru4elephant
287cf8152e4532c402923c64b18ebe8d3bb61ad9
4,017
cxx
C++
xp_comm_proj/repalpha/repalpha.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
3
2020-08-03T08:52:20.000Z
2021-04-10T11:55:49.000Z
xp_comm_proj/repalpha/repalpha.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
null
null
null
xp_comm_proj/repalpha/repalpha.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
1
2021-06-08T18:16:45.000Z
2021-06-08T18:16:45.000Z
// // Sabreen's Replace Alpha Module // // Input RGB image Input scalar Alpha image // | | // ---- ---- // | | // Replace_Alpha // | // new image #include "xp_comm_proj/repalpha/gen.h" #define FREE_ARRAYS \ if (input_image_arr!=NULL) ARRfree(input_image_arr);\ if (input_alpha_arr!=NULL) ARRfree(input_alpha_arr);\ if (output_arr!=NULL) ARRfree(output_arr); int ReplaceAlpha_ReplaceAlphaMods_ReplaceAlphaCore::update(OMevent_mask event_mask,int seq_num) { // input_image (OMXbyte_array read req notify) int input_image_size; unsigned char *input_image_arr = NULL; // input_alpha (OMXbyte_array read req notify) int input_alpha_size; unsigned char *input_alpha_arr = NULL; // output (OMXbyte_array write) int output_size; unsigned char *output_arr = NULL; int i; /***********************/ /* Function's Body */ /***********************/ // ERRverror("",ERR_NO_HEADER | ERR_PRINT, // "I'm in method: ReplaceAlphaCore::update\n"); // Get and Check Image array //========================== input_image_arr = (unsigned char *)input_image.ret_array_ptr(OM_GET_ARRAY_RD,&input_image_size); if (input_image_arr==NULL) { ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Can't get input_image_arr.\n"); FREE_ARRAYS; return (0); } if (input_image_size <= 0) { ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Input Image array is of zero size.\n"); FREE_ARRAYS; return (0); } // Get and Check Alpha array //========================== input_alpha_arr = (unsigned char *)input_alpha.ret_array_ptr(OM_GET_ARRAY_RD,&input_alpha_size); if (input_alpha_arr==NULL) { ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Can't get input_alpha_arr.\n"); FREE_ARRAYS; return (0); } if (input_alpha_size <= 0) { ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Input Alpha array is of zero size.\n"); FREE_ARRAYS; return (0); } // Ensure image and alpha arrays have same dimensions if (input_image_size != input_alpha_size * 4){ ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Images are different dimensions - they must be the same"); FREE_ARRAYS; return (0); } // set the output size to be the same as the primary input // The output array is defined as output[out_size][4] in V: //out_size = input_image_size / 4; out_size = input_alpha_size; // Get and Check Output array //=========================== output_arr = (unsigned char *)output.ret_array_ptr(OM_GET_ARRAY_WR,&output_size); if (output_arr==NULL) { ERRverror("",ERR_NO_HEADER | ERR_PRINT,"Can't get output_arr.\n"); FREE_ARRAYS; return (0); } if (output_size != input_image_size) { ERRverror("",ERR_NO_HEADER | ERR_PRINT, "Output array is of invalid size.\n"); FREE_ARRAYS; return (0); } // Pixels are arrays of 4 bytes, not integers. // However, on 32 bit machines we can speed this up // by casting pixels to unsigned ints. //================================================= if (sizeof(int) == 4) { unsigned int* dst = (unsigned int*)output_arr; unsigned int* rgb = (unsigned int*)input_image_arr; unsigned int mask; mask = AVS_RED_MASK | AVS_GREEN_MASK | AVS_BLUE_MASK; for (i=0; i<input_alpha_size; i++) { dst[i] = (rgb[i] & mask) | (input_alpha_arr[i]<<AVS_ALPHA_SHIFT); } } else { for (i=0; i<input_alpha_size; i++) { output_arr[i*4+AVS_ALPHA_BYTE] = input_alpha_arr[i]; output_arr[i*4+AVS_RED_BYTE] = input_image_arr[i*4+AVS_RED_BYTE]; output_arr[i*4+AVS_GREEN_BYTE] = input_image_arr[i*4+AVS_GREEN_BYTE]; output_arr[i*4+AVS_BLUE_BYTE] = input_image_arr[i*4+AVS_BLUE_BYTE]; } } FREE_ARRAYS; // return 1 for success return(1); }
27.895833
105
0.598457
avs
287dec43b9967143ed2b1bb4fbd223df8c90e73f
4,936
cpp
C++
DISCONTINUED/runtime/JSNotAnObject.cpp
openaphid/AJ
0c81ec4f297cf981423e1aa3b3cf0dc448d98052
[ "Apache-2.0" ]
2
2016-11-08T07:27:59.000Z
2016-11-29T12:22:19.000Z
DISCONTINUED/runtime/JSNotAnObject.cpp
PioneerLab/OpenAphid-AJ
0c81ec4f297cf981423e1aa3b3cf0dc448d98052
[ "Apache-2.0" ]
1
2015-03-30T08:13:25.000Z
2015-03-31T10:45:12.000Z
DISCONTINUED/runtime/JSNotAnObject.cpp
PioneerLab/OpenAphid-AJ
0c81ec4f297cf981423e1aa3b3cf0dc448d98052
[ "Apache-2.0" ]
2
2015-05-23T06:43:01.000Z
2015-11-27T14:52:31.000Z
/* Copyright 2012 Aphid Mobile 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. */ /* * Copyright (C) 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "JSNotAnObject.h" #include <wtf/UnusedParam.h> namespace AJ { ASSERT_CLASS_FITS_IN_CELL(JSNotAnObject); // AJValue methods AJValue JSNotAnObject::toPrimitive(ExecState* exec, PreferredPrimitiveType) const { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return m_exception; } bool JSNotAnObject::getPrimitiveNumber(ExecState* exec, double&, AJValue&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } bool JSNotAnObject::toBoolean(ExecState* exec) const { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } double JSNotAnObject::toNumber(ExecState* exec) const { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return NaN; } UString JSNotAnObject::toString(ExecState* exec) const { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return ""; } AJObject* JSNotAnObject::toObject(ExecState* exec) const { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return m_exception; } // Marking void JSNotAnObject::markChildren(MarkStack& markStack) { AJObject::markChildren(markStack); markStack.append(m_exception); } // AJObject methods bool JSNotAnObject::getOwnPropertySlot(ExecState* exec, const Identifier&, PropertySlot&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } bool JSNotAnObject::getOwnPropertySlot(ExecState* exec, unsigned, PropertySlot&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } bool JSNotAnObject::getOwnPropertyDescriptor(ExecState* exec, const Identifier&, PropertyDescriptor&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } void JSNotAnObject::put(ExecState* exec, const Identifier& , AJValue, PutPropertySlot&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); } void JSNotAnObject::put(ExecState* exec, unsigned, AJValue) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); } bool JSNotAnObject::deleteProperty(ExecState* exec, const Identifier&) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } bool JSNotAnObject::deleteProperty(ExecState* exec, unsigned) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); return false; } void JSNotAnObject::getOwnPropertyNames(ExecState* exec, PropertyNameArray&, EnumerationMode) { ASSERT_UNUSED(exec, exec->hadException() && exec->exception() == m_exception); } } // namespace AJ
33.578231
101
0.743112
openaphid
287eb292b81eea2783eef1959fb8ff0af8eafb2f
1,052
cpp
C++
Algorithms/Sorting/can_make_ap.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
11
2020-03-20T17:24:28.000Z
2022-01-08T02:43:24.000Z
Algorithms/Sorting/can_make_ap.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
1
2021-07-25T11:24:46.000Z
2021-07-25T12:09:25.000Z
Algorithms/Sorting/can_make_ap.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
4
2020-03-20T17:24:36.000Z
2021-12-07T19:22:59.000Z
// A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. // Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. // Example 1: // Input: arr = [3,5,1] // Output: true // Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with // differences 2 and -2 respectively, between each consecutive elements. // Example 2: // Input: arr = [1,2,4] // Output: false // Explanation: There is no way to reorder the elements to obtain an arithmetic progression. #include<bits/stdc++.h> using namespace std; bool canMakeArithmeticProgression(vector<int>& arr) { sort(arr.begin(), arr.end()); int n = arr.size(); int exp_diff = arr[1] - arr[0]; for(int i=0; i<n-1; i++) { int j = i + 1; int calc_diff = arr[j] - arr[i]; if(calc_diff != exp_diff) { return false; } } return true; }
26.3
136
0.622624
abhishekjha786
287fca21f327dd38480403a18c9b28f2e8de0c41
1,925
cc
C++
complex/src/complexs.cc
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Guillermo-A
b0b1861336aacbb5f5f3990cb2691a17358904a6
[ "MIT" ]
null
null
null
complex/src/complexs.cc
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Guillermo-A
b0b1861336aacbb5f5f3990cb2691a17358904a6
[ "MIT" ]
null
null
null
complex/src/complexs.cc
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-Guillermo-A
b0b1861336aacbb5f5f3990cb2691a17358904a6
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include "complex.h" #include <cmath> #include <string> Complex::Complex(){ real = 0.0; imag = 0.0; } Complex::Complex(double _real){ real = _real; imag = 0.0; } Complex::Complex(double _real, double _imag){ real = _real; imag = _imag; } Complex::Complex(Complex &obj){ real=obj.real; imag=obj.imag; } Complex Complex::add(Complex z2){ Complex Add; Add.real = real + z2.real; Add.imag = imag + z2.imag; return Add; } Complex Complex::sub(Complex z2){ Complex Sub; Sub.real = real - z2.real; Sub.imag = imag - z2.imag; return Sub; } Complex Complex::mult(Complex z2){ Complex Mult; Mult.real = real * z2.real; Mult.imag = imag * z2.imag; return Mult; } Complex Complex::div(Complex z2){ Complex Div; Div.real = (real * z2.real) / (z2.real * z2.real); Div.imag = (imag * (- z2.imag)) / (z2.imag * (- z2.imag)); return Div; } void Complex::setReal(double _real){ real = _real; } void Complex::setImag(double _imag){ imag = _imag; } double Complex::getReal(){ return real; } double Complex:: getImag(){ return imag; } void Complex::print_complex(){ std::cout << real << " + (" << imag << ")i" << std::endl; } void Usage(int argc, char*argv[]){ if(argc == 2){ const std::string kHelpText = "Este programa realiza la suma resta division y multiplicacion de numeros complejos"; std::string parameter{argv[1]}; if(parameter == "--help"){ std::cout << kHelpText << std::endl; std::cout << "Modo de uso: " << std::endl; std::cout << argv[0] << " n.real1 n.imaginario1 "; std::cout << "n.real2 n.imaginario2" << std::endl; exit(EXIT_SUCCESS); } } if(argc != 5){ std::cout << argv[0] << ": Error, pruebe --help para mas informacion" << std::endl; } }
20.263158
124
0.576104
ULL-ESIT-IB-2020-2021
28816d855a9a0b6432c37304f0c3c828b2ec9fba
1,737
hpp
C++
vendor/src/anchorable_element.hpp
crails-framework/comet.cpp
c43b5e72a065b7a2e34f723fcca11d9a673c564e
[ "BSD-3-Clause" ]
null
null
null
vendor/src/anchorable_element.hpp
crails-framework/comet.cpp
c43b5e72a065b7a2e34f723fcca11d9a673c564e
[ "BSD-3-Clause" ]
null
null
null
vendor/src/anchorable_element.hpp
crails-framework/comet.cpp
c43b5e72a065b7a2e34f723fcca11d9a673c564e
[ "BSD-3-Clause" ]
null
null
null
#ifndef COMET_ANCHORABLE_ELEMENT_HPP # define COMET_ANCHORABLE_ELEMENT_HPP # include "element.hpp" # include "exception.hpp" namespace Comet { enum AnchorMode { ChildrenAnchor, AppendAnchor, PrependAnchor, AnchorsEnd }; struct AnchorableElement { Comet::Element anchor; AnchorMode anchor_mode = AnchorsEnd; inline void set_anchor(Comet::Element el, AnchorMode mode) { anchor = el; anchor_mode = mode; } inline bool is_anchorable() const { return anchor_mode != AnchorsEnd; } template<typename LIST> void attach_elements(const LIST& elements) { switch (anchor_mode) { case ChildrenAnchor: for (auto el : elements) el->append_to(anchor); break ; case AppendAnchor: append_to_anchor(elements); break ; case PrependAnchor: prepend_to_anchor(elements); break ; case AnchorsEnd: raise(std::logic_error("AnchorableElement::attach_element called with unset anchor")); break ; } } private: template<typename LIST> void append_to_anchor(const LIST& elements) { auto current_anchor = anchor; for (auto it = elements.begin() ; it != elements.end() ; ++it) { (*it)->insert_after(current_anchor); current_anchor = Comet::Element(*(*it)); } } template<typename LIST> void prepend_to_anchor(const LIST& elements) { auto current_anchor = anchor; for (auto it = elements.rbegin() ; it != elements.rend() ; ++it) { (*it)->insert_before(current_anchor); current_anchor = Comet::Element(*(*it)); } } }; } #endif
21.7125
94
0.607369
crails-framework
28824cfd496f7c78282b2cba602888c1bda14262
130
hpp
C++
Render_IOS/Render_IOS/opencv2.framework/Versions/A/Headers/photo.hpp
hzx829/Render_IOS
268085cc95cef5d90ce996df83a6b5da7f992e6d
[ "MIT" ]
null
null
null
Render_IOS/Render_IOS/opencv2.framework/Versions/A/Headers/photo.hpp
hzx829/Render_IOS
268085cc95cef5d90ce996df83a6b5da7f992e6d
[ "MIT" ]
null
null
null
Render_IOS/Render_IOS/opencv2.framework/Versions/A/Headers/photo.hpp
hzx829/Render_IOS
268085cc95cef5d90ce996df83a6b5da7f992e6d
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:4a7563ecfc3b8699913508012396395eefe0eebe53e6ce2f6b758d87183d2d81 size 38844
32.5
75
0.884615
hzx829
2888fa094d4459c7b2a8e5738dbd18546d79042f
1,272
cpp
C++
000/ISN/test_cpp/learn-dll2/header/Duree.cpp
Tehcam/Studies
69477a211d8c686473b171ad2fa4298ead2ee60d
[ "MIT" ]
null
null
null
000/ISN/test_cpp/learn-dll2/header/Duree.cpp
Tehcam/Studies
69477a211d8c686473b171ad2fa4298ead2ee60d
[ "MIT" ]
null
null
null
000/ISN/test_cpp/learn-dll2/header/Duree.cpp
Tehcam/Studies
69477a211d8c686473b171ad2fa4298ead2ee60d
[ "MIT" ]
null
null
null
#include "Duree.h" Duree::Duree(int hour, int min, int sec):m_hour(hour), m_min(min), m_sec(sec) { if(m_sec >= 60){ int rest_sec = m_sec % 60; m_min += (m_sec - rest_sec)/60; m_sec = rest_sec; } if(m_min >= 60){ int rest_min = m_min % 60; m_hour += (m_min - rest_min)/60; m_min = rest_min; } } bool Duree::equial(Duree const& b) const { return (m_hour == b.m_hour and m_min == b.m_min and m_sec == b.m_sec); } bool operator==(Duree const& a, Duree const& b) { return a.equial(b); } bool operator!=(Duree const& a, Duree const& b) { return !(a == b); } bool Duree::smaller(Duree const& b) const { if(m_hour < b.m_hour){ return true; }else if(m_hour == b.m_hour){ if(m_min < b.m_min){ return true; }else if(m_min == b.m_min){ if(m_sec < b.m_sec){ return true; } return false; }else{ return false; } }else{ return false; } } bool operator<(Duree const& a, Duree const& b) { return a.smaller(b); } bool operator<=(Duree const& a, Duree const& b) { if(a == b or a < b){ return true; } return false; } bool operator>(Duree const& a, Duree const& b) { if(!(a <= b)){ return true; } return false; } bool operator>=(Duree const& a, Duree const& b) { if(a == b or a > b){ return true; } return false; }
15.9
77
0.606132
Tehcam
288a93f29e4d1c8b37253c755674a2c2dd31f182
6,148
cpp
C++
src/cube/ColumnGenerator.cpp
qcoumes/mastercraft
5ee36fde6eab80d18075970eff47b4a5c45143f5
[ "MIT" ]
1
2021-01-12T16:58:05.000Z
2021-01-12T16:58:05.000Z
src/cube/ColumnGenerator.cpp
qcoumes/mastercraft
5ee36fde6eab80d18075970eff47b4a5c45143f5
[ "MIT" ]
null
null
null
src/cube/ColumnGenerator.cpp
qcoumes/mastercraft
5ee36fde6eab80d18075970eff47b4a5c45143f5
[ "MIT" ]
null
null
null
#include <stdexcept> #include <cube/ColumnGenerator.hpp> namespace cube { ColumnGenerator::Column ColumnGenerator::waterColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= app::Config::GEN_WATER_LEVEL + 1; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else if (y < height) { column[y] = cube::CubeData::SAND_BEACH; } else { column[y] = cube::CubeData::WATER; } } return column; } ColumnGenerator::Column ColumnGenerator::iceColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= app::Config::GEN_WATER_LEVEL + 1; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else if (y < height) { column[y] = cube::CubeData::SNOW; } else if (y == app::Config::GEN_WATER_LEVEL + 1) { column[y] = cube::CubeData::ICE; } else { column[y] = cube::CubeData::WATER; } } return column; } ColumnGenerator::Column ColumnGenerator::sandBeachColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 2) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::SAND_BEACH; } } return column; } ColumnGenerator::Column ColumnGenerator::sandDesertColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 5) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::SAND_DESERT; } } return column; } ColumnGenerator::Column ColumnGenerator::snowColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::SNOW; } } return column; } ColumnGenerator::Column ColumnGenerator::stoneColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { column[y] = cube::CubeData::STONE; } return column; } ColumnGenerator::Column ColumnGenerator::stoneSnowColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 2) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::STONE_SNOW; } } return column; } ColumnGenerator::Column ColumnGenerator::dirtPlainColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::DIRT_PLAIN; } } return column; } ColumnGenerator::Column ColumnGenerator::dirtJungleColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::DIRT_JUNGLE; } } return column; } ColumnGenerator::Column ColumnGenerator::dirtSnowColumn(GLuint height) { Column column = {}; column.fill(cube::CubeData::AIR); for (GLuint y = 0; y <= height; y++) { if (y < height - 3) { column[y] = cube::CubeData::STONE; } else { column[y] = cube::CubeData::DIRT_SNOW; } } return column; } ColumnGenerator::Column ColumnGenerator::generate(GLuint height, cube::CubeData type) { switch (type) { case WATER: return waterColumn(height); case ICE: return iceColumn(height); case SAND_BEACH: return sandBeachColumn(height); case SAND_DESERT: return sandDesertColumn(height); case SNOW: return snowColumn(height); case STONE: return stoneColumn(height); case STONE_SNOW: return stoneSnowColumn(height); case DIRT_PLAIN: return dirtPlainColumn(height); case DIRT_JUNGLE: return dirtJungleColumn(height); case DIRT_SNOW: return dirtSnowColumn(height); case AIR: case WOOD_PLAIN: case FLOWERS: case WOOD_JUNGLE: case WOOD_SNOW: case CACTUS: case LEAVES_PLAIN: case LEAVES_JUNGLE: case LEAVES_SNOW: throw std::runtime_error( "Cannot generate column for biome of type '" + std::to_string(type) + "'." ); default: throw std::runtime_error("Invalid block type."); } } }
27.819005
94
0.458198
qcoumes
288f05157ce971404bed0768b375b3eecbe32995
8,898
hpp
C++
src/base/hip/hip_kernels_vector.hpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
1
2020-04-15T18:26:58.000Z
2020-04-15T18:26:58.000Z
src/base/hip/hip_kernels_vector.hpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
null
null
null
src/base/hip/hip_kernels_vector.hpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2018 Advanced Micro Devices, Inc. * * 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 ROCALUTION_HIP_HIP_KERNELS_VECTOR_HPP_ #define ROCALUTION_HIP_HIP_KERNELS_VECTOR_HPP_ #include <hip/hip_runtime.h> namespace rocalution { template <typename ValueType, typename IndexType> __global__ void kernel_scaleadd(IndexType n, ValueType alpha, const ValueType* __restrict__ x, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = alpha * out[ind] + x[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_scaleaddscale(IndexType n, ValueType alpha, ValueType beta, const ValueType* __restrict__ x, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = alpha * out[ind] + beta * x[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_scaleaddscale_offset(IndexType n, IndexType src_offset, IndexType dst_offset, ValueType alpha, ValueType beta, const ValueType* __restrict__ x, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind + dst_offset] = alpha * out[ind + dst_offset] + beta * x[ind + src_offset]; } template <typename ValueType, typename IndexType> __global__ void kernel_scaleadd2(IndexType n, ValueType alpha, ValueType beta, ValueType gamma, const ValueType* __restrict__ x, const ValueType* __restrict__ y, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = alpha * out[ind] + beta * x[ind] + gamma * y[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_pointwisemult(IndexType n, const ValueType* __restrict__ x, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = out[ind] * x[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_pointwisemult2(IndexType n, const ValueType* __restrict__ x, const ValueType* __restrict__ y, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = y[ind] * x[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_copy_offset_from(IndexType n, IndexType src_offset, IndexType dst_offset, const ValueType* __restrict__ in, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind + dst_offset] = in[ind + src_offset]; } template <typename ValueType, typename IndexType> __global__ void kernel_permute(IndexType n, const IndexType* __restrict__ permute, const ValueType* __restrict__ in, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[permute[ind]] = in[ind]; } template <typename ValueType, typename IndexType> __global__ void kernel_permute_backward(IndexType n, const IndexType* __restrict__ permute, const ValueType* __restrict__ in, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = in[permute[ind]]; } template <typename ValueType, typename IndexType> __global__ void kernel_get_index_values(IndexType size, const IndexType* __restrict__ index, const ValueType* __restrict__ in, ValueType* __restrict__ out) { IndexType i = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(i >= size) { return; } out[i] = in[index[i]]; } template <typename ValueType, typename IndexType> __global__ void kernel_set_index_values(IndexType size, const IndexType* __restrict__ index, const ValueType* __restrict__ in, ValueType* __restrict__ out) { IndexType i = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(i >= size) { return; } out[index[i]] = in[i]; } template <typename ValueType, typename IndexType> __global__ void kernel_power(IndexType n, double power, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = pow(out[ind], power); } template <typename ValueType, typename IndexType> __global__ void kernel_copy_from_float(IndexType n, const float* __restrict__ in, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = static_cast<ValueType>(in[ind]); } template <typename ValueType, typename IndexType> __global__ void kernel_copy_from_double(IndexType n, const double* __restrict__ in, ValueType* __restrict__ out) { IndexType ind = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(ind >= n) { return; } out[ind] = static_cast<ValueType>(in[ind]); } } // namespace rocalution #endif // ROCALUTION_HIP_HIP_KERNELS_VECTOR_HPP_
34.223077
91
0.512812
pruthvistony
288f69959a8c8ce13c1825a1587fcc74594aa847
1,198
hpp
C++
venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/arr/err/check_matching_sizes.hpp
vchiapaikeo/prophet
e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7
[ "MIT" ]
null
null
null
venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/arr/err/check_matching_sizes.hpp
vchiapaikeo/prophet
e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7
[ "MIT" ]
null
null
null
venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/arr/err/check_matching_sizes.hpp
vchiapaikeo/prophet
e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7
[ "MIT" ]
null
null
null
#ifndef STAN_MATH_PRIM_ARR_ERR_CHECK_MATCHING_SIZES_HPP #define STAN_MATH_PRIM_ARR_ERR_CHECK_MATCHING_SIZES_HPP #include <stan/math/prim/scal/err/domain_error.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> namespace stan { namespace math { /** * Check if two structures at the same size. * This function only checks the runtime sizes for variables that * implement a <code>size()</code> method. * @tparam T_y1 Type of the first variable * @tparam T_y2 Type of the second variable * @param function Function name (for error messages) * @param name1 First variable name (for error messages) * @param y1 First variable * @param name2 Second variable name (for error messages) * @param y2 Second variable * @throw <code>std::invalid_argument</code> if the sizes do not match */ template <typename T_y1, typename T_y2> inline void check_matching_sizes(const char* function, const char* name1, const T_y1& y1, const char* name2, const T_y2& y2) { check_size_match(function, "size of ", name1, y1.size(), "size of ", name2, y2.size()); } } // namespace math } // namespace stan #endif
35.235294
77
0.69783
vchiapaikeo
2891c4cbc78cbe9a77bc17dbf1dff0fd6f26a7b8
16,767
cpp
C++
Folly/folly/portability/PThread.cpp
hasridha/react-native
dbf44ed0ba802ed80d9df9a913228b7aa19b17a1
[ "CC-BY-4.0", "MIT" ]
2,114
2020-05-06T10:05:45.000Z
2022-03-31T23:19:28.000Z
Folly/folly/portability/PThread.cpp
hasridha/react-native
dbf44ed0ba802ed80d9df9a913228b7aa19b17a1
[ "CC-BY-4.0", "MIT" ]
623
2020-05-05T21:24:26.000Z
2022-03-30T21:00:31.000Z
Folly/folly/portability/PThread.cpp
hasridha/react-native
dbf44ed0ba802ed80d9df9a913228b7aa19b17a1
[ "CC-BY-4.0", "MIT" ]
214
2019-04-11T09:36:41.000Z
2022-02-19T08:10:31.000Z
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/portability/PThread.h> #if !FOLLY_HAVE_PTHREAD && _WIN32 #include <boost/thread/tss.hpp> // @manual #include <errno.h> #include <chrono> #include <condition_variable> #include <exception> #include <limits> #include <mutex> #include <shared_mutex> #include <thread> #include <folly/lang/Assume.h> #include <folly/portability/Windows.h> namespace folly { namespace portability { namespace pthread { int pthread_attr_init(pthread_attr_t* attr) { if (attr == nullptr) { errno = EINVAL; return -1; } attr->stackSize = 0; attr->detached = false; return 0; } int pthread_attr_setdetachstate(pthread_attr_t* attr, int state) { if (attr == nullptr) { errno = EINVAL; return -1; } attr->detached = state == PTHREAD_CREATE_DETACHED ? true : false; return 0; } int pthread_attr_setstacksize(pthread_attr_t* attr, size_t kb) { if (attr == nullptr) { errno = EINVAL; return -1; } attr->stackSize = kb; return 0; } namespace pthread_detail { pthread_t::~pthread_t() noexcept { if (handle != INVALID_HANDLE_VALUE && !detached) { CloseHandle(handle); } } } // namespace pthread_detail int pthread_equal(pthread_t threadA, pthread_t threadB) { if (threadA == threadB) { return 1; } // Note that, in the presence of detached threads, it is in theory possible // for two different pthread_t handles to be compared as the same due to // Windows HANDLE and Thread ID re-use. If you're doing anything useful with // a detached thread, you're probably doing it wrong, but I felt like leaving // this note here anyways. if (threadA->handle == threadB->handle && threadA->threadID == threadB->threadID) { return 1; } return 0; } namespace { thread_local pthread_t current_thread_self; struct pthread_startup_info { pthread_t thread; void* (*startupFunction)(void*); void* startupArgument; }; DWORD internal_pthread_thread_start(void* arg) { // We are now in the new thread. auto startupInfo = reinterpret_cast<pthread_startup_info*>(arg); current_thread_self = startupInfo->thread; auto ret = startupInfo->startupFunction(startupInfo->startupArgument); if /* constexpr */ (sizeof(void*) != sizeof(DWORD)) { auto tmp = reinterpret_cast<uintptr_t>(ret); if (tmp > std::numeric_limits<DWORD>::max()) { throw std::out_of_range( "Exit code of the pthread is outside the range representable on Windows"); } } delete startupInfo; return static_cast<DWORD>(reinterpret_cast<uintptr_t>(ret)); } } // namespace int pthread_create( pthread_t* thread, const pthread_attr_t* attr, void* (*start_routine)(void*), void* arg) { if (thread == nullptr) { errno = EINVAL; return -1; } size_t stackSize = attr != nullptr ? attr->stackSize : 0; bool detach = attr != nullptr ? attr->detached : false; // Note that the start routine passed into pthread returns a void* and the // windows API expects DWORD's, so we need to stub around that. auto startupInfo = new pthread_startup_info(); startupInfo->startupFunction = start_routine; startupInfo->startupArgument = arg; startupInfo->thread = std::make_shared<pthread_detail::pthread_t>(); // We create the thread suspended so we can assign the handle and thread id // in the pthread_t. startupInfo->thread->handle = CreateThread( nullptr, stackSize, internal_pthread_thread_start, startupInfo, CREATE_SUSPENDED, &startupInfo->thread->threadID); ResumeThread(startupInfo->thread->handle); if (detach) { *thread = std::make_shared<pthread_detail::pthread_t>(); (*thread)->detached = true; (*thread)->handle = startupInfo->thread->handle; (*thread)->threadID = startupInfo->thread->threadID; } else { *thread = startupInfo->thread; } return 0; } pthread_t pthread_self() { // Not possible to race :) if (current_thread_self == nullptr) { current_thread_self = std::make_shared<pthread_detail::pthread_t>(); current_thread_self->threadID = GetCurrentThreadId(); // The handle returned by GetCurrentThread is a pseudo-handle and needs to // be swapped out for a real handle to be useful anywhere other than this // thread. DuplicateHandle( GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &current_thread_self->handle, DUPLICATE_SAME_ACCESS, TRUE, 0); } return current_thread_self; } int pthread_join(pthread_t thread, void** exitCode) { if (thread->detached) { errno = EINVAL; return -1; } if (WaitForSingleObjectEx(thread->handle, INFINITE, FALSE) == WAIT_FAILED) { return -1; } if (exitCode != nullptr) { DWORD e; if (!GetExitCodeThread(thread->handle, &e)) { return -1; } *exitCode = reinterpret_cast<void*>(static_cast<uintptr_t>(e)); } return 0; } HANDLE pthread_getw32threadhandle_np(pthread_t thread) { return thread->handle; } DWORD pthread_getw32threadid_np(pthread_t thread) { return thread->threadID; } int pthread_setschedparam( pthread_t thread, int policy, const sched_param* param) { if (thread->detached) { errno = EINVAL; return -1; } auto newPrior = param->sched_priority; if (newPrior > THREAD_PRIORITY_TIME_CRITICAL || newPrior < THREAD_PRIORITY_IDLE) { errno = EINVAL; return -1; } if (GetPriorityClass(GetCurrentProcess()) != REALTIME_PRIORITY_CLASS) { if (newPrior > THREAD_PRIORITY_IDLE && newPrior < THREAD_PRIORITY_LOWEST) { // The values between IDLE and LOWEST are invalid unless the process is // running as realtime. newPrior = THREAD_PRIORITY_LOWEST; } else if ( newPrior < THREAD_PRIORITY_TIME_CRITICAL && newPrior > THREAD_PRIORITY_HIGHEST) { // Same as above. newPrior = THREAD_PRIORITY_HIGHEST; } } if (!SetThreadPriority(thread->handle, newPrior)) { return -1; } return 0; } int pthread_mutexattr_init(pthread_mutexattr_t* attr) { if (attr == nullptr) { return EINVAL; } attr->type = PTHREAD_MUTEX_DEFAULT; return 0; } int pthread_mutexattr_destroy(pthread_mutexattr_t* attr) { if (attr == nullptr) { return EINVAL; } return 0; } int pthread_mutexattr_settype(pthread_mutexattr_t* attr, int type) { if (attr == nullptr) { return EINVAL; } if (type != PTHREAD_MUTEX_DEFAULT && type != PTHREAD_MUTEX_RECURSIVE) { return EINVAL; } attr->type = type; return 0; } struct pthread_mutex_t_ { private: int type; union { std::timed_mutex timed_mtx; std::recursive_timed_mutex recursive_timed_mtx; }; public: pthread_mutex_t_(int mutex_type) : type(mutex_type) { switch (type) { case PTHREAD_MUTEX_NORMAL: new (&timed_mtx) std::timed_mutex(); break; case PTHREAD_MUTEX_RECURSIVE: new (&recursive_timed_mtx) std::recursive_timed_mutex(); break; } } ~pthread_mutex_t_() noexcept { switch (type) { case PTHREAD_MUTEX_NORMAL: timed_mtx.~timed_mutex(); break; case PTHREAD_MUTEX_RECURSIVE: recursive_timed_mtx.~recursive_timed_mutex(); break; } } void lock() { switch (type) { case PTHREAD_MUTEX_NORMAL: timed_mtx.lock(); break; case PTHREAD_MUTEX_RECURSIVE: recursive_timed_mtx.lock(); break; } } bool try_lock() { switch (type) { case PTHREAD_MUTEX_NORMAL: return timed_mtx.try_lock(); case PTHREAD_MUTEX_RECURSIVE: return recursive_timed_mtx.try_lock(); } folly::assume_unreachable(); } bool timed_try_lock(std::chrono::system_clock::time_point until) { switch (type) { case PTHREAD_MUTEX_NORMAL: return timed_mtx.try_lock_until(until); case PTHREAD_MUTEX_RECURSIVE: return recursive_timed_mtx.try_lock_until(until); } folly::assume_unreachable(); } void unlock() { switch (type) { case PTHREAD_MUTEX_NORMAL: timed_mtx.unlock(); break; case PTHREAD_MUTEX_RECURSIVE: recursive_timed_mtx.unlock(); break; } } void condition_wait(std::condition_variable_any& cond) { switch (type) { case PTHREAD_MUTEX_NORMAL: { std::unique_lock<std::timed_mutex> lock(timed_mtx); cond.wait(lock); break; } case PTHREAD_MUTEX_RECURSIVE: { std::unique_lock<std::recursive_timed_mutex> lock(recursive_timed_mtx); cond.wait(lock); break; } } } bool condition_timed_wait( std::condition_variable_any& cond, std::chrono::system_clock::time_point until) { switch (type) { case PTHREAD_MUTEX_NORMAL: { std::unique_lock<std::timed_mutex> lock(timed_mtx); return cond.wait_until(lock, until) == std::cv_status::no_timeout; } case PTHREAD_MUTEX_RECURSIVE: { std::unique_lock<std::recursive_timed_mutex> lock(recursive_timed_mtx); return cond.wait_until(lock, until) == std::cv_status::no_timeout; } } folly::assume_unreachable(); } }; int pthread_mutex_init( pthread_mutex_t* mutex, const pthread_mutexattr_t* attr) { if (mutex == nullptr) { return EINVAL; } auto type = attr != nullptr ? attr->type : PTHREAD_MUTEX_DEFAULT; auto ret = new pthread_mutex_t_(type); *mutex = ret; return 0; } int pthread_mutex_destroy(pthread_mutex_t* mutex) { if (mutex == nullptr) { return EINVAL; } delete *mutex; *mutex = nullptr; return 0; } int pthread_mutex_lock(pthread_mutex_t* mutex) { if (mutex == nullptr) { return EINVAL; } // This implementation does not implement deadlock detection, as the // STL mutexes we're wrapping don't either. (*mutex)->lock(); return 0; } int pthread_mutex_trylock(pthread_mutex_t* mutex) { if (mutex == nullptr) { return EINVAL; } if ((*mutex)->try_lock()) { return 0; } else { return EBUSY; } } static std::chrono::system_clock::time_point timespec_to_time_point( const timespec* t) { using time_point = std::chrono::system_clock::time_point; auto ns = std::chrono::seconds(t->tv_sec) + std::chrono::nanoseconds(t->tv_nsec); return time_point(std::chrono::duration_cast<time_point::duration>(ns)); } int pthread_mutex_timedlock( pthread_mutex_t* mutex, const timespec* abs_timeout) { if (mutex == nullptr || abs_timeout == nullptr) { return EINVAL; } auto time = timespec_to_time_point(abs_timeout); if ((*mutex)->timed_try_lock(time)) { return 0; } else { return ETIMEDOUT; } } int pthread_mutex_unlock(pthread_mutex_t* mutex) { if (mutex == nullptr) { return EINVAL; } // This implementation allows other threads to unlock it, // as the STL containers also do. (*mutex)->unlock(); return 0; } struct pthread_rwlock_t_ { std::shared_timed_mutex mtx; std::atomic<bool> writing{false}; }; int pthread_rwlock_init(pthread_rwlock_t* rwlock, const void* attr) { if (attr != nullptr) { return EINVAL; } if (rwlock == nullptr) { return EINVAL; } *rwlock = new pthread_rwlock_t_(); return 0; } int pthread_rwlock_destroy(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } delete *rwlock; *rwlock = nullptr; return 0; } int pthread_rwlock_rdlock(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } (*rwlock)->mtx.lock_shared(); return 0; } int pthread_rwlock_tryrdlock(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } if ((*rwlock)->mtx.try_lock_shared()) { return 0; } else { return EBUSY; } } int pthread_rwlock_timedrdlock( pthread_rwlock_t* rwlock, const timespec* abs_timeout) { if (rwlock == nullptr) { return EINVAL; } auto time = timespec_to_time_point(abs_timeout); if ((*rwlock)->mtx.try_lock_shared_until(time)) { return 0; } else { return ETIMEDOUT; } } int pthread_rwlock_wrlock(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } (*rwlock)->mtx.lock(); (*rwlock)->writing = true; return 0; } // Note: As far as I can tell, rwlock is technically supposed to // be an upgradable lock, but we don't implement it that way. int pthread_rwlock_trywrlock(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } if ((*rwlock)->mtx.try_lock()) { (*rwlock)->writing = true; return 0; } else { return EBUSY; } } int pthread_rwlock_timedwrlock( pthread_rwlock_t* rwlock, const timespec* abs_timeout) { if (rwlock == nullptr) { return EINVAL; } auto time = timespec_to_time_point(abs_timeout); if ((*rwlock)->mtx.try_lock_until(time)) { (*rwlock)->writing = true; return 0; } else { return ETIMEDOUT; } } int pthread_rwlock_unlock(pthread_rwlock_t* rwlock) { if (rwlock == nullptr) { return EINVAL; } // Note: We don't have any checking to ensure we have actually // locked things first, so you'll actually be in undefined behavior // territory if you do attempt to unlock things you haven't locked. if ((*rwlock)->writing) { (*rwlock)->mtx.unlock(); // If we fail, then another thread has already immediately acquired // the write lock, so this should stay as true :) bool dump = true; (void)(*rwlock)->writing.compare_exchange_strong(dump, false); } else { (*rwlock)->mtx.unlock_shared(); } return 0; } struct pthread_cond_t_ { // pthread_mutex_t is backed by timed // mutexes, so no basic condition variable for // us :( std::condition_variable_any cond; }; int pthread_cond_init(pthread_cond_t* cond, const void* attr) { if (attr != nullptr) { return EINVAL; } if (cond == nullptr) { return EINVAL; } *cond = new pthread_cond_t_(); return 0; } int pthread_cond_destroy(pthread_cond_t* cond) { if (cond == nullptr) { return EINVAL; } delete *cond; *cond = nullptr; return 0; } int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex) { if (cond == nullptr || mutex == nullptr) { return EINVAL; } (*mutex)->condition_wait((*cond)->cond); return 0; } int pthread_cond_timedwait( pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* abstime) { if (cond == nullptr || mutex == nullptr || abstime == nullptr) { return EINVAL; } auto time = timespec_to_time_point(abstime); if ((*mutex)->condition_timed_wait((*cond)->cond, time)) { return 0; } else { return ETIMEDOUT; } } int pthread_cond_signal(pthread_cond_t* cond) { if (cond == nullptr) { return EINVAL; } (*cond)->cond.notify_one(); return 0; } int pthread_cond_broadcast(pthread_cond_t* cond) { if (cond == nullptr) { return EINVAL; } (*cond)->cond.notify_all(); return 0; } int pthread_key_create(pthread_key_t* key, void (*destructor)(void*)) { try { auto newKey = new boost::thread_specific_ptr<void>(destructor); *key = newKey; return 0; } catch (boost::thread_resource_error) { return -1; } } int pthread_key_delete(pthread_key_t key) { try { auto realKey = reinterpret_cast<boost::thread_specific_ptr<void>*>(key); delete realKey; return 0; } catch (boost::thread_resource_error) { return -1; } } void* pthread_getspecific(pthread_key_t key) { auto realKey = reinterpret_cast<boost::thread_specific_ptr<void>*>(key); // This can't throw as-per the documentation. return realKey->get(); } int pthread_setspecific(pthread_key_t key, const void* value) { try { auto realKey = reinterpret_cast<boost::thread_specific_ptr<void>*>(key); // We can't just call reset here because that would invoke the cleanup // function, which we don't want to do. boost::detail::set_tss_data( realKey, boost::shared_ptr<boost::detail::tss_cleanup_function>(), const_cast<void*>(value), false); return 0; } catch (boost::thread_resource_error) { return -1; } } } // namespace pthread } // namespace portability } // namespace folly #endif
24.02149
84
0.670126
hasridha
2891ed38416ea18d8896a89d72a5821689796278
5,186
cpp
C++
lib/io/pipe.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
1
2021-02-05T23:20:07.000Z
2021-02-05T23:20:07.000Z
lib/io/pipe.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
lib/io/pipe.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
// $Id: pipe.cpp 1040 2014-02-15 16:31:04Z jerry $ #include "stdafx.h" #include "common.h" #include "thread.h" #include "log.h" #include "io/pipe.h" #include "WaitQueue.h" //------------------------------------------------------------------------------ bool Pipe::listen(const tstring &pipeName, int maxInstances) { tstring name(_T("\\\\.\\pipe\\")); name += pipeName; HANDLE hPipe = CreateNamedPipe( name.c_str() , PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE , PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE , maxInstances , 32768 , 32768 , NMPWAIT_USE_DEFAULT_WAIT , NULL); if (hPipe != INVALID_HANDLE_VALUE) { Log("Pipe created (%08X)", hPipe); openServer(hPipe); return true; } else { DWORD lastError = GetLastError(); Log("Pipe failed to create with %u", lastError); error_.setFromGLE(lastError); return false; } } bool Pipe::connect(const tstring &pipeName) { tstring name(_T("\\\\.\\pipe\\")); name += pipeName; HANDLE hPipe = CreateFile( name.c_str() , GENERIC_READ | GENERIC_WRITE , 0 , NULL , OPEN_EXISTING , FILE_FLAG_OVERLAPPED , NULL); if (hPipe != INVALID_HANDLE_VALUE) { DWORD dwMode = PIPE_READMODE_MESSAGE; if ( ! SetNamedPipeHandleState( hPipe, &dwMode, NULL, NULL)) { Log("SetNamedPipeHandleState failed"); CloseHandle(hPipe); throw eWinapiError; } openClient(hPipe); return true; } else { DWORD lastError = GetLastError(); Log("Pipe failed to create with %u", lastError); error_.setFromGLE(lastError); return false; } } //------------------------------------------------------------------------------ bool Pipe::acceptConnection(HANDLE hFile, bool *fatalError, bool *terminating) { bool connected = false; *fatalError = false; *terminating = false; Event<false> connectEvent; OVERLAPPED olpd; memset(&olpd, 0, sizeof(olpd)); olpd.hEvent = connectEvent; WaitQueue connectWq; connectWq.add(stopEvent_); connectWq.add(connectEvent); // connect the pipe loop while (!connected && !*fatalError && !(*terminating)) { bool pending = false; if (ConnectNamedPipe(hFile, &olpd) == 0) { DWORD error = GetLastError(); switch(error) { case ERROR_PIPE_CONNECTED: connected = true; break; case ERROR_IO_PENDING: pending = true; break; case ERROR_NO_DATA: Log("Stale end of pipe"); Sleep(100); break; default: Log("ConnectNamedPipe failed with %d.", error); error_.setFromGLE(error); *fatalError = true; break; } } // if connection is pending - wait for its completion if (pending) { bool isCancelled; HANDLE evt = connectWq.wait(isCancelled); if (isCancelled) { *terminating = true; break; } if (evt == connectEvent) { DWORD unused; if (GetOverlappedResult(hFile, &olpd, &unused, FALSE) == 0) { Log("Connect was failed (async) with %u", GetLastError()); } else { // connected, eah connected = true; } } else if (evt == stopEvent_) { *terminating = true; break; } else { Log("This should not ever happen!"); throw eStateError; } } // if pending if (!connected && !*fatalError && !(*terminating)) { Log("retrying.."); Sleep(1000); } } return connected; } bool Pipe::closeClient(HANDLE hFile) { if (hFile != INVALID_HANDLE_VALUE && ! CloseHandle(hFile)) { Log("CloseHandle failed with %d.", GetLastError()); return false; } return true; } bool Pipe::closeServer(HANDLE hFile) { if (hFile != INVALID_HANDLE_VALUE && ! DisconnectNamedPipe(hFile) ) { Log("DisconnectNamedPipe failed with %d.", GetLastError()); return false; } return true; }
26.459184
80
0.446973
siilky
289313a9b246c3a912889a3ee73bfb5035229e90
907
cpp
C++
Ray/Utils/RLogger.cpp
CAt0mIcS/NodePlanningEditor
d332fcef0dd2b7747727a7cb03edffba26abb1f7
[ "MIT" ]
null
null
null
Ray/Utils/RLogger.cpp
CAt0mIcS/NodePlanningEditor
d332fcef0dd2b7747727a7cb03edffba26abb1f7
[ "MIT" ]
null
null
null
Ray/Utils/RLogger.cpp
CAt0mIcS/NodePlanningEditor
d332fcef0dd2b7747727a7cb03edffba26abb1f7
[ "MIT" ]
null
null
null
#include "Rpch.h" #include "RLogger.h" namespace At0::Ray { RAY_EXPORT Violent::FileLogger g_FileLogger; RAY_EXPORT Violent::ConsoleLogger g_ConsoleLogger; void CLog::Close() { g_ConsoleLogger.Close(); } void CLog::SetLogLevel(Violent::LogLevel lvl) { g_ConsoleLogger.SetLogLevel(lvl); } void CLog::Flush() { g_ConsoleLogger.Flush(); } void FLog::Open(const char* filepath) { g_FileLogger.Open(filepath); } void FLog::Close() { g_FileLogger.Close(); } void FLog::SetLogLevel(Violent::LogLevel lvl) { g_FileLogger.SetLogLevel(lvl); } void FLog::Flush() { g_FileLogger.Flush(); } void Log::Open(const char* filepath) { FLog::Open(filepath); } void Log::Close() { FLog::Close(); CLog::Close(); } void Log::SetLogLevel(Violent::LogLevel lvl) { FLog::SetLogLevel(lvl); CLog::SetLogLevel(lvl); } void Log::Flush() { FLog::Flush(); CLog::Flush(); } } // namespace At0::Ray
23.25641
84
0.689085
CAt0mIcS
28959903e63b3e3abceac96ea6c94df321d34dde
11,435
cpp
C++
Engine/source/gui/controls/guiMLTextEditCtrl.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/gui/controls/guiMLTextEditCtrl.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/gui/controls/guiMLTextEditCtrl.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "gui/controls/guiMLTextEditCtrl.h" #include "gui/containers/guiScrollCtrl.h" #include "gui/core/guiCanvas.h" #include "console/consoleTypes.h" #include "core/frameAllocator.h" #include "core/stringBuffer.h" #include "gfx/gfxDrawUtil.h" #include "console/engineAPI.h" IMPLEMENT_CONOBJECT(GuiMLTextEditCtrl); ConsoleDocClass( GuiMLTextEditCtrl, "@brief A text entry control that accepts the Gui Markup Language ('ML') tags and multiple lines.\n\n" "@tsexample\n" "new GuiMLTextEditCtrl()\n" " {\n" " lineSpacing = \"2\";\n" " allowColorChars = \"0\";\n" " maxChars = \"-1\";\n" " deniedSound = \"DeniedSoundProfile\";\n" " text = \"\";\n" " escapeCommand = \"onEscapeScriptFunction();\";\n" " //Properties not specific to this control have been omitted from this example.\n" " };\n" "@endtsexample\n\n" "@see GuiMLTextCtrl\n" "@see GuiControl\n\n" "@ingroup GuiControls\n" ); //-------------------------------------------------------------------------- GuiMLTextEditCtrl::GuiMLTextEditCtrl() { mEscapeCommand = StringTable->insert( "" ); mIsEditCtrl = true; mActive = true; mVertMoveAnchorValid = false; } //-------------------------------------------------------------------------- GuiMLTextEditCtrl::~GuiMLTextEditCtrl() { } //-------------------------------------------------------------------------- bool GuiMLTextEditCtrl::resize(const Point2I &newPosition, const Point2I &newExtent) { // We don't want to get any smaller than our parent: Point2I newExt = newExtent; GuiControl* parent = getParent(); if ( parent ) newExt.y = getMax( parent->getHeight(), newExt.y ); return Parent::resize( newPosition, newExt ); } //-------------------------------------------------------------------------- void GuiMLTextEditCtrl::initPersistFields() { addField( "escapeCommand", TypeString, Offset( mEscapeCommand, GuiMLTextEditCtrl ), "Script function to run whenever the 'escape' key is pressed when this control is in focus.\n"); Parent::initPersistFields(); } //-------------------------------------------------------------------------- void GuiMLTextEditCtrl::setFirstResponder() { Parent::setFirstResponder(); GuiCanvas *root = getRoot(); if (root != NULL) { root->enableKeyboardTranslation(); // If the native OS accelerator keys are not disabled // then some key events like Delete, ctrl+V, etc may // not make it down to us. root->setNativeAcceleratorsEnabled( false ); } } void GuiMLTextEditCtrl::onLoseFirstResponder() { GuiCanvas *root = getRoot(); if (root != NULL) { root->setNativeAcceleratorsEnabled( true ); root->disableKeyboardTranslation(); } // Redraw the control: setUpdate(); } //-------------------------------------------------------------------------- bool GuiMLTextEditCtrl::onWake() { if( !Parent::onWake() ) return false; getRoot()->enableKeyboardTranslation(); return true; } //-------------------------------------------------------------------------- // Key events... bool GuiMLTextEditCtrl::onKeyDown(const GuiEvent& event) { if ( !isActive() ) return false; setUpdate(); //handle modifiers first... if (event.modifier & SI_PRIMARY_CTRL) { switch(event.keyCode) { //copy/cut case KEY_C: case KEY_X: { //make sure we actually have something selected if (mSelectionActive) { copyToClipboard(mSelectionStart, mSelectionEnd); //if we're cutting, also delete the selection if (event.keyCode == KEY_X) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd); mCursorPosition = mSelectionStart; } else mCursorPosition = mSelectionEnd + 1; } return true; } //paste case KEY_V: { const char *clipBuf = Platform::getClipboard(); if (dStrlen(clipBuf) > 0) { // Normal ascii keypress. Go ahead and add the chars... if (mSelectionActive == true) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd); mCursorPosition = mSelectionStart; } insertChars(clipBuf, dStrlen(clipBuf), mCursorPosition); } return true; } default: break; } } else if ( event.modifier & SI_SHIFT ) { switch ( event.keyCode ) { case KEY_TAB: return( Parent::onKeyDown( event ) ); default: break; } } else if ( event.modifier == 0 ) { switch (event.keyCode) { // Escape: case KEY_ESCAPE: if ( mEscapeCommand[0] ) { Con::evaluate( mEscapeCommand ); return( true ); } return( Parent::onKeyDown( event ) ); // Deletion case KEY_BACKSPACE: case KEY_DELETE: handleDeleteKeys(event); return true; // Cursor movement case KEY_LEFT: case KEY_RIGHT: case KEY_UP: case KEY_DOWN: case KEY_HOME: case KEY_END: handleMoveKeys(event); return true; // Special chars... case KEY_TAB: // insert 3 spaces if (mSelectionActive == true) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd); mCursorPosition = mSelectionStart; } insertChars( "\t", 1, mCursorPosition ); return true; case KEY_RETURN: // insert carriage return if (mSelectionActive == true) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd); mCursorPosition = mSelectionStart; } insertChars( "\n", 1, mCursorPosition ); return true; default: break; } } if ( (mFont && mFont->isValidChar(event.ascii)) || (!mFont && event.ascii != 0) ) { // Normal ascii keypress. Go ahead and add the chars... if (mSelectionActive == true) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd); mCursorPosition = mSelectionStart; } UTF8 *outString = NULL; U32 outStringLen = 0; #ifdef TORQUE_UNICODE UTF16 inData[2] = { event.ascii, 0 }; StringBuffer inBuff(inData); FrameTemp<UTF8> outBuff(4); inBuff.getCopy8(outBuff, 4); outString = outBuff; outStringLen = dStrlen(outBuff); #else char ascii = char(event.ascii); outString = &ascii; outStringLen = 1; #endif insertChars(outString, outStringLen, mCursorPosition); mVertMoveAnchorValid = false; return true; } // Otherwise, let the parent have the event... return Parent::onKeyDown(event); } //-------------------------------------- void GuiMLTextEditCtrl::handleDeleteKeys(const GuiEvent& event) { if ( isSelectionActive() ) { mSelectionActive = false; deleteChars(mSelectionStart, mSelectionEnd+1); mCursorPosition = mSelectionStart; } else { switch ( event.keyCode ) { case KEY_BACKSPACE: if (mCursorPosition != 0) { // delete one character left deleteChars(mCursorPosition-1, mCursorPosition); setUpdate(); } break; case KEY_DELETE: if (mCursorPosition != mTextBuffer.length()) { // delete one character right deleteChars(mCursorPosition, mCursorPosition+1); setUpdate(); } break; default: AssertFatal(false, "Unknown key code received!"); } } } //-------------------------------------- void GuiMLTextEditCtrl::handleMoveKeys(const GuiEvent& event) { if ( event.modifier & SI_SHIFT ) return; mSelectionActive = false; switch ( event.keyCode ) { case KEY_LEFT: mVertMoveAnchorValid = false; // move one left if ( mCursorPosition != 0 ) { mCursorPosition--; setUpdate(); } break; case KEY_RIGHT: mVertMoveAnchorValid = false; // move one right if ( mCursorPosition != mTextBuffer.length() ) { mCursorPosition++; setUpdate(); } break; case KEY_UP: case KEY_DOWN: { Line* walk; for ( walk = mLineList; walk->next; walk = walk->next ) { if ( mCursorPosition <= ( walk->textStart + walk->len ) ) break; } if ( !walk ) return; if ( event.keyCode == KEY_UP ) { if ( walk == mLineList ) return; } else if ( walk->next == NULL ) return; Point2I newPos; newPos.set( 0, walk->y ); // Find the x-position: if ( !mVertMoveAnchorValid ) { Point2I cursorTopP, cursorBottomP; ColorI color; getCursorPositionAndColor(cursorTopP, cursorBottomP, color); mVertMoveAnchor = cursorTopP.x; mVertMoveAnchorValid = true; } newPos.x = mVertMoveAnchor; // Set the new y-position: if (event.keyCode == KEY_UP) newPos.y--; else newPos.y += (walk->height + 1); if (setCursorPosition(getTextPosition(newPos))) mVertMoveAnchorValid = false; break; } case KEY_HOME: case KEY_END: { mVertMoveAnchorValid = false; Line* walk; for (walk = mLineList; walk->next; walk = walk->next) { if (mCursorPosition <= (walk->textStart + walk->len)) break; } if (walk) { if (event.keyCode == KEY_HOME) { //place the cursor at the beginning of the first atom if there is one if (walk->atomList) mCursorPosition = walk->atomList->textStart; else mCursorPosition = walk->textStart; } else { mCursorPosition = walk->textStart; mCursorPosition += walk->len; } setUpdate(); } break; } default: AssertFatal(false, "Unknown move key code was received!"); } ensureCursorOnScreen(); } //-------------------------------------------------------------------------- void GuiMLTextEditCtrl::onRender(Point2I offset, const RectI& updateRect) { Parent::onRender(offset, updateRect); // We are the first responder, draw our cursor in the appropriate position... if (isFirstResponder()) { Point2I top, bottom; ColorI color; getCursorPositionAndColor(top, bottom, color); GFX->getDrawUtil()->drawLine(top + offset, bottom + offset, mProfile->mCursorColor); } }
25.467706
183
0.529252
fr1tz
2896d5cd500af8503aade3c7b74201f9e1f36d70
553
cpp
C++
src/main.cpp
ivan-volnov/uvserver
6beaee50488599ff3a2719c9f5604350e0624587
[ "MIT" ]
null
null
null
src/main.cpp
ivan-volnov/uvserver
6beaee50488599ff3a2719c9f5604350e0624587
[ "MIT" ]
null
null
null
src/main.cpp
ivan-volnov/uvserver
6beaee50488599ff3a2719c9f5604350e0624587
[ "MIT" ]
1
2020-04-29T08:33:03.000Z
2020-04-29T08:33:03.000Z
#include "server.h" #include "uv_network/uv_buffers.h" int main(int /*argc*/, char **argv) { const auto host = "0.0.0.0"; const auto port = 9000; std::cout << "Listening " << host << " " << port << std::endl; { std::string tzdb_filepath(*argv); tzdb_filepath.resize(tzdb_filepath.rfind('/') + 1); tzdb_filepath.append("date_time_zonespec.csv"); Server server(host, port, tzdb_filepath); server.run_loop(); UVBuffers::instance().clear(); } std::cout << "Shutdown" << std::endl; }
27.65
66
0.585895
ivan-volnov
289b1016343b2ac978d310446674bae88800a404
2,455
cpp
C++
src/trash/logwriter/benchmarking.cpp
WebWorksCollection/treefrog-framework
9da400135c5fa6c4effa878cca395d8f200cf0f0
[ "BSD-3-Clause" ]
942
2015-01-16T02:02:10.000Z
2022-03-31T02:11:50.000Z
src/trash/logwriter/benchmarking.cpp
WebWorksCollection/treefrog-framework
9da400135c5fa6c4effa878cca395d8f200cf0f0
[ "BSD-3-Clause" ]
250
2015-04-26T23:46:48.000Z
2022-03-30T09:32:05.000Z
src/trash/logwriter/benchmarking.cpp
WebWorksCollection/treefrog-framework
9da400135c5fa6c4effa878cca395d8f200cf0f0
[ "BSD-3-Clause" ]
244
2015-01-16T17:41:06.000Z
2022-02-11T09:34:42.000Z
#include <QtTest/QtTest> #include "tlogsender.h" #include "tlogfilewriter.h" #define LOG_SERVER_NAME_PREFIX QLatin1String(".tflogsvr_") class BenchMark : public QObject { Q_OBJECT private slots: void sendLog(); void writeFileLog(); }; void BenchMark::sendLog() { TLogSender sender(LOG_SERVER_NAME_PREFIX + "treefrog"); //sender.waitForConnected(); QBENCHMARK { sender.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); sender.writeLog("o0sa8dufassljf6823648236826"); sender.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); sender.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); sender.writeLog("o0sa8dufassljf6823648236826"); sender.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); sender.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); sender.writeLog("o0sa8dufassljf6823648236826"); sender.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); } } void BenchMark::writeFileLog() { QString file = "temp.log"; TLogFileWriter writer(file); QBENCHMARK { writer.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); writer.writeLog("o0sa8dufassljf6823648236826"); writer.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); writer.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); writer.writeLog("o0sa8dufassljf6823648236826"); writer.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); writer.writeLog("aildjfliasjdl;fijaswelirjas;lidfja;lsiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); writer.writeLog("o0sa8dufassljf6823648236826"); writer.writeLog("aildjfliasjdl;fijaswusdifhsidfhskdjfhksuhfkhwkefrkwjnfksjdnfkunknkiwejf;alsdf;lakjer;liajds;flkasd;lfaj;esrldfij"); } QFile::remove(file); } QTEST_MAIN(BenchMark) #include "benchmarking.moc"
43.070175
140
0.774745
WebWorksCollection
289bff44c94f9d581d9dccce9efd97e682ef9529
7,587
cpp
C++
src/ban.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
1
2018-09-16T03:17:50.000Z
2018-09-16T03:17:50.000Z
src/ban.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
src/ban.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
#include "system.h" const char** badname_array = NULL; int max_badname = 0; class ban_data { public: ban_data* next; char* name; ban_data( ); ~ban_data( ); }; ban_data* ban_list = NULL; ban_data :: ban_data( ) { name = empty_string; record_new( sizeof( ban_data ), MEM_BAN ); append( ban_list, this ); }; ban_data :: ~ban_data( ) { free_string( name, MEM_BAN ); record_delete( sizeof( ban_data ), MEM_BAN ); remove( ban_list, this ); }; /* * BAN/ALLOW ROUTINES */ void do_ban( char_data* ch, char* argument ) { account_data* account; ban_data* ban; pfile_data* pfile = NULL; int flags; int i; bool first = TRUE; const char* name; player_data* victim; if( !get_flags( ch, argument, &flags, "srn", "Ban" ) ) return; if( is_set( &flags, 2 ) ) { if( *argument == '\0' ) { if( badname_array == NULL ) { send( ch, "The badname array is empty.\r\n" ); } else { display_array( ch, "Bad Name Array", &badname_array[0], &badname_array[1], max_badname ); } return; } i = pntr_search( badname_array, max_badname, argument ); if( is_set( &flags, 1 ) ) { if( i < 0 ) { send( ch, "The name '%s' wasn't in the badname array.\r\n", argument ); } else { record_delete( sizeof( char* ), MEM_BADNAME ); remove( badname_array, max_badname, i ); send( ch, "Name removed from badname array.\r\n" ); save_badname( ); } } else { if( i > 0 ) { send( ch, "The name '%s' is already in the badname array.\r\n", argument ); } else if( check_parse_name( ch->link, argument ) ) { i = -i - 1; record_new( sizeof( char* ), MEM_BADNAME ); name = alloc_string( argument, MEM_BADNAME ); insert( badname_array, max_badname, name, i ); send( ch, "The name '%s' is added to the badname array.\r\n", name ); save_badname( ); } } return; } if( is_set( &flags, 0 ) ) { if( *argument == '\0' ) { page_title( ch, "Banned Sites" ); for( ban = ban_list; ban != NULL; ban = ban->next ) page( ch, "%s\r\n", ban->name ); return; } if( !is_set( &flags, 1 ) ) { for( ban = ban_list; ban != NULL; ban = ban->next ) { if( !strcasecmp( argument, ban->name ) ) { send( "That site is already banned!\r\n", ch ); return; } } ban = new ban_data; ban->name = alloc_string( argument, MEM_BAN ); save_banned( ); send( ch, "Ok.\r\n" ); } else { for( ban = ban_list; ban != NULL; ban = ban->next ) { if( !strcasecmp( argument, ban->name ) ) { delete ban; save_banned(); send( ch, "Ok.\r\n" ); return; } } send( ch, "Site is not banned.\r\n" ); } return; } if( *argument == '\0' ) { page_title( ch, "Banned Accounts" ); for( i = 0; i < max_account; i++ ) if( account_list[i]->banned != -1 ) display_account( ch, account_list[i], first ); return; } if( ( account = account_arg( argument ) ) == NULL ) { if( ( pfile = player_arg( argument ) ) == NULL ) { send( ch, "No such account or player.\r\n" ); return; } if( ( account = pfile->account ) == NULL ) { send( ch, "That player doesn't have an account which makes banning it difficult.\r\n" ); return; } } if( is_set( &flags, 1 ) ) { if( account->banned == -1 ) { send( ch, "That account was not banned.\r\n" ); } else { send( ch, "Ban lifted.\r\n" ); account->banned = -1; save_accounts( ); } return; } if( ch->pcdata->pfile->account == account ) { send( ch, "Banning yourself is rather phulish.\r\n" ); return; } for( i = 0; i < max_pfile; i++ ) if( pfile_list[i]->account == account && pfile_list[i]->trust >= ch->pcdata->trust ) { send( ch, "You do not have permission to ban that account.\r\n" ); return; } if( *argument == '\0' ) { send( ch, "For how what time period?\r\n" ); return; } if( ( i = time_arg( argument, ch ) ) == -1 ) return; if( i == 0 ) { account->banned = 0; send( ch, "Account %s banned forever.\r\n", account->name ); } else { account->banned = time(0) + i; send( ch, "Account %s banned until %s.\r\n", account->name, ltime( account->banned )+4 ); } save_accounts( ); for( i = 0; i < player_list; i++ ) { victim = player_list[i]; if( victim->Is_Valid( ) && victim->pcdata->pfile->account == account ) { send( victim, "-- You have been banned. --\r\n" ); forced_quit( victim ); } } return; } /* * IS_BANNED ROUTINE */ bool is_banned( const char* host ) { ban_data* ban; int host_len = strlen( host ); int ban_len; for( ban = ban_list; ban != NULL; ban = ban->next ) { ban_len = strlen( ban->name ); if( ban_len <= host_len && !strcasecmp( &host[host_len-ban_len], ban->name ) ) break; } return( ban != NULL ); } bool is_banned( account_data* account, link_data* link ) { if( account == NULL || account->banned == -1 ) return FALSE; if( account->banned != 0 && account->banned < time(0) ) { account->banned = -1; return FALSE; } help_link( link, "Banned_Acnt" ); if( account->banned != 0 ) send( link, "Ban Expires: %s\r\n", ltime( account->banned ) ); close_socket( link, TRUE ); return TRUE; } /* * READ/WRITE BADNAME */ void load_badname( void ) { FILE* fp; char* name; log( "Loading Bad Names...\r\n" ); if( ( fp = fopen( BADNAME_FILE, "rb" ) ) == NULL ) { perror( BADNAME_FILE ); throw( 1 ); } if( strcmp( fread_word( fp ), "#BADNAME" ) ) panic( "Load_badname: missing header" ); for( ; ; ) { name = fread_string( fp, MEM_BADNAME ); if( *name == '$' ) break; record_new( sizeof( char* ), MEM_BADNAME ); insert( badname_array, max_badname, (const char *) name, max_badname ); } free_string( name, MEM_BADNAME ); fclose( fp ); return; } void save_badname( void ) { FILE* fp; int i; rename_file( AREA_DIR, BADNAME_FILE, PREV_DIR, BADNAME_FILE ); if( ( fp = fopen( BADNAME_FILE, "wb" ) ) == NULL ) { bug( "Save_badname: fopen" ); return; } fprintf( fp, "#BADNAME\n\n" ); for( i = 0; i < max_badname; i++ ) fprintf( fp, "%s~\n", badname_array[i] ); fprintf( fp, "$~\n" ); fclose( fp ); return; } /* * READ/WRITE BANNED */ void load_banned( void ) { ban_data* ban; char* name; FILE* fp; log( "Loading Banned Sites...\r\n" ); if( ( fp = fopen( BANNED_FILE, "rb" ) ) == NULL ) { perror( BANNED_FILE ); throw( 1 ); } if( strcmp( fread_word( fp ), "#BANNED" ) ) panic( "Load_banned: missing header" ); for( ; ; ) { name = fread_string( fp, MEM_BAN ); if( *name == '$' ) break; ban = new ban_data; ban->name = name; } free_string( name, MEM_BAN ); fclose( fp ); return; } void save_banned( ) { ban_data* ban; FILE* fp; rename_file( AREA_DIR, BANNED_FILE, PREV_DIR, BANNED_FILE ); fp = open_file( BANNED_FILE, "wb" ); fprintf( fp, "#BANNED\n\n" ); for( ban = ban_list; ban != NULL; ban = ban->next ) fprintf( fp, "%s~\n", ban->name ); fprintf( fp, "$~\n" ); fclose( fp ); return; }
21.371831
97
0.529458
Celissa
289cbb5ebfe7afe1dfff865eab6a305210cff2db
27,820
cc
C++
ext/snowcrash/test/test-ActionParser.cc
darkcl/drafter
62dcc54341d76b1dae7bca1777f5eea8815b0c3b
[ "MIT" ]
194
2015-01-12T03:33:33.000Z
2021-03-27T04:08:15.000Z
ext/snowcrash/test/test-ActionParser.cc
darkcl/drafter
62dcc54341d76b1dae7bca1777f5eea8815b0c3b
[ "MIT" ]
142
2015-01-04T15:35:17.000Z
2018-10-01T13:02:21.000Z
ext/snowcrash/test/test-ActionParser.cc
darkcl/drafter
62dcc54341d76b1dae7bca1777f5eea8815b0c3b
[ "MIT" ]
36
2015-01-28T05:41:01.000Z
2018-07-18T08:48:26.000Z
// // test-ActionParser.cc // snowcrash // // Created by Zdenek Nemec on 5/6/13. // Copyright (c) 2013 Apiary Inc. All rights reserved. // #include "snowcrash.h" #include "snowcrashtest.h" #include "ActionParser.h" using namespace snowcrash; using namespace snowcrashtest; const mdp::ByteBuffer ActionFixture = "# My Method [GET]\n\n" "Method Description\n\n" "+ Response 200 (text/plain)\n\n" " OK."; TEST_CASE("Method block classifier", "[action]") { mdp::MarkdownParser markdownParser; mdp::MarkdownNode markdownAST; SectionType sectionType; markdownParser.parse(ActionFixture, markdownAST); REQUIRE(!markdownAST.children().empty()); sectionType = SectionProcessor<Action>::sectionType(markdownAST.children().begin()); REQUIRE(sectionType == ActionSectionType); // Nameless method markdownAST.children().front().text = "GET"; REQUIRE(!markdownAST.children().empty()); sectionType = SectionProcessor<Action>::sectionType(markdownAST.children().begin()); REQUIRE(sectionType == ActionSectionType); } TEST_CASE("Parsing action", "[action]") { ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(ActionFixture, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); CHECK(action.report.warnings.empty()); REQUIRE(action.node.name == "My Method"); REQUIRE(action.node.method == "GET"); REQUIRE(action.node.description == "Method Description"); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples.front().requests.size() == 0); REQUIRE(action.node.examples.front().responses.size() == 1); REQUIRE(action.node.examples.front().responses[0].name == "200"); REQUIRE(action.node.examples.front().responses[0].body == "OK.\n"); REQUIRE(action.node.examples.front().responses[0].headers.size() == 1); REQUIRE(action.node.examples.front().responses[0].headers[0].first == "Content-Type"); REQUIRE(action.node.examples.front().responses[0].headers[0].second == "text/plain"); SourceMapHelper::check(action.sourceMap.name.sourceMap, 0, 19); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 19); SourceMapHelper::check(action.sourceMap.description.sourceMap, 19, 20); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); SourceMapHelper::check(action.sourceMap.examples.collection[0].responses.collection[0].body.sourceMap, 72, 7); SourceMapHelper::check(action.sourceMap.examples.collection[0].responses.collection[0].name.sourceMap, 41, 27); REQUIRE(action.sourceMap.examples.collection[0].responses.collection[0].headers.collection.size() == 1); SourceMapHelper::check( action.sourceMap.examples.collection[0].responses.collection[0].headers.collection[0].sourceMap, 41, 27); } TEST_CASE("Parse named action with () in title", "[action]") { mdp::ByteBuffer source = "# My Action (Deprecated) [GET]\n" "+ Response 204\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); CHECK(action.report.warnings.empty()); REQUIRE(action.node.name == "My Action (Deprecated)"); REQUIRE(action.node.method == "GET"); } TEST_CASE("Parse named action with path including () in title", "[action]") { mdp::ByteBuffer source = "# My Action (Deprecated) [GET /test]\n" "+ Response 204\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); CHECK(action.report.warnings.empty()); REQUIRE(action.node.name == "My Action (Deprecated)"); REQUIRE(action.node.method == "GET"); REQUIRE(action.node.uriTemplate == "/test"); } TEST_CASE("Parse named action with [] in title", "[action]") { mdp::ByteBuffer source = "# My Action [DEPRECATED] [GET]\n" "+ Response 204\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); CHECK(action.report.warnings.empty()); REQUIRE(action.node.name == "My Action [DEPRECATED]"); REQUIRE(action.node.method == "GET"); } TEST_CASE("Parse Action description with list", "[action]") { mdp::ByteBuffer source = "# GET\n" "Small Description\n" "+ A\n" "+ B\n" "+ Response 204\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); CHECK(action.report.warnings.empty()); REQUIRE(action.node.method == "GET"); REQUIRE(action.node.description == "Small Description\n\n+ A\n\n+ B"); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples.front().responses.size() == 1); REQUIRE(action.node.examples.front().requests.empty()); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 6); SourceMapHelper::check(action.sourceMap.description.sourceMap, 6, 26); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Parse method with multiple requests and responses", "[action]") { mdp::ByteBuffer source = "# PUT\n" "+ Request A\n" " B\n" " + Body\n\n" " C\n\n" "+ Request D\n" " E\n" " + Body\n\n" " F\n\n" "+ Response 200\n" " G\n" " + Body\n\n" " H\n\n" "+ Response 200\n" " I\n" " + Body\n\n" " J\n\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); // warn responses with the same name REQUIRE(action.node.name.empty()); REQUIRE(action.node.method == "PUT"); REQUIRE(action.node.description.empty()); REQUIRE(action.node.parameters.empty()); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples.front().requests.size() == 2); REQUIRE(action.node.examples.front().requests[0].name == "A"); REQUIRE(action.node.examples.front().requests[0].description == "B"); REQUIRE(action.node.examples.front().requests[0].body == "C\n"); REQUIRE(action.node.examples.front().requests[0].schema.empty()); REQUIRE(action.node.examples.front().requests[0].parameters.empty()); REQUIRE(action.node.examples.front().requests[0].headers.empty()); REQUIRE(action.node.examples.front().requests[1].name == "D"); REQUIRE(action.node.examples.front().requests[1].description == "E"); REQUIRE(action.node.examples.front().requests[1].body == "F\n"); REQUIRE(action.node.examples.front().requests[1].schema.empty()); REQUIRE(action.node.examples.front().requests[1].parameters.empty()); REQUIRE(action.node.examples.front().requests[1].headers.empty()); REQUIRE(action.node.examples.front().responses.size() == 2); REQUIRE(action.node.examples.front().responses[0].name == "200"); REQUIRE(action.node.examples.front().responses[0].description == "G"); REQUIRE(action.node.examples.front().responses[0].body == "H\n"); REQUIRE(action.node.examples.front().responses[0].schema.empty()); REQUIRE(action.node.examples.front().responses[0].parameters.empty()); REQUIRE(action.node.examples.front().responses[0].headers.empty()); REQUIRE(action.node.examples.front().responses[1].name == "200"); REQUIRE(action.node.examples.front().responses[1].description == "I"); REQUIRE(action.node.examples.front().responses[1].body == "J\n"); REQUIRE(action.node.examples.front().responses[1].schema.empty()); REQUIRE(action.node.examples.front().responses[1].parameters.empty()); REQUIRE(action.node.examples.front().responses[1].headers.empty()); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 6); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 2); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 2); } TEST_CASE("Parse method with multiple incomplete requests", "[action][blocks]") { mdp::ByteBuffer source = "# GET /1\n" "+ Request A\n" "+ Request B\n" " C\n" "+ Response 200\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 2); // empty asset & preformatted asset REQUIRE(action.report.warnings[0].code == EmptyDefinitionWarning); REQUIRE(action.report.warnings[1].code == IndentationWarning); REQUIRE(action.node.name.empty()); REQUIRE(action.node.method == "GET"); REQUIRE(action.node.description.empty()); REQUIRE(action.node.parameters.empty()); REQUIRE(action.node.examples.front().requests.size() == 2); REQUIRE(action.node.examples.front().requests[0].name == "A"); REQUIRE(action.node.examples.front().requests[0].body.empty()); REQUIRE(action.node.examples.front().requests[0].schema.empty()); REQUIRE(action.node.examples.front().requests[0].parameters.empty()); REQUIRE(action.node.examples.front().requests[0].headers.empty()); REQUIRE(action.node.examples.front().requests[1].name == "B"); REQUIRE(action.node.examples.front().requests[1].description.empty()); REQUIRE(action.node.examples.front().requests[1].body == "C\n\n"); REQUIRE(action.node.examples.front().requests[1].schema.empty()); REQUIRE(action.node.examples.front().requests[1].parameters.empty()); REQUIRE(action.node.examples.front().requests[1].headers.empty()); REQUIRE(action.node.examples.front().responses.size() == 1); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 9); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 2); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Parse method with foreign item", "[action]") { mdp::ByteBuffer source = "# MKCOL\n" "+ Request\n" " + Body\n\n" " Foo\n\n" "+ Bar\n" "+ Response 200\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); REQUIRE(action.report.warnings[0].code == IgnoringWarning); REQUIRE(action.node.name.empty()); REQUIRE(action.node.method == "MKCOL"); REQUIRE(action.node.description.empty()); REQUIRE(action.node.parameters.empty()); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples.front().requests.size() == 1); REQUIRE(action.node.examples.front().requests[0].name.empty()); REQUIRE(action.node.examples.front().requests[0].body == "Foo\n"); REQUIRE(action.node.examples.front().requests[0].schema.empty()); REQUIRE(action.node.examples.front().requests[0].parameters.empty()); REQUIRE(action.node.examples.front().requests[0].headers.empty()); REQUIRE(action.node.examples.front().responses.size() == 1); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 8); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Parse method with a HR", "[action]") { mdp::ByteBuffer source = "# PATCH /1\n\n" "A\n" "---\n" "B\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); // no response REQUIRE(action.node.name.empty()); REQUIRE(action.node.method == "PATCH"); REQUIRE(action.node.description == "A\n---\n\nB"); REQUIRE(action.node.examples.empty()); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 12); SourceMapHelper::check(action.sourceMap.description.sourceMap, 12, 8); REQUIRE(action.sourceMap.examples.collection.size() == 0); } TEST_CASE("Parse method without name", "[action]") { mdp::ByteBuffer source = "# GET"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); // no response REQUIRE(action.node.name.empty()); REQUIRE(action.node.method == "GET"); REQUIRE(action.node.description.empty()); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 5); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 0); } TEST_CASE("Parse action with parameters", "[action]") { mdp::ByteBuffer source = "# GET /resource/{id}\n" "+ Parameters\n" " + id (required, number, `42`) ... Resource Id\n" "\n" "+ Response 204\n" "\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.empty()); REQUIRE(action.node.parameters.size() == 1); REQUIRE(action.node.parameters[0].name == "id"); REQUIRE(action.node.parameters[0].description == "Resource Id"); REQUIRE(action.node.parameters[0].type == "number"); REQUIRE(action.node.parameters[0].defaultValue.empty()); REQUIRE(action.node.parameters[0].exampleValue == "42"); REQUIRE(action.node.parameters[0].values.empty()); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 21); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.parameters.collection.size() == 1); SourceMapHelper::check(action.sourceMap.parameters.collection[0].name.sourceMap, 40, 44); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Give a warning when 2xx CONNECT has a body", "[action]") { mdp::ByteBuffer source = "# CONNECT /1\n" "+ Response 201\n\n" " {}\n\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); REQUIRE(action.node.method == "CONNECT"); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples[0].responses.size() == 1); REQUIRE(action.node.examples[0].responses[0].body == "{}\n"); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 13); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Give a warning when response to HEAD has a body", "[action]") { mdp::ByteBuffer source = "# HEAD /1\n" "+ Response 200\n\n" " {}\n\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); REQUIRE(action.report.warnings[0].code == EmptyDefinitionWarning); REQUIRE(action.node.method == "HEAD"); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples[0].responses.size() == 1); REQUIRE(action.node.examples[0].responses[0].body == "{}\n"); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 10); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Missing 'LINK' HTTP request method", "[action]") { mdp::ByteBuffer source = "# LINK /1\n" "+ Response 204\n\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.empty()); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples[0].requests.empty()); REQUIRE(action.node.examples[0].responses.size() == 1); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 10); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); } TEST_CASE("Warn when request is not followed by a response", "[action]") { mdp::ByteBuffer source = "# GET /1\n" "+ response 200 \n" "\n" " 200\n" "\n" "+ request A\n" "\n" " A\n"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 1); REQUIRE(action.report.warnings[0].code == EmptyDefinitionWarning); REQUIRE(action.node.examples.size() == 2); REQUIRE(action.node.examples[0].requests.size() == 0); REQUIRE(action.node.examples[0].responses.size() == 1); REQUIRE(action.node.examples[1].requests.size() == 1); REQUIRE(action.node.examples[1].responses.size() == 0); REQUIRE(action.sourceMap.name.sourceMap.empty()); SourceMapHelper::check(action.sourceMap.method.sourceMap, 0, 9); REQUIRE(action.sourceMap.description.sourceMap.empty()); REQUIRE(action.sourceMap.examples.collection.size() == 2); REQUIRE(action.sourceMap.examples.collection[0].requests.collection.size() == 0); REQUIRE(action.sourceMap.examples.collection[0].responses.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[1].requests.collection.size() == 1); REQUIRE(action.sourceMap.examples.collection[1].responses.collection.size() == 0); } // TODO: This test is failing because of a bug in action attributes. Need to fix the bug. // TEST_CASE("Parse action attributes", "[action]") // { // mdp::ByteBuffer source = \ // "# GET /1\n\n"\ // "+ attributes (Coupon)\n"\ // "+ request A\n\n"\ // "+ response 204\n\n" // "+ request B\n\n"\ // " + attributes (string)\n\n"\ // "+ response 204"; // ParseResult<Action> action; // NamedTypes namedTypes; // NamedTypeHelper::build("Coupon", mson::ObjectBaseType, namedTypes); // SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption, // Models(), NULL, namedTypes); // REQUIRE(action.report.error.code == Error::OK); // REQUIRE(action.report.warnings.empty()); // REQUIRE(action.node.attributes.source.typeDefinition.typeSpecification.name.symbol.literal == "Coupon"); // REQUIRE(action.node.examples.size() == 2); // REQUIRE(action.node.examples[0].requests.size() == 1); // REQUIRE(action.node.examples[0].requests[0].attributes.source.empty()); // REQUIRE(action.node.examples[0].responses.size() == 1); // REQUIRE(action.node.examples[1].requests.size() == 1); // REQUIRE(action.node.examples[1].requests[0].attributes.source.typeDefinition.typeSpecification.name.base == // mson::StringTypeName); // REQUIRE(action.node.examples[1].responses.size() == 1); // } TEST_CASE("Named Endpoint", "[named_endpoint]") { const mdp::ByteBuffer source = "# Group Test Group\n\n" "## My Named Endpoint [GET /test/endpoint]\n\n" "Endpoint Description\n\n" "+ Response 200 (text/plain)\n\n" " OK."; ParseResult<Blueprint> blueprint; snowcrash::parse(source, 0, blueprint); REQUIRE(blueprint.report.error.code == Error::OK); REQUIRE(blueprint.report.warnings.empty()); REQUIRE(blueprint.node.content.elements().size() == 1); REQUIRE(blueprint.node.content.elements().at(0).element == Element::CategoryElement); REQUIRE(blueprint.node.content.elements().at(0).content.elements().size() == 1); REQUIRE(blueprint.node.content.elements().at(0).content.elements().at(0).element == Element::ResourceElement); Resource resource = blueprint.node.content.elements().at(0).content.elements().at(0).content.resource; REQUIRE(resource.name == "My Named Endpoint"); REQUIRE(resource.uriTemplate == "/test/endpoint"); REQUIRE(resource.actions.size() == 1); Action action = resource.actions.at(0); REQUIRE(action.method == "GET"); } TEST_CASE("Named Endpoints Edge Cases", "[named_endpoint]") { const mdp::ByteBuffer source = "# Endpoint 1 [GET /e1]\n\n" "+ Response 204\n\n" "# Endpoint 2 [GET /e1]\n\n" "+ Response 204\n\n" "# Endpoint 3 [POST /e1]\n\n" "+ Response 204\n"; ParseResult<Blueprint> blueprint; snowcrash::parse(source, 0, blueprint); REQUIRE(blueprint.report.error.code == Error::OK); REQUIRE(blueprint.report.warnings.size() == 2); REQUIRE(blueprint.report.warnings.at(0).code == DuplicateWarning); REQUIRE(blueprint.report.warnings.at(1).code == DuplicateWarning); REQUIRE(blueprint.node.content.elements().size() == 1); REQUIRE(blueprint.node.content.elements().at(0).element == Element::CategoryElement); REQUIRE(blueprint.node.content.elements().at(0).content.elements().size() == 3); REQUIRE(blueprint.node.content.elements().at(0).content.elements().at(0).element == Element::ResourceElement); { Resource resource = blueprint.node.content.elements().at(0).content.elements().at(0).content.resource; REQUIRE(resource.name == "Endpoint 1"); REQUIRE(resource.uriTemplate == "/e1"); REQUIRE(resource.actions.size() == 1); Action action = resource.actions.at(0); REQUIRE(action.method == "GET"); } { Resource resource = blueprint.node.content.elements().at(0).content.elements().at(1).content.resource; REQUIRE(resource.name == "Endpoint 2"); REQUIRE(resource.uriTemplate == "/e1"); REQUIRE(resource.actions.size() == 1); Action action = resource.actions.at(0); REQUIRE(action.method == "GET"); } { Resource resource = blueprint.node.content.elements().at(0).content.elements().at(2).content.resource; REQUIRE(resource.name == "Endpoint 3"); REQUIRE(resource.uriTemplate == "/e1"); REQUIRE(resource.actions.size() == 1); Action action = resource.actions.at(0); REQUIRE(action.method == "POST"); } } TEST_CASE("Action section containing properties keyword under it", "[action][127]") { const mdp::ByteBuffer source = "# A [GET /]\n" "+ Properties\n" "+ Response 204"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.empty()); REQUIRE(action.node.examples.size() == 1); REQUIRE(action.node.examples[0].requests.empty()); REQUIRE(action.node.examples[0].responses.size() == 1); } TEST_CASE("Miss leading slash in URI", "[action][350]") { const mdp::ByteBuffer source = "A [GET {param}]"; snowcrash::ParseResult<snowcrash::Blueprint> blueprint; snowcrash::SectionParserData pd(0, source, blueprint.node); MarkdownNodes nodes; nodes.push_back(mdp::MarkdownNode(mdp::HeaderMarkdownNodeType, NULL, mdp::ByteBuffer(source))); Report report; SectionProcessor<Action>::checkForTypoMistake(nodes.begin(), pd, report); REQUIRE(report.error.code == Error::OK); REQUIRE(report.warnings.size() == 1); REQUIRE(report.warnings.begin()->code == snowcrash::URIWarning); REQUIRE(report.warnings.begin()->message == "URI path in 'A [GET {param}]' is not absolute, it should have a leading forward slash"); } TEST_CASE("Detect invalid reference to URI Template parameters in Action", "[action]") { mdp::ByteBuffer source = "## List [GET /orders{?abc}]\n\n" "+ Parameters\n" " + ab (string)\n" " + bc (string)\n" " + ac (string)\n\n" "+ Response 200"; ParseResult<Action> action; SectionParserHelper<Action, ActionParser>::parse(source, ActionSectionType, action, ExportSourcemapOption); REQUIRE(action.report.error.code == Error::OK); REQUIRE(action.report.warnings.size() == 3); REQUIRE(action.report.warnings[0].code == LogicalErrorWarning); REQUIRE(action.report.warnings[1].code == LogicalErrorWarning); REQUIRE(action.report.warnings[2].code == LogicalErrorWarning); REQUIRE(action.node.name == "List"); REQUIRE(action.node.uriTemplate == "/orders{?abc}"); SourceMapHelper::check(action.report.warnings[0].location, 0, 29); SourceMapHelper::check(action.report.warnings[1].location, 0, 29); SourceMapHelper::check(action.report.warnings[2].location, 0, 29); }
40.732064
118
0.671819
darkcl
289cdd8a187b2fe67322faacd80f5ad341dcfbe8
6,190
cpp
C++
src/buffers/AudioBufferSamples.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
null
null
null
src/buffers/AudioBufferSamples.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
1
2019-05-03T11:35:22.000Z
2019-05-03T23:22:58.000Z
src/buffers/AudioBufferSamples.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
null
null
null
/* * AudioBuffer.cpp * * Created on: 09-oct-2008 * Author: arturo castro */ #include "AudioBufferSamples.h" namespace ofxPm{ //----------------------------------------------------------------------------------------- AudioBufferSamples::AudioBufferSamples(AudioSource & source, float size, int sampleR, int bufferS,int numCh) { setup(source,size,sampleR,bufferS,numCh); } //----------------------------------------------------------------------------------------- AudioBufferSamples::AudioBufferSamples() { source = NULL; fps=0; stopped=false; } //----------------------------------------------------------------------------------------- AudioBufferSamples::~AudioBufferSamples() { } //----------------------------------------------------------------------------------------- void AudioBufferSamples::setup(AudioSource & source,float sizeInSecs,int sampleR, int bufferS, int numCh) { this->source=&source; fps=source.getFps(); aSampleRate=sampleR; aSoundStreamBufferSize=bufferS; aNumCh=numCh; // this is the max size related to seconds ... but ... keep reading : this->usedSizeSamples = sizeInSecs * aSampleRate; this->maxSize = this->usedSizeSamples/aSoundStreamBufferSize +1 ; // ? because aex. to fill 7s we need 656,25 AudioFrames ... we need 657 AF to be declared. this->maxSizeSamples = this->maxSize * aSoundStreamBufferSize; this->unusedSamples = maxSizeSamples - usedSizeSamples; resume(); stopped = false; } //---------------------------------------------------------------------------------------- unsigned int AudioBufferSamples::size(){ return frames.size(); } //---------------------------------------------------------------------------------------- unsigned int AudioBufferSamples::getMaxSize(){ return maxSize; } //---------------------------------------------------------------------------------------- unsigned int AudioBufferSamples::sizeInSamples() { //return this->samples.size(); return (frames.size())*(aSoundStreamBufferSize); } //---------------------------------------------------------------------------------------- unsigned int AudioBufferSamples::getMaxSizeInSamples() { return maxSizeSamples; } //---------------------------------------------------------------------------------------- unsigned int AudioBufferSamples::getUsedSizeInSamples() { return usedSizeSamples; } //---------------------------------------------------------------------------------------- void AudioBufferSamples::newAudioFrame(AudioFrame &frame) { if(size()==0)initTime=frame.getTimestamp(); // AudioFrames managing, store AudioFrame on the cue. frames.push_back(frame); if(size()>maxSize) { frames.erase(frames.begin()); } // what for ?? newFrameEvent.notify(this,frame); } //---------------------------------------------------------------------------------------- AudioSample AudioBufferSamples::getAudioSample(int index) { int samplesPerFrame = aSoundStreamBufferSize; int whichAudioFrame = index / samplesPerFrame; int whichSampleInAudioFrame = index % samplesPerFrame; //printf("ABS :: num Chan :: %d || index :: %d || samplesPerFrame %d || whichAudioFrame %d || whichSample %d \n",aNumCh,index,samplesPerFrame,whichAudioFrame,whichSampleInAudioFrame); /*float* sampleData = new float[aNumCh]; for(int i=0;i<aNumCh;i++) { sampleData[i] = frames[whichAudioFrame]->getAudioData()[whichSampleInAudioFrame*aNumCh+i]; } AudioSample * aS = new AudioSample(sampleData,aNumCh); delete[] sampleData;*/ return AudioSample(&frames[whichAudioFrame].getAudioData()[whichSampleInAudioFrame*aNumCh],aNumCh); } //---------------------------------------------------------------------------------------- float AudioBufferSamples::getFps() { return this->fps; } //---------------------------------------------------------------------------------------- float AudioBufferSamples::getRealFPS() { return 0.0; } //---------------------------------------------------------------------------------------- void AudioBufferSamples::draw() { float length=float(size())/((float)maxSize)*(float)(ofGetWidth()-PMDRAWSPACING*2); float oneLength=(float)(ofGetWidth()-PMDRAWSPACING*2)/(float)(maxSize); float oneFrame =((float)ofGetWidth()-float(2*PMDRAWSPACING))/(float)maxSize; if(stopped==true) ofSetColor(255,0,0); else ofSetColor(0,120,255); ofLine(PMDRAWSPACING,650,length,650); for(int i=0;i<size();i++){ ofSetColor(0,120,255); // draw wave if(i%2==0) ofRect((oneLength*i)+PMDRAWSPACING,650-frames[i].getAverageValue()*150,oneLength*2,(frames[i].getAverageValue()*450+1)); // draw grid float X = fmod(i,source->getFps()); if(X<1.0) { ofSetColor(0,255,255); ofLine((oneLength*i)+PMDRAWSPACING,650,(oneLength*i)+PMDRAWSPACING,640); ofDrawBitmapString(ofToString(float(size()-i)/source->getFps()),(oneLength*i)+PMDRAWSPACING,635); // + " s" } } } //--------------------------------------------------------------------------------------- void AudioBufferSamples::stop() { stopped=true; ofRemoveListener(source->newFrameEvent,this,&AudioBufferSamples::newAudioFrame); } //--------------------------------------------------------------------------------------- void AudioBufferSamples::resume() { stopped=false; ofAddListener(source->newFrameEvent,this,&AudioBufferSamples::newAudioFrame); } //-------------------------------------------------------------------------------------- int AudioBufferSamples::getSoundStreamBufferSize() { return aSoundStreamBufferSize; } //-------------------------------------------------------------------------------------- int AudioBufferSamples::getSampleRate() { return aSampleRate; } //-------------------------------------------------------------------------------------- int AudioBufferSamples::getNumChannels() { return aNumCh; } //-------------------------------------------------------------------------------------- int AudioBufferSamples::getUnusedSamples() { return unusedSamples; } bool AudioBufferSamples::getIsStopped() { return stopped; } }
33.641304
185
0.501777
PlaymodesStudio
289ee21335e0a37b119be2588ad92c6cff352a14
352
hpp
C++
Pong/GameObjects/PlayerRacket.hpp
emersonmx/pong-sfml
497e0dd390f5b3cc321b856b8260eb0df3f016ee
[ "MIT" ]
null
null
null
Pong/GameObjects/PlayerRacket.hpp
emersonmx/pong-sfml
497e0dd390f5b3cc321b856b8260eb0df3f016ee
[ "MIT" ]
null
null
null
Pong/GameObjects/PlayerRacket.hpp
emersonmx/pong-sfml
497e0dd390f5b3cc321b856b8260eb0df3f016ee
[ "MIT" ]
null
null
null
#ifndef PONG_GAMEOBJECTS_PLAYERRACKET_HPP_ #define PONG_GAMEOBJECTS_PLAYERRACKET_HPP_ #include "Pong/GameObjects/Racket.hpp" namespace pong { class PlayerRacket : public Racket { public: using Racket::Racket; protected: void handleInput() override; }; } /* namespace pong */ #endif /* PONG_GAMEOBJECTS_PLAYERRACKET_HPP_ */
19.555556
47
0.738636
emersonmx
80bd6bd04b8ca2715e8216fae10118ba6afc0a11
1,901
cpp
C++
lib/ssl/src/Init.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
lib/ssl/src/Init.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
lib/ssl/src/Init.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
#include "astateful/ssl/Init.hpp" #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/conf.h> #include <openssl/engine.h> #include "Windows.h" namespace astateful { namespace ssl { struct Init::pimpl { pimpl() : num_mutex( CRYPTO_num_locks() ) { handle_mutex = static_cast<HANDLE *>( CRYPTO_malloc( num_mutex * sizeof( HANDLE ), __FILE__, __LINE__ )); for ( int i = 0; i < num_mutex; i++ ) { handle_mutex[i] = CreateMutex( nullptr, FALSE, nullptr ); } CRYPTO_set_locking_callback( &mutexCallback ); CRYPTO_set_id_callback( &idCallback ); } static void holdMutex( int mutex ) { WaitForSingleObject( handle_mutex[mutex], INFINITE ); } static void releaseMutex( int mutex ) { ::ReleaseMutex( handle_mutex[mutex] ); } static void __cdecl mutexCallback( int mode, int mutex, const char * data, int line ) { ( mode & CRYPTO_LOCK ) ? holdMutex( mutex ) : releaseMutex( mutex ); } static unsigned long __cdecl idCallback() { return static_cast<unsigned long>( GetCurrentThreadId() ); } ~pimpl() { for ( int i = 0; i < num_mutex; i++ ) CloseHandle( handle_mutex[i] ); CRYPTO_set_locking_callback( nullptr ); CRYPTO_set_id_callback( nullptr ); CRYPTO_free( handle_mutex, nullptr, 0 ); } private: const int num_mutex; static HANDLE * handle_mutex; }; HANDLE * Init::pimpl::handle_mutex = nullptr; Init::Init() : m_pimpl( std::make_unique<pimpl>() ) { SSL_library_init(); SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); } Init::~Init() { ERR_remove_state(0); ENGINE_cleanup(); CONF_modules_unload(1); ERR_free_strings(); EVP_cleanup(); sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); CRYPTO_cleanup_all_ex_data(); } } }
25.689189
91
0.647028
astateful
80c3095b456838a25274041a1557e382121155fd
3,908
cc
C++
src/Observer.cc
homer6/jetstream
e38818de9d24598ac3b3ad7fc5529142db793aad
[ "MIT" ]
null
null
null
src/Observer.cc
homer6/jetstream
e38818de9d24598ac3b3ad7fc5529142db793aad
[ "MIT" ]
null
null
null
src/Observer.cc
homer6/jetstream
e38818de9d24598ac3b3ad7fc5529142db793aad
[ "MIT" ]
null
null
null
#include "Observer.h" #include "Common.h" #include <iostream> using std::cout; using std::cerr; using std::endl; namespace jetstream{ Observer::Observer(){ } Observer::~Observer(){ } void Observer::addMetricEntry( const string& metric_entry ){ size_t entry_length = metric_entry.size(); if( entry_length == 0 ){ return; } string json_meta = "{\"generated_at\":" + get_timestamp(); //unstructured single-line entry if( metric_entry[0] != '{' ){ cout << json_meta + ",\"metric\":\"" + escape_to_json_string(metric_entry) + "\"}" << endl; } //embedded single-line JSON if( metric_entry[0] == '{' ){ //this embedded single-line JSON MUST begin and end with a brace cout << json_meta + ",\"metric\":" + metric_entry + "}" << endl; } } void Observer::addEventEntry( const string& event_entry ){ size_t entry_length = event_entry.size(); if( entry_length == 0 ){ return; } string json_meta = "{\"generated_at\":" + get_timestamp(); //unstructured single-line entry if( event_entry[0] != '{' ){ cout << json_meta + ",\"event\":\"" + escape_to_json_string(event_entry) + "\"}" << endl; } //embedded single-line JSON if( event_entry[0] == '{' ){ //this embedded single-line JSON MUST begin and end with a brace cout << json_meta + ",\"event\":" + event_entry + "}" << endl; } } void Observer::addTraceEntry( const string& trace_entry ){ size_t entry_length = trace_entry.size(); if( entry_length == 0 ){ return; } string json_meta = "{\"generated_at\":" + get_timestamp(); //unstructured single-line entry if( trace_entry[0] != '{' ){ cout << json_meta + ",\"trace\":\"" + escape_to_json_string(trace_entry) + "\"}" << endl; } //embedded single-line JSON if( trace_entry[0] == '{' ){ //this embedded single-line JSON MUST begin and end with a brace cout << json_meta + ",\"trace\":" + trace_entry + "}" << endl; } } void Observer::addTelemetryEntry( const string& telemetry_entry ){ size_t entry_length = telemetry_entry.size(); if( entry_length == 0 ){ return; } string json_meta = "{\"generated_at\":" + get_timestamp(); //unstructured single-line entry if( telemetry_entry[0] != '{' ){ cout << json_meta + ",\"telemetry\":\"" + escape_to_json_string(telemetry_entry) + "\"}" << endl; } //embedded single-line JSON if( telemetry_entry[0] == '{' ){ //this embedded single-line JSON MUST begin and end with a brace cout << json_meta + ",\"telemetry\":" + telemetry_entry + "}" << endl; } } void Observer::addLogEntry( const string& log_line ){ size_t entry_length = log_line.size(); if( entry_length == 0 ){ return; } string json_meta = "{\"generated_at\":" + get_timestamp(); //unstructured single-line entry if( log_line[0] != '{' ){ cout << json_meta + ",\"log\":\"" + escape_to_json_string(log_line) + "\"}" << endl; } //embedded single-line JSON if( log_line[0] == '{' ){ //this embedded single-line JSON MUST begin and end with a brace cout << json_meta + ",\"log\":" + log_line + "}" << endl; } } }
25.710526
114
0.494371
homer6
80c5263c024777b939b5f6d1b211f72eb2268b1e
13,997
cpp
C++
opensubdiv/far/stencilBuilder.cpp
dazcjones/OpenSubdiv
dcdfc47f24e091591c59df1b0e90736973cd6da1
[ "Apache-2.0" ]
2
2016-11-04T09:55:36.000Z
2021-05-02T11:20:34.000Z
opensubdiv/far/stencilBuilder.cpp
dazcjones/OpenSubdiv
dcdfc47f24e091591c59df1b0e90736973cd6da1
[ "Apache-2.0" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
opensubdiv/far/stencilBuilder.cpp
dazcjones/OpenSubdiv
dcdfc47f24e091591c59df1b0e90736973cd6da1
[ "Apache-2.0" ]
null
null
null
// // Copyright 2015 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../far/stencilBuilder.h" #include "../far/topologyRefiner.h" namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { namespace internal { struct PointDerivWeight { float p; float du; float dv; PointDerivWeight() : p(0.0f), du(0.0f), dv(0.0f) { } PointDerivWeight(float w) : p(w), du(w), dv(w) { } PointDerivWeight(float w, float wDu, float wDv) : p(w), du(wDu), dv(wDv) { } friend PointDerivWeight operator*(PointDerivWeight lhs, PointDerivWeight const& rhs) { lhs.p *= rhs.p; lhs.du *= rhs.du; lhs.dv *= rhs.dv; return lhs; } PointDerivWeight& operator+=(PointDerivWeight const& rhs) { p += rhs.p; du += rhs.du; dv += rhs.dv; return *this; } }; /// Stencil table constructor set. /// class WeightTable { public: WeightTable(int coarseVerts, bool genCtrlVertStencils, bool compactWeights) : _size(0) , _lastOffset(0) , _coarseVertCount(coarseVerts) , _compactWeights(compactWeights) { // These numbers were chosen by profiling production assets at uniform // level 3. size_t n = std::max(coarseVerts, std::min(int(5*1024*1024), coarseVerts*2)); _dests.reserve(n); _sources.reserve(n); _weights.reserve(n); if (!genCtrlVertStencils) return; // Generate trivial control vert stencils _sources.resize(coarseVerts); _weights.resize(coarseVerts); _dests.resize(coarseVerts); _indices.resize(coarseVerts); _sizes.resize(coarseVerts); for (int i = 0; i < coarseVerts; i++) { _indices[i] = i; _sizes[i] = 1; _dests[i] = i; _sources[i] = i; _weights[i] = 1.0; } _size = static_cast<int>(_sources.size()); _lastOffset = _size - 1; } template <class W, class WACCUM> void AddWithWeight(int src, int dest, W weight, WACCUM weights) { // Factorized stencils are expressed purely in terms of the control // mesh verts. Without this flattening, level_i's weights would point // to level_i-1, which would point to level_i-2, until the final level // points to the control verts. // // So here, we check if the incoming vert (src) is in the control mesh, // if it is, we can simply merge it without attempting to resolve it // first. if (src < _coarseVertCount) { merge(src, dest, weight, W(1.0), _lastOffset, _size, weights); return; } // src is not in the control mesh, so resolve all contributing coarse // verts (src itself is made up of many control vert weights). // // Find the src stencil and number of contributing CVs. int len = _sizes[src]; int start = _indices[src]; for (int i = start; i < start+len; i++) { // Invariant: by processing each level in order and each vertex in // dependent order, any src stencil vertex reference is guaranteed // to consist only of coarse verts: therefore resolving src verts // must yield verts in the coarse mesh. assert(_sources[i] < _coarseVertCount); // Merge each of src's contributing verts into this stencil. merge(_sources[i], dest, weights.Get(i), weight, _lastOffset, _size, weights); } } class PointDerivAccumulator { WeightTable* _tbl; public: PointDerivAccumulator(WeightTable* tbl) : _tbl(tbl) { } void PushBack(PointDerivWeight weight) { _tbl->_weights.push_back(weight.p); _tbl->_duWeights.push_back(weight.du); _tbl->_dvWeights.push_back(weight.dv); } void Add(size_t i, PointDerivWeight weight) { _tbl->_weights[i] += weight.p; _tbl->_duWeights[i] += weight.du; _tbl->_dvWeights[i] += weight.dv; } PointDerivWeight Get(size_t index) { return PointDerivWeight(_tbl->_weights[index], _tbl->_duWeights[index], _tbl->_dvWeights[index]); } }; PointDerivAccumulator GetPointDerivAccumulator() { return PointDerivAccumulator(this); }; class ScalarAccumulator { WeightTable* _tbl; public: ScalarAccumulator(WeightTable* tbl) : _tbl(tbl) { } void PushBack(PointDerivWeight weight) { _tbl->_weights.push_back(weight.p); } void Add(size_t i, float w) { _tbl->_weights[i] += w; } float Get(size_t index) { return _tbl->_weights[index]; } }; ScalarAccumulator GetScalarAccumulator() { return ScalarAccumulator(this); }; std::vector<int> const& GetOffsets() const { return _indices; } std::vector<int> const& GetSizes() const { return _sizes; } std::vector<int> const& GetSources() const { return _sources; } std::vector<float> const& GetWeights() const { return _weights; } std::vector<float> const& GetDuWeights() const { return _duWeights; } std::vector<float> const& GetDvWeights() const { return _dvWeights; } private: // Merge a vertex weight into the stencil table, if there is an existing // weight for a given source vertex it will be combined. // // PERFORMANCE: caution, this function is super hot. template <class W, class WACCUM> void merge(int src, int dst, W weight, // Delaying weight*factor multiplication hides memory latency of // accessing weight[i], yielding more stable performance. W weightFactor, // Similarly, passing offset & tableSize as params yields higher // performance than accessing the class members directly. int lastOffset, int tableSize, WACCUM weights) { // The lastOffset is the vertex we're currently processing, by // leveraging this we need not lookup the dest stencil size or offset. // // Additionally, if the client does not want the resulting verts // compacted, do not attempt to combine weights. if (_compactWeights and !_dests.empty() and _dests[lastOffset] == dst) { // tableSize is exactly _sources.size(), but using tableSize is // significantly faster. for (int i = lastOffset; i < tableSize; i++) { // If we find an existing vertex that matches src, we need to // combine the weights to avoid duplicate entries for src. if (_sources[i] == src) { weights.Add(i, weight*weightFactor); return; } } } // We haven't seen src yet, insert it as a new vertex weight. add(src, dst, weight*weightFactor, weights); } // Add a new vertex weight to the stencil table. template <class W, class WACCUM> void add(int src, int dst, W weight, WACCUM weights) { // The _dests array has num(weights) elements mapping each individual // element back to a specific stencil. The array is constructed in such // a way that the current stencil being built is always at the end of // the array, so if the dests array is empty or back() doesn't match // dst, then we just started building a new stencil. if (_dests.empty() or dst != _dests.back()) { // _indices and _sizes always have num(stencils) elements so that // stencils can be directly looked up by their index in these // arrays. So here, ensure that they are large enough to hold the // new stencil about to be built. if (dst+1 > (int)_indices.size()) { _indices.resize(dst+1); _sizes.resize(dst+1); } // Initialize the new stencil's meta-data (offset, size). _indices[dst] = static_cast<int>(_sources.size()); _sizes[dst] = 0; // Keep track of where the current stencil begins, which lets us // avoid having to look it up later. _lastOffset = static_cast<int>(_sources.size()); } // Cache the number of elements as an optimization, it's faster than // calling size() on any of the vectors. _size++; // Increment the current stencil element size. _sizes[dst]++; // Track this element as belonging to the stencil "dst". _dests.push_back(dst); // Store the actual stencil data. _sources.push_back(src); weights.PushBack(weight); } // The following vectors are explicitly stored as non-interleaved elements // to reduce cache misses. // Stencil to destination vertex map. std::vector<int> _dests; // The actual stencil data. std::vector<int> _sources; std::vector<float> _weights; std::vector<float> _duWeights; std::vector<float> _dvWeights; // Index data used to recover stencil-to-vertex mapping. std::vector<int> _indices; std::vector<int> _sizes; // Acceleration members to avoid pointer chasing and reverse loops. int _size; int _lastOffset; int _coarseVertCount; bool _compactWeights; }; StencilBuilder::StencilBuilder(int coarseVertCount, bool genCtrlVertStencils, bool compactWeights) : _weightTable(new WeightTable(coarseVertCount, genCtrlVertStencils, compactWeights)) { } StencilBuilder::~StencilBuilder() { delete _weightTable; } size_t StencilBuilder::GetNumVerticesTotal() const { return _weightTable->GetWeights().size(); } int StencilBuilder::GetNumVertsInStencil(size_t stencilIndex) const { if (stencilIndex > _weightTable->GetSizes().size() - 1) return 0; return (int)_weightTable->GetSizes()[stencilIndex]; } std::vector<int> const& StencilBuilder::GetStencilOffsets() const { return _weightTable->GetOffsets(); } std::vector<int> const& StencilBuilder::GetStencilSizes() const { return _weightTable->GetSizes(); } std::vector<int> const& StencilBuilder::GetStencilSources() const { return _weightTable->GetSources(); } std::vector<float> const& StencilBuilder::GetStencilWeights() const { return _weightTable->GetWeights(); } std::vector<float> const& StencilBuilder::GetStencilDuWeights() const { return _weightTable->GetDuWeights(); } std::vector<float> const& StencilBuilder::GetStencilDvWeights() const { return _weightTable->GetDvWeights(); } void StencilBuilder::Index::AddWithWeight(Index const & src, float weight) { // Ignore no-op weights. if (weight == 0) return; _owner->_weightTable->AddWithWeight(src._index, _index, weight, _owner->_weightTable->GetScalarAccumulator()); } void StencilBuilder::Index::AddWithWeight(Stencil const& src, float weight) { if(weight == 0.0f) { return; } int srcSize = *src.GetSizePtr(); Vtr::Index const * srcIndices = src.GetVertexIndices(); float const * srcWeights = src.GetWeights(); for (int i = 0; i < srcSize; ++i) { float w = srcWeights[i]; if (w == 0.0f) { continue; } Vtr::Index srcIndex = srcIndices[i]; float wgt = weight * w; _owner->_weightTable->AddWithWeight(srcIndex, _index, wgt, _owner->_weightTable->GetScalarAccumulator()); } } void StencilBuilder::Index::AddWithWeight(Stencil const& src, float weight, float du, float dv) { if(weight == 0.0f and du == 0.0f and dv == 0.0f) { return; } int srcSize = *src.GetSizePtr(); Vtr::Index const * srcIndices = src.GetVertexIndices(); float const * srcWeights = src.GetWeights(); for (int i = 0; i < srcSize; ++i) { float w = srcWeights[i]; if (w == 0.0f) { continue; } Vtr::Index srcIndex = srcIndices[i]; PointDerivWeight wgt = PointDerivWeight(weight, du, dv) * w; _owner->_weightTable->AddWithWeight(srcIndex, _index, wgt, _owner->_weightTable->GetPointDerivAccumulator()); } } } // end namespace internal } // end namespace Far } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv
32.400463
80
0.602343
dazcjones
80c907b094d75c1d775f0291f8d081ec452bdb2e
157
hh
C++
utils/include/utils/misc.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
utils/include/utils/misc.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
utils/include/utils/misc.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#pragma once #define ROUND_UP(x, m) (((x) + (m)-1) & ~((m)-1)) #define ROUND_DOWN(x, m) ((x) & ~((m)-1)) #define IS_POWER_OF_TWO(x) (((x) & ((x)-1)) == 0)
22.428571
49
0.496815
balayette
80c9cf625553f0801ac7b14b697c2f2df8b2a96b
55,161
cpp
C++
src/gui/jb_scrollset.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
src/gui/jb_scrollset.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
8
2015-02-24T19:38:35.000Z
2016-05-25T02:33:48.000Z
src/gui/jb_scrollset.cpp
JadeMatrix/jadebase
c4575cc9f0b73c18ea82b671f6b347211507b71b
[ "Zlib" ]
null
null
null
/* * jb_scrollset.cpp * * About * */ /* INCLUDES *******************************************************************//******************************************************************************/ #include "jb_scrollset.hpp" #include "jb_named_resources.hpp" #include "jb_group.hpp" #include "jb_resource.hpp" #include "../utility/jb_exception.hpp" #include "../utility/jb_settings.hpp" #include "../windowsys/jb_window.hpp" #include "../utility/jb_log.hpp" /* INTERNAL GLOBALS ***********************************************************//******************************************************************************/ namespace { jade::mutex scroll_rsrc_mutex; bool got_resources = false; struct button_set { jade::gui_resource* up; jade::gui_resource* down; }; struct bar_set { button_set left_top; button_set fill; button_set right_bottom; }; struct corner_set { jade::gui_resource* up; jade::gui_resource* down; jade::gui_resource* evil; }; struct { button_set left_top; button_set right_bottom; bar_set bar; jade::gui_resource* fill; corner_set corner; } scroll_set; } /******************************************************************************//******************************************************************************/ #define SCROLLBAR_HEIGHT ( ( dpi::points )12 ) #define MIN_SCROLLBAR_LENGTH ( ( dpi::points )12 ) #define SCROLLBAR_BUTTON_REAL_WIDTH ( ( dpi::points )18 ) // Width of the button bounds #define SCROLLBAR_BUTTON_VISUAL_WIDTH ( ( dpi::points )25 ) // Width of the button sprite #define SLIDER_END_WIDTH ( ( dpi::points )6 ) // #define DEPRESSABLE_SLIDER_BARS namespace jade { scrollset::scrollset( dpi::points x, dpi::points y, dpi::points w, dpi::points h, const std::shared_ptr< scrollable >& c ) : gui_element( x, y, w, h ), contents( c ) { contents -> setParentElement( this ); contents -> setRealDimensions( dimensions[ 0 ], dimensions[ 1 ] ); init(); // Yes, this calls arrangeBars() on purpose arrangeBars(); } scrollset::scrollset( dpi::points x, dpi::points y, const std::shared_ptr< scrollable >& c ) : gui_element( x, y, 0, 0 ), contents( c ) { std::pair< dpi::points, dpi::points > c_dims( contents -> getRealDimensions() ); setRealDimensions( c_dims.first, c_dims.second ); contents -> setParentElement( this ); init(); arrangeBars(); } scrollset::~scrollset() { // Empty } void scrollset::setRealPosition( dpi::points x, dpi::points y ) { scoped_lock< mutex > slock( element_mutex ); position[ 0 ] = x; position[ 1 ] = y; if( parent != NULL ) parent -> requestRedraw(); } void scrollset::setRealDimensions( dpi::points w, dpi::points h ) { scoped_lock< mutex > slock( element_mutex ); dimensions[ 0 ] = w; dimensions[ 1 ] = h; ff::write( jb_out, ">>> Setting scrollset dimensions to ", w, " x ", h, "\n" ); contents -> setRealDimensions( dimensions[ 0 ] - SCROLLBAR_HEIGHT, dimensions[ 1 ] - SCROLLBAR_HEIGHT ); arrangeBars(); // May call parent -> requestRedraw() } void scrollset::setBarsAlwaysVisible( bool v ) { scoped_lock< mutex > slock( element_mutex ); bars_always_visible = v; arrangeBars(); // May call parent -> requestRedraw() } bool scrollset::getBarsAlwaysVisible() { scoped_lock< mutex > slock( element_mutex ); return bars_always_visible; } bool scrollset::acceptEvent( window_event& e ) { scoped_lock< mutex > slock( element_mutex ); // Set up area flags /////////////////////////////////////////////////// enum area { IN_CONTENTS = 0x800, // 0000 1000 0000 0000 IN_CONTROL_AREA = 0x7FF, // 0000 0111 1111 1111 - meta IN_CORNER_AREA = 0x400, // 0000 0100 0000 0000 IN_BOTTOM_AREA = 0x01F, // 0000 0000 0001 1111 - meta IN_BOTTOM_LEFT_BUTTON = 0x010, // 0000 0000 0001 0000 IN_BOTTOM_LEFT_SPACE = 0x008, // 0000 0000 0000 1000 IN_BOTTOM_BAR = 0x004, // 0000 0000 0000 0100 IN_BOTTOM_RIGHT_SPACE = 0x002, // 0000 0000 0000 0010 IN_BOTTOM_RIGHT_BUTTON = 0x001, // 0000 0000 0000 0001 IN_SIDE_AREA = 0x3E0, // 0000 0011 1110 0000 - meta IN_SIDE_TOP_BUTTON = 0x200, // 0000 0010 0000 0000 IN_SIDE_TOP_SPACE = 0x100, // 0000 0001 0000 0000 IN_SIDE_BAR = 0x080, // 0000 0000 1000 0000 IN_SIDE_BOTTOM_SPACE = 0x040, // 0000 0000 0100 0000 IN_SIDE_BOTTOM_BUTTON = 0x020, // 0000 0000 0010 0000 IN_ANYWHERE = 0xFFF, // 0000 1111 1111 1111 - meta IN_NOWHERE = 0x000 // 0000 0000 0000 0000 - init }; area place = IN_NOWHERE; area prev_place = IN_NOWHERE; bool bar_visible[ 2 ] = { slider_state[ 0 ] != DISABLED || bars_always_visible, slider_state[ 1 ] != DISABLED || bars_always_visible }; switch( e.type ) { case STROKE: if( !pointInsideRect( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], 0, 0, dimensions[ 0 ], dimensions[ 1 ] ) ) // Break early if not in scrollset bounds { goto rest; // Can't break quite yet } if( !bar_visible[ 1 ] || e.stroke.prev_pos[ 0 ] < dimensions[ 0 ] - SCROLLBAR_HEIGHT )// Left of the vertical scrollbar { if( !bar_visible[ 0 ] || e.stroke.prev_pos[ 1 ] < dimensions[ 1 ] - SCROLLBAR_HEIGHT ) // Outside of both bars so inside contents { prev_place = IN_CONTENTS; } else { // If we get here, horizontal bar is enabled if( pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], slider_pos[ 0 ] + SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) || pointInsideRect( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], slider_pos[ 0 ] + SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT, // This could also be 0 as we already checked not above slider_width[ 0 ] - SCROLLBAR_HEIGHT, SCROLLBAR_HEIGHT ) || pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], slider_pos[ 0 ] + slider_width[ 0 ] - SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside scroll bar handle { prev_place = IN_BOTTOM_BAR; } else if( e.stroke.prev_pos[ 0 ] < slider_pos[ 0 ] + slider_width[ 0 ] / 2 ) // Left hand side of bottom area { if( e.stroke.prev_pos[ 0 ] < SCROLLBAR_BUTTON_VISUAL_WIDTH && !pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], SCROLLBAR_BUTTON_VISUAL_WIDTH, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside bottom left button { prev_place = IN_BOTTOM_LEFT_BUTTON; } else prev_place = IN_BOTTOM_LEFT_SPACE; } else // Right hand side of bottom area { dpi::points vert_offset = bar_visible[ 1 ] ? SCROLLBAR_HEIGHT : 0; if( e.stroke.prev_pos[ 0 ] >= dimensions[ 0 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + vert_offset ) && !pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + vert_offset ), dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside bottom right button { prev_place = IN_BOTTOM_RIGHT_BUTTON; } else prev_place = IN_BOTTOM_RIGHT_SPACE; } } } else // (Potentially) in the vertical scrollbar { if( !bar_visible[ 0 ] || e.stroke.prev_pos[ 1 ] < dimensions[ 1 ] - SCROLLBAR_HEIGHT ) { if( pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, slider_pos[ 1 ] + SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) || pointInsideRect( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT, // This could also be 0 as we already checked not left slider_pos[ 1 ] + SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT, slider_width[ 1 ] - SCROLLBAR_HEIGHT ) || pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, slider_pos[ 1 ] + slider_width[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside scroll bar handle { prev_place = IN_SIDE_BAR; } else if( e.stroke.prev_pos[ 1 ] < slider_pos[ 1 ] + slider_width[ 1 ] / 2 ) // Top of side area { if( e.stroke.prev_pos[ 1 ] < SCROLLBAR_BUTTON_VISUAL_WIDTH && !pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_BUTTON_VISUAL_WIDTH, SCROLLBAR_HEIGHT / 2 ) ) // Inside side top button { prev_place = IN_SIDE_TOP_BUTTON; } else prev_place = IN_SIDE_TOP_SPACE; } else // Bottom of side area { dpi::points horz_offset = bar_visible[ 0 ] ? SCROLLBAR_HEIGHT : 0; if( e.stroke.prev_pos[ 1 ] >= dimensions[ 1 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + horz_offset ) && !pointInsideCircle( e.stroke.prev_pos[ 0 ], e.stroke.prev_pos[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + horz_offset ), SCROLLBAR_HEIGHT / 2 ) ) // Inside side bottom button { prev_place = IN_SIDE_BOTTOM_BUTTON; } else prev_place = IN_SIDE_BOTTOM_SPACE; } } else prev_place = IN_CORNER_AREA; } rest: case SCROLL: if( !pointInsideRect( e.position[ 0 ], e.position[ 1 ], 0, 0, dimensions[ 0 ], dimensions[ 1 ] ) ) // Break early if not in scrollset bounds { break; } if( !bar_visible[ 1 ] || e.position[ 0 ] < dimensions[ 0 ] - SCROLLBAR_HEIGHT ) // Left of the vertical scrollbar { if( !bar_visible[ 0 ] || e.position[ 1 ] < dimensions[ 1 ] - SCROLLBAR_HEIGHT ) // Outside of both bars so inside contents { place = IN_CONTENTS; } else { // If we get here, horizontal bar is enabled if( pointInsideCircle( e.position[ 0 ], e.position[ 1 ], slider_pos[ 0 ] + SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) || pointInsideRect( e.position[ 0 ], e.position[ 1 ], slider_pos[ 0 ] + SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT, // This could also be 0 as we already checked not above slider_width[ 0 ] - SCROLLBAR_HEIGHT, SCROLLBAR_HEIGHT ) || pointInsideCircle( e.position[ 0 ], e.position[ 1 ], slider_pos[ 0 ] + slider_width[ 0 ] - SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside scroll bar handle { place = IN_BOTTOM_BAR; } else if( e.position[ 0 ] < slider_pos[ 0 ] + slider_width[ 0 ] / 2 ) // Left hand side of bottom area { if( e.position[ 0 ] < SCROLLBAR_BUTTON_VISUAL_WIDTH && !pointInsideCircle( e.position[ 0 ], e.position[ 1 ], SCROLLBAR_BUTTON_VISUAL_WIDTH, dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside bottom left button { place = IN_BOTTOM_LEFT_BUTTON; } else place = IN_BOTTOM_LEFT_SPACE; } else // Right hand side of bottom area { dpi::points vert_offset = bar_visible[ 1 ] ? SCROLLBAR_HEIGHT : 0; if( e.position[ 0 ] >= dimensions[ 0 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + vert_offset ) && !pointInsideCircle( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + vert_offset ), dimensions[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside bottom right button { place = IN_BOTTOM_RIGHT_BUTTON; } else place = IN_BOTTOM_RIGHT_SPACE; } } } else // (Potentially) in the vertical scrollbar { if( !bar_visible[ 0 ] || e.position[ 1 ] < dimensions[ 1 ] - SCROLLBAR_HEIGHT ) { if( pointInsideCircle( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, slider_pos[ 1 ] + SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) || pointInsideRect( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT, // This could also be 0 as we already checked not left slider_pos[ 1 ] + SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT, slider_width[ 1 ] - SCROLLBAR_HEIGHT ) || pointInsideCircle( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, slider_pos[ 1 ] + slider_width[ 1 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_HEIGHT / 2 ) ) // Inside scroll bar handle { place = IN_SIDE_BAR; } else if( e.position[ 1 ] < slider_pos[ 1 ] + slider_width[ 1 ] / 2 ) // Top of side area { if( e.position[ 1 ] < SCROLLBAR_BUTTON_VISUAL_WIDTH && !pointInsideCircle( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, SCROLLBAR_BUTTON_VISUAL_WIDTH, SCROLLBAR_HEIGHT / 2 ) ) // Inside side top button { place = IN_SIDE_TOP_BUTTON; } else place = IN_SIDE_TOP_SPACE; } else // Bottom of side area { dpi::points horz_offset = bar_visible[ 0 ] ? SCROLLBAR_HEIGHT : 0; if( e.position[ 1 ] >= dimensions[ 1 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + horz_offset ) && !pointInsideCircle( e.position[ 0 ], e.position[ 1 ], dimensions[ 0 ] - SCROLLBAR_HEIGHT / 2, dimensions[ 1 ] - ( SCROLLBAR_BUTTON_VISUAL_WIDTH + horz_offset ), SCROLLBAR_HEIGHT / 2 ) ) // Inside side bottom button { place = IN_SIDE_BOTTOM_BUTTON; } else place = IN_SIDE_BOTTOM_SPACE; } } else place = IN_CORNER_AREA; } break; case DROP: case PINCH: case KEYCOMMAND: case COMMAND: case TEXT: break; default: throw exception( "scrollset::acceptEvent(): Unknown event type" ); break; } // Handle events based on area ///////////////////////////////////////// enum { NOTHING = 0, EVENT_USED = 1, SHOULD_ARRANGE = 2 } final = NOTHING; if( e.type == STROKE ) { if( capturing ) { if( e.stroke.dev_id == captured_dev ) { switch( capturing ) { case NONE: // Not possible break; case HORIZONTAL_BAR: if( !( e.stroke.click & CLICK_PRIMARY ) ) // Released { slider_state[ 0 ] = UP; capturing = NONE; final = NOTHING; } else { dpi::points slide_space = dimensions[ 0 ] - ( SCROLLBAR_BUTTON_REAL_WIDTH * 2 ) - slider_width[ 0 ]; if( bars_always_visible || slider_state[ 1 ] != DISABLED ) { slide_space -= SCROLLBAR_HEIGHT; } auto percent_limits = contents -> getScrollLimitPercent(); contents -> setScrollPercent( ( ( ( e.position[ 0 ] - capture_start[ 0 ] ) + ( capture_start[ 2 ] - SCROLLBAR_BUTTON_REAL_WIDTH ) ) / slide_space ) * percent_limits.first, contents -> getScrollPercent().second ); final = SHOULD_ARRANGE; } break; case VERTICAL_BAR: if( !( e.stroke.click & CLICK_PRIMARY ) ) // Released { slider_state[ 1 ] = UP; capturing = NONE; final = NOTHING; } else { dpi::points slide_space = dimensions[ 1 ] - ( SCROLLBAR_BUTTON_REAL_WIDTH * 2 ) - slider_width[ 1 ]; if( bars_always_visible || slider_state[ 0 ] != DISABLED ) { slide_space -= SCROLLBAR_HEIGHT; } auto percent_limits = contents -> getScrollLimitPercent(); contents -> setScrollPercent( contents -> getScrollPercent().first, ( ( e.position[ 1 ] - capture_start[ 1 ] + capture_start[ 2 ] - SCROLLBAR_BUTTON_REAL_WIDTH ) / slide_space ) * percent_limits.second ); final = SHOULD_ARRANGE; } break; case LEFT_BUTTON: if( !( place & IN_BOTTOM_LEFT_BUTTON ) && prev_place & IN_BOTTOM_LEFT_BUTTON ) { horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else if( place & IN_BOTTOM_LEFT_BUTTON && !( e.stroke.click & CLICK_PRIMARY ) ) { contents -> scrollPoints( getSetting_num( "jb_ScrollDistance" ) * -1, 0 ); horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else final = EVENT_USED; break; case RIGHT_BUTTON: if( !( place & IN_BOTTOM_RIGHT_BUTTON ) && prev_place & IN_BOTTOM_RIGHT_BUTTON ) { horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else if( place & IN_BOTTOM_RIGHT_BUTTON && !( e.stroke.click & CLICK_PRIMARY ) ) { contents -> scrollPoints( getSetting_num( "jb_ScrollDistance" ), 0 ); horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else final = EVENT_USED; break; case TOP_BUTTON: if( !( place & IN_SIDE_TOP_BUTTON ) && prev_place & IN_SIDE_TOP_BUTTON ) { horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else if( place & IN_SIDE_TOP_BUTTON && !( e.stroke.click & CLICK_PRIMARY ) ) { contents -> scrollPoints( 0, getSetting_num( "jb_ScrollDistance" ) * -1 ); horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else final = EVENT_USED; break; case BOTTOM_BUTTON: if( !( place & IN_SIDE_BOTTOM_BUTTON ) && prev_place & IN_SIDE_BOTTOM_BUTTON ) { horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else if( place & IN_SIDE_BOTTOM_BUTTON && !( e.stroke.click & CLICK_PRIMARY ) ) { contents -> scrollPoints( 0, getSetting_num( "jb_ScrollDistance" ) ); horz_state[ 0 ] = UP; capturing = NONE; final = SHOULD_ARRANGE; } else final = EVENT_USED; break; case CORNER: if( !( place & IN_CORNER_AREA ) && prev_place & IN_CORNER_AREA ) // Moved out of area { if( corner_state == DOWN ) corner_state = UP; else corner_state = EVIL; capturing = NONE; final = SHOULD_ARRANGE; } else if( place & IN_CORNER_AREA && !( e.stroke.click & CLICK_PRIMARY ) ) // Click release = trigger { if( corner_state == DOWN ) corner_state = EVIL; else corner_state = UP; capturing = NONE; final = SHOULD_ARRANGE; } else final = EVENT_USED; break; case SPACES: // if( ( !( place & IN_BOTTOM_LEFT_SPACE ) // && !( place & IN_BOTTOM_RIGHT_SPACE ) // && !( place & IN_SIDE_TOP_SPACE ) // && !( place & IN_SIDE_BOTTOM_SPACE ) ) // || !( e.stroke.click & CLICK_PRIMARY ) ) if( !( e.stroke.click & CLICK_PRIMARY ) ) { capturing = NONE; } break; default: throw exception( "scrollset::acceptEvent(): Unknown capturing state" ); } if( !capturing ) deassociateDevice( captured_dev ); } // else pass on to contents } if( !capturing ) // Explicitly check else condition, as above may alter capturing state { if( place & IN_CONTROL_AREA && e.stroke.click & CLICK_PRIMARY ) { switch( place ) { case IN_CORNER_AREA: if( corner_state == EVIL ) corner_state = EVIL_DOWN; else corner_state = DOWN; capturing = CORNER; break; case IN_BOTTOM_LEFT_BUTTON: horz_state[ 0 ] = DOWN; capturing = LEFT_BUTTON; break; case IN_BOTTOM_LEFT_SPACE: // TODO: Jump-page vs. jump-to-point setting contents -> scrollPercent( -1.0, 0.0 ); capturing = SPACES; final = SHOULD_ARRANGE; break; case IN_BOTTOM_BAR: slider_state[ 0 ] = DOWN; capturing = HORIZONTAL_BAR; capture_start[ 2 ] = slider_pos[ 0 ]; break; case IN_BOTTOM_RIGHT_SPACE: // TODO: Jump-page vs. jump-to-point setting contents -> scrollPercent( 1.0, 0.0 ); capturing = SPACES; final = SHOULD_ARRANGE; break; case IN_BOTTOM_RIGHT_BUTTON: horz_state[ 1 ] = DOWN; capturing = RIGHT_BUTTON; break; case IN_SIDE_TOP_BUTTON: vert_state[ 0 ] = DOWN; capturing = TOP_BUTTON; break; case IN_SIDE_TOP_SPACE: // TODO: Jump-page vs. jump-to-point setting contents -> scrollPercent( 0.0, -1.0 ); capturing = SPACES; final = SHOULD_ARRANGE; break; case IN_SIDE_BAR: slider_state[ 1 ] = DOWN; capturing = VERTICAL_BAR; capture_start[ 2 ] = slider_pos[ 1 ]; break; case IN_SIDE_BOTTOM_SPACE: // TODO: Jump-page vs. jump-to-point setting contents -> scrollPercent( 0.0, 1.0 ); capturing = SPACES; final = SHOULD_ARRANGE; break; case IN_SIDE_BOTTOM_BUTTON: vert_state[ 1 ] = DOWN; capturing = BOTTOM_BUTTON; break; default: // All other cases handled in above sanity check break; } if( capturing ) { captured_dev = e.stroke.dev_id; associateDevice( captured_dev ); capture_start[ 0 ] = e.position[ 0 ]; capture_start[ 1 ] = e.position[ 1 ]; final = SHOULD_ARRANGE; } else if( final != SHOULD_ARRANGE ) { final = EVENT_USED; } } // else we don't care, so pass on to contents } } // Pass event to contents ////////////////////////////////////////////// bool contents_accepted = false; if( final == NOTHING && place & IN_CONTENTS ) // Due to reasons, this and event_used can not both be true or false contents_accepted = contents -> acceptEvent( e ); // The contents have a 0,0 relative position to the scrollset // Check for scrolling around contents ///////////////////////////////// if( e.type == SCROLL && !contents_accepted ) { if( ( place & IN_CORNER_AREA ) || !( place & IN_ANYWHERE ) ) { return false; // No scrolling in corner } contents -> scrollPoints( e.scroll.amount[ 0 ], e.scroll.amount[ 1 ] ); arrangeBars(); // May call parent -> requestRedraw() return true; } if( final == SHOULD_ARRANGE ) arrangeBars(); return final > NONE || contents_accepted; } void scrollset::draw( window* w ) { scoped_lock< mutex > slock_e( element_mutex ); scoped_lock< mutex > slock_r( scroll_rsrc_mutex ); // Draw bars first (below) ///////////////////////////////////////////// glTranslatef( position[ 0 ], position[ 1 ], 0.0f ); { for( int i = 0; i < 2; ++i ) // Iterate through the 2 scrollbars for code reuse { glPushMatrix(); { if( i == 1 ) glRotatef( 180.0f, 1.0f, 1.0f, 0.0f ); // Flips around a vector pointing down left for the vertical bar // This means that the corners furthest from CORNER are always the draw origin if( slider_state[ i ] != DISABLED || bars_always_visible ) { glTranslatef( 0.0f, dimensions[ 1 - i ] - SCROLLBAR_HEIGHT, 0.0f ); glPushMatrix(); { glScalef( dimensions[ i ], 1.0f, 1.0f ); scroll_set.fill -> draw( w ); } glPopMatrix(); } if( slider_state[ i ] != DISABLED ) { glPushMatrix(); { for( int j = 0; j < 2; ++j ) { switch( ( i ? vert_state : horz_state )[ j ] ) // Nice little bit of pointer magic { case UP: if( j ) scroll_set.right_bottom.up -> draw( w ); else scroll_set.left_top.up -> draw( w ); break; case DOWN: if( j ) scroll_set.right_bottom.down -> draw( w ); else scroll_set.left_top.down -> draw( w ); break; default: throw exception( "scrollset::draw(): Invalid/unknown button state" ); break; } if( !j ) { if( bars_always_visible || slider_state[ 1 - i ] != DISABLED ) // If the other slider takes up its space { glTranslatef( dimensions[ i ] - SCROLLBAR_BUTTON_VISUAL_WIDTH - SCROLLBAR_HEIGHT, 0.0f, 0.0f ); } else glTranslatef( dimensions[ i ] - SCROLLBAR_BUTTON_VISUAL_WIDTH, 0.0f, 0.0f ); } } } glPopMatrix(); glTranslatef( slider_pos[ i ], 0.0f, 0.0f ); #ifdef DEPRESSABLE_SLIDER_BARS switch( slider_state[ i ] ) { case UP: scroll_set.bar.left_top.up -> draw( w ); break; case DOWN: scroll_set.bar.left_top.down -> draw( w ); break; default: throw exception( "scrollset::draw(): Invalid/unknown slider state" ); } #else scroll_set.bar.left_top.up -> draw( w ); // Always draw the bars "up" #endif glTranslatef( SLIDER_END_WIDTH, 0.0f, 0.0f ); glPushMatrix(); { glScalef( slider_width[ i ] - SLIDER_END_WIDTH * 2, 1.0f, 1.0f ); #ifdef DEPRESSABLE_SLIDER_BARS switch( slider_state[ i ] ) { case UP: scroll_set.bar.fill.up -> draw( w ); break; case DOWN: scroll_set.bar.fill.down -> draw( w ); break; default: throw exception( "scrollset::draw(): Invalid/unknown slider state" ); } #else scroll_set.bar.fill.up -> draw( w ); // Always draw the bars "up," for now #endif } glPopMatrix(); glTranslatef( slider_width[ i ] - SLIDER_END_WIDTH * 2, 0.0f, 0.0f ); #ifdef DEPRESSABLE_SLIDER_BARS switch( slider_state[ i ] ) { case UP: scroll_set.bar.right_bottom.up -> draw( w ); break; case DOWN: scroll_set.bar.right_bottom.down -> draw( w ); break; default: throw exception( "scrollset::draw(): Invalid/unknown slider state" ); } #else scroll_set.bar.right_bottom.up -> draw( w ); #endif } glColor4f( 1.0, 1.0, 1.0, 1.0 ); } glPopMatrix(); } } glTranslatef( position[ 0 ] * -1.0f, position[ 1 ] * -1.0f, 0.0f ); // Then draw corner //////////////////////////////////////////////////// if( bars_always_visible || ( slider_state[ 0 ] != DISABLED && slider_state[ 1 ] != DISABLED ) ) { glPushMatrix(); { glTranslatef( dimensions[ 0 ] - SCROLLBAR_HEIGHT, dimensions[ 1 ] - SCROLLBAR_HEIGHT, 0.0f ); switch( corner_state ) { case UP: scroll_set.corner.up -> draw( w ); break; case DOWN: case EVIL_DOWN: scroll_set.corner.down -> draw( w ); break; case EVIL: scroll_set.corner.evil -> draw( w ); break; default: throw exception( "scrollset::draw(): Invalid corner state" ); } } glPopMatrix(); } // Finally draw contents (on top); they mask themselves //////////////// contents -> draw( w ); // Contents keep track of their own position & dimensions } void scrollset::clearDeviceAssociations() // clearDeviceAssociations() is not required to be thread-safe { switch( capturing ) { case NONE: break; case HORIZONTAL_BAR: case VERTICAL_BAR: case LEFT_BUTTON: case RIGHT_BUTTON: case TOP_BUTTON: case BOTTOM_BUTTON: case CORNER: case SPACES: deassociateDevice( captured_dev ); break; default: throw exception( "scrollset::clearDeviceAssociations(): Unknown capturing state" ); } } void scrollset::arrangeBars() { scoped_lock< mutex > slock( element_mutex ); std::pair< dpi::points, dpi::points > scroll_limits = contents -> getScrollLimitPoints(); std::pair< dpi::points, dpi::points > scroll_offsets = contents -> getScrollPoints(); // Enable/disable slider bars, corner ////////////////////////////////// if( scroll_limits.first == 0 && !bars_always_visible ) // Horizontal { horz_state[ 0 ] = DISABLED; horz_state[ 1 ] = DISABLED; slider_state[ 0 ] = DISABLED; } else { horz_state[ 0 ] = UP; horz_state[ 1 ] = UP; slider_state[ 0 ] = UP; } if( scroll_limits.second == 0 && !bars_always_visible ) // Vertical { vert_state[ 0 ] = DISABLED; vert_state[ 1 ] = DISABLED; slider_state[ 1 ] = DISABLED; } else { vert_state[ 0 ] = UP; vert_state[ 1 ] = UP; slider_state[ 1 ] = UP; } if( bars_always_visible || slider_state[ 0 ] != DISABLED || slider_state[ 1 ] != DISABLED ) // Corner { if( corner_state == DISABLED ) corner_state = UP; // else leave in current state } else corner_state = DISABLED; // Set actual bar states /////////////////////////////////////////////// bool release_capture = false; switch( capturing ) { case NONE: break; // Nothing needs to be done case HORIZONTAL_BAR: if( slider_state[ 0 ] == DISABLED ) release_capture = true; else slider_state[ 0 ] = DOWN; break; case VERTICAL_BAR: if( slider_state[ 1 ] == DISABLED ) release_capture = true; else slider_state[ 1 ] = DOWN; break; case LEFT_BUTTON: if( horz_state[ 0 ] == DISABLED ) release_capture = true; else horz_state[ 0 ] = DOWN; break; case RIGHT_BUTTON: if( horz_state[ 1 ] == DISABLED ) release_capture = true; else horz_state[ 1 ] = DOWN; break; case TOP_BUTTON: if( vert_state[ 0 ] == DISABLED ) release_capture = true; else vert_state[ 0 ] = DOWN; break; case BOTTOM_BUTTON: if( vert_state[ 1 ] == DISABLED ) release_capture = true; else vert_state[ 1 ] = DOWN; break; case CORNER: if( corner_state == DISABLED ) release_capture = true; // No else, acceptEvent() takes care of non-DISABLED state break; case SPACES: break; // Next time we get an event while capturing==SPACES, it'll release if necessary default: throw exception( "scrollset::arrangeBars(): Unknown capturing state" ); } if( release_capture ) { deassociateDevice( captured_dev ); capturing = NONE; } // Resize contents ///////////////////////////////////////////////////// dpi::points internal_dims[ 2 ]; if( slider_state[ 1 ] != DISABLED // Check if vertical is disabled for horizontal size || bars_always_visible ) { internal_dims[ 0 ] = dimensions[ 0 ] - SCROLLBAR_HEIGHT; } else internal_dims[ 0 ] = dimensions[ 0 ]; if( slider_state[ 0 ] != DISABLED // Check if horizontal is disabled for vertical size || bars_always_visible ) { internal_dims[ 1 ] = dimensions[ 1 ] - SCROLLBAR_HEIGHT; } else internal_dims[ 1 ] = dimensions[ 1 ]; contents -> setRealDimensions( internal_dims[ 0 ], internal_dims[ 1 ] ); // Position slider bars //////////////////////////////////////////////// for( int i = 0; i < 2; ++i ) { if( bars_always_visible || slider_state[ i ] != DISABLED ) { dpi::points scroll_limit = i ? scroll_limits.second : scroll_limits.first; dpi::points scroll_offset = i ? scroll_offsets.second : scroll_offsets.first; scroll_limit *= ( scroll_limit < 0 ? -1 : 1 ); // For this we want it always positive dpi::points max_length = internal_dims[ i ] - ( SCROLLBAR_BUTTON_REAL_WIDTH * 2 ); slider_width[ i ] = max_length * internal_dims[ i ] / ( internal_dims[ i ] + scroll_limit ); slider_pos[ i ] = SCROLLBAR_BUTTON_REAL_WIDTH + ( max_length - slider_width[ i ] ) * ( scroll_offset / scroll_limit ); } } // Request redraw ////////////////////////////////////////////////////// if( parent != NULL ) parent -> requestRedraw(); } void scrollset::init() { if( !contents ) throw exception( "scrollset::init(): Contents empty shared_ptr" ); horz_state[ 0 ] = DISABLED; horz_state[ 1 ] = DISABLED; vert_state[ 0 ] = DISABLED; vert_state[ 1 ] = DISABLED; corner_state = UP; slider_state[ 0 ] = DISABLED; slider_state[ 1 ] = DISABLED; capturing = NONE; bars_always_visible = false; contents -> setRealPosition( position[ 0 ], position[ 1 ] ); arrangeBars(); scoped_lock< mutex > slock( scroll_rsrc_mutex ); if( !got_resources ) { scroll_set.left_top.up = getNamedResource( scrollbar_button_left_top_up ); scroll_set.left_top.down = getNamedResource( scrollbar_button_left_top_down ); scroll_set.right_bottom.up = getNamedResource( scrollbar_button_right_bottom_up ); scroll_set.right_bottom.down = getNamedResource( scrollbar_button_right_bottom_down ); scroll_set.bar.left_top.up = getNamedResource( scrollbar_bar_left_top_up ); scroll_set.bar.left_top.down = getNamedResource( scrollbar_bar_left_top_down ); scroll_set.bar.fill.up = getNamedResource( scrollbar_bar_center_up ); scroll_set.bar.fill.down = getNamedResource( scrollbar_bar_center_down ); scroll_set.bar.right_bottom.up = getNamedResource( scrollbar_bar_right_bottom_up ); scroll_set.bar.right_bottom.down = getNamedResource( scrollbar_bar_right_bottom_down ); scroll_set.fill = getNamedResource( scrollbar_fill ); scroll_set.corner.up = getNamedResource( scrollbar_corner_up ); scroll_set.corner.down = getNamedResource( scrollbar_corner_down ); scroll_set.corner.evil = getNamedResource( scrollbar_corner_evil ); got_resources = true; } } }
45.512376
160
0.358133
JadeMatrix
80cc755d1843c1ec1a9b1fdc9075682481b29719
577
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.19.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.19.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.19.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise5.19.cpp // Ad // Use a do while loop to repetitively request two string form user and report which is less. #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; int main() { std::string str1 = {}, str2 = {}; cin >> str1 >> str2; do { if (str1 == str2) { cout << "Equal." << endl; } else { cout << (str1 < str2 ? str1 : str2) << " is less." << endl; } } while (cin >> str1 >> str2); // pause system("pause"); return 0; }
19.233333
94
0.493934
alaxion
80ce28b9632f6cbb22de2470d4dc83819b37a658
172
hpp
C++
Color.hpp
C0ff33C0d3r/WindowSystemLib
161799d395228cf00b7ffe70c6a41dd1ba1ed900
[ "MIT" ]
null
null
null
Color.hpp
C0ff33C0d3r/WindowSystemLib
161799d395228cf00b7ffe70c6a41dd1ba1ed900
[ "MIT" ]
null
null
null
Color.hpp
C0ff33C0d3r/WindowSystemLib
161799d395228cf00b7ffe70c6a41dd1ba1ed900
[ "MIT" ]
1
2021-03-26T12:54:29.000Z
2021-03-26T12:54:29.000Z
#ifndef COLOR_HPP_ #define COLOR_HPP_ #include <cstdint> struct Color { uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; }; #endif // COLOR_HPP_
13.230769
21
0.680233
C0ff33C0d3r
80cf36d94737c33e51bf9178a34764f408867d06
5,801
cpp
C++
MathLib/MathLibUtilities.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
1
2016-02-17T17:03:37.000Z
2016-02-17T17:03:37.000Z
MathLib/MathLibUtilities.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
null
null
null
MathLib/MathLibUtilities.cpp
bryanlawsmith/Raytracing
519b3f3867e0c00b92091dd755a4a73121e22064
[ "MIT" ]
null
null
null
#include "MathLibUtilities.h" #include "MathLib_MatrixVectorOps.h" #include "MathLib_QuaternionMatrixOps.h" namespace MathLib { void GenerateTransformMatrix(matrix4x4& transform, const vector4& position, const vector4& rotation, const vector4& scale) { // Generate the translation transform. matrix4x4 translationMatrix ( 1.0f, 0.0f, 0.0f, position.x, 0.0f, 1.0f, 0.0f, position.y, 0.0f, 0.0f, 1.0f, position.z, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the rotation transform. vector4 xAxis(1.0f, 0.0f, 0.0f, 0.0f); vector4 yAxis(0.0f, 1.0f, 0.0f, 0.0f); vector4 zAxis(0.0f, 0.0f, 1.0f, 0.0f); // Perform rotation around the x axis. { float angleRads = MATHLIB_DEG_TO_RAD(rotation.x); float sinAngle = sinf(angleRads); float cosAngle = cosf(angleRads); // Caclulate modified y axis. vector4 perpendicularContribution; vector4_scale(zAxis, sinAngle, perpendicularContribution); vector4_scale(yAxis, cosAngle, yAxis); vector4_add(yAxis, perpendicularContribution, yAxis); // Calculate modified z axis. vector4_crossProduct(xAxis, yAxis, zAxis); } // Perform rotation around the y axis. matrix4x4 rotateAroundY; rotateAroundY.loadRotationY(rotation.y); matrix4x4_vectorMul(rotateAroundY, xAxis, xAxis); matrix4x4_vectorMul(rotateAroundY, yAxis, yAxis); matrix4x4_vectorMul(rotateAroundY, zAxis, zAxis); // Perform rotaiton around the z axis. { float angleRads = MATHLIB_DEG_TO_RAD(rotation.z); float sinAngle = sinf(angleRads); float cosAngle = cosf(angleRads); // Calculate modified y axis. vector4 perpendicularContribution; vector4_scale(xAxis, sinAngle, perpendicularContribution); vector4_scale(yAxis, cosAngle, yAxis); vector4_sub(yAxis, perpendicularContribution, yAxis); // Calculate modified x axis. vector4_crossProduct(yAxis, zAxis, xAxis); } matrix4x4 rotationMatrix ( xAxis.x, yAxis.x, zAxis.x, 0.0f, xAxis.y, yAxis.y, zAxis.y, 0.0f, xAxis.z, yAxis.z, zAxis.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the scale transform. matrix4x4 scaleMatrix ( scale.x, 0.0f, 0.0f, 0.0f, 0.0f, scale.y, 0.0f, 0.0f, 0.0f, 0.0f, scale.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the final transform. matrix4x4 scaledRotationMatrix; matrix4x4_mul(rotationMatrix, scaleMatrix, scaledRotationMatrix); matrix4x4_mul(translationMatrix, scaledRotationMatrix, transform); } void GenerateTransformMatrix(matrix4x4& transform, const vector4& position, const quaternion& orientation, const vector4& scale) { // Generation the translation transform. matrix4x4 translationTransform ( 1.0f, 0.0f, 0.0f, position.x, 0.0f, 1.0f, 0.0f, position.y, 0.0f, 0.0f, 1.0f, position.z, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the orientation transform. matrix4x4 orientationTransform; quaternion_toMatrix(orientation, orientationTransform); // Gemerate the scale transform. matrix4x4 scaleTransform ( scale.x, 0.0f, 0.0f, 0.0f, 0.0f, scale.y, 0.0f, 0.0f, 0.0f, 0.0f, scale.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the final transform. matrix4x4 scaledOrientationTransform; matrix4x4_mul(orientationTransform, scaleTransform, scaledOrientationTransform); matrix4x4_mul(translationTransform, scaledOrientationTransform, transform); } void GenerateInverseTransformMatrix(matrix4x4& transform, const vector4& position, const quaternion& orientation, const vector4& scale) { // Generate the inverse translation transform. matrix4x4 invTranslationTransform ( 1.0f, 0.0f, 0.0f, -position.x, 0.0f, 1.0f, 0.0f, -position.y, 0.0f, 0.0f, 1.0f, -position.z, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the inverse orientation transform. matrix4x4 invOrientationTransform; quaternion invOrientation; quaternion_inverse(orientation, invOrientation); quaternion_toMatrix(invOrientation, invOrientationTransform); // Generate the inverse scale transform. matrix4x4 invScaleTransform ( 1.0f / scale.x, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f / scale.y, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f / scale.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the final transform. matrix4x4 orientationTranslation; matrix4x4_mul(invOrientationTransform, invTranslationTransform, orientationTranslation); matrix4x4_mul(invScaleTransform, orientationTranslation, transform); } void GenerateInverseTransformMatrix(matrix4x4& transform, const vector4& position, const quaternion& orientation, float scale) { GenerateInverseTransformMatrix(transform, position, orientation, MathLib::vector4(scale, scale, scale, 1.0f)); } void GenerateTransformMatrix(matrix4x4& transform, const vector4& position, const quaternion& orientation, const float scale) { // Generation the translation transform. matrix4x4 translationTransform ( 1.0f, 0.0f, 0.0f, position.x, 0.0f, 1.0f, 0.0f, position.y, 0.0f, 0.0f, 1.0f, position.z, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the orientation transform. matrix4x4 orientationTransform; quaternion_toMatrix(orientation, orientationTransform); // Gemerate the scale transform. matrix4x4 scaleTransform ( scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // Generate the final transform. matrix4x4 scaledOrientationTransform; matrix4x4_mul(orientationTransform, scaleTransform, scaledOrientationTransform); matrix4x4_mul(translationTransform, scaledOrientationTransform, transform); } }
28.860697
89
0.689364
bryanlawsmith
80d3c792638be9c6a62079724a1cb9f695dbe3b4
5,260
cpp
C++
src/Dtw/Dtw.cpp
EDBE/MUSIC-8903-2016-assignment5-PPM
69e229d7510ba1e605ac48f214091c5287453ed3
[ "MIT" ]
null
null
null
src/Dtw/Dtw.cpp
EDBE/MUSIC-8903-2016-assignment5-PPM
69e229d7510ba1e605ac48f214091c5287453ed3
[ "MIT" ]
2
2016-02-18T02:36:53.000Z
2016-03-06T06:03:41.000Z
src/Dtw/Dtw.cpp
RitheshKumar/MUSI-8903-Assignment3
94ccd2c8277cf98f8f94bdf3dea62be1c31b6d69
[ "MIT" ]
null
null
null
#include "Vector.h" #include "Util.h" #include "Dtw.h" CDtw::CDtw( void ) : m_bIsInitialized(false), m_bWasProcessed(false), m_fOverallCost(0), m_ppePathIdx(0), m_iLengthOfPath(0) { CVector::setZero(m_apfCost, kNumVectors); CVector::setZero(m_aiMatrixDimensions, kNumMatrixDimensions); reset(); } CDtw::~CDtw( void ) { reset(); } Error_t CDtw::init( int iNumRows, int iNumCols ) { if (iNumRows <= 0 || iNumCols <= 0) return kFunctionInvalidArgsError; reset(); m_aiMatrixDimensions[kRow] = iNumRows; m_aiMatrixDimensions[kCol] = iNumCols; // allocate memory for (int i = 0; i < kNumVectors; i++) m_apfCost[i] = new float [m_aiMatrixDimensions[kCol]]; m_ppePathIdx = new Directions_t* [m_aiMatrixDimensions[kRow]]; for (int i = 0; i < m_aiMatrixDimensions[kRow]; i++) m_ppePathIdx[i] = new Directions_t [m_aiMatrixDimensions[kCol]]; // all done here m_bIsInitialized = true; return kNoError; } Error_t CDtw::reset() { m_bIsInitialized = false; m_bWasProcessed = false; if (m_ppePathIdx) { for (int i = 0; i < m_aiMatrixDimensions[kRow]; i++) { delete [] m_ppePathIdx[i]; m_ppePathIdx[i] = 0; } } delete [] m_ppePathIdx; m_ppePathIdx = 0; for (int i = 0; i < kNumVectors; i++) { delete [] m_apfCost[i]; m_apfCost[i] = 0; } m_aiMatrixDimensions[kRow] = 0; m_aiMatrixDimensions[kCol] = 0; m_fOverallCost = 0; m_iLengthOfPath = 0; return kNoError; } Error_t CDtw::process(float **ppfDistanceMatrix) { if (!m_bIsInitialized) return kNotInitializedError; if (!ppfDistanceMatrix) return kFunctionInvalidArgsError; float fFirstColCost = 0; //!< variable that will only contain the cost of the first column (for the current row to be processed) // initialize CVectorFloat::setZero(m_apfCost[kRowNext], m_aiMatrixDimensions[kCol]); m_apfCost[kRowCurr][0] = ppfDistanceMatrix[0][0]; fFirstColCost = ppfDistanceMatrix[0][0]; m_ppePathIdx[0][0] = kDiag; for (int j = 1; j < m_aiMatrixDimensions[kCol]; j++) { m_apfCost[kRowCurr][j] = m_apfCost[kRowCurr][j-1] + ppfDistanceMatrix[0][j]; m_ppePathIdx[0][j] = kHoriz; } for (int i = 1; i < m_aiMatrixDimensions[kRow]; i++) { m_ppePathIdx[i][0] = kVert; } // compute cost 'matrix' and store backtracking path for (int i = 1; i < m_aiMatrixDimensions[kRow]; i++) { float fColCost; //!< variable containing the cost of the index left of the current matrix index // init the variables we need for the current row (remember the cost in the first column, and then increment it) m_apfCost[kRowCurr][0] = fFirstColCost; fFirstColCost += ppfDistanceMatrix[i][0]; fColCost = fFirstColCost; for (int j = 1; j < m_aiMatrixDimensions[kCol]; j++) { m_ppePathIdx[i][j] = findMinimum(fColCost, m_apfCost[kRowCurr][j], m_apfCost[kRowCurr][j-1], fColCost); fColCost += ppfDistanceMatrix[i][j]; m_apfCost[kRowNext][j] = fColCost; } // swap the pointers of our two buffers as we proceed to the next row CUtil::swap(m_apfCost[kRowCurr], m_apfCost[kRowNext]); } // all done m_bWasProcessed = true; return kNoError; } int CDtw::getPathLength() { const int aiDecrement[kNumDirections][kNumMatrixDimensions] = { {0, -1}, // kHoriz {-1, 0}, // kVert {-1, -1} // kDiag }; int i = m_aiMatrixDimensions[kRow]-1; int j = m_aiMatrixDimensions[kCol]-1; if (!m_bWasProcessed) return 0; m_iLengthOfPath = 1; while (i > 0 || j > 0) { int iNewI = i + aiDecrement[m_ppePathIdx[i][j]][kRow]; j += aiDecrement[m_ppePathIdx[i][j]][kCol]; i = iNewI; m_iLengthOfPath++; } return m_iLengthOfPath; } float CDtw::getPathCost() const { return m_apfCost[kRowCurr][m_aiMatrixDimensions[kCol]-1]; } Error_t CDtw::getPath( int **ppiPathResult ) const { if (!ppiPathResult) return kFunctionInvalidArgsError; if (m_iLengthOfPath <= 0) return kFunctionIllegalCallError; int iIdx = m_iLengthOfPath - 1; const int aiDecrement[kNumDirections][kNumMatrixDimensions] = { {0, -1}, // kHoriz {-1, 0}, // kVert {-1, -1} // kDiag }; // init ppiPathResult[kRow][0] = 0; ppiPathResult[kCol][0] = 0; ppiPathResult[kRow][iIdx] = m_aiMatrixDimensions[kRow]-1; ppiPathResult[kCol][iIdx] = m_aiMatrixDimensions[kCol]-1; while (iIdx > 0) { ppiPathResult[kRow][iIdx-1] = ppiPathResult[kRow][iIdx] + aiDecrement[m_ppePathIdx[ppiPathResult[kRow][iIdx]][ppiPathResult[kCol][iIdx]]][kRow]; ppiPathResult[kCol][iIdx-1] = ppiPathResult[kCol][iIdx] + aiDecrement[m_ppePathIdx[ppiPathResult[kRow][iIdx]][ppiPathResult[kCol][iIdx]]][kCol]; iIdx--; } return kNoError; }
27.253886
152
0.598859
EDBE
80d3dc5d6c385885bb2f29a68f03cd442b275f9d
3,787
cpp
C++
Wolf/Sources/fuhrercube.cpp
cppdvl/wolf
cea686a9da92f93ad70d029f22acff7c0b1c69f9
[ "Unlicense", "MIT" ]
null
null
null
Wolf/Sources/fuhrercube.cpp
cppdvl/wolf
cea686a9da92f93ad70d029f22acff7c0b1c69f9
[ "Unlicense", "MIT" ]
null
null
null
Wolf/Sources/fuhrercube.cpp
cppdvl/wolf
cea686a9da92f93ad70d029f22acff7c0b1c69f9
[ "Unlicense", "MIT" ]
null
null
null
#include <map> #include <array> #include <cstdlib> #include <utility> #include <iomanip> #include <iostream> #include <algorithm> #include <nlohmann/json.hpp> #include <glad/glad.h> #include <wolf/utils/maputils.hpp> #include <wolf/utils/filesystemutils.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using json = nlohmann::json; //This should be replaced with a builder pattern void fuhrerCube( std::vector<unsigned int>&vaovector, std::vector<unsigned int>&vbovector, std::vector<unsigned int>&vertexcount, std::vector<std::map<std::string, glm::vec3>>& matdictionaryvector, std::vector<std::string>& texturenamevector){ auto fuhrerJson = json{}; auto fuhrerData = std::vector<float>{}; auto fuhrerCubeFile = Wolf::FileSystemUtils::open("Objects/wolf/fuhrercube.obj"); //if (!fuhrerCubeFile.Valid())exit(-1); //auto [fuhrerCubeJson, fuhrerCubeData] = Wolf::OBJParser(fuhrerCubeFile).Serialize(); //Wolf::_3DFormats::OBJFileParser objdata("Objects/wolf/fuhrercube.obj"); //objdata.Serialize(); //auto geometryData = objdata.DumpCodeVectorMap("Cube"); //auto geometryDataKeys = Wolf::MapUtils::keys(geometryData); //std::for_each(geometryDataKeys.begin(), geometryDataKeys.end(), /*[&](auto&p){ std::cout << std::endl << "Generating OpenGl vao's and vbo's for material: " << p << std::endl; auto dataVector = objdata.DumpCodeVector("Cube", p); auto dataVectorPtr = dataVector.data(); auto dataVectorSz = dataVector.size(); auto matInfo = objdata.DumpMaterialInformation("Objects/wolf/fuhrercube.mtl",p); auto materialDictionary = std::map<std::string, glm::vec3>{ std::make_pair("kd", matInfo.kd), std::make_pair("ka", matInfo.ka), std::make_pair("ke", matInfo.ke), std::make_pair("ks", matInfo.ks), std::make_pair("op_se_od", matInfo.op_se_od) }; std::cout << "Mat : " << p << " " << matInfo.kd.x << " " << matInfo.kd.y << " " << matInfo.kd.z << std::endl; matdictionaryvector.push_back(materialDictionary); std::cout << "Mat : " << p << " pushing texture " << matInfo.texturefile << std::endl; texturenamevector.push_back(matInfo.texturefile); std::cout << "Mat : " << p << " has " << (dataVectorSz >> 3) << " vertices" << std::endl; auto texturenamevectorsz = texturenamevector.size(); if (texturenamevector[texturenamevectorsz - 1].empty() == false) std::cout << "Mat : " << p << " has texture " << texturenamevector[texturenamevectorsz - 1] << std::endl; unsigned int vbo; unsigned int vao; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); //-- Grab Vao --/ glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); //-- VBO Header --/ glBufferData(GL_ARRAY_BUFFER, sizeof(float) * dataVector.size(), dataVectorPtr, GL_STATIC_DRAW); //-- Vertex --/ glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); //-- Texture Coordinat glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); //-- Normal --/ glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(5 * sizeof(float))); //-- Release Vao --/ glBindVertexArray(0); //Number of vertices auto nvertices = dataVector.size() / 8; vaovector.push_back(vao); vbovector.push_back(vbo); vertexcount.push_back(nvertices); } );*/ }
39.041237
179
0.62741
cppdvl
80d656e7a63e8e2df7247bd4c93bcfc37eba48f2
7,171
cpp
C++
packages/data_gen/xsdir/test/tstPhotonuclearXsdirEntry.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/data_gen/xsdir/test/tstPhotonuclearXsdirEntry.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/data_gen/xsdir/test/tstPhotonuclearXsdirEntry.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file tstPhotonuclearXsdirEntry.cpp //! \author Alex Robinson //! \brief Photonuclear xsdir entry unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // Trilinos Includes #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_VerboseObject.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_ParameterList.hpp> #include <Teuchos_XMLParameterListCoreHelpers.hpp> // FRENSIE Includes #include "DataGen_PhotonuclearXsdirEntry.hpp" #include "MonteCarlo_CrossSectionsXMLProperties.hpp" #include "Utility_UnitTestHarnessExtensions.hpp" //---------------------------------------------------------------------------// // Testing Variables //---------------------------------------------------------------------------// std::string line_a( " 1002.24u 1.996300 la150u 0 1 216233 3686 0 0 0.000E+00" ); std::string line_b( " 82208.24u 206.190000 xdata/la150u 0 1 196946 77099 0 0 0.000E+00 " ); std::string line_c( " 93237.70u 235.011800 xmc/endf7u 0 1 4868895 48076 " ); //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// // Check that the table alias can be returned TEUCHOS_UNIT_TEST( PhotonuclearXsdirEntry, getTableAlias ) { Teuchos::Array<std::string> entry_tokens; DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_a, entry_tokens ); Teuchos::RCP<DataGen::XsdirEntry> entry( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); TEST_EQUALITY_CONST( entry->getTableAlias(), "H-2_v2" ); DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_b, entry_tokens ); entry.reset( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); TEST_EQUALITY_CONST( entry->getTableAlias(), "Pb-208_v2" ); DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_c, entry_tokens ); entry.reset( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); TEST_EQUALITY_CONST( entry->getTableAlias(), "Np-237_v7" ); } //---------------------------------------------------------------------------// // Check that the xsdir entry can be added to a parameter list TEUCHOS_UNIT_TEST( PhotonuclearXsdirEntry, addInfoToParameterList ) { Teuchos::ParameterList parameter_list( "Cross Sections Directory" ); Teuchos::Array<std::string> entry_tokens; DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_a, entry_tokens ); Teuchos::RCP<DataGen::XsdirEntry> entry( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); Teuchos::ParameterList& sublist_a = parameter_list.sublist( entry->getTableAlias() ); entry->addInfoToParameterList( sublist_a ); TEST_EQUALITY_CONST( sublist_a.numParams(), 8 ); TEST_EQUALITY_CONST( sublist_a.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_path_prop ), "la150u" ); TEST_EQUALITY_CONST( sublist_a.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_type_prop ), MonteCarlo::CrossSectionsXMLProperties::ace_file ); TEST_EQUALITY_CONST( sublist_a.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_table_name_prop ), "1002.24u" ); TEST_EQUALITY_CONST( sublist_a.get<int>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_start_line_prop ), 216233 ); TEST_EQUALITY_CONST( sublist_a.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_number_prop ), 1 ); TEST_EQUALITY_CONST( sublist_a.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_mass_number_prop ), 2 ); TEST_EQUALITY_CONST( sublist_a.get<int>( MonteCarlo::CrossSectionsXMLProperties::isomer_number_prop ), 0 ); TEST_EQUALITY_CONST( sublist_a.get<double>( MonteCarlo::CrossSectionsXMLProperties::atomic_weight_ratio_prop ), 1.996300 ); DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_b, entry_tokens ); entry.reset( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); Teuchos::ParameterList& sublist_b = parameter_list.sublist( entry->getTableAlias() ); entry->addInfoToParameterList( sublist_b ); TEST_EQUALITY_CONST( sublist_b.numParams(), 8 ); TEST_EQUALITY_CONST( sublist_b.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_path_prop ), "xdata/la150u" ); TEST_EQUALITY_CONST( sublist_b.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_type_prop ), MonteCarlo::CrossSectionsXMLProperties::ace_file ); TEST_EQUALITY_CONST( sublist_b.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_table_name_prop ), "82208.24u" ); TEST_EQUALITY_CONST( sublist_b.get<int>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_start_line_prop ), 196946 ); TEST_EQUALITY_CONST( sublist_b.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_number_prop ), 82 ); TEST_EQUALITY_CONST( sublist_b.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_mass_number_prop ), 208 ); TEST_EQUALITY_CONST( sublist_b.get<int>( MonteCarlo::CrossSectionsXMLProperties::isomer_number_prop ), 0 ); TEST_EQUALITY_CONST( sublist_b.get<double>( MonteCarlo::CrossSectionsXMLProperties::atomic_weight_ratio_prop ), 206.190000 ); DataGen::XsdirEntry::extractTableTokensFromXsdirLine( line_c, entry_tokens ); entry.reset( new DataGen::PhotonuclearXsdirEntry( entry_tokens ) ); Teuchos::ParameterList& sublist_c = parameter_list.sublist( entry->getTableAlias() ); entry->addInfoToParameterList( sublist_c ); TEST_EQUALITY_CONST( sublist_c.numParams(), 8 ); TEST_EQUALITY_CONST( sublist_c.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_path_prop ), "xmc/endf7u" ); TEST_EQUALITY_CONST( sublist_c.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_type_prop ), MonteCarlo::CrossSectionsXMLProperties::ace_file ); TEST_EQUALITY_CONST( sublist_c.get<std::string>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_table_name_prop ), "93237.70u" ); TEST_EQUALITY_CONST( sublist_c.get<int>( MonteCarlo::CrossSectionsXMLProperties::photonuclear_file_start_line_prop ), 4868895 ); TEST_EQUALITY_CONST( sublist_c.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_number_prop ), 93 ); TEST_EQUALITY_CONST( sublist_c.get<int>( MonteCarlo::CrossSectionsXMLProperties::atomic_mass_number_prop ), 237 ); TEST_EQUALITY_CONST( sublist_c.get<int>( MonteCarlo::CrossSectionsXMLProperties::isomer_number_prop ), 0 ); TEST_EQUALITY_CONST( sublist_c.get<double>( MonteCarlo::CrossSectionsXMLProperties::atomic_weight_ratio_prop ), 235.011800 ); } //---------------------------------------------------------------------------// // end tstPhotonuclearXsdirEntry.cpp //---------------------------------------------------------------------------//
46.264516
122
0.684005
lkersting
80d681a8712a6b97f1baf57fbbd91f581fc7c06b
3,299
cc
C++
test/drive_view_colors.cc
rzadp/lnav
853ef11435e04717249ad2f643afffa510cddfc7
[ "BSD-2-Clause" ]
1
2020-12-16T08:55:30.000Z
2020-12-16T08:55:30.000Z
test/drive_view_colors.cc
Sifor/lnav
92f28f1174f1c26408d7b3dd548b80d54adad6f4
[ "BSD-2-Clause" ]
null
null
null
test/drive_view_colors.cc
Sifor/lnav
92f28f1174f1c26408d7b3dd548b80d54adad6f4
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "view_curses.hh" class test_colors : public view_curses { public: test_colors() : tc_window(NULL) { } void do_update(void) { view_colors &vc = view_colors::singleton(); int lpc; for (lpc = 0; lpc < 16; lpc++) { int attrs; char label[64]; attr_line_t al; line_range lr; snprintf(label, sizeof(label), "This is line: %d", lpc); attrs = view_colors::singleton().attrs_for_ident(label); al = label; al.get_attrs().push_back(string_attr( line_range(0, -1), &view_curses::VC_STYLE, attrs )); lr.lr_start = 0; lr.lr_end = 40; this->mvwattrline(this->tc_window, lpc, 0, al, lr, view_colors::VCR_TEXT); } attr_line_t al; line_range lr{0, 40}; al = "before <123> after"; al.with_attr({line_range{8, 11}, &VC_STYLE, (int64_t) vc.ansi_color_pair(COLOR_CYAN, COLOR_BLACK)}); al.with_attr({line_range{8, 11}, &VC_STYLE, A_REVERSE}); this->mvwattrline(this->tc_window, lpc, 0, al, lr, view_colors::VCR_TEXT); }; WINDOW *tc_window; }; int main(int argc, char *argv[]) { int c, retval = EXIT_SUCCESS; bool wait_for_input = false; WINDOW *win; test_colors tc; win = initscr(); noecho(); while ((c = getopt(argc, argv, "w")) != -1) { switch (c) { case 'w': wait_for_input = true; break; } } view_colors::singleton().init(); curs_set(0); tc.tc_window = win; tc.do_update(); refresh(); if (wait_for_input) { getch(); } endwin(); return retval; }
27.040984
81
0.659291
rzadp
80d9055f5e028362b7b101defa6d7bb6d3e58e08
4,420
hpp
C++
app/src/main/jni/src/Runtime/PlayerControl.hpp
BLACK-ARCHON/among-us-android-mod
a66c6c189caab15644bde3853a1e73d1037437ad
[ "Apache-2.0" ]
6
2020-11-15T14:15:19.000Z
2021-07-27T22:53:58.000Z
app/src/main/jni/src/Runtime/PlayerControl.hpp
LGLTeam/among-us-android-mod
e62de079d7767bf63624e21816dc46f88100e829
[ "Apache-2.0" ]
1
2020-12-03T07:56:15.000Z
2020-12-20T06:25:41.000Z
app/src/main/jni/src/Runtime/PlayerControl.hpp
BLACK-ARCHON/among-us-android-mod
a66c6c189caab15644bde3853a1e73d1037437ad
[ "Apache-2.0" ]
2
2021-03-03T03:37:49.000Z
2021-04-06T08:21:36.000Z
#pragma once #include "BaseObject.hpp" class PlayerInfo; class PlayerControl : public BaseObject { private: public: enum MethodOffset : uintptr_t { MethodOffset_Constructor = 0x693C34, MethodOffset_get_CanMove = 0x689914, MethodOffset_CmdCheckColor = 0x68F3B0, MethodOffset_CmdCheckName = 0x68E948, MethodOffset_CmdReportDeadBody = 0x68FAE8, MethodOffset_FindClosestTarget_IsImpostor = 0x69265C, MethodOffset_MurderPlayer = 0x690020, MethodOffset_RpcMurderPlayer = 0x68FF50, MethodOffset_RpcSetName = 0x68F1D8 }; enum FieldOffset : uintptr_t { FieldOffset_GameOptions = 0x08, FieldOffset_AllPlayerControls = 0x10, FieldOffset_SpawnId = 0x18, FieldOffset_NetId = 0x1C, FieldOffset_DirtyBits = 0x20, FieldOffset_SpawnFlags = 0x24, FieldOffset_sendMode = 0x25, FieldOffset_OwnerId = 0x28, FieldOffset_DespawnOnDestroy = 0x2C, FieldOffset_LastStartCounter = 0x30, FieldOffset_PlayerId = 0x34, FieldOffset_MaxReportDistance = 0x38, FieldOffset_moveable = 0x3C, FieldOffset_inVent = 0x3D, FieldOffset__cachedData = 0x40, FieldOffset_FootSteps = 0x48, FieldOffset_KillSfx = 0x50, FieldOffset_KillAnimations = 0x58, FieldOffset_killTimer = 0x60, FieldOffset_RemainingEmergencies = 0x64, FieldOffset_nameText = 0x68, FieldOffset_LightPrefab = 0x70, FieldOffset_myLight = 0x78, FieldOffset_Collider = 0x80, FieldOffset_MyPhysics = 0x88, FieldOffset_NetTransform = 0x90, FieldOffset_CurrentPet = 0x98, FieldOffset_HatRenderer = 0xA0, FieldOffset_myRend = 0xA8, FieldOffset_hitBuffer = 0xB0, FieldOffset_myTasks = 0xB8, FieldOffset_ScannerAnims = 0xC0, FieldOffset_ScannersImages = 0xC8, FieldOffset_closest = 0xD0, FieldOffset_isNew = 0xD8, FieldOffset_cache = 0xE0, FieldOffset_itemsInRange = 0xE8, FieldOffset_newItemsInRange = 0xF0, FieldOffset_scannerCount = 0xF8, FieldOffset_infectedSet = 0xF9 }; template<FieldOffset Offset> using DetermineFieldType = typename std::conditional<Offset == FieldOffset_SpawnId || Offset == FieldOffset_NetId || Offset == FieldOffset_DirtyBits, unsigned int, typename std::conditional<Offset == FieldOffset_SpawnFlags || Offset == FieldOffset_sendMode || Offset == FieldOffset_PlayerId || Offset == FieldOffset_scannerCount, unsigned char, typename std::conditional<Offset == FieldOffset_DespawnOnDestroy || Offset == FieldOffset_moveable || Offset == FieldOffset_inVent || Offset == FieldOffset_isNew || Offset == FieldOffset_infectedSet, bool, typename std::conditional<Offset == FieldOffset_OwnerId || Offset == FieldOffset_LastStartCounter || Offset == FieldOffset_RemainingEmergencies, signed int, typename std::conditional<Offset == FieldOffset_MaxReportDistance || Offset == FieldOffset_killTimer, float, uintptr_t>::type>::type>::type>::type>::type; static PlayerControl& getInstance() { static PlayerControl* instance = new PlayerControl(NULL); return *instance; } static void addInstance(uintptr_t pointer); static void clearInstances(); static size_t removeDisposedInstances(); static std::vector<PlayerControl> getInstances(); static PlayerControl getLocalPlayer(); static void EnableCounterImpostor(); static void DisableCounterImpostor(); static void EnableLockdownImpostor(); static void DisableLockdownImpostor(); static void EnableKillByOtherHand(); static void DisableKillByOtherHand(); static void EnableImpostorCanKillImpostor(); static void DisableImpostorCanKillImpostor(); static void EnableCanMoveInVent(); static void DisableCanMoveInVent(); static void EnableEmptyName(); static void DisableEmptyName(); static void EmptyName(); static void ReportSomeone(); PlayerControl(uintptr_t pointer); ~PlayerControl(); virtual bool isInitialized() override; virtual bool isUsable() override; virtual void init() override; bool isLocalPlayer(); PlayerInfo getPlayerInfo(); void CmdCheckColor(unsigned int colorId); void CmdReportDeadBody(PlayerControl target); };
36.833333
160
0.70905
BLACK-ARCHON
80db12575158da5bbf7f2d37cbbae7f57392d33c
395
cpp
C++
AchiKochiFolder/SHBrowseForFolder/A.cpp
HiraokaHyperTools/AchiKochiFolder
8255942160a210ae697ed0bf20e3ec37bcd583ce
[ "BSD-3-Clause" ]
null
null
null
AchiKochiFolder/SHBrowseForFolder/A.cpp
HiraokaHyperTools/AchiKochiFolder
8255942160a210ae697ed0bf20e3ec37bcd583ce
[ "BSD-3-Clause" ]
null
null
null
AchiKochiFolder/SHBrowseForFolder/A.cpp
HiraokaHyperTools/AchiKochiFolder
8255942160a210ae697ed0bf20e3ec37bcd583ce
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> #include <shlobj.h> #include <tchar.h> #include <atlbase.h> #include <atlcom.h> int _tmain() { HRESULT hr; if (FAILED(hr = OleInitialize(NULL))) return 1; BROWSEINFO bi; ZeroMemory(&bi, sizeof(bi)); bi.ulFlags |= BIF_RETURNFSANCESTORS; bi.ulFlags |= BIF_RETURNONLYFSDIRS; //bi.ulFlags |= BIF_USENEWUI; SHBrowseForFolder(&bi); return 0; }
17.954545
39
0.660759
HiraokaHyperTools
80dd10c054b0e307654fcba8746df2c3512a4b94
1,635
cpp
C++
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-07-18T12:58:02.000Z
2020-07-18T12:58:02.000Z
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAppInstancesPreferencePage.h" #include <berryIPreferencesService.h> #include <berryQtPreferences.h> #include <berryPlatform.h> QmitkAppInstancesPreferencePage::QmitkAppInstancesPreferencePage() { } void QmitkAppInstancesPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkAppInstancesPreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); prefs = prefService->GetSystemPreferences()->Node("/General"); Update(); } QWidget* QmitkAppInstancesPreferencePage::GetQtControl() const { return mainWidget; } bool QmitkAppInstancesPreferencePage::PerformOk() { prefs->PutBool("newInstance.always", controls.newInstanceAlways->isChecked()); prefs->PutBool("newInstance.scene", controls.newInstanceScene->isChecked()); return true; } void QmitkAppInstancesPreferencePage::PerformCancel() { } void QmitkAppInstancesPreferencePage::Update() { bool always = prefs->GetBool("newInstance.always", false); bool scene = prefs->GetBool("newInstance.scene", true); controls.newInstanceAlways->setChecked(always); controls.newInstanceScene->setChecked(scene); }
25.153846
85
0.706422
zhaomengxiao