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 108 | 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 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c403ff5a3810febf624d8bd9279b6b4689089dc7 | 15,300 | hpp | C++ | include/multiformats/multicodec.hpp | matt1795/multiformats | 52dac14cad10c0e3066bc20d068f8475b9cde0ea | [
"MIT"
] | null | null | null | include/multiformats/multicodec.hpp | matt1795/multiformats | 52dac14cad10c0e3066bc20d068f8475b9cde0ea | [
"MIT"
] | null | null | null | include/multiformats/multicodec.hpp | matt1795/multiformats | 52dac14cad10c0e3066bc20d068f8475b9cde0ea | [
"MIT"
] | null | null | null | // Multicodec -- self-describing serialization
//
// Author: Matthew Knight
// File Name: multicodec.hpp
// Date: 2019-09-12
// Multicode: self-des
//
// Author: Matthew Knight
// File Name: varint.hpp
// Date: 2019-09-12
#pragma once
#include "varint.hpp"
#include <unordered_map>
namespace Multiformats::Multicodec {
/** @brief Map of protocols and their specific varint code values */
std::unordered_map<std::string, Varint> const table {
{ "identity", 0x00 },
{ "ip4", 0x04 },
{ "tcp", 0x06 },
{ "sha1", 0x11 },
{ "sha2-256", 0x12 },
{ "sha2-512", 0x13 },
{ "sha3-512", 0x14 },
{ "sha3-384", 0x15 },
{ "sha3-256", 0x16 },
{ "sha3-224", 0x17 },
{ "shake-128", 0x18 },
{ "shake-256", 0x19 },
{ "keccak-224", 0x1a },
{ "keccak-256", 0x1b },
{ "keccak-384", 0x1c },
{ "keccak-512", 0x1d },
{ "dccp", 0x21 },
{ "murmur3-128", 0x22 },
{ "murmur3-32", 0x23 },
{ "ip6", 0x29 },
{ "ip6zone", 0x2a },
{ "path", 0x2f },
{ "multicodec", 0x30 },
{ "multihash", 0x31 },
{ "multiaddr", 0x32 },
{ "multibase", 0x33 },
{ "dns", 0x35 },
{ "dns4", 0x36 },
{ "dns6", 0x37 },
{ "dnsaddr", 0x38 },
{ "protobuf", 0x50 },
{ "cbor", 0x51 },
{ "raw", 0x55 },
{ "dbl-sha2-256", 0x56 },
{ "rlp", 0x60 },
{ "bencode", 0x63 },
{ "dag-pb", 0x70 },
{ "dag-cbor", 0x71 },
{ "libp2p-key", 0x72 },
{ "git-raw", 0x78 },
{ "torrent-info", 0x7b },
{ "torrent-file", 0x7c },
{ "leofcoin-block", 0x81 },
{ "leofcoin-tx", 0x82 },
{ "leofcoin-pr", 0x83 },
{ "sctp", 0x84 },
{ "eth-block", 0x90 },
{ "eth-block-list", 0x91 },
{ "eth-tx-trie", 0x92 },
{ "eth-tx", 0x93 },
{ "eth-tx-receipt-trie", 0x94 },
{ "eth-tx-receipt", 0x95 },
{ "eth-state-trie", 0x96 },
{ "eth-account-snapshot", 0x97 },
{ "eth-storage-trie", 0x98 },
{ "bitcoin-block", 0xb0 },
{ "bitcoin-tx", 0xb1 },
{ "zcash-block", 0xc0 },
{ "zcash-tx", 0xc1 },
{ "stellar-block", 0xd0 },
{ "stellar-tx", 0xd1 },
{ "md4", 0xd4 },
{ "md5", 0xd5 },
{ "bmt", 0xd6 },
{ "decred-block", 0xe0 },
{ "decred-tx", 0xe1 },
{ "ipld-ns", 0xe2 },
{ "ipfs-ns", 0xe3 },
{ "swarm-ns", 0xe4 },
{ "ipns-ns", 0xe5 },
{ "zeronet", 0xe6 },
{ "ed25519-pub", 0xed },
{ "dash-block", 0xf0 },
{ "dash-tx", 0xf1 },
{ "swarm-manifest", 0xfa },
{ "swarm-feed", 0xfb },
{ "udp", 0x0111 },
{ "p2p-webrtc-star", 0x0113 },
{ "p2p-webrtc-direct", 0x0114 },
{ "p2p-stardust", 0x0115 },
{ "p2p-circuit", 0x0122 },
{ "dag-json", 0x0129 },
{ "udt", 0x012d },
{ "utp", 0x012e },
{ "unix", 0x0190 },
{ "p2p", 0x01a5 },
{ "ipfs", 0x01a5 },
{ "https", 0x01bb },
{ "onion", 0x01bc },
{ "onion3", 0x01bd },
{ "garlic64", 0x01be },
{ "garlic32", 0x01bf },
{ "tls", 0x01c0 },
{ "quic", 0x01cc },
{ "ws", 0x01dd },
{ "wss", 0x01de },
{ "p2p-websocket-star", 0x01df },
{ "http", 0x01e0 },
{ "json", 0x0200 },
{ "messagepack", 0x0201 },
{ "x11", 0x1100 },
{ "blake2b-8", 0xb201 },
{ "blake2b-16", 0xb202 },
{ "blake2b-24", 0xb203 },
{ "blake2b-32", 0xb204 },
{ "blake2b-40", 0xb205 },
{ "blake2b-48", 0xb206 },
{ "blake2b-56", 0xb207 },
{ "blake2b-64", 0xb208 },
{ "blake2b-72", 0xb209 },
{ "blake2b-80", 0xb20a },
{ "blake2b-88", 0xb20b },
{ "blake2b-96", 0xb20c },
{ "blake2b-104", 0xb20d },
{ "blake2b-112", 0xb20e },
{ "blake2b-120", 0xb20f },
{ "blake2b-128", 0xb210 },
{ "blake2b-136", 0xb211 },
{ "blake2b-144", 0xb212 },
{ "blake2b-152", 0xb213 },
{ "blake2b-160", 0xb214 },
{ "blake2b-168", 0xb215 },
{ "blake2b-176", 0xb216 },
{ "blake2b-184", 0xb217 },
{ "blake2b-192", 0xb218 },
{ "blake2b-200", 0xb219 },
{ "blake2b-208", 0xb21a },
{ "blake2b-216", 0xb21b },
{ "blake2b-224", 0xb21c },
{ "blake2b-232", 0xb21d },
{ "blake2b-240", 0xb21e },
{ "blake2b-248", 0xb21f },
{ "blake2b-256", 0xb220 },
{ "blake2b-264", 0xb221 },
{ "blake2b-272", 0xb222 },
{ "blake2b-280", 0xb223 },
{ "blake2b-288", 0xb224 },
{ "blake2b-296", 0xb225 },
{ "blake2b-304", 0xb226 },
{ "blake2b-312", 0xb227 },
{ "blake2b-320", 0xb228 },
{ "blake2b-328", 0xb229 },
{ "blake2b-336", 0xb22a },
{ "blake2b-344", 0xb22b },
{ "blake2b-352", 0xb22c },
{ "blake2b-360", 0xb22d },
{ "blake2b-368", 0xb22e },
{ "blake2b-376", 0xb22f },
{ "blake2b-384", 0xb230 },
{ "blake2b-392", 0xb231 },
{ "blake2b-400", 0xb232 },
{ "blake2b-408", 0xb233 },
{ "blake2b-416", 0xb234 },
{ "blake2b-424", 0xb235 },
{ "blake2b-432", 0xb236 },
{ "blake2b-440", 0xb237 },
{ "blake2b-448", 0xb238 },
{ "blake2b-456", 0xb239 },
{ "blake2b-464", 0xb23a },
{ "blake2b-472", 0xb23b },
{ "blake2b-480", 0xb23c },
{ "blake2b-488", 0xb23d },
{ "blake2b-496", 0xb23e },
{ "blake2b-504", 0xb23f },
{ "blake2b-512", 0xb240 },
{ "blake2s-8", 0xb241 },
{ "blake2s-16", 0xb242 },
{ "blake2s-24", 0xb243 },
{ "blake2s-32", 0xb244 },
{ "blake2s-40", 0xb245 },
{ "blake2s-48", 0xb246 },
{ "blake2s-56", 0xb247 },
{ "blake2s-64", 0xb248 },
{ "blake2s-72", 0xb249 },
{ "blake2s-80", 0xb24a },
{ "blake2s-88", 0xb24b },
{ "blake2s-96", 0xb24c },
{ "blake2s-104", 0xb24d },
{ "blake2s-112", 0xb24e },
{ "blake2s-120", 0xb24f },
{ "blake2s-128", 0xb250 },
{ "blake2s-136", 0xb251 },
{ "blake2s-144", 0xb252 },
{ "blake2s-152", 0xb253 },
{ "blake2s-160", 0xb254 },
{ "blake2s-168", 0xb255 },
{ "blake2s-176", 0xb256 },
{ "blake2s-184", 0xb257 },
{ "blake2s-192", 0xb258 },
{ "blake2s-200", 0xb259 },
{ "blake2s-208", 0xb25a },
{ "blake2s-216", 0xb25b },
{ "blake2s-224", 0xb25c },
{ "blake2s-232", 0xb25d },
{ "blake2s-240", 0xb25e },
{ "blake2s-248", 0xb25f },
{ "blake2s-256", 0xb260 },
{ "skein256-8", 0xb301 },
{ "skein256-16", 0xb302 },
{ "skein256-24", 0xb303 },
{ "skein256-32", 0xb304 },
{ "skein256-40", 0xb305 },
{ "skein256-48", 0xb306 },
{ "skein256-56", 0xb307 },
{ "skein256-64", 0xb308 },
{ "skein256-72", 0xb309 },
{ "skein256-80", 0xb30a },
{ "skein256-88", 0xb30b },
{ "skein256-96", 0xb30c },
{ "skein256-104", 0xb30d },
{ "skein256-112", 0xb30e },
{ "skein256-120", 0xb30f },
{ "skein256-128", 0xb310 },
{ "skein256-136", 0xb311 },
{ "skein256-144", 0xb312 },
{ "skein256-152", 0xb313 },
{ "skein256-160", 0xb314 },
{ "skein256-168", 0xb315 },
{ "skein256-176", 0xb316 },
{ "skein256-184", 0xb317 },
{ "skein256-192", 0xb318 },
{ "skein256-200", 0xb319 },
{ "skein256-208", 0xb31a },
{ "skein256-216", 0xb31b },
{ "skein256-224", 0xb31c },
{ "skein256-232", 0xb31d },
{ "skein256-240", 0xb31e },
{ "skein256-248", 0xb31f },
{ "skein256-256", 0xb320 },
{ "skein512-8", 0xb321 },
{ "skein512-16", 0xb322 },
{ "skein512-24", 0xb323 },
{ "skein512-32", 0xb324 },
{ "skein512-40", 0xb325 },
{ "skein512-48", 0xb326 },
{ "skein512-56", 0xb327 },
{ "skein512-64", 0xb328 },
{ "skein512-72", 0xb329 },
{ "skein512-80", 0xb32a },
{ "skein512-88", 0xb32b },
{ "skein512-96", 0xb32c },
{ "skein512-104", 0xb32d },
{ "skein512-112", 0xb32e },
{ "skein512-120", 0xb32f },
{ "skein512-128", 0xb330 },
{ "skein512-136", 0xb331 },
{ "skein512-144", 0xb332 },
{ "skein512-152", 0xb333 },
{ "skein512-160", 0xb334 },
{ "skein512-168", 0xb335 },
{ "skein512-176", 0xb336 },
{ "skein512-184", 0xb337 },
{ "skein512-192", 0xb338 },
{ "skein512-200", 0xb339 },
{ "skein512-208", 0xb33a },
{ "skein512-216", 0xb33b },
{ "skein512-224", 0xb33c },
{ "skein512-232", 0xb33d },
{ "skein512-240", 0xb33e },
{ "skein512-248", 0xb33f },
{ "skein512-256", 0xb340 },
{ "skein512-264", 0xb341 },
{ "skein512-272", 0xb342 },
{ "skein512-280", 0xb343 },
{ "skein512-288", 0xb344 },
{ "skein512-296", 0xb345 },
{ "skein512-304", 0xb346 },
{ "skein512-312", 0xb347 },
{ "skein512-320", 0xb348 },
{ "skein512-328", 0xb349 },
{ "skein512-336", 0xb34a },
{ "skein512-344", 0xb34b },
{ "skein512-352", 0xb34c },
{ "skein512-360", 0xb34d },
{ "skein512-368", 0xb34e },
{ "skein512-376", 0xb34f },
{ "skein512-384", 0xb350 },
{ "skein512-392", 0xb351 },
{ "skein512-400", 0xb352 },
{ "skein512-408", 0xb353 },
{ "skein512-416", 0xb354 },
{ "skein512-424", 0xb355 },
{ "skein512-432", 0xb356 },
{ "skein512-440", 0xb357 },
{ "skein512-448", 0xb358 },
{ "skein512-456", 0xb359 },
{ "skein512-464", 0xb35a },
{ "skein512-472", 0xb35b },
{ "skein512-480", 0xb35c },
{ "skein512-488", 0xb35d },
{ "skein512-496", 0xb35e },
{ "skein512-504", 0xb35f },
{ "skein512-512", 0xb360 },
{ "skein1024-8", 0xb361 },
{ "skein1024-16", 0xb362 },
{ "skein1024-24", 0xb363 },
{ "skein1024-32", 0xb364 },
{ "skein1024-40", 0xb365 },
{ "skein1024-48", 0xb366 },
{ "skein1024-56", 0xb367 },
{ "skein1024-64", 0xb368 },
{ "skein1024-72", 0xb369 },
{ "skein1024-80", 0xb36a },
{ "skein1024-88", 0xb36b },
{ "skein1024-96", 0xb36c },
{ "skein1024-104", 0xb36d },
{ "skein1024-112", 0xb36e },
{ "skein1024-120", 0xb36f },
{ "skein1024-128", 0xb370 },
{ "skein1024-136", 0xb371 },
{ "skein1024-144", 0xb372 },
{ "skein1024-152", 0xb373 },
{ "skein1024-160", 0xb374 },
{ "skein1024-168", 0xb375 },
{ "skein1024-176", 0xb376 },
{ "skein1024-184", 0xb377 },
{ "skein1024-192", 0xb378 },
{ "skein1024-200", 0xb379 },
{ "skein1024-208", 0xb37a },
{ "skein1024-216", 0xb37b },
{ "skein1024-224", 0xb37c },
{ "skein1024-232", 0xb37d },
{ "skein1024-240", 0xb37e },
{ "skein1024-248", 0xb37f },
{ "skein1024-256", 0xb380 },
{ "skein1024-264", 0xb381 },
{ "skein1024-272", 0xb382 },
{ "skein1024-280", 0xb383 },
{ "skein1024-288", 0xb384 },
{ "skein1024-296", 0xb385 },
{ "skein1024-304", 0xb386 },
{ "skein1024-312", 0xb387 },
{ "skein1024-320", 0xb388 },
{ "skein1024-328", 0xb389 },
{ "skein1024-336", 0xb38a },
{ "skein1024-344", 0xb38b },
{ "skein1024-352", 0xb38c },
{ "skein1024-360", 0xb38d },
{ "skein1024-368", 0xb38e },
{ "skein1024-376", 0xb38f },
{ "skein1024-384", 0xb390 },
{ "skein1024-392", 0xb391 },
{ "skein1024-400", 0xb392 },
{ "skein1024-408", 0xb393 },
{ "skein1024-416", 0xb394 },
{ "skein1024-424", 0xb395 },
{ "skein1024-432", 0xb396 },
{ "skein1024-440", 0xb397 },
{ "skein1024-448", 0xb398 },
{ "skein1024-456", 0xb399 },
{ "skein1024-464", 0xb39a },
{ "skein1024-472", 0xb39b },
{ "skein1024-480", 0xb39c },
{ "skein1024-488", 0xb39d },
{ "skein1024-496", 0xb39e },
{ "skein1024-504", 0xb39f },
{ "skein1024-512", 0xb3a0 },
{ "skein1024-520", 0xb3a1 },
{ "skein1024-528", 0xb3a2 },
{ "skein1024-536", 0xb3a3 },
{ "skein1024-544", 0xb3a4 },
{ "skein1024-552", 0xb3a5 },
{ "skein1024-560", 0xb3a6 },
{ "skein1024-568", 0xb3a7 },
{ "skein1024-576", 0xb3a8 },
{ "skein1024-584", 0xb3a9 },
{ "skein1024-592", 0xb3aa },
{ "skein1024-600", 0xb3ab },
{ "skein1024-608", 0xb3ac },
{ "skein1024-616", 0xb3ad },
{ "skein1024-624", 0xb3ae },
{ "skein1024-632", 0xb3af },
{ "skein1024-640", 0xb3b0 },
{ "skein1024-648", 0xb3b1 },
{ "skein1024-656", 0xb3b2 },
{ "skein1024-664", 0xb3b3 },
{ "skein1024-672", 0xb3b4 },
{ "skein1024-680", 0xb3b5 },
{ "skein1024-688", 0xb3b6 },
{ "skein1024-696", 0xb3b7 },
{ "skein1024-704", 0xb3b8 },
{ "skein1024-712", 0xb3b9 },
{ "skein1024-720", 0xb3ba },
{ "skein1024-728", 0xb3bb },
{ "skein1024-736", 0xb3bc },
{ "skein1024-744", 0xb3bd },
{ "skein1024-752", 0xb3be },
{ "skein1024-760", 0xb3bf },
{ "skein1024-768", 0xb3c0 },
{ "skein1024-776", 0xb3c1 },
{ "skein1024-784", 0xb3c2 },
{ "skein1024-792", 0xb3c3 },
{ "skein1024-800", 0xb3c4 },
{ "skein1024-808", 0xb3c5 },
{ "skein1024-816", 0xb3c6 },
{ "skein1024-824", 0xb3c7 },
{ "skein1024-832", 0xb3c8 },
{ "skein1024-840", 0xb3c9 },
{ "skein1024-848", 0xb3ca },
{ "skein1024-856", 0xb3cb },
{ "skein1024-864", 0xb3cc },
{ "skein1024-872", 0xb3cd },
{ "skein1024-880", 0xb3ce },
{ "skein1024-888", 0xb3cf },
{ "skein1024-896", 0xb3d0 },
{ "skein1024-904", 0xb3d1 },
{ "skein1024-912", 0xb3d2 },
{ "skein1024-920", 0xb3d3 },
{ "skein1024-928", 0xb3d4 },
{ "skein1024-936", 0xb3d5 },
{ "skein1024-944", 0xb3d6 },
{ "skein1024-952", 0xb3d7 },
{ "skein1024-960", 0xb3d8 },
{ "skein1024-968", 0xb3d9 },
{ "skein1024-976", 0xb3da },
{ "skein1024-984", 0xb3db },
{ "skein1024-992", 0xb3dc },
{ "skein1024-1000", 0xb3dd },
{ "skein1024-1008", 0xb3de },
{ "skein1024-1016", 0xb3df },
{ "skein1024-1024", 0xb3e0 },
{ "holochain-adr-v0", 0x807124 },
{ "holochain-adr-v1", 0x817124 },
{ "holochain-key-v0", 0x947124 },
{ "holochain-key-v1", 0x957124 },
{ "holochain-sig-v0", 0xa27124 },
{ "holochain-sig-v1", 0xa37124 }
};
}
| 34 | 72 | 0.462353 | matt1795 |
c404c9bd1852b6a0b6a16a8985f4edd9e05ff1a1 | 3,677 | cpp | C++ | tools/src/fmlhpp32.cpp | georgekap1an/tuxpp | eb62d765b029c63c35a35375fb040227c7e7d96b | [
"MIT"
] | null | null | null | tools/src/fmlhpp32.cpp | georgekap1an/tuxpp | eb62d765b029c63c35a35375fb040227c7e7d96b | [
"MIT"
] | null | null | null | tools/src/fmlhpp32.cpp | georgekap1an/tuxpp | eb62d765b029c63c35a35375fb040227c7e7d96b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cstring>
#include <map>
#include <vector>
#include <algorithm>
#include "fml32.h"
using namespace std;
map<string, int> field_types = { {"short", FLD_SHORT},
{"long", FLD_LONG},
{"char", FLD_CHAR},
{"float", FLD_FLOAT},
{"double", FLD_DOUBLE},
{"string", FLD_STRING},
{"carray", FLD_CARRAY},
{"mbstring", FLD_MBSTRING},
{"ptr", FLD_PTR},
{"fml32", FLD_FML32},
{"view32", FLD_VIEW32} };
struct field_def
{
string name;
int number = 0;
FLDID32 id = 0;
string type_str;
};
bool starts_with(string const& source, string const& pattern)
{
if(source.size() < pattern.size())
{
return false;
}
return memcmp(source.data(), pattern.data(), pattern.size()) == 0;
}
vector<field_def> read_input(istream& is)
{
vector<field_def> result;
string line;
int base = 0;
while(getline(is, line))
{
if(line.empty() || line[0] == '#')
{
continue;
}
else if(starts_with(line, "*base"))
{
base = stoi(line.substr(5));
}
else
{
string name, type_str;
int number = 0;
stringstream s(line);
s >> name >> number >> type_str;
if(name.empty() || type_str.empty())
{
continue;
}
number += base;
FLDID32 id = Fmkfldid32(field_types[type_str], number);
if(id == BADFLDID)
{
throw runtime_error(line + "[" + Fstrerror32(Ferror32) + "]");
}
field_def f;
f.name = name;
f.number = number;
f.id = id;
f.type_str = type_str;
result.push_back(f);
}
}
return result;
}
size_t get_max_name_size(vector<field_def> const& fields)
{
size_t result = 0;
for(auto&& f : fields)
{
result = max(result, f.name.size());
}
return result;
}
void write_output(ostream& os, vector<field_def> const& fields)
{
size_t name_width = get_max_name_size(fields);
os << R"(
#include "fml32.h"
namespace field32 {
)";
for(auto&& f : fields)
{
os << "const FLDID32 " << setw(name_width) << left << f.name
<< " = " << setw(12) << f.id << "; // number: "
<< setw(12) << f.number << " type: " << f.type_str << "\n";
}
os << "} // end namespace" << endl;
}
int main(int argc, char** argv)
{
try
{
string program_name = argv[0];
if(argc < 3)
{
throw runtime_error("Usage: " + program_name + " INPUT_FILE OUTPUT_FILE");
}
string input_file_name = argv[1];
string output_file_name = argv[2];
ifstream is(input_file_name);
if(!is)
{
throw runtime_error("error reading from " + input_file_name);
}
ofstream os(output_file_name);
if(!os)
{
throw runtime_error("error opening " + output_file_name + " for write");
}
write_output(os, read_input(is));
return 0;
}
catch(exception const& e)
{
cerr << "error: " << e.what() << endl;
return 1;
}
}
| 25.013605 | 86 | 0.468045 | georgekap1an |
c406b67425e72a0706e0b857c7b610d383085ed7 | 1,285 | cpp | C++ | firmware/communicator.cpp | rustbuggy/sharprust | 8a72b0bed544216529d8a65012be23ca2790a995 | [
"MIT"
] | null | null | null | firmware/communicator.cpp | rustbuggy/sharprust | 8a72b0bed544216529d8a65012be23ca2790a995 | [
"MIT"
] | null | null | null | firmware/communicator.cpp | rustbuggy/sharprust | 8a72b0bed544216529d8a65012be23ca2790a995 | [
"MIT"
] | null | null | null | #include "communicator.h"
#include "buggy.h"
#define TELEMETRY_SEND_INTERVAL_MS 20
Communicator::Communicator() :
rx_len(0), tx_len(0), hdlc(rx_buffer, 255) {
}
Communicator::~Communicator() {
}
void Communicator::setup() {
SERIALDEV.begin(57600);
}
void Communicator::send_telemetry(bc_telemetry_packet_t& telemetry) {
if (send_telemetry_timer.start_or_triggered(telemetry.time, TELEMETRY_SEND_INTERVAL_MS, false, true)) {
tx_len = hdlc.encode((uint8_t*) &telemetry, sizeof(bc_telemetry_packet_t), tx_buffer);
SERIALDEV.write(tx_buffer, tx_len);
}
}
drive_cmd_t& Communicator::read_command(bc_telemetry_packet_t& telemetry) {
drive_cmd.received = false;
while (SERIALDEV.available() > 0) {
rx_len = hdlc.decode(SERIALDEV.read());
// check if HDLC packet is received
if (rx_len > 0) {
uint8_t header = ((uint8_t*) rx_buffer)[0];
if (CB_MOTOR_COMMAND == header) {
cb_motor_command_packet_t* motor = (cb_motor_command_packet_t*) rx_buffer;
drive_cmd.received = true;
drive_cmd.automatic = motor->automatic;
drive_cmd.steering_pwm = motor->steering_pwm;
drive_cmd.driving_pwm = motor->driving_pwm;
}
}
}
Buggy::clamp_steering_and_speed(drive_cmd);
return drive_cmd;
}
| 25.7 | 105 | 0.703502 | rustbuggy |
c407af2e873f201a2050a01ec30a53118ba9d4a5 | 6,854 | cc | C++ | tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 1 | 2022-03-18T17:36:11.000Z | 2022-03-18T17:36:11.000Z | tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | null | null | null | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA && GOOGLE_TENSORRT
#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h"
#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h"
namespace tensorflow {
namespace tensorrt {
namespace convert {
const BinaryOperationMapType* BinaryOperationMap() {
static const auto* map = new BinaryOperationMapType({
{"Add", nvinfer1::ElementWiseOperation::kSUM},
{"AddV2", nvinfer1::ElementWiseOperation::kSUM},
{"Mul", nvinfer1::ElementWiseOperation::kPROD},
{"Sub", nvinfer1::ElementWiseOperation::kSUB},
{"Div", nvinfer1::ElementWiseOperation::kDIV},
{"FloorDiv", nvinfer1::ElementWiseOperation::kFLOOR_DIV},
{"RealDiv", nvinfer1::ElementWiseOperation::kDIV},
{"Minimum", nvinfer1::ElementWiseOperation::kMIN},
{"Maximum", nvinfer1::ElementWiseOperation::kMAX},
{"Pow", nvinfer1::ElementWiseOperation::kPOW},
});
return map;
}
const BinaryOperationMapType* BinaryBooleanOperationMap() {
static const auto* map = new BinaryOperationMapType({
{"LogicalOr", nvinfer1::ElementWiseOperation::kOR},
{"LogicalAnd", nvinfer1::ElementWiseOperation::kAND},
});
return map;
}
namespace {
class ConvertBinaryImpl {
protected:
ConvertBinaryImpl(const BinaryOperationMapType* pOperMap)
: pOperMap_(pOperMap) {}
Status ValidateImpl(const OpConverterParams& params,
bool both_tensors = false,
const std::vector<string>& not_supported_ops = {}) {
const auto& node_def = params.node_def;
const auto op = node_def.op();
const auto op_pair = pOperMap_->find(op);
if (op_pair == pOperMap_->end()) {
return errors::Unimplemented("Binary op: ", op, " not supported");
}
// Constant folding should have been done by TensorFlow.
const auto& inputs = params.inputs;
if (inputs.at(0).is_weights() && inputs.at(1).is_weights()) {
return errors::Unimplemented(
"Constant folding is falled back to TensorFlow, binary op '", op,
"' received both input as constant");
}
if (!not_supported_ops.empty() && params.use_implicit_batch) {
const auto& end = not_supported_ops.end();
if (std::find(not_supported_ops.begin(), end, op) != end) {
return errors::Unimplemented(
"Binary op: '", op, "' is not supported in implicit batch mode");
}
}
if (both_tensors) {
if (inputs.at(0).is_weights() || inputs.at(1).is_weights()) {
return errors::InvalidArgument("Both inputs of '", op,
"' are expected to be tensors");
}
}
nvinfer1::Dims broadcasted_dims[2];
TF_RETURN_IF_ERROR(GetTrtBroadcastShape(
inputs.at(0), inputs.at(1), true, params.use_implicit_batch,
broadcasted_dims, broadcasted_dims + 1));
for (int i = 0; i < tensor_.size(); i++) {
// This will also convert constants to tensors.
TF_RETURN_IF_ERROR(PrepareTensorForShape(
params.converter, inputs.at(i), broadcasted_dims[i],
params.validation_only, &tensor_[i], node_def, i));
}
operation_ = op_pair->second;
return Status::OK();
}
Status ConvertImpl(const OpConverterParams& params) {
const auto& node_def = params.node_def;
// Add ElementWise layer.
nvinfer1::ILayer* layer = params.converter->network()->addElementWise(
*tensor_[0]->trt_tensor(), *tensor_[1]->trt_tensor(), operation_);
TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
if (params.use_explicit_precision) {
layer->setPrecision(nvinfer1::DataType::kFLOAT);
}
params.converter->SetLayerName(layer, node_def);
params.outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0)));
return Status::OK();
}
static constexpr std::array<InputArgSpec, 2> InputSpec() {
return std::array<InputArgSpec, 2>{
InputArgSpec::Create("x", TrtInputArg::kBoth),
InputArgSpec::Create("y", TrtInputArg::kBoth)};
}
private:
const BinaryOperationMapType* pOperMap_;
std::array<ITensorProxyPtr, 2> tensor_{nullptr, nullptr};
nvinfer1::ElementWiseOperation operation_;
};
class ConvertBinary : public OpConverterBase<ConvertBinary>,
protected ConvertBinaryImpl {
public:
explicit ConvertBinary(OpConverterParams* params)
: OpConverterBase<ConvertBinary>(params),
ConvertBinaryImpl(BinaryOperationMap()) {}
static constexpr std::array<DataType, 3> AllowedDataTypes() {
return {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32};
}
static constexpr std::array<InputArgSpec, 2> InputSpec() {
return ConvertBinaryImpl::InputSpec();
}
Status Validate() { return ValidateImpl(*params_); }
Status Convert() { return ConvertImpl(*params_); }
};
class ConvertBooleanBinary : public OpConverterBase<ConvertBooleanBinary>,
public ConvertBinaryImpl {
public:
explicit ConvertBooleanBinary(OpConverterParams* params)
: OpConverterBase<ConvertBooleanBinary>(params),
ConvertBinaryImpl(BinaryBooleanOperationMap()) {}
static constexpr std::array<DataType, 1> AllowedDataTypes() {
return {DataType::DT_BOOL};
}
static constexpr std::array<InputArgSpec, 2> InputSpec() {
return ConvertBinaryImpl::InputSpec();
}
static constexpr const char* NodeDefDataTypeAttributeName() { return ""; }
Status Validate() {
#if IS_TRT_VERSION_GE(8, 2, 0, 0)
return ValidateImpl(*params_, true, {"LogicalOr", "LogicalAnd"});
#else
return errors::Unimplemented("Boolean op: ", params_->node_def.op(),
" is not supported in TRT version < 8.2");
#endif
}
Status Convert() { return ConvertImpl(*params_); }
};
} // namespace
REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction<ConvertBinary>(),
GetOperationNames(*BinaryOperationMap()));
REGISTER_DEFAULT_TRT_OP_CONVERTER(
MakeConverterFunction<ConvertBooleanBinary>(),
GetOperationNames(*BinaryBooleanOperationMap()));
} // namespace convert
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_CUDA && GOOGLE_TENSORRT
| 36.457447 | 80 | 0.680041 | TheRakeshPurohit |
c40c1d04c07da1e11bdf85f84f5de02707442315 | 7,955 | cpp | C++ | api/core/nodejs/NJSHttpRequestCpp.cpp | kodxana/lib-ledger-core | 96f04d378b7747e1b80b49da7ae637eb33b23678 | [
"MIT"
] | null | null | null | api/core/nodejs/NJSHttpRequestCpp.cpp | kodxana/lib-ledger-core | 96f04d378b7747e1b80b49da7ae637eb33b23678 | [
"MIT"
] | null | null | null | api/core/nodejs/NJSHttpRequestCpp.cpp | kodxana/lib-ledger-core | 96f04d378b7747e1b80b49da7ae637eb33b23678 | [
"MIT"
] | null | null | null | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from http_client.djinni
#include "NJSHttpRequestCpp.hpp"
using namespace v8;
using namespace node;
using namespace std;
NAN_METHOD(NJSHttpRequest::getMethod) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSHttpRequest::getMethod needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_impl = obj->getCppImpl();
if(!cpp_impl)
{
return Nan::ThrowError("NJSHttpRequest::getMethod : implementation of HttpRequest is not valid");
}
auto result = cpp_impl->getMethod();
//Wrap result in node object
auto arg_0 = Nan::New<Integer>((int)result);
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSHttpRequest::getHeaders) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSHttpRequest::getHeaders needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_impl = obj->getCppImpl();
if(!cpp_impl)
{
return Nan::ThrowError("NJSHttpRequest::getHeaders : implementation of HttpRequest is not valid");
}
auto result = cpp_impl->getHeaders();
//Wrap result in node object
Local<Map> arg_0 = Map::New((Nan::GetCurrentContext())->GetIsolate());
for(auto const& arg_0_elem : result)
{
auto arg_0_first = Nan::New<String>(arg_0_elem.first).ToLocalChecked();
auto arg_0_second = Nan::New<String>(arg_0_elem.second).ToLocalChecked();
arg_0->Set(Nan::GetCurrentContext(), arg_0_first, arg_0_second);
}
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSHttpRequest::getBody) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSHttpRequest::getBody needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_impl = obj->getCppImpl();
if(!cpp_impl)
{
return Nan::ThrowError("NJSHttpRequest::getBody : implementation of HttpRequest is not valid");
}
auto result = cpp_impl->getBody();
//Wrap result in node object
Local<Array> arg_0 = Nan::New<Array>();
for(size_t arg_0_id = 0; arg_0_id < result.size(); arg_0_id++)
{
auto arg_0_elem = Nan::New<Uint32>(result[arg_0_id]);
arg_0->Set((int)arg_0_id,arg_0_elem);
}
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSHttpRequest::getUrl) {
//Check if method called with right number of arguments
if(info.Length() != 0)
{
return Nan::ThrowError("NJSHttpRequest::getUrl needs 0 arguments");
}
//Check if parameters have correct types
//Unwrap current object and retrieve its Cpp Implementation
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_impl = obj->getCppImpl();
if(!cpp_impl)
{
return Nan::ThrowError("NJSHttpRequest::getUrl : implementation of HttpRequest is not valid");
}
auto result = cpp_impl->getUrl();
//Wrap result in node object
auto arg_0 = Nan::New<String>(result).ToLocalChecked();
//Return result
info.GetReturnValue().Set(arg_0);
}
NAN_METHOD(NJSHttpRequest::complete) {
//Check if method called with right number of arguments
if(info.Length() != 2)
{
return Nan::ThrowError("NJSHttpRequest::complete needs 2 arguments");
}
//Check if parameters have correct types
std::shared_ptr<NJSHttpUrlConnection> arg_0 = nullptr;
if(!info[0]->IsNull())
{
Local<Object> njs_opt_arg_0 = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked();
NJSHttpUrlConnection *njs_ptr_opt_arg_0 = static_cast<NJSHttpUrlConnection *>(Nan::GetInternalFieldPointer(njs_opt_arg_0,0));
std::shared_ptr<NJSHttpUrlConnection> opt_arg_0(njs_ptr_opt_arg_0);
arg_0 = opt_arg_0;
}
auto arg_1 = std::experimental::optional<Error>();
if(!info[1]->IsNull())
{
auto field_opt_arg_1_1 = Nan::Get(info[1]->ToObject(), Nan::New<String>("code").ToLocalChecked()).ToLocalChecked();
auto opt_arg_1_1 = (ledger::core::api::ErrorCode)Nan::To<int>(field_opt_arg_1_1).FromJust();
auto field_opt_arg_1_2 = Nan::Get(info[1]->ToObject(), Nan::New<String>("message").ToLocalChecked()).ToLocalChecked();
String::Utf8Value string_opt_arg_1_2(field_opt_arg_1_2->ToString());
auto opt_arg_1_2 = std::string(*string_opt_arg_1_2);
Error opt_arg_1(opt_arg_1_1, opt_arg_1_2);
arg_1.emplace(opt_arg_1);
}
//Unwrap current object and retrieve its Cpp Implementation
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_impl = obj->getCppImpl();
if(!cpp_impl)
{
return Nan::ThrowError("NJSHttpRequest::complete : implementation of HttpRequest is not valid");
}
cpp_impl->complete(arg_0,arg_1);
}
NAN_METHOD(NJSHttpRequest::New) {
//Only new allowed
if(!info.IsConstructCall())
{
return Nan::ThrowError("NJSHttpRequest function can only be called as constructor (use New)");
}
NJSHttpRequest *node_instance = new NJSHttpRequest(nullptr);
if(node_instance)
{
//Wrap and return node instance
node_instance->Wrap(info.This());
node_instance->Ref();
info.GetReturnValue().Set(info.This());
}
}
Nan::Persistent<ObjectTemplate> NJSHttpRequest::HttpRequest_prototype;
Handle<Object> NJSHttpRequest::wrap(const std::shared_ptr<ledger::core::api::HttpRequest> &object) {
Nan::HandleScope scope;
Local<ObjectTemplate> local_prototype = Nan::New(HttpRequest_prototype);
Handle<Object> obj;
if(!local_prototype.IsEmpty())
{
obj = local_prototype->NewInstance();
NJSHttpRequest *new_obj = new NJSHttpRequest(object);
if(new_obj)
{
new_obj->Wrap(obj);
new_obj->Ref();
}
}
else
{
Nan::ThrowError("NJSHttpRequest::wrap: object template not valid");
}
return obj;
}
NAN_METHOD(NJSHttpRequest::isNull) {
NJSHttpRequest* obj = Nan::ObjectWrap::Unwrap<NJSHttpRequest>(info.This());
auto cpp_implementation = obj->getCppImpl();
auto isNull = !cpp_implementation ? true : false;
return info.GetReturnValue().Set(Nan::New<Boolean>(isNull));
}
void NJSHttpRequest::Initialize(Local<Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> func_template = Nan::New<FunctionTemplate>(NJSHttpRequest::New);
Local<ObjectTemplate> objectTemplate = func_template->InstanceTemplate();
objectTemplate->SetInternalFieldCount(1);
func_template->SetClassName(Nan::New<String>("NJSHttpRequest").ToLocalChecked());
//SetPrototypeMethod all methods
Nan::SetPrototypeMethod(func_template,"getMethod", getMethod);
Nan::SetPrototypeMethod(func_template,"getHeaders", getHeaders);
Nan::SetPrototypeMethod(func_template,"getBody", getBody);
Nan::SetPrototypeMethod(func_template,"getUrl", getUrl);
Nan::SetPrototypeMethod(func_template,"complete", complete);
//Set object prototype
HttpRequest_prototype.Reset(objectTemplate);
Nan::SetPrototypeMethod(func_template,"isNull", isNull);
//Add template to target
target->Set(Nan::New<String>("NJSHttpRequest").ToLocalChecked(), func_template->GetFunction());
}
| 32.736626 | 133 | 0.684098 | kodxana |
c410f0432ed40acfb602906bd40567884995f094 | 4,384 | hxx | C++ | src/B200Control.hxx | kb1vc/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 14 | 2017-10-27T16:01:05.000Z | 2021-03-16T08:12:42.000Z | src/B200Control.hxx | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 11 | 2017-09-16T03:13:11.000Z | 2020-12-11T09:11:35.000Z | src/B200Control.hxx | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 6 | 2017-09-13T12:47:43.000Z | 2020-12-02T20:54:25.000Z | /*
Copyright (c) 2015, Matthew H. Reilly (kb1vc)
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.
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
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef B200Serial_HDR
#define B200Serial_HDR
#include "TRControl.hxx"
#include "IPSockets.hxx"
#include <string>
#include <list>
#include <boost/format.hpp>
#include <iostream>
#include <uhd/usrp/multi_usrp.hpp>
namespace SoDa {
/**
* @brief B2xxy-z subtypes for simplified usage (DD0VS)
*
* This is a workaraound, to integrate B200mini (Sept 2019) into
* SoDaRadio.
* All specific action for B200/B210/B2xx are not carried out for
* B200mini.
* On specific places special care will be taken for B200mini only.
* In a first attempt TX/RX relay switching will be implemented via
* B200mini GPIO pin. Today (16th of Feb 2020, all versions of B2xx
* have GPIOs). To avoid interferences with the original code only
* B200mini specific actions will be carried, the others are kept
* functional.
*/
typedef enum {
eB200, // e = enum; B200 seems to be defined somewhere else
eB210,
eB200mini,
eB200mini_i,
eB205mini_i
} SoDa_B200_type_t;
/**
* @brief Transmit/Receive switch control for B200/B210 via the
* FX3 debug GPIO pins.
*
* This module requires a special version of the B2x0 fpga firmware.
*
* On TRANSMIT, pin 1 of J400 will be pulled HIGH. On RECEIVE
* pin 1 of J400 will be pulled LOW.
* On TRANSMIT, pin 3 of J400 will be pulled LOW. On RECEIVE
* pin 1 of J400 will be pulled HIGH.
*/
class B200Control : public TRControl {
public:
/**
* @brief constructor
* @param usrp a pointer to the radio object
* @param mboard which B200 object in the usrp
*
*/
B200Control(uhd::usrp::multi_usrp::sptr usrp, int mboard = 0);
/**
* @brief activate external controls to enable transmit mode.
* @return true if the operation completed successfully
*/
bool setTXOn();
/**
* @brief activate external controls to disable transmit mode.
* @return true if the operation completed successfully
*/
bool setTXOff();
/**
* @brief report state of transmit-enable.
* @return true iff the transmitter is currently enabled.
*/
bool getTX();
/**
* @brief turn on/off signal path for selected band
* note that multiple bands can be enabled at one time(!)
*
* @param band band selector (typically index from 1...7)
* @param state true to enable band, false otherwise.
* @return true if band state was changed.
*/
bool setBand(unsigned int band, bool state);
/**
* @brief query state of signal path for selected band
*
* @param band band selector (typically index from 1...7)
* @return true if band signal path is enabled.
*/
bool getBand(unsigned int band);
private:
bool sendCommand(const std::string & cmd, int retry_count);
uhd::usrp::multi_usrp::sptr usrp;
int mboard;
SoDa_B200_type_t B200_type; //see comment above
std::string modelname; //is redundant, but used for simpler programming
};
}
#endif
| 33.465649 | 76 | 0.697765 | kb1vc |
c414c54065c421c49d58c31d44f944112adfe4a8 | 689 | cpp | C++ | experiments/InternalOscillatorCalibration/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 4 | 2016-12-10T13:20:52.000Z | 2019-10-25T19:47:44.000Z | experiments/InternalOscillatorCalibration/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | null | null | null | experiments/InternalOscillatorCalibration/src/main.cpp | chacal/arduino | 6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd | [
"Apache-2.0"
] | 1 | 2019-05-03T17:31:38.000Z | 2019-05-03T17:31:38.000Z | #include "Arduino.h"
int initialValue = OSCCAL;
void setup() {
OSCCAL = 152;
Serial.begin(115200);
Serial.print("Factory OSCCAL value: ");
Serial.println(initialValue);
delay(1000);
int start = initialValue - 30;
int end = initialValue + 30;
for(int i = start; i <= end; i++) {
OSCCAL = i;
Serial.print("Trying value ");
Serial.println(OSCCAL);
delay(30);
}
OSCCAL = 152;
Serial.print("Trying value ");
Serial.println(OSCCAL);
Serial.println("Done!");
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13,!digitalRead(13));// Turn the LED from off to on, or on to off
delay(10000); // Wait for 1 second (1000 milliseconds)
}
| 20.264706 | 80 | 0.63135 | chacal |
c41ad1f3189dbe817d84577affcaa45b525c0d2d | 7,028 | cpp | C++ | src/WMIMapper/WMIProvider/WMIAssociatorProvider.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | null | null | null | src/WMIMapper/WMIProvider/WMIAssociatorProvider.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | null | null | null | src/WMIMapper/WMIProvider/WMIAssociatorProvider.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | 1 | 2022-03-07T22:54:02.000Z | 2022-03-07T22:54:02.000Z | //%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Barbara Packard (barbara_packard@hp.com)
//
// Modified By:
//
//%/////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider.cpp: implementation of the WMIAssociatorProvider class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "WMICollector.h"
#include "WMIBaseProvider.h"
#include "WMIClassProvider.h"
#include "WMIInstanceProvider.h"
#include "WMIAssociatorProvider.h"
#include "WMIProperty.h"
#include "WMIString.h"
#include "WMIValue.h"
#include "WMIQualifier.h"
#include "WMIQualifierSet.h"
#include "WMIType.h"
#include "WMIException.h"
//////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider::
//
// ///////////////////////////////////////////////////////////////////////////
PEGASUS_NAMESPACE_BEGIN
/////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
WMIAssociatorProvider::WMIAssociatorProvider()
{
_collector = NULL;
m_bInitialized = false;
}
WMIAssociatorProvider::~WMIAssociatorProvider()
{
cleanup();
}
//////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider::associators
//
// NOTE: This method sets up the query string and then calls
// WMIBaseProvider::execCIMQuery
//////////////////////////////////////////////////////////////////////////////
Array<CIMObject> WMIAssociatorProvider::associators(
const String& nameSpace,
const String& userName,
const String& password,
const CIMObjectPath& objectName,
const String& assocClass,
const String& resultClass,
const String& role,
const String& resultRole,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
String sQuery;
String sQueryLanguage;
Array<CIMObject> objects;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIAssociatorProvider::associators()");
sQueryLanguage = qString(Q_WQL);
sQuery = getAssocQueryString(objectName,
assocClass,
resultClass,
role,
resultRole);
objects = execCIMQuery(nameSpace,
userName,
password,
sQueryLanguage,
sQuery,
propertyList,
includeQualifiers,
includeClassOrigin);
PEG_METHOD_EXIT();
return objects;
}
//////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider::associatorNames
//
// ///////////////////////////////////////////////////////////////////////////
Array<CIMObjectPath> WMIAssociatorProvider::associatorNames(
const String& nameSpace,
const String& userName,
const String& password,
const CIMObjectPath& objectName,
const String& assocClass,
const String& resultClass,
const String& role,
const String& resultRole)
{
Array<CIMObject> objects;
Array<CIMObjectPath> objectNames;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIAssociatorProvider::associatorNames()");
// create an empty property list to save time...
Array<CIMName> propNames;
CIMPropertyList propertyList(propNames);
// now get the objects
objects = associators( nameSpace,
userName,
password,
objectName,
assocClass,
resultClass,
role,
resultRole,
false,
false,
propertyList);
// now get the names from the object
Uint32 size = objects.size();
Uint32 i;
//check if namespace is remote
CIMNamespaceName oNamespace(nameSpace);
String strNamespace = oNamespace.getString();
String strNamespaceLower = strNamespace;
strNamespaceLower.toLower();
String strRemotePrefix = "";
if (strNamespaceLower.subString(0, 4) != "root")
{
Uint32 uiPos = strNamespaceLower.find("root");
if (uiPos == PEG_NOT_FOUND)
throw CIMException(CIM_ERR_FAILED);
strRemotePrefix = strNamespace.subString(0, uiPos);
}
for (i=0; i<size; i++)
{
CIMObjectPath oObjectPath = objects[i].getPath();
if (strRemotePrefix != "")
{
strNamespace = strRemotePrefix;
oNamespace = strNamespace.append(oObjectPath.getNameSpace().getString());
oObjectPath.setNameSpace(oNamespace);
}
objectNames.append(oObjectPath);
}
PEG_METHOD_EXIT();
return objectNames;
}
//////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider
// private methods
//
// ///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// WMIAssociatorProvider::getAssocQueryString - calls the BaseProvider method
// to build the query string from the input parameters
//
// ///////////////////////////////////////////////////////////////////////////
String WMIAssociatorProvider::getAssocQueryString(const CIMObjectPath &objectName,
const String &assocClass,
const String &resultClass,
const String &role,
const String &resultRole)
{
String sQuery;
sQuery = qString(Q_ASSOCIATORS);
return getQueryString(objectName, sQuery, assocClass, resultClass, role, resultRole);
}
PEGASUS_NAMESPACE_END
| 30.960352 | 86 | 0.601736 | ncultra |
c41b4b5918c025516f31de6bedf75081b80944b7 | 4,667 | cc | C++ | src/ts_date.cc | viild/Timestamp | 9eefb7246bfc454b9f078f572ba17c54dbeea41a | [
"Apache-2.0"
] | null | null | null | src/ts_date.cc | viild/Timestamp | 9eefb7246bfc454b9f078f572ba17c54dbeea41a | [
"Apache-2.0"
] | null | null | null | src/ts_date.cc | viild/Timestamp | 9eefb7246bfc454b9f078f572ba17c54dbeea41a | [
"Apache-2.0"
] | null | null | null | #include "ts_date.h"
#include <iostream>
namespace timestamp {
/**
* Date - class constructor
* @_date_separator: date separator specifier
* @_date_format: date format specifier
*
* This constructor creates an object of the Date class. This also sets variables
* date_separator and date_format by values given by an user.
*/
Date::Date(const DateSeparator & _date_separator, const DateFormat & _date_format) :
date_separator(_date_separator), date_format(_date_format)
{}
/**
* Get - return date in specific format
*
* This method forms string with current date in format defined by "date_format"
* and "date_separator" and then returns it.
*/
const std::string Date::Get() const
{
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t(now);
tm local_tm = *localtime(&tt);
int day = local_tm.tm_mday;
int month = local_tm.tm_mon + 1;
int year = local_tm.tm_year + 1900;
std::stringstream string_stream;
switch (this->date_format) {
case timestamp::Date::DateFormat::DMY:
switch (this->date_separator) {
case timestamp::Date::DateSeparator::DASH:
string_stream << AuxStamp::PlaceTwoDigits(day) << "-"
<< AuxStamp::PlaceTwoDigits(month) << "-"
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
case timestamp::Date::DateSeparator::DOT:
string_stream << AuxStamp::PlaceTwoDigits(day) << "."
<< AuxStamp::PlaceTwoDigits(month) << "."
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
case timestamp::Date::DateSeparator::SLASH:
string_stream << AuxStamp::PlaceTwoDigits(day) << "/"
<< AuxStamp::PlaceTwoDigits(month) << "/"
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
default:
return "";
}
;
break;
case timestamp::Date::DateFormat::MDY:
switch (this->date_separator) {
case timestamp::Date::DateSeparator::DASH:
string_stream << AuxStamp::PlaceTwoDigits(month) << "-"
<< AuxStamp::PlaceTwoDigits(day) << "-"
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
case timestamp::Date::DateSeparator::DOT:
string_stream << AuxStamp::PlaceTwoDigits(month) << "."
<< AuxStamp::PlaceTwoDigits(day) << "."
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
case timestamp::Date::DateSeparator::SLASH:
string_stream << AuxStamp::PlaceTwoDigits(month) << "/"
<< AuxStamp::PlaceTwoDigits(day) << "/"
<< AuxStamp::PlaceFourDigits(year);
return string_stream.str();
default:
return "";
}
;
break;
case timestamp::Date::DateFormat::YMD:
switch (this->date_separator) {
case timestamp::Date::DateSeparator::DASH:
string_stream << AuxStamp::PlaceFourDigits(year) << "-"
<< AuxStamp::PlaceTwoDigits(day) << "-"
<< AuxStamp::PlaceTwoDigits(month);
return string_stream.str();
case timestamp::Date::DateSeparator::DOT:
string_stream << AuxStamp::PlaceFourDigits(year) << "."
<< AuxStamp::PlaceTwoDigits(day) << "."
<< AuxStamp::PlaceTwoDigits(month);
return string_stream.str();
case timestamp::Date::DateSeparator::SLASH:
string_stream << AuxStamp::PlaceFourDigits(year) << "/"
<< AuxStamp::PlaceTwoDigits(day) << "/"
<< AuxStamp::PlaceTwoDigits(month);
return string_stream.str();
default:
return "";
}
;
break;
default:
return "";
};
}
} // namespace timestamp
| 42.816514 | 84 | 0.501393 | viild |
c42248c19c9cc378643079329c525eae88ba2b59 | 650 | cpp | C++ | cells.cpp | mdyring/tumor_phenotyping | dcc5ee38bc56128d649759b96a2f984b54375d18 | [
"MIT"
] | null | null | null | cells.cpp | mdyring/tumor_phenotyping | dcc5ee38bc56128d649759b96a2f984b54375d18 | [
"MIT"
] | null | null | null | cells.cpp | mdyring/tumor_phenotyping | dcc5ee38bc56128d649759b96a2f984b54375d18 | [
"MIT"
] | null | null | null | #include "cells.hpp"
double distance(cell_ptr_type const& cell, cell_ptr_type const& candidate)
{
std::int64_t const x_distance(cell->x - candidate->x);
std::int64_t const y_distance(cell->y - candidate->y);
return std::sqrt((x_distance * x_distance) + (y_distance * y_distance));
}
void nearest(cell_ptr_type const& cell, cells_type const& candidates, double& nearest_distance, cell_ptr_type& nearest_cell)
{
for(auto const& candidate: candidates)
{
double const candidate_distance(distance(cell, candidate));
if(candidate_distance < nearest_distance)
{
nearest_distance = candidate_distance;
nearest_cell = candidate;
}
}
}
| 27.083333 | 124 | 0.750769 | mdyring |
c42518839cae6410547324002541980702a5a16f | 5,739 | cpp | C++ | empirical-analyses-sort-algorithms/src/timing_template.cpp | fernando-ff/EDB | d87fadb58623f71d028ba2b3434a4b59a94be694 | [
"MIT"
] | null | null | null | empirical-analyses-sort-algorithms/src/timing_template.cpp | fernando-ff/EDB | d87fadb58623f71d028ba2b3434a4b59a94be694 | [
"MIT"
] | null | null | null | empirical-analyses-sort-algorithms/src/timing_template.cpp | fernando-ff/EDB | d87fadb58623f71d028ba2b3434a4b59a94be694 | [
"MIT"
] | null | null | null | /*!
* This is a template code to demonstrate how to measure runtime of part of your code.
* I'm using the chrono C++ library.
* @date September 8th, 2020.
* @author Selan
*/
#include <iostream>
#include "../include/sorting.h"
using namespace sa;
using namespace scenario;
int main(int argc, char* argv[])
{
unsigned int limit_sample { 100000 };// limit sample
if(argc > 1)
{
if(strcmp(argv[1],"--help") == 0)// Reading command line arguments
{
render::help();
return EXIT_SUCCESS;
}
else
limit_sample = std::stoi(argv[1]);
}
unsigned int* arr = new unsigned int[1000000]; //array that will contain the samples
// unsigned long int sample { 10000 }; // default sample value
unsigned long int sample { 1000 };
unsigned long int sample_backup { sample };
unsigned short int indx_algth { 0 };//index of algorithm analyses
unsigned short int indx_scn { 0 };// index of scenario analyses
std::chrono::duration<double> avarege_time;
std::chrono::duration<double> avarege_time_backup;
std::string file_path[6]
{
"../data/1-scenario/",
"../data/2-scenario/",
"../data/3-scenario/",
"../data/4-scenario/",
"../data/5-scenario/",
"../data/6-scenario/"
};
std::string files_name[7]
{
"insertion_sort.data",
"selection_sort.data",
"bublle_sort.data",
"shell_sort.data",
"quick_sort.data",
"merge_sort.data",
"radix sort"
};
unsigned short int execution { 1 };// counter of executions
std::string algorithm_name[7]
{
"Insertion Sort",
"Selection Sort",
"Bubble Sort",
"Shell Sort",
"Quick Sort",
"Merge Sort",
"Radix Sort"
};
void (*scenario_functions[6]) (array_type * first, array_type *last);
scenario_functions[0] = first;
scenario_functions[1] = second;
scenario_functions[2] = third;
scenario_functions[3] = fourth;
scenario_functions[4] = fifth;
scenario_functions[5] = sixth;
void (*sort_algorithms[7]) (value_type *first, value_type * last);
sort_algorithms[0] = insertion;
sort_algorithms[1] = selection;
sort_algorithms[2] = bubble;
sort_algorithms[3] = shell;
sort_algorithms[4] = quicksort;
sort_algorithms[5] = mergesort;
sort_algorithms[6] = radix;
bool open_file { false };
char input_file;
unsigned short input;
render::intro();
while (true)
{
render::guide();
std::cin.clear();
std::cin >> input;
indx_algth = input;
if(indx_algth == 8)
break;
render::open_file_guide();
std::cin.clear();
std::cin>> input_file;
if(input_file == 'y')
open_file = true;
else
open_file = false;
auto start_all_analyses = std::chrono::steady_clock::now();
indx_scn = 0;
std::ofstream file;
while(indx_scn < 6)
{
if(open_file)
{
file.open(file_path[indx_scn] + files_name[indx_algth]);
std::cout << ">>> File name: " << file_path[indx_scn] + files_name[indx_algth] << std::endl;
if(file.is_open())
{
std::cout << ">>> Open with sucess!" << std::endl;
std::cout << "This will cost a time, so... make a coffe, read a book! And after look here!" << std::endl;
}
else
{
std::cout << ">>> We cannot open this file, I'm sorry" << std::endl;
std::cout << " Try again!" << std::endl;
return EXIT_SUCCESS;
}
}
sample = sample_backup;
while( sample <= limit_sample)
{
avarege_time = avarege_time_backup;
execution = 1;
while(execution <= 50)
{
(*scenario_functions[indx_algth]) (arr, arr+sample);
auto start = std::chrono::steady_clock::now();
(*sort_algorithms[indx_algth]) (arr, arr+sample);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> time_taken = end - start;
// render::body( sample,time_taken, algorithm_name[indx_algth], execution, indx_scn+1);
avarege_time += ((time_taken - avarege_time)/execution);
execution++;
}
render::body( sample,avarege_time, algorithm_name[indx_algth], execution, indx_scn+1);
file << sample << "\t" << std::chrono::duration <double, std::milli> (avarege_time).count() << std::endl;;
sample += 4 * 1000;
}
file.close();
indx_scn++;
}
auto end_all_analyses = std::chrono::steady_clock::now();
std::chrono::duration<double> time_taken_all_analyses = end_all_analyses - start_all_analyses;
std::cout << "\nAll analyses costed [" << std::chrono::duration <double, std::milli> (time_taken_all_analyses).count() << "]" << std::endl;
std::cout << "Inital Sample: " << sample << " " << " Limit Sample: " << limit_sample <<"\n"<< std::endl;
std::cin.sync();
}
std::cout << "\nBye bye! ;D" << std::endl;
return EXIT_SUCCESS;
}
| 32.241573 | 147 | 0.520822 | fernando-ff |
c427e994ecf404db3580dad5752fd8d515da6ca9 | 929 | cpp | C++ | Infinity Runner/Motor2D/Button.cpp | DavidTello1/IDI-game | db242c47389a6219f50fde68a4b475fe9262033e | [
"MIT"
] | null | null | null | Infinity Runner/Motor2D/Button.cpp | DavidTello1/IDI-game | db242c47389a6219f50fde68a4b475fe9262033e | [
"MIT"
] | null | null | null | Infinity Runner/Motor2D/Button.cpp | DavidTello1/IDI-game | db242c47389a6219f50fde68a4b475fe9262033e | [
"MIT"
] | null | null | null | #include "Button.h"
Button::Button()
{
initial_pos = { 0,0 };
position = { 0,0 };
state = IDLE;
type = UIType::BUTTON;
action = NO_ACTION;
parent = nullptr;
callback = nullptr;
visible = true;
color = GREY;
movable = false;
is_moving = false;
}
Button::Button(iPoint pos,const Button & b,ActionType action, UIElement* parent) : UIElement(b.type, parent, b.visible)
{
this->initial_pos = pos;
this->position = pos;
this->state = IDLE;
this->action = action;
this->callback = b.callback;
this->rect[IDLE] = b.rect[IDLE];
this->rect[HOVER] = b.rect[HOVER];
this->rect[CLICK_DOWN] = b.rect[CLICK_DOWN];
this->rect[CLICK_UP] = b.rect[CLICK_UP];
this->color = b.color;
}
void Button::HandleAction()
{
switch (action)
{
case JUMP:
App->entitycontroller->want_jump = true;
break;
case SLIDE:
App->entitycontroller->want_slide = true;
break;
}
}
| 18.58 | 119 | 0.629709 | DavidTello1 |
c42afb3fa52986dae505e3caccfae1a6374c7b86 | 2,154 | cpp | C++ | LEDSignToolKit/LEDSignToolKit/LogFile.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | null | null | null | LEDSignToolKit/LEDSignToolKit/LogFile.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | null | null | null | LEDSignToolKit/LEDSignToolKit/LogFile.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | 1 | 2020-06-13T08:34:26.000Z | 2020-06-13T08:34:26.000Z |
#include "stdafx.h"
char _szLogFilePath[MAX_PATH] = _T("");
bool _bEnableLogFile = TRUE;
#define MAX_LOG_FILE_SIZE (10*1024*1024)
void LOG_TO_FILE(const char* szMsg, ... )
{
int nBuf;
CFile file;
BOOL result=FALSE;
TCHAR szLog[MAX_PATH];
TCHAR szBuffer[MAX_PATH];
SYSTEMTIME time;
DWORD dwFileSize = 0;
TCHAR szPath[MAX_PATH] = _T("");
try{
GetLocalTime(&time);
if (_bEnableLogFile){
#ifdef _UNICODE
swprintf(szPath,_T("%s%02d%02d%02d.log"),_szLogFilePath,time.wYear,time.wMonth,time.wDay);
result=file.Open(szPath,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);
#else
sprintf(szPath,"%s%02d%02d%02d.log",_szLogFilePath,time.wYear,time.wMonth,time.wDay);
result=file.Open(szPath,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);
#endif
if (result){
dwFileSize = file.SeekToEnd();
if (dwFileSize > MAX_LOG_FILE_SIZE)
{
file.Flush();
file.Close();
file.Open(szPath,CFile::modeCreate|CFile::modeReadWrite);
}
}
}
va_list args;
va_start(args, szMsg);
nBuf = _vsntprintf(szBuffer, sizeof(szBuffer), szMsg, args);
va_end(args);
#ifdef _UNICODE
swprintf(szLog,_T("[%02d:%02d:%02d]- %s\r\n"),time.wHour,time.wMinute,time.wSecond,szBuffer);
char szTemp[MAX_PATH];
UnicodeToMultiByte(szTemp,sizeof(szTemp),szLog);
if (_bEnableLogFile){
if (result){
file.Write(szTemp,strlen(szTemp)+1);
}
}
#else
sprintf(szLog,_T("[%02d:%02d:%02d]- %s\r\n"),time.wHour,time.wMinute,time.wSecond,szBuffer);
if (_bEnableLogFile){
if (result){
file.Write(szLog,strlen(szLog)+1);
}
}
#endif
if (_bEnableLogFile){
if (result){
file.Close();
}
}
TRACE(szLog);
}
catch( CMemoryException* e ){
TCHAR szError[MAX_PATH];
e->GetErrorMessage(szError,sizeof(szError),0);
TRACE(szError);
}
catch( CFileException* e ){
TCHAR szError[MAX_PATH];
e->GetErrorMessage(szError,sizeof(szError),0);
TRACE(szError);
}
catch( CException* e ){
TCHAR szError[MAX_PATH];
e->GetErrorMessage(szError,sizeof(szError),0);
TRACE(szError);
}
// end of LOG_FILE
}
| 24.477273 | 96 | 0.665738 | cuongquay |
c42b6a0e93098a30341ca88730d5da4230d28d46 | 1,839 | cpp | C++ | core/src/attribute/attr_op_ctx.cpp | qf6101/algorithm-components | f7307e4bd9697ee473d5763e0a61df7891b699f6 | [
"Apache-2.0"
] | 2 | 2019-11-27T11:43:45.000Z | 2020-11-09T09:21:23.000Z | core/src/attribute/attr_op_ctx.cpp | qf6101/algorithm-components | f7307e4bd9697ee473d5763e0a61df7891b699f6 | [
"Apache-2.0"
] | null | null | null | core/src/attribute/attr_op_ctx.cpp | qf6101/algorithm-components | f7307e4bd9697ee473d5763e0a61df7891b699f6 | [
"Apache-2.0"
] | 2 | 2019-12-16T18:54:17.000Z | 2020-02-24T07:52:24.000Z | //
// Created by qfeng on 2019-01-08.
//
#include "attribute/attr_op_ctx.h"
namespace algocomp {
bool AttrOpCtx::parse_patterns(const string in_aname, const string out_gname, const string out_fname,
const string proc_desc, const string param_desc) {
// Check the lengths of inputs (necessary inputs must not be empty)
if (in_aname.length() == 0 || out_gname.length() == 0 || out_fname.length() == 0) {
_logger->error("Parsed empty attribute patterns (in_aname = {}, out_gname = {}, out_fname = {}).", in_aname,
out_gname, out_fname);
return false;
}
// Assign input attribute name
_in_aname = in_aname;
// Parse output feature group name
if (out_gname[0] == '=') {
_out_gname = _in_aname;
} else {
_out_gname = out_gname;
}
// Parse generation pattern of output feature name
if (out_fname[0] == '=') {
_gen_out_fname = _GEN_OUT_FNAME::EQ_OUT_GNAME;
} else if (out_fname[0] == '%') {
_gen_out_fname = _GEN_OUT_FNAME::EX_OUT_GNAME_WITH_VAL;
} else {
_logger->error("Parsed unknown out_fname {}", out_fname);
}
// Parse processes together with their parameters
if (!parse_procs_and_params(proc_desc, param_desc)) {
_logger->error("Parsed wrong procs and params (proc_desc={}, param_desc={}).", proc_desc, param_desc);
return false;
}
// Check if the necessary information is parsed
if (_gen_out_fname == _GEN_OUT_FNAME::UNKNOWN) {
_logger->error("Parsed unknown out_fname generation configuration.");
return false;
}
// Everything is OK
return true;
}
}
| 34.055556 | 120 | 0.578575 | qf6101 |
c42bd72bc949eae469cdb64fb79257ba0a6f03c7 | 337 | cpp | C++ | B/B463.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | B/B463.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | B/B463.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int sum = 0,prev = 0,n,curr,mx = -1;
cin>>n;
for(int i=0;i<n;i++){
cin>>curr;
mx = max(mx, curr);
sum+=(prev - curr);
prev = curr;
}
if(-mx < sum){
cout<<mx<<endl;
}else{
cout<<(-sum)<<endl;
}
return 0;
} | 18.722222 | 40 | 0.445104 | Darknez07 |
c42ef21b974a5abebada1141571cd117b3940722 | 6,072 | hpp | C++ | src/rank-tree.hpp | jcipar/stack-distance | 641aab09fcde746dd1cd0d5f05c4aeac841ac0ce | [
"MIT"
] | 23 | 2015-04-22T19:50:01.000Z | 2021-12-14T03:15:28.000Z | src/rank-tree.hpp | jcipar/stack-distance | 641aab09fcde746dd1cd0d5f05c4aeac841ac0ce | [
"MIT"
] | 2 | 2015-12-03T01:57:57.000Z | 2017-08-02T10:35:16.000Z | src/rank-tree.hpp | jcipar/stack-distance | 641aab09fcde746dd1cd0d5f05c4aeac841ac0ce | [
"MIT"
] | 7 | 2015-04-24T18:50:05.000Z | 2021-09-01T22:26:16.000Z | #ifndef __RANK_TREE_H__
#define __RANK_TREE_H__
#define __STDC_LIMIT_MACROS
#include <cstdint>
#include <set>
#include <string>
using namespace std;
class RankTree;
class RankTreeNode;
/*
This file contains two classes that implement a treap-based
RankTree. A RankTree is an unsorted (i.e. not sorted by the values
of the data) binary tree augmented with parent pointers and
weights. The weight of a node is the number of nodes rooted at that
subtree.
Using this extra data, the tree can be viewed as a vector that
supports the following operations efficiently:
- Insert(node, i): insert a new node at position i.
- Get(i): get the node at position i.
- GetLast(i): get the last node.
- Remove(i): remove the node at position i.
- Rank(node): find the position of the node in the tree.
Note that Rank() is *not* finding the position of a node in the tree
with matching data, as in a binary search tree. The node must be a
pointer to an actual element of the tree (generally one returned by
Get().
For purposes of this program only a subset of these operations are
supported, though the tree could be easily extended to support the
more general set of operations. These are the supported operations:
- Insert(node or string): insert at position 0, i.e. Insert(_, i).
- First(): i.e. Get(0).
- GetLast()
- Remove(node)
- Rank(node)
*/
class RankTreeNode {
friend class RankTree;
public:
// Rank() gives the number of nodes in the tree with a lower
// position (in standard tree traversal order) than this one. Runs
// in O(lg n) time.
int64_t Rank();
void setWeight(uint64_t weight);
// ~RankTreeNode() deletes the node's children, recursively
// freeing the tree.
~RankTreeNode();
private:
string _name;
int64_t _subtreeWeight;
uint64_t _weight;
int _priority;
RankTreeNode* _left;
RankTreeNode* _right;
RankTreeNode* _parent;
// RankTreeNode() constructs a new node with the given name.
RankTreeNode(string name, uint64_t weight);
bool leaf(); // leaf() indicates that this node is a leaf.
bool root(); // root() indicates that this node is the root.
// leftChild() and rightChild() indicate that this node is the
// left (or right) child of its parent.
bool leftChild();
bool rightChild();
// leftWeight() and rightWeight() get the weight of the left (or
// right child of this node. If the child doesn't exist, they
// return 0.
int64_t leftWeight();
int64_t rightWeight();
// print() recursively prints the nodes, indenting each node to
// indicate its level in the tree.
void print(int level);
// fixWeights() recursively (up the tree, following parent
// pointers) fixes the weights of nodes after an insertion or
// deletion.
void fixWeights();
// promote() performs a rotation on the parent node to make this
// node closer to the root. It is an error to promote the root.
void promote();
// demote() performs a rotation on this node to make one of its
// children its new parent. If demote() changes the root (i.e. the
// given node was the root), it returns the new root. Otherwise it
// returns nullptr.
RankTreeNode* demote();
// unlink() removes the node from the tree, and calls fixWeights()
// so that the weight invariant is restored. It is an error to
// unlink a non-leaf.
void unlink();
// makeLeaf() demotes the node until it's a leaf. If this causes the
// root to change, it returns the new root.
RankTreeNode* makeLeaf();
// fixPriority() returns true if this node is the new head.
bool fixPriority();
// leftChildRank() and rightChildRank() are called recursively (up
// the tree towards the root) by Rank() to compute the rank of a
// node. Their parameter is the currently computed rank based on
// the subtree. leftChildRank() is called if the current node is a
// left child, rightChildRank() is called if the current node is a
// right child.
int64_t leftChildRank(int64_t);
int64_t rightChildRank(int64_t);
////
//// Check functions
////
// checkWeights() recursively checks that the weight is equal to the
// number of nodes rooted at the given subtree (including the
// current node).
int64_t checkWeights();
// checkPriorities() recursively checks that child nodes' priorities
// are <= their parent nodes' priority.
void checkPriorities(int priority);
// checkParentPointers() recursively checks that each nodes'
// children point back to it.
void checkParentPointers(RankTreeNode* parent);
// checkUniqueness() checks that each node only appears in the tree
// once.
void checkUniqueness(std::set<RankTreeNode*>& ptrs);
size_t computeSize();
};
class RankTree {
public:
// RankTree() constructs a new empty tree.
RankTree();
// Insert() creates a new node with the given name and inserts it
// into the tree. O(lg n)
RankTreeNode* Insert(string name, uint64_t weight);
// InsertNode() inserts the given node into the tree. O(lg n)
void InsertNode(RankTreeNode* node);
// Remove() removes a node from the tree, BUT DOES NOT DELETE THE
// OBJECT. It is now the caller's responsibility to free the
// memory. O(lg n)
void Remove(RankTreeNode* node);
// The following methods are public to ease testing. While they
// are safe to use by other classes, they are not considered part
// of the main public API. Following golang conventions, they're
// given lower case names to indicate this.
// first() returns the first node in the tree. O(lg n)
RankTreeNode* first();
// last() returns the last node in the tree. O(lg n)
RankTreeNode* last();
// print() prints a representation of the tree to stdout.
void print();
// check() verifies the invariants of the tree. E.g. "are parent
// pointers pointing the right place?" "are the heap properties
// maintained?"
void check();
// computeSize() computes the total size of the tree by walking all
// pointers.
int64_t computeSize();
// ~RankTree() frees all nodes still in the tree.
~RankTree();
private:
RankTreeNode* _root;
};
#endif // #ifndef __RANK_TREE_H__
| 30.512563 | 70 | 0.716074 | jcipar |
c431a77079049e64dc2de53094506c3399cfd1ea | 7,501 | cpp | C++ | src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp | hanxingyixue/peridyno | 5c963dae20384f6af7a15866dac0d06adfcba236 | [
"Apache-2.0"
] | 2 | 2022-01-29T08:51:50.000Z | 2022-02-22T12:07:09.000Z | src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp | hanxingyixue/peridyno | 5c963dae20384f6af7a15866dac0d06adfcba236 | [
"Apache-2.0"
] | null | null | null | src/Rendering/GUI/QtGUI/NodeEditor/QtNodeWidget.cpp | hanxingyixue/peridyno | 5c963dae20384f6af7a15866dac0d06adfcba236 | [
"Apache-2.0"
] | null | null | null | #include "QtNodeWidget.h"
#include "Node.h"
#include "NodePort.h"
#include "Common.h"
#include "FInstance.h"
#include "Field.h"
namespace Qt
{
QtNodeWidget::QtNodeWidget(std::shared_ptr<Node> base)
{
mNode = base;
if (mNode != nullptr)
{
//initialize in node ports
auto inputs = mNode->getImportNodes();
auto input_num = inputs.size();
mNodeInport.resize(input_num);
for (int i = 0; i < inputs.size(); i++)
{
mNodeInport[i] = std::make_shared<QtImportNode>(inputs[i]);
}
//initialize out node ports
mNodeExport = std::make_shared<QtExportNode>(base);
int output_fnum = getOutputFields().size();
mFieldExport.resize(output_fnum);
auto fOutputs = getOutputFields();
for (int i = 0; i < fOutputs.size(); i++)
{
mFieldExport[i] = std::make_shared<QtFieldData>(fOutputs[i]);
}
//initialize in ports
int input_fnum = getInputFields().size();
mFieldInport.resize(input_fnum);
auto fInputs = getInputFields();
for (int i = 0; i < fInputs.size(); i++)
{
mFieldInport[i] = std::make_shared<QtFieldData>(fInputs[i]);;
}
}
}
QtNodeWidget::~QtNodeWidget()
{
}
unsigned int
QtNodeWidget::nPorts(PortType portType) const
{
unsigned int result;
if (portType == PortType::In)
{
result = (unsigned int)mNode->getImportNodes().size() + mFieldInport.size();
}
else
{
result = 1 + mFieldExport.size();
}
return result;
}
NodeDataType QtNodeWidget::dataType(PortType portType, PortIndex portIndex) const
{
switch (portType)
{
case PortType::In:
if (portIndex < mNodeInport.size()) {
return NodeDataType{ "port", "port", PortShape::Bullet };
}
else {
auto& inputFields = this->getInputFields();
std::string str = inputFields[portIndex - mNodeInport.size()]->getClassName();
return NodeDataType{ str.c_str(), str.c_str(), PortShape::Point };
}
break;
case PortType::Out:
if (portIndex == 0) {
return NodeDataType{ "port", "port", PortShape::Bullet };
}
else {
auto& outputFields = this->getOutputFields();
std::string str = outputFields[portIndex - 1]->getClassName();
return NodeDataType{ str.c_str(), str.c_str(), PortShape::Point };
}
break;
case PortType::None:
break;
}
return NodeDataType{ "port", "port", PortShape::Point };
}
std::shared_ptr<QtNodeData>
QtNodeWidget::outData(PortIndex port)
{
return port == 0 ? std::static_pointer_cast<QtNodeData>(mNodeExport) : std::static_pointer_cast<QtNodeData>(mFieldExport[port - 1]);
}
// std::shared_ptr<QtNodeData> QtNodeWidget::inData(PortIndex port)
// {
// return port < mNodeInport.size() ? std::static_pointer_cast<QtNodeData>(mNodeInport[port]) : std::static_pointer_cast<QtNodeData>(mFieldInport[port - mNodeInport.size()]);
// }
QString QtNodeWidget::caption() const
{
return dyno::FormatBlockCaptionName(mNode->getClassInfo()->getClassName());
}
QString QtNodeWidget::name() const
{
return QString::fromStdString(mNode->getClassInfo()->getClassName());
}
bool QtNodeWidget::portCaptionVisible(PortType portType, PortIndex portIndex) const
{
Q_UNUSED(portType); Q_UNUSED(portIndex);
return true;
}
QString QtNodeWidget::portCaption(PortType portType, PortIndex portIndex) const
{
switch (portType)
{
case PortType::In:
if (portIndex < mNodeInport.size()) {
return dyno::FormatBlockPortName(mNode->getImportNodes()[portIndex]->getPortName());
}
else {
auto& inputFields = this->getInputFields();
return dyno::FormatBlockPortName(inputFields[portIndex - mNodeInport.size()]->getObjectName());
}
break;
case PortType::Out:
if (portIndex == 0) {
//return dyno::FormatBlockPortName(mNode->getClassInfo()->getClassName());
return dyno::FormatBlockPortName("Out");
}
else {
auto& outputFields = this->getOutputFields();
return dyno::FormatBlockPortName(outputFields[portIndex - 1]->getObjectName());
}
break;
case PortType::None:
break;
}
}
void QtNodeWidget::setInData(std::shared_ptr<QtNodeData> data, PortIndex portIndex)
{
if (!mEditingEnabled)
return;
if (portIndex < mNodeInport.size())
{
auto node_port = std::dynamic_pointer_cast<QtExportNode>(data);
if (node_port != nullptr)
{
auto nd = node_port->getNode();
if (node_port->connectionType() == CntType::Break)
{
//mNodeInport[portIndex]->getNodePort()->removeNode(nd.get());
nd->disconnect(mNodeInport[portIndex]->getNodePort());
//TODO: recover the connection state, use a more elegant way in the future
data->setConnectionType(CntType::Link);
}
else
{
//mNodeInport[portIndex]->getNodePort()->addNode(nd.get());
nd->connect(mNodeInport[portIndex]->getNodePort());
}
}
}
else
{
auto fieldData = std::dynamic_pointer_cast<QtFieldData>(data);
if (fieldData != nullptr)
{
auto field = fieldData->getField();
if (fieldData->connectionType() == CntType::Break)
{
field->disconnect(mFieldInport[portIndex - mNodeInport.size()]->getField());
fieldData->setConnectionType(CntType::Link);
}
else
{
field->connect(mFieldInport[portIndex - mNodeInport.size()]->getField());
}
}
}
updateModule();
}
bool QtNodeWidget::tryInData(PortIndex portIndex, std::shared_ptr<QtNodeData> nodeData)
{
if (!mEditingEnabled)
return false;
if (portIndex < mNodeInport.size())
{
try
{
auto& nodeExp = std::dynamic_pointer_cast<QtExportNode>(nodeData);
if (nodeExp == nullptr)
return false;
auto nodeInp = mNodeInport[portIndex];
return nodeInp->getNodePort()->isKindOf(nodeExp->getNode().get());;
}
catch (std::bad_cast)
{
return false;
}
}
else
{
try
{
auto& fieldExp = std::dynamic_pointer_cast<QtFieldData>(nodeData);
if (fieldExp == nullptr)
return false;
auto fieldInp = mFieldInport[portIndex - mNodeInport.size()];
if (fieldInp->getField()->getClassName() == fieldExp->getField()->getClassName())
{
std::string className = fieldInp->getField()->getClassName();
if (className == dyno::InstanceBase::className())
{
return true;
}
else
return fieldInp->getField()->getTemplateName() == fieldExp->getField()->getTemplateName();
}
else
{
return false;
}
}
catch (std::bad_cast)
{
return false;
}
}
}
NodeValidationState QtNodeWidget::validationState() const
{
return modelValidationState;
}
QtNodeDataModel::ConnectionPolicy QtNodeWidget::portInConnectionPolicy(PortIndex portIndex) const
{
if (portIndex < mNodeInport.size())
{
auto portType = mNodeInport[portIndex]->getNodePort()->getPortType();
return portType == dyno::NodePortType::Single ? ConnectionPolicy::One : ConnectionPolicy::Many;
}
else
{
return ConnectionPolicy::One;
}
}
std::shared_ptr<Node> QtNodeWidget::getNode()
{
return mNode;
}
QString QtNodeWidget::validationMessage() const
{
return modelValidationError;
}
void QtNodeWidget::updateModule()
{
modelValidationState = NodeValidationState::Valid;
}
std::vector<FBase*>& QtNodeWidget::getOutputFields() const
{
return mNode->getOutputFields();
}
std::vector<FBase*>& QtNodeWidget::getInputFields() const
{
return mNode->getInputFields();
}
void QtNodeWidget::enableEditing()
{
mEditingEnabled = true;
}
void QtNodeWidget::disableEditing()
{
mEditingEnabled = false;
}
}
| 22.730303 | 176 | 0.669111 | hanxingyixue |
c43258d612d7a20d4320976bd321012ea237f7f3 | 11,239 | cpp | C++ | car_control/four_wheels/src/stm32.cpp | MingshanHe/hybrid_robot_demo | 49fdd466bc9936acf947a18f2f66348e981360ff | [
"MIT"
] | 2 | 2021-11-18T14:23:35.000Z | 2022-03-16T08:17:16.000Z | car_control/four_wheels/src/stm32.cpp | MingshanHe/hybrid_robot_demo | 49fdd466bc9936acf947a18f2f66348e981360ff | [
"MIT"
] | null | null | null | car_control/four_wheels/src/stm32.cpp | MingshanHe/hybrid_robot_demo | 49fdd466bc9936acf947a18f2f66348e981360ff | [
"MIT"
] | null | null | null | //ROS headers
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/String.h"
#include "sensor_msgs/JointState.h"
#include "std_msgs/Float64MultiArray.h"
#include "std_msgs/Int64MultiArray.h"
#include "nav_msgs/Odometry.h"
#include "sensor_msgs/Range.h"
#include <tf/transform_broadcaster.h>
#include <tf/message_filter.h>
#include "sensor_msgs/Range.h"
//C++ headers
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <cstring>
//custom headers
#include "four_wheels/DeviceState.h"
//int socket(int domain, int type, int protocol);
int sock_cli;
ros::Publisher device_state_pub;
ros::Publisher odom_pub;
ros::Publisher device_raw_pub;
std::string sendBuffer;
std::string recvBuffer;
four_wheels::DeviceState deviceState;
four_wheels::DeviceState last_deviceState;
ros::NodeHandle* node_handle_ptr;
std::vector<ros::Publisher> sonar_pubs;
//parameter server
std::string p_controller_ip_;
int p_controller_port_;
double p_wheel_ratio_;
bool p_provide_odom_frame_;
bool p_provide_odom_topic_;
fd_set rfds;
int retval,maxfd;
struct timeval tv;
bool shutdown_flag;
geometry_msgs::Twist cmdVel,targetCmdVel;
nav_msgs::Odometry odom_msg;
bool odom_received = false;
bool decode()
{
if (recvBuffer.find('~',0)==std::string::npos) return false;
std_msgs::String raw_str;
raw_str.data = recvBuffer;
device_raw_pub.publish(raw_str);
//ROS_INFO("decode %s",recvBuffer.c_str());
while (recvBuffer.find('~',0)!=std::string::npos)
{
char command[100][100];
int cmd_index=0,tmp_index=0;
for (int i =0;i<recvBuffer.length();i++)
{
if (recvBuffer[i] == '~')
{
recvBuffer = recvBuffer.substr(i+1);
break;
}
else
if (recvBuffer[i] == ',')
{
command[cmd_index++][tmp_index]=0;
tmp_index = 0;
}
else
if (recvBuffer[i] == '|')//process command
{
//ROS_INFO("processing request %s",command[0]);
bool illegal = false;
command[cmd_index][tmp_index] = 0;
if (strcmp(command[0],"CONTROLMODE")==0)
{
if (strcmp(command[1],"MANUAL")==0)
{
}
else
if (strcmp(command[1],"AUTO")==0)
{
char str[50];
sprintf(str,"SET_CONTROLMODE,MANUAL|");
sendBuffer.append(str);
}
else
illegal = true;
}
else
if (strcmp(command[0],"BUTTON")==0)
{
if (strcmp(command[1],"EMERSTOPF")==0)
{
if (strcmp(command[2],"T")==0)
{
deviceState.button_emergency = true;
}
if (strcmp(command[2],"F")==0)
{
deviceState.button_emergency = false;
}
}
else
if (strcmp(command[1],"POWER")==0)
{
if (strcmp(command[2],"T")==0)
{
deviceState.button_power = true;
}
if (strcmp(command[2],"F")==0)
{
deviceState.button_power = false;
}
}
}
else
if (strcmp(command[0],"CHARGE")==0)
{
if (strcmp(command[1],"CONTACK")==0)
{
if (strcmp(command[2],"T")==0)
{
deviceState.sen_charger = true;
}
else
{
deviceState.sen_charger = false;
}
}
else
illegal = true;
}
else
if (strcmp(command[0],"STATE")==0)
{
deviceState.state.assign(command[1]);
if(strcmp(command[1],"PAUSE")==0)
{
sendBuffer.append(std::string("SET_STATE,NORMAL|"));//急停后切换到正常状态
std_msgs::String msg;
}
}
else
if (strcmp(command[0],"BATT")==0)
{
if (strcmp(command[1],"N")==0)
{
deviceState.batt_n = std::atoi(command[2]);
if (deviceState.batt_n>100) deviceState.batt_n/=10;
}
else
if (strcmp(command[1],"C")==0)
{
deviceState.batt_c = std::atoi(command[2]);
}
else
if (strcmp(command[1],"V")==0)
{
deviceState.batt_v = std::atoi(command[2]);
}
}
else if(strcmp(command[0],"SONAR")==0)
{
ros::Time time_now = ros::Time::now();
int sonar_size = std::atoi(command[1]);
for(int i = 0;i<sonar_size;i++)
{
char sonar_frame_name[30];
sprintf(sonar_frame_name,"sonar_%d",i);
sensor_msgs::Range sonar_msgs;
sonar_msgs.header.frame_id.assign(sonar_frame_name);
sonar_msgs.header.stamp = time_now;
sonar_msgs.range = std::atoi(command[i+2])/1000.0;
sonar_msgs.min_range = 0.01;
sonar_msgs.max_range = 1.5;
sonar_msgs.radiation_type = 0;
if (sonar_pubs.size()<=i){
sonar_pubs.push_back(node_handle_ptr->advertise<sensor_msgs::Range>(sonar_frame_name,5,false));
}
sonar_pubs[i].publish(sonar_msgs);
}
}
else if (strcmp(command[0],"ODOM2D")==0 || strcmp(command[0],"LOCATION")==0)
{
odom_msg.pose.pose.position.x = std::atoi(command[1])/10000.0;
odom_msg.pose.pose.position.y = std::atoi(command[2])/10000.0;
double theta = std::atoi(command[3])/10000.0;
odom_msg.pose.pose.orientation.w = cos(theta/2);
odom_msg.pose.pose.orientation.z = sin(theta/2);
//if (odom_msg.pose.pose.position.x!=0 || odom_msg.pose.pose.position.y!=0 || theta!=0)
odom_received = true;
}
else
if (strcmp(command[0],"FAULT_CODE")==0)
{
deviceState.fault_code.assign(command[1]);
}
else
if (strcmp(command[0],"FORCEDSHUTDOWN")==0) //已准备强制关机
{
}
else
{
illegal = true;
}
if (illegal)
{
//ROS_ERROR("[cmdvel2stm32] Illegal Command %s,%s,%s from STM32!",command[0],command[1],command[2]);
}
cmd_index = 0;
tmp_index = 0;
}
else
command[cmd_index][tmp_index++] = recvBuffer[i];
}
}
return true;
}
//-----------------receive from com-----------------
void readSocket()
{
const int LEN = 1000;
unsigned char str[LEN+1];
int num;
int read_len=0;
FD_ZERO(&rfds);
FD_SET(sock_cli,&rfds);
maxfd = 0;
if (maxfd< sock_cli)
maxfd = sock_cli;
static int cnt = 0;
retval = select(maxfd+1,&rfds,NULL,NULL,&tv);
if (retval ==-1)
{
ROS_ERROR("Socket select error!\n");
exit(0);
}
else
if (retval ==0)
{
cnt = cnt+1;
if (cnt ==200)
{
ROS_ERROR("Socket no receive\n");
}
if (cnt==400)
{
ROS_ERROR("Closing stm32\n");
shutdown_flag = true;
}
}
else
{
cnt = 0;
if (FD_ISSET(sock_cli,&rfds))
{
memset(str,0,sizeof(str));
int len = recv(sock_cli,str,LEN,0);
str[len] = '\0';
if (len <=0)
{
ROS_ERROR("Socket connection lost!\n");
close(sock_cli);
exit(0);
}
recvBuffer.append(reinterpret_cast<char*>(str));
}
}
}
//ROS callback
void onCmdVel(const geometry_msgs::Twist::ConstPtr& msgs)
{
targetCmdVel=*msgs;
}
void pubControl()
{
char str[200];
sprintf(str,"SET_VA,%d,%d,%d|",int(cmdVel.linear.x*10000),int(cmdVel.linear.y*10000),int(cmdVel.angular.z*10000));
sendBuffer.append(std::string(str));
}
bool socketInit()
{
tv.tv_sec = 0;
tv.tv_usec = 500000;
sock_cli = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(p_controller_port_);
servaddr.sin_addr.s_addr = inet_addr(p_controller_ip_.c_str());
if (connect(sock_cli,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
{
ROS_ERROR("Socket connection error");
exit(0);
}
return true;
}
void initMsg()
{
odom_msg.header.frame_id = "odom";
odom_msg.child_frame_id = "base_link";
const double cov[36] = {
0.5,0,0,0,0,0,
0,0.5,0,0,0,0,
0,0,0.5,0,0,0,
0,0,0,0.5,0,0,
0,0,0,0,0.5,0,
0,0,0,0,0,0.5,
};
for (int i=0;i<36;i++)
{
odom_msg.pose.covariance[i]=cov[i];
odom_msg.twist.covariance[i]=cov[i];
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "cmdvel2stm32");
ros::NodeHandle n;
ros::NodeHandle private_nh("~");
node_handle_ptr = new ros::NodeHandle();
//ROS parameter server
private_nh.param("ip",p_controller_ip_,std::string("192.168.188.5"));
private_nh.param("port",p_controller_port_,2048);
private_nh.param("wheel_ratio",p_wheel_ratio_,10000.0);
private_nh.param("provide_odom_frame",p_provide_odom_frame_,true);
private_nh.param("provide_odom_topic",p_provide_odom_topic_,true);
//subscribers
ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel", 2, onCmdVel);
//publishers
device_state_pub = n.advertise<four_wheels::DeviceState>("device_state",10,true);
odom_pub = n.advertise<nav_msgs::Odometry>("odom", 10);
device_raw_pub = n.advertise<std_msgs::String>("device_raw",2); //底层传过来的原始数据
initMsg();
ros::Rate read_rate(100);
ros::Rate loop_rate(20);
ros::Rate try_connection_rate(0.5);
ROS_INFO("Connecting TCP-STM32");
socketInit();
ROS_INFO("Connected TCP-STM32");
ros::Time last_time = ros::Time::now();
while (ros::ok() && !shutdown_flag)
{
ros::spinOnce();
//发送一次速度
cmdVel.linear.x = (cmdVel.linear.x+targetCmdVel.linear.x)/2;
cmdVel.linear.y = (cmdVel.linear.y+targetCmdVel.linear.y)/2;
cmdVel.angular.z = (cmdVel.angular.z+targetCmdVel.angular.z)/2;
pubControl();
sendBuffer.append("~");
char buf[1000];
strcpy(buf, sendBuffer.c_str());
if (send(sock_cli,buf,sendBuffer.length(),0)<0)
ROS_ERROR("Socket send fail!\n");
else
{
ROS_INFO("Socket sent data:%s",sendBuffer.c_str());
}
sendBuffer.clear();
last_time = ros::Time::now();
do {
readSocket();
read_rate.sleep();
}
while(!decode() && !shutdown_flag && ros::ok());
//odometry
geometry_msgs::TransformStamped transformStamped;
static tf::TransformBroadcaster broadcaster;
if (odom_received)
{
if (p_provide_odom_topic_)
{
odom_msg.header.stamp = ros::Time::now();
odom_msg.header.seq++;
odom_pub.publish(odom_msg);
}
if (p_provide_odom_frame_)
{
transformStamped.header.stamp = ros::Time::now();
transformStamped.header.frame_id = "odom";
transformStamped.child_frame_id = "base_link";
transformStamped.transform.translation.x = odom_msg.pose.pose.position.x;
transformStamped.transform.translation.y = odom_msg.pose.pose.position.y;
transformStamped.transform.translation.z = odom_msg.pose.pose.position.z;
transformStamped.transform.rotation.x = odom_msg.pose.pose.orientation.x;
transformStamped.transform.rotation.y = odom_msg.pose.pose.orientation.y;
transformStamped.transform.rotation.z = odom_msg.pose.pose.orientation.z;
transformStamped.transform.rotation.w = odom_msg.pose.pose.orientation.w;
broadcaster.sendTransform(transformStamped);
}
}
if (last_deviceState!=deviceState)
{
last_deviceState=deviceState;
device_state_pub.publish(deviceState); //向ROS中发送STM32信息
}
loop_rate.sleep();
}
cmdVel.linear.x = 0;
cmdVel.linear.y = 0;
cmdVel.angular.z = 0;
pubControl();
sendBuffer.append("~");
char buf[1000];
strcpy(buf, sendBuffer.c_str());
send(sock_cli,buf,sendBuffer.length(),0);
try_connection_rate.sleep();
ROS_INFO("stm32 closed");
return 0;
}
| 25.25618 | 118 | 0.634309 | MingshanHe |
c43c00bdcc437ef647e6ce9b56c6a0577620bd87 | 317 | hpp | C++ | pds2/vpls/lista_problematica/List.hpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | pds2/vpls/lista_problematica/List.hpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | pds2/vpls/lista_problematica/List.hpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | #ifndef LIST_H
#define LIST_H
#include <iostream>
#include <cstdlib>
struct Node{
int _value;
Node *_next;
};
struct List{
Node *_head;
Node *_toe;
int _size;
List();
void insert(int value);
void remove(int value);
void print();
void clearList();
int removeFirst();
int indexOf(int value);
};
#endif | 12.192308 | 24 | 0.678233 | pganaclara |
c43c3810a2fcb02d8fefa698ad44adb50bc57366 | 469 | hpp | C++ | src/shared/Constants.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | 3 | 2022-01-21T10:38:06.000Z | 2022-02-01T16:44:46.000Z | src/shared/Constants.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | src/shared/Constants.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | #pragma once
#include "common/Constants.hpp"
#include <string_view>
namespace Constants
{
#if SERVER
constexpr std::int32_t MAX_PUSHTICK = 0;
#else
constexpr std::int32_t MAX_PUSHTICK = 125;
#endif
#if !SERVER
constexpr std::int32_t WEP_RESTRICT_WIDTH = 64;
constexpr std::int32_t WEP_RESTRICT_HEIGHT = 64;
constexpr std::int32_t GOS_RESTRICT_WIDTH = 16;
constexpr std::int32_t GOS_RESTRICT_HEIGHT = 16;
#endif
}; // namespace Constants
#include "Constants.cpp.h"
| 19.541667 | 48 | 0.773987 | darkenk |
c43f941882e34e24e3847d5a088a4dd6c6c05ad7 | 1,588 | hpp | C++ | rmf_task/test/mock/MockEvent.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/test/mock/MockEvent.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/test/mock/MockEvent.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2021 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef TEST__MOCK__MOCKEVENT_HPP
#define TEST__MOCK__MOCKEVENT_HPP
#include <rmf_task/Event.hpp>
namespace test_rmf_task {
//==============================================================================
class MockEvent : public rmf_task::Event::State
{
public:
MockEvent(
uint64_t id_,
std::string name_,
std::string detail_,
Status initial_status = Status::Standby);
// Interface
uint64_t id() const final;
Status status() const final;
rmf_task::VersionedString::View name() const final;
rmf_task::VersionedString::View detail() const final;
rmf_task::Log::View log() const final;
std::vector<rmf_task::Event::ConstStatePtr> dependencies() const final;
// Fields
uint64_t _id;
Status _status;
rmf_task::VersionedString _name;
rmf_task::VersionedString _detail;
rmf_task::Log _log;
std::vector<std::shared_ptr<MockEvent>> _dependencies;
};
} // namespace test_rmf_task
#endif // TEST__MOCK__MOCKCONDITION_HPP
| 27.859649 | 80 | 0.702141 | Rouein |
c43f960bc7bc771bbfe611a40384bad0874f9ead | 500 | cpp | C++ | cpp-prime/c3/ex3-17.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | cpp-prime/c3/ex3-17.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | cpp-prime/c3/ex3-17.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by 崔晓晨 on 2019-07-13.
//
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<string> v;
string word;
while (cin >> word) {
cout << word << endl;
v.push_back(word);
}
cout << "input end" << endl;
for (auto &w: v)
for (auto &c: w)
c = toupper(c);
for (decltype(v.size()) i = 0; i < v.size(); i++) {
cout << v[i] << '\t';
if ((i + 1) % 8 == 0)
cout << endl;
}
} | 17.857143 | 55 | 0.448 | XiaochenCui |
c44054490a86b5f2e548ea13a7bc9f615c1c1da2 | 3,403 | cpp | C++ | game/picktransportform.cpp | spiffcode/hostile-takeover | 363c8f7f02c25f90255b28a5e2eaea784b2a502f | [
"BSD-2-Clause-FreeBSD"
] | 113 | 2015-01-07T00:37:37.000Z | 2022-03-08T17:58:24.000Z | game/picktransportform.cpp | ptitSeb/hostile-takeover | db70254a966ca3223178e669594f3b704b5471a2 | [
"BSD-2-Clause-FreeBSD"
] | 6 | 2015-04-13T16:16:00.000Z | 2021-06-08T04:49:09.000Z | game/picktransportform.cpp | spiffcode/hostile-takeover | 363c8f7f02c25f90255b28a5e2eaea784b2a502f | [
"BSD-2-Clause-FreeBSD"
] | 49 | 2015-01-08T04:27:35.000Z | 2022-03-08T04:55:08.000Z | #include "picktransportform.h"
namespace wi {
PickTransportForm::PickTransportForm()
{
m_ptra = NULL;
}
bool PickTransportForm::Init(FormMgr *pfrmm, IniReader *pini, word idf)
{
if (!ShellForm::Init(pfrmm, pini, idf))
return false;
m_ctrad = gtram.GetTransportDescriptions(m_atrad, kctradMax);
LabelControl *plbl =
(LabelControl *)GetControlPtr(kidcNoTransportsAvailable);
if (m_ctrad != 0)
plbl->Show(false);
for (int i = kidcTransport1; i <= kidcTransport6; i++) {
ButtonControl *pbtn = (ButtonControl *)GetControlPtr(i);
if ((i - kidcTransport1) < m_ctrad) {
pbtn->SetText(m_atrad[i - kidcTransport1].szName);
} else {
pbtn->Show(false);
}
}
return true;
}
bool PickTransportForm::DoModal(int *pnResult, bool fAnimate, bool fShowSound)
{
// If there is only one valid transport, don't waste the user's time by
// making them choose it.
if (m_ctrad != 1)
return ShellForm::DoModal(pnResult, fAnimate, fShowSound);
dword result;
m_ptra = OpenTransport(&m_atrad[0], &result);
return m_ptra != NULL;
}
Transport *PickTransportForm::OpenTransport(TransportDescription *ptrad,
dword *result) {
*result = knTransportOpenResultFail;
Transport *ptra = NULL;
{
char szT[64];
sprintf(szT, "OPENING %s...", ptrad->szName);
TransportWaitingUI twui(szT);
*result = ptrad->pfnOpen(ptrad, &ptra);
}
const char *message = NULL;
switch (*result) {
case knTransportOpenResultSuccess:
return ptra;
default:
case knTransportOpenResultFail:
message = "Failure accessing network.";
break;
case knTransportOpenResultNoNetwork:
message = "Please check for network connectivity.";
break;
case knTransportOpenResultCantConnect:
message = "Could not connect to game server.";
break;
case knTransportOpenResultNotResponding:
message = "Timed out waiting for Game server to respond.";
break;
case knTransportOpenResultProtocolMismatch:
message = "Please upgrade to the latest version of Hostile Takeover before playing multiplayer.";
//message = "Please upgrade to the latest version of Hostile Takeover.";
break;
case knTransportOpenResultServerFull:
message = "This server is full. Please try another server.";
break;
}
if (message != NULL) {
HtMessageBox(kfMbWhiteBorder, "Error!", message);
}
return NULL;
}
void PickTransportForm::OnControlSelected(word idc)
{
if (idc == kidcCancel) {
EndForm(idc);
return;
}
dword result;
m_ptra = OpenTransport(&m_atrad[idc - kidcTransport1], &result);
if (m_ptra != NULL) {
EndForm(idc);
}
}
bool PickTransport(Transport **pptra)
{
*pptra = NULL;
PickTransportForm *pfrm = (PickTransportForm *)gpmfrmm->LoadForm(
gpiniForms, kidfPickTransport, new PickTransportForm());
Assert(pfrm != NULL);
if (pfrm == NULL)
return true;
int idc;
pfrm->DoModal(&idc);
*pptra = pfrm->GetTransport();
delete pfrm;
if (gevm.IsAppStopping())
return false;
if (idc == kidcCancel)
return true;
return true;
}
} // namespace wi
| 25.395522 | 105 | 0.624743 | spiffcode |
c44189af9440f3c37acb9d41835c67f360cdebec | 13,746 | cpp | C++ | CBP/CBP/Template.cpp | clayne/CBPSSE | c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5 | [
"MIT"
] | 3 | 2020-06-21T18:10:19.000Z | 2021-02-05T21:33:18.000Z | CBP/CBP/Template.cpp | clayne/CBPSSE | c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5 | [
"MIT"
] | 2 | 2020-08-29T14:29:19.000Z | 2020-09-10T18:40:52.000Z | CBP/CBP/Template.cpp | clayne/CBPSSE | c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5 | [
"MIT"
] | 4 | 2020-08-25T17:56:35.000Z | 2021-11-25T09:39:47.000Z | #include "pch.h"
#include "Template.h"
#include "Drivers/cbp.h"
#include "Drivers/data.h"
#include "Drivers/tasks.h"
namespace CBP
{
ITemplate ITemplate::m_Instance;
ITemplate::ITemplate() :
m_dataPhysics("^[a-zA-Z0-9_\\- ]+$"),
m_dataNode("^[a-zA-Z0-9_\\- ]+$")
{
}
TRecPlugin::TRecPlugin(const fs::path& a_path) :
m_path(a_path)
{
}
bool TRecPlugin::Load()
{
try
{
std::ifstream fs;
fs.open(m_path, std::ifstream::in | std::ifstream::binary);
if (!fs.is_open())
throw std::exception("Could not open file for reading");
Json::Value root;
fs >> root;
if (!root.isObject())
throw std::exception("Root not an object");
if (!root.isMember("plugin"))
throw std::exception("Missing plugin name");
if (!root.isMember("data"))
throw std::exception("Missing data");
auto& pt = root["plugin"];
if (!pt.isString())
throw std::exception("Invalid plugin name");
std::string pluginName(pt.asString());
if (pluginName.size() == 0)
throw std::exception("Plugin name len == 0");
if (pluginName.size() >= sizeof(ModInfo::name))
throw std::exception("Plugin name too long");
//transform(pluginName.begin(), pluginName.end(), pluginName.begin(), ::tolower);
auto& data = root["data"];
if (!data.isObject())
throw std::exception("Invalid data");
decltype(m_data) tmp;
for (auto it1 = data.begin(); it1 != data.end(); ++it1)
{
if (it1->empty())
continue;
if (!it1->isObject())
throw std::exception("Unexpected data (1)");
auto typestr = it1.key().asString();
TRecType type;
if (typestr == "physics")
type = TRecType::Physics;
else if (typestr == "node")
type = TRecType::Node;
else
throw std::exception("Unrecognized data type");
auto& e1 = tmp[type];
for (auto it2 = it1->begin(); it2 != it1->end(); ++it2)
{
if (!it2->isObject())
throw std::exception("Unexpected data (2) (expected object)");
std::string templ(it2.key().asString());
if (templ.empty())
throw std::exception("Zero length template name");
//transform(templ.begin(), templ.end(), templ.begin(), ::tolower);
auto& t = (*it2)["target"];
if (!t.isNumeric())
throw std::exception("Invalid target type");
auto& e2 = e1[templ];
auto type = static_cast<std::uint32_t>(t.asUInt());
switch (type)
{
case 0:
e2.type = TRecTargetType::All;
break;
case 1:
{
auto& v = (*it2)["formids"];
if (!v.isArray())
throw std::exception("Invalid formid list");
for (const auto& e : v) {
if (!e.isNumeric())
throw std::exception("Unexpected formid data (not numeric)");
e2.formids.push_back(static_cast<Game::FormID>(e.asUInt()));
}
e2.type = TRecTargetType::FormIDs;
}
break;
default:
throw std::exception("Unrecognized type");
}
auto& v = (*it2)["gender"];
if (!v.isNull())
{
if (!v.isNumeric())
throw std::exception("Invalid gender specifier");
switch (v.asInt())
{
case -1:
e2.gender = TRecTargetGender::Any;
break;
case 0:
e2.gender = TRecTargetGender::Male;
break;
case 1:
e2.gender = TRecTargetGender::Female;
break;
}
}
}
}
m_pluginName = std::move(pluginName);
m_data = std::move(tmp);
return true;
}
catch (const std::exception& e)
{
m_lastExcept = e;
return false;
}
}
template <class T>
void ProfileManagerTemplate<T>::OnProfileAdd(T& a_profile)
{
//DTasks::AddTask<ITemplate::AddProfileRecordsTask<T>>(a_profile.Name());
ITaskPool::AddTask([name = a_profile.Name()]()
{
IScopedLock _(DCBP::GetLock());
auto& tif = ITemplate::GetSingleton();
tif.AddProfileRecords<T>(name.c_str());
});
}
template <class T>
void ProfileManagerTemplate<T>::OnProfileDelete(T& a_profile)
{
auto& tif = ITemplate::GetSingleton();
tif.DeleteProfileRecords(a_profile);
}
/*template <class T>
ITemplate::AddProfileRecordsTask<T>::AddProfileRecordsTask(
const std::string& a_profileName)
:
m_profileName(a_profileName)
{
}
template <class T>
void ITemplate::AddProfileRecordsTask<T>::Run()
{
IScopedCriticalSection _(DCBP::GetLock());
auto& tif = ITemplate::GetSingleton();
tif.AddProfileRecords<T>(m_profileName.c_str());
}*/
template <class T>
void ITemplate::AddProfileRecords(
const char* a_profileName)
{
const auto& data = GetPluginData();
auto& mm = DData::GetPluginData().GetLookupRef();
auto& dataHolder = GetDataHolder<T>();
auto type = GetRecordType<T>();
for (auto& rec : data)
{
auto it = mm.find(rec.GetPluginName());
if (it == mm.end())
continue;
auto& rd = rec.GetData();
for (auto& e : rd)
{
if (e.first != type)
continue;
ProcessTemplateRecord(
dataHolder,
e.second,
it->second,
a_profileName
);
}
}
}
template <typename T>
void ITemplate::DeleteProfileRecords(T& a_profile)
{
auto& data = GetDataHolder<T>();
auto& mm = data.GetModMap();
auto& fm = data.GetFormMap();
auto addr = std::addressof(a_profile);
auto itmm = mm.begin();
while (itmm != mm.end())
{
if (itmm->second.profile == addr) {
itmm = mm.erase(itmm);
}
else {
++itmm;
}
}
auto itfm = fm.begin();
while (itfm != fm.end())
{
auto& d = itfm->second;
auto itfmn = d.first.begin();
while (itfmn != d.first.end())
{ // TESNPC
if (itfmn->second.profile == addr) {
itfmn = d.first.erase(itfmn);
}
else {
++itfmn;
}
}
auto itfmr = d.second.begin();
while (itfmr != d.second.end())
{ // TESRace
if (itfmr->second.profile == addr) {
itfmr = d.second.erase(itfmr);
}
else {
++itfmr;
}
}
if (d.first.empty() && d.second.empty()) {
itfm = fm.erase(itfm);
}
else {
++itfm;
}
}
}
bool ITemplate::LoadPluginData()
{
try
{
auto& driverConf = DCBP::GetDriverConfig();
fs::path ext(".json");
for (const auto& entry :
fs::directory_iterator(driverConf.paths.templatePlugins))
{
if (!entry.is_regular_file())
continue;
auto& path = entry.path();
if (!path.has_extension() || path.extension() != ext)
continue;
TRecPlugin rec(path);
if (!rec.Load())
{
Error("%s: %s: failed loading plugin data: %s",
__FUNCTION__, path.string().c_str(), rec.GetLastException().what());
continue;
}
m_pluginData.emplace_back(std::move(rec));
}
return true;
}
catch (const std::exception& e)
{
m_lastExcept = e;
return false;
}
}
template <typename T>
void ITemplate::ProcessTemplateRecord(
DataHolder<T>& a_data,
const TRecPlugin::entry_t& a_entry,
const pluginInfo_t& a_modData,
const char* a_profileName) const
{
auto& pm = a_data.GetProfileManager();
auto& mm = a_data.GetModMap();
auto& fm = a_data.GetFormMap();
for (auto& t : a_entry)
{
if (a_profileName) {
if (StrHelpers::icompare(t.first.c_str(), a_profileName) != 0)
continue;
}
auto it = pm.Find(t.first);
if (it == pm.End()) {
Warning("%s: [%s] template profile not found: %s",
__FUNCTION__, a_modData.name.c_str(), t.first.c_str());
continue;
}
UInt32 modIndex = a_modData.GetPartialIndex();
switch (t.second.type)
{
case TRecTargetType::All:
mm.insert_or_assign(
modIndex,
DataHolder<T>::profileData_t(
Enum::Underlying(t.second.gender),
std::addressof(it->second)
)
);
//gLog.Debug("!!>>> %X, %s | %hhd", modIndex, t.first.c_str(), Enum::Underlying(t.second.gender));
break;
case TRecTargetType::FormIDs:
{
for (auto& p : t.second.formids)
{
auto formid = a_modData.GetFormID(p);
auto form = formid.Lookup();
if (!form) {
Warning("%s: [%s] [%s] %.8X: form not found",
__FUNCTION__, a_modData.name.c_str(), t.first.c_str(), formid);
continue;
}
if (form->formType == TESNPC::kTypeID)
{
fm[modIndex].first.insert_or_assign(
formid, DataHolder<T>::profileData_t(
Enum::Underlying(t.second.gender),
std::addressof(it->second)
));
}
else if (form->formType == TESRace::kTypeID)
{
fm[modIndex].second.insert_or_assign(
formid, DataHolder<T>::profileData_t(
Enum::Underlying(t.second.gender),
std::addressof(it->second)
));
}
else
{
Warning("%s: [%s] [%s] %.8X: unexpected form type %hhu",
__FUNCTION__, a_modData.name.c_str(), t.first.c_str(), formid, form->formType);
}
//gLog.Debug("!!>>> %hhu, 0x%X -> %s", form->formType, formid, t.first.c_str());
}
}
break;
}
}
}
bool ITemplate::LoadProfiles()
{
return m_Instance.LoadProfilesImpl();
}
bool ITemplate::LoadProfilesImpl()
{
auto& driverConf = DCBP::GetDriverConfig();
if (!m_dataPhysics.Load(driverConf.paths.templateProfilesPhysics))
return false;
if (!m_dataNode.Load(driverConf.paths.templateProfilesNode))
return false;
if (!LoadPluginData())
return false;
const auto& data = GetPluginData();
auto& mm = DData::GetPluginData().GetLookupRef();
for (auto& rec : data)
{
//gLog.Debug("|| %s", rec.GetPluginName().c_str());
auto it = mm.find(rec.GetPluginName());
if (it == mm.end())
continue;
auto& rd = rec.GetData();
for (auto& e : rd)
{
switch (e.first)
{
case TRecType::Physics:
ProcessTemplateRecord(m_dataPhysics, e.second, it->second);
break;
case TRecType::Node:
ProcessTemplateRecord(m_dataNode, e.second, it->second);
break;
}
}
//gLog.Debug("!! 0x%X", it->second->GetPartialIndex());
}
return true;
}
} | 29.371795 | 114 | 0.427615 | clayne |
c451dd0429e13c18467bad9561ae85fed6c0d775 | 4,557 | cpp | C++ | src/proposals/suspend_proposal.cpp | josejulio/dao-contracts | 2c774185f00ac89c31061da4e15567140876b1c8 | [
"MIT"
] | null | null | null | src/proposals/suspend_proposal.cpp | josejulio/dao-contracts | 2c774185f00ac89c31061da4e15567140876b1c8 | [
"MIT"
] | null | null | null | src/proposals/suspend_proposal.cpp | josejulio/dao-contracts | 2c774185f00ac89c31061da4e15567140876b1c8 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <eosio/asset.hpp>
#include <eosio/crypto.hpp>
#include <document_graph/document.hpp>
#include <document_graph/content_wrapper.hpp>
#include <common.hpp>
#include <util.hpp>
#include <proposals/suspend_proposal.hpp>
#include <assignment.hpp>
#include <period.hpp>
#include <logger/logger.hpp>
namespace hypha
{
void SuspendProposal::proposeImpl(const name &proposer, ContentWrapper &contentWrapper)
{
//TODO: Setup ballot_title according to document type [Assignment, Badge, etc.]
TRACE_FUNCTION()
// original_document is a required hash
auto originalDocHash = contentWrapper.getOrFail(DETAILS, ORIGINAL_DOCUMENT)->getAs<eosio::checksum256>();
Document originalDoc(m_dao.get_self(), originalDocHash);
ContentWrapper ocw = originalDoc.getContentWrapper();
auto type = ocw.getOrFail(SYSTEM, TYPE)->getAs<name>();
switch (type.value)
{
case common::ASSIGNMENT.value: {
Assignment assignment(&m_dao, originalDoc.getHash());
auto currentTimeSecs = eosio::current_time_point().sec_since_epoch();
auto lastPeriodEndSecs = assignment.getLastPeriod()
.getEndTime()
.sec_since_epoch();
EOS_CHECK(
currentTimeSecs < lastPeriodEndSecs,
"Assignment is already expired"
);
} break;
default:
EOS_CHECK(
false,
to_str("Unexpected document type for suspension: ",
type, ". Valid types [", common::ASSIGNMENT ,"]")
);
break;
}
auto title = ocw.getOrFail(DETAILS, TITLE)->getAs<string>();
ContentWrapper::insertOrReplace(*contentWrapper.getGroupOrFail(DETAILS),
Content { TITLE, to_str("Suspention of ", type, ":", title ) });
}
void SuspendProposal::postProposeImpl (Document &proposal)
{
TRACE_FUNCTION()
auto originalDocHash = proposal.getContentWrapper()
.getOrFail(DETAILS, ORIGINAL_DOCUMENT)
->getAs<eosio::checksum256>();
Edge::write (m_dao.get_self(), m_dao.get_self(), proposal.getHash(), originalDocHash, common::SUSPEND);
}
void SuspendProposal::passImpl(Document &proposal)
{
TRACE_FUNCTION()
auto edges = m_dao.getGraph().getEdgesFrom(proposal.getHash(), common::SUSPEND);
EOS_CHECK(
edges.size() == 1,
"Missing edge from suspension proposal: " + readableHash(proposal.getHash()) + " to document"
);
Document originalDoc(m_dao.get_self(), edges[0].getToNode());
ContentWrapper ocw = originalDoc.getContentWrapper();
auto type = ocw.getOrFail(SYSTEM, TYPE)->getAs<name>();
switch (type.value)
{
case common::ASSIGNMENT.value: {
Assignment assignment(&m_dao, originalDoc.getHash());
auto cw = assignment.getContentWrapper();
auto originalPeriods = assignment.getPeriodCount();
//Calculate the number of periods since start period to the current period
auto currentPeriod = Period::current(&m_dao);
auto periodsToCurrent = assignment.getStartPeriod().getPeriodCountTo(currentPeriod);
periodsToCurrent = std::min(periodsToCurrent + 1, originalPeriods);
if (originalPeriods != periodsToCurrent) {
auto detailsGroup = cw.getGroupOrFail(DETAILS);
ContentWrapper::insertOrReplace(*detailsGroup, Content { PERIOD_COUNT, periodsToCurrent });
auto newHash = m_dao.getGraph().updateDocument(assignment.getCreator(),
assignment.getHash(),
cw.getContentGroups()).getHash();
assignment = Assignment(&m_dao, newHash);
}
m_dao.modifyCommitment(assignment, 0, std::nullopt, common::MOD_WITHDRAW);
} break;
default: {
EOS_CHECK(
false,
to_str("Unexpected document type for suspension: ",
type, ". Valid types [", common::ASSIGNMENT ,"]")
);
} break;
}
}
std::string SuspendProposal::getBallotContent (ContentWrapper &contentWrapper)
{
TRACE_FUNCTION()
return getTitle(contentWrapper);
}
name SuspendProposal::getProposalType ()
{
return common::SUSPEND;
}
} // namespace hypha | 31.645833 | 111 | 0.608075 | josejulio |
c452ebadb7f1449e7544266d9ccd6ff610a13784 | 9,964 | cc | C++ | cc/signature/rsa_ssa_pss_verify_key_manager_test.cc | ishworgurung/tink | a534939d24261604f703003ae91e493cfdedc8d5 | [
"Apache-2.0"
] | 1 | 2019-03-31T07:52:05.000Z | 2019-03-31T07:52:05.000Z | cc/signature/rsa_ssa_pss_verify_key_manager_test.cc | J-Sarkcess/tink | ba64189ae1a44c2935f060a4de06bdc2df721a93 | [
"Apache-2.0"
] | 1 | 2020-11-11T16:45:00.000Z | 2020-11-11T16:45:00.000Z | cc/signature/rsa_ssa_pss_verify_key_manager_test.cc | J-Sarkcess/tink | ba64189ae1a44c2935f060a4de06bdc2df721a93 | [
"Apache-2.0"
] | 1 | 2019-09-20T01:59:16.000Z | 2019-09-20T01:59:16.000Z | // Copyright 2018 Google 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 "tink/signature/rsa_ssa_pss_verify_key_manager.h"
#include "gtest/gtest.h"
#include "absl/strings/escaping.h"
#include "tink/public_key_sign.h"
#include "tink/public_key_verify.h"
#include "tink/registry.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_util.h"
#include "proto/common.pb.h"
#include "proto/rsa_ssa_pss.pb.h"
#include "proto/tink.pb.h"
namespace pb = google::crypto::tink;
// TODO(quannguyen): add more tests once RsaSsaPssSignKeyManager is available.
namespace crypto {
namespace tink {
using google::crypto::tink::KeyData;
using google::crypto::tink::RsaSsaPssKeyFormat;
using google::crypto::tink::RsaSsaPssPublicKey;
namespace {
class RsaSsaPssVerifyKeyManagerTest : public ::testing::Test {
protected:
std::string key_type_prefix_ = "type.googleapis.com/";
std::string rsa_ssa_pss_verify_key_type_ =
"type.googleapis.com/google.crypto.tink.RsaSsaPssPublicKey";
};
// Test vector from
// https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Digital-Signatures
struct NistTestVector {
std::string n;
std::string e;
std::string message;
std::string signature;
pb::HashType sig_hash;
pb::HashType mgf1_hash;
int salt_length;
};
static const NistTestVector nist_test_vector{
absl::HexStringToBytes(
"a47d04e7cacdba4ea26eca8a4c6e14563c2ce03b623b768c0d49868a57121301dbf783"
"d82f4c055e73960e70550187d0af62ac3496f0a3d9103c2eb7919a72752fa7ce8c688d"
"81e3aee99468887a15288afbb7acb845b7c522b5c64e678fcd3d22feb84b44272700be"
"527d2b2025a3f83c2383bf6a39cf5b4e48b3cf2f56eef0dfff18555e31037b91524869"
"4876f3047814415164f2c660881e694b58c28038a032ad25634aad7b39171dee368e3d"
"59bfb7299e4601d4587e68caaf8db457b75af42fc0cf1ae7caced286d77fac6cedb03a"
"d94f1433d2c94d08e60bc1fdef0543cd2951e765b38230fdd18de5d2ca627ddc032fe0"
"5bbd2ff21e2db1c2f94d8b"),
absl::HexStringToBytes("10e43f"),
absl::HexStringToBytes(
"e002377affb04f0fe4598de9d92d31d6c786040d5776976556a2cfc55e54a1dcb3cb1b"
"126bd6a4bed2a184990ccea773fcc79d246553e6c64f686d21ad4152673cafec22aeb4"
"0f6a084e8a5b4991f4c64cf8a927effd0fd775e71e8329e41fdd4457b3911173187b4f"
"09a817d79ea2397fc12dfe3d9c9a0290c8ead31b6690a6"),
absl::HexStringToBytes(
"4f9b425c2058460e4ab2f5c96384da2327fd29150f01955a76b4efe956af06dc08779a"
"374ee4607eab61a93adc5608f4ec36e47f2a0f754e8ff839a8a19b1db1e884ea4cf348"
"cd455069eb87afd53645b44e28a0a56808f5031da5ba9112768dfbfca44ebe63a0c057"
"2b731d66122fb71609be1480faa4e4f75e43955159d70f081e2a32fbb19a48b9f162cf"
"6b2fb445d2d6994bc58910a26b5943477803cdaaa1bd74b0da0a5d053d8b1dc593091d"
"b5388383c26079f344e2aea600d0e324164b450f7b9b465111b7265f3b1b063089ae7e"
"2623fc0fda8052cf4bf3379102fbf71d7c98e8258664ceed637d20f95ff0111881e650"
"ce61f251d9c3a629ef222d"),
pb::HashType::SHA256,
pb::HashType::SHA256,
32};
TEST_F(RsaSsaPssVerifyKeyManagerTest, testBasic) {
RsaSsaPssVerifyKeyManager key_manager;
EXPECT_EQ(0, key_manager.get_version());
EXPECT_EQ("type.googleapis.com/google.crypto.tink.RsaSsaPssPublicKey",
key_manager.get_key_type());
EXPECT_TRUE(key_manager.DoesSupport(key_manager.get_key_type()));
// NIST test vector should work.
RsaSsaPssPublicKey key;
key.mutable_params()->set_mgf1_hash(nist_test_vector.mgf1_hash);
key.mutable_params()->set_sig_hash(nist_test_vector.sig_hash);
key.mutable_params()->set_salt_length(nist_test_vector.salt_length);
key.set_version(0);
key.set_n(nist_test_vector.n);
key.set_e(nist_test_vector.e);
auto result = key_manager.GetPrimitive(key);
EXPECT_TRUE(result.ok());
EXPECT_TRUE(result.ValueOrDie()
->Verify(nist_test_vector.signature, nist_test_vector.message)
.ok());
}
TEST_F(RsaSsaPssVerifyKeyManagerTest, testKeyDataErrors) {
RsaSsaPssVerifyKeyManager key_manager;
{ // Bad key type.
KeyData key_data;
std::string bad_key_type = "type.googleapis.com/google.crypto.tink.SomeOtherKey";
key_data.set_type_url(bad_key_type);
auto result = key_manager.GetPrimitive(key_data);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "not supported",
result.status().error_message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, bad_key_type,
result.status().error_message());
}
{ // Bad key value.
KeyData key_data;
key_data.set_type_url(rsa_ssa_pss_verify_key_type_);
key_data.set_value("some bad serialized proto");
auto result = key_manager.GetPrimitive(key_data);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "not parse",
result.status().error_message());
}
{ // Bad version.
KeyData key_data;
RsaSsaPssPublicKey key;
key.set_version(1);
key_data.set_type_url(rsa_ssa_pss_verify_key_type_);
key_data.set_value(key.SerializeAsString());
auto result = key_manager.GetPrimitive(key_data);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "version",
result.status().error_message());
}
}
TEST_F(RsaSsaPssVerifyKeyManagerTest, testKeyMessageErrors) {
RsaSsaPssVerifyKeyManager key_manager;
{ // Use SHA1 as signature hash.
RsaSsaPssPublicKey key;
key.mutable_params()->set_mgf1_hash(pb::HashType::SHA1);
key.mutable_params()->set_sig_hash(pb::HashType::SHA1);
key.mutable_params()->set_salt_length(20);
key.set_version(0);
key.set_n(nist_test_vector.n);
key.set_e(nist_test_vector.e);
auto result = key_manager.GetPrimitive(key);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring,
"SHA1 is not safe for digital signature",
result.status().error_message());
}
{ // Small modulus.
RsaSsaPssPublicKey key;
key.mutable_params()->set_mgf1_hash(pb::HashType::SHA256);
key.mutable_params()->set_sig_hash(pb::HashType::SHA256);
key.mutable_params()->set_salt_length(32);
key.set_version(0);
key.set_n("\x23");
key.set_e("\x3");
auto result = key_manager.GetPrimitive(key);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring,
"only modulus size >= 2048-bit is supported",
result.status().error_message());
}
{ // MGF1 hash and signature hash mismatch.
RsaSsaPssPublicKey key;
key.mutable_params()->set_mgf1_hash(pb::HashType::SHA256);
key.mutable_params()->set_sig_hash(pb::HashType::SHA512);
key.mutable_params()->set_salt_length(32);
key.set_version(0);
key.set_n(nist_test_vector.n);
key.set_e(nist_test_vector.e);
auto result = key_manager.GetPrimitive(key);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring,
"is different from signature hash",
result.status().error_message());
}
}
TEST_F(RsaSsaPssVerifyKeyManagerTest, testNewKeyError) {
RsaSsaPssVerifyKeyManager key_manager;
const KeyFactory& key_factory = key_manager.get_key_factory();
{ // Via NewKey(format_proto).
RsaSsaPssKeyFormat key_format;
auto result = key_factory.NewKey(key_format);
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::UNIMPLEMENTED, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "not supported",
result.status().error_message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "use the RsaSsaPssSignKeyManager",
result.status().error_message());
}
{ // Via NewKey(serialized_format_proto).
RsaSsaPssKeyFormat key_format;
auto result = key_factory.NewKey(key_format.SerializeAsString());
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::UNIMPLEMENTED, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "not supported",
result.status().error_message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "use the RsaSsaPssSignKeyManager",
result.status().error_message());
}
{ // Via NewKeyData(serialized_format_proto).
RsaSsaPssKeyFormat key_format;
auto result = key_factory.NewKeyData(key_format.SerializeAsString());
EXPECT_FALSE(result.ok());
EXPECT_EQ(util::error::UNIMPLEMENTED, result.status().error_code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "not supported",
result.status().error_message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "use the RsaSsaPssSignKeyManager",
result.status().error_message());
}
}
} // namespace
} // namespace tink
} // namespace crypto
| 40.016064 | 95 | 0.721397 | ishworgurung |
c4537ba4537cc9b03abcf586ad609e65902780fd | 178,970 | cpp | C++ | GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | null | null | null | GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | null | null | null | GameEngineCore/VulkanAPI/VulkanHardwareRenderer.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | null | null | null | #include "../GameEngineCore/HardwareRenderer.h"
#include "CoreLib/WinForm/Debug.h"
#include "CoreLib/VectorMath.h"
#include "CoreLib/PerformanceCounter.h"
#include "../Engine.h"
#include "CoreLib/ShortList.h"
#include "CoreLib/LibIO.h"
#include "volk.h"
#include "vulkan.hpp"
#include <mutex>
// Only execute actions of DEBUG_ONLY in DEBUG mode
#if _DEBUG
#define DEBUG_ONLY(x) { x; }
#define USE_VALIDATION_LAYER 1
#else
#define DEBUG_ONLY(x) {}
#endif
#ifdef __linux__
#undef Always
#undef None
#endif
using namespace GameEngine;
using namespace CoreLib::IO;
using namespace CoreLib;
namespace VK
{
const int TargetVulkanVersion_Major = 1;
const int TargetVulkanVersion_Minor = 0;
const int MaxRenderThreads = 4;
int MaxThreadCount = MaxRenderThreads;
unsigned int GpuId = 0;
thread_local int renderThreadId = -1;
namespace VkDebug
{
// Print device info
void PrintDeviceInfo(const std::vector<vk::PhysicalDevice>& physicalDevices);
// Debug callback direct to stderr
VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage,
void* pUserData);
// VkDebug Implementation
void PrintDeviceInfo(const std::vector<vk::PhysicalDevice>& physicalDevices)
{
for (uint32_t i = 0; i < physicalDevices.size(); i++)
{
// Print out device properties
vk::PhysicalDeviceProperties deviceProperties = physicalDevices.at(i).getProperties();
printf("Device ID: %d\n", deviceProperties.deviceID);
printf("Driver Version: %d\n", deviceProperties.driverVersion);
printf("Device Name: %s\n", deviceProperties.deviceName);
printf("Device Type: %d\n", static_cast<int>(deviceProperties.deviceType));
printf("API Version: %d.%d.%d\n",
VK_VERSION_MAJOR(deviceProperties.apiVersion),
VK_VERSION_MINOR(deviceProperties.apiVersion),
VK_VERSION_PATCH(deviceProperties.apiVersion));
printf("\n");
// Print out device queue info
std::vector<vk::QueueFamilyProperties> familyProperties = physicalDevices.at(i).getQueueFamilyProperties();
for (size_t j = 0; j < familyProperties.size(); j++) {
printf("Count of Queues: %d\n", familyProperties[j].queueCount);
printf("Supported operations on this queue: %s\n", to_string(familyProperties[j].queueFlags).c_str());
printf("\n");
}
// Print out device memory properties
vk::PhysicalDeviceMemoryProperties memoryProperties = physicalDevices.at(i).getMemoryProperties();
printf("Memory Type Count: %d\n", memoryProperties.memoryTypeCount);
for (size_t j = 0; j < memoryProperties.memoryTypeCount; j++)
{
auto type = memoryProperties.memoryTypes[j];
printf("(Heap %d) %s\n", type.heapIndex, to_string(type.propertyFlags).c_str());
}
printf("\n");
printf("Memory Heap Count: %d\n", memoryProperties.memoryHeapCount);
for (size_t j = 0; j < memoryProperties.memoryHeapCount; j++)
{
auto heap = memoryProperties.memoryHeaps[j];
printf("(Heap %zu)\n", j);
printf("\tsize: %u MB\n", static_cast<unsigned>(heap.size / 1024 / 1024));
printf("\tflags:%s\n", to_string(heap.flags).c_str());
printf("\n");
}
printf("\n");
// Print out device features
printf("Supported Features:\n");
vk::PhysicalDeviceFeatures deviceFeatures = physicalDevices.at(i).getFeatures();
if (deviceFeatures.shaderClipDistance == VK_TRUE) printf("Shader Clip Distance\n");
if (deviceFeatures.textureCompressionBC == VK_TRUE) printf("BC Texture Compression\n");
printf("\n");
// Print out device limits
printf("Device Limits:\n");
printf("Max Vertex Input Attributes: %u\n", deviceProperties.limits.maxVertexInputAttributes);
printf("Max Push Constants Size: %u\n", deviceProperties.limits.maxPushConstantsSize);
// Readability
printf("\n---\n\n");
}
}
VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t /*object*/,
size_t /*location*/,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage,
void* /*pUserData*/)
{
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
CoreLib::Diagnostics::Debug::Write("ERROR");
if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
CoreLib::Diagnostics::Debug::Write("WARNING");
if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
CoreLib::Diagnostics::Debug::Write("PERFORMANCE");
if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
CoreLib::Diagnostics::Debug::Write("INFO");
if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
CoreLib::Diagnostics::Debug::Write("DEBUG");
CoreLib::Diagnostics::Debug::Write(" [");
CoreLib::Diagnostics::Debug::Write(pLayerPrefix);
CoreLib::Diagnostics::Debug::Write("] ");
CoreLib::Diagnostics::Debug::Write("(");
CoreLib::Diagnostics::Debug::Write(to_string((vk::DebugReportObjectTypeEXT)objectType).c_str());
CoreLib::Diagnostics::Debug::Write(") ");
CoreLib::Diagnostics::Debug::Write((long long)messageCode);
CoreLib::Diagnostics::Debug::Write(" ");
CoreLib::Diagnostics::Debug::WriteLine(pMessage);
return VK_FALSE;
}
}
class DescriptorPoolObject : public CoreLib::Object
{
public:
vk::DescriptorPool pool;
DescriptorPoolObject();
~DescriptorPoolObject();
};
/*
* Internal Vulkan state
*/
class RendererState
{
//TODO: check class for multithreading safety
private:
bool initialized = false;
int rendererCount = 0;
vk::DebugReportCallbackEXT callback;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::DescriptorSetLayout emptyDescriptorSetLayout;
vk::DescriptorSet emptyDescriptorSet;
vk::CommandPool swapchainCommandPool;
CoreLib::Array<vk::CommandPool, MaxRenderThreads> renderCommandPools;
CoreLib::Array<CoreLib::RefPtr<CoreLib::List<CoreLib::List<vk::CommandBuffer>>>, MaxRenderThreads> renderCommandBufferPools;
int currentBufferVersions[MaxRenderThreads] = {};
int renderCommandBufferAllocPtrs[MaxRenderThreads] = {};
int renderQueueIndex;
int transferQueueIndex;
vk::Queue presentQueue;
CoreLib::Array<vk::Queue, MaxRenderThreads> renderQueues;
vk::Queue transferQueue;
vk::PipelineCache pipelineCache;
CoreLib::String pipelineCacheLocation;
CoreLib::Array<CoreLib::RefPtr<CoreLib::List<DescriptorPoolObject*>>, MaxRenderThreads> descriptorPoolChains;
RendererState() {}
static vk::CommandBuffer GetTempCommandBuffer(vk::CommandPool cmdPool, CoreLib::List<CoreLib::List<vk::CommandBuffer>> & bufferPool, int & allocPtr)
{
if (allocPtr == bufferPool[State().currentBufferVersions[renderThreadId]].Count())
{
bufferPool[State().currentBufferVersions[renderThreadId]].Add(CreateCommandBuffer(cmdPool, vk::CommandBufferLevel::ePrimary));
}
return bufferPool[State().currentBufferVersions[renderThreadId]][allocPtr++];
}
static RendererState& State()
{
static RendererState singleton;
return singleton;
}
static void CreateDebugCallback()
{
vk::DebugReportCallbackCreateInfoEXT callbackCreateInfo(
vk::DebugReportFlagsEXT(
//vk::DebugReportFlagBitsEXT::eInformation |
vk::DebugReportFlagBitsEXT::eDebug |
vk::DebugReportFlagBitsEXT::ePerformanceWarning |
vk::DebugReportFlagBitsEXT::eWarning |
vk::DebugReportFlagBitsEXT::eError
),
&VkDebug::DebugCallback,
nullptr // userdata
);
State().callback = State().instance.createDebugReportCallbackEXT(callbackCreateInfo);
}
static void CreateInstance()
{
// Application and Instance Info
vk::ApplicationInfo appInfo = vk::ApplicationInfo()
.setPApplicationName("lll")
.setPEngineName("Engine")
.setEngineVersion(1)
.setApiVersion(VK_API_VERSION_1_0);
// Enabled Layers
CoreLib::List<const char*> enabledInstanceLayers;
#if _DEBUG
bool hasValidationLayer = false;
auto supportedLayers = vk::enumerateInstanceLayerProperties();
for (auto & l : supportedLayers)
if (strcmp(l.layerName, "VK_LAYER_KHRONOS_validation") == 0)
{
hasValidationLayer = true;
break;
}
#if USE_VALIDATION_LAYER
if (hasValidationLayer)
enabledInstanceLayers.Add("VK_LAYER_KHRONOS_validation");
#endif
#endif
// Enabled Extensions
CoreLib::List<const char*> enabledInstanceExtensions;
enabledInstanceExtensions.Add(VK_KHR_SURFACE_EXTENSION_NAME);
enabledInstanceExtensions.Add(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
#if _WIN32
enabledInstanceExtensions.Add(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#elif defined(__linux__)
enabledInstanceExtensions.Add(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
#endif
DEBUG_ONLY(enabledInstanceExtensions.Add(VK_EXT_DEBUG_REPORT_EXTENSION_NAME));
// Instance Create Info
vk::InstanceCreateInfo instInfo = vk::InstanceCreateInfo()
.setPApplicationInfo(&appInfo)
.setEnabledLayerCount(enabledInstanceLayers.Count())
.setPpEnabledLayerNames(enabledInstanceLayers.Buffer())
.setEnabledExtensionCount(enabledInstanceExtensions.Count())
.setPpEnabledExtensionNames(enabledInstanceExtensions.Buffer());
// Create the instance
State().instance = vk::createInstance(instInfo);
// Load instance level function pointers
volkLoadInstance((VkInstance)(State().instance));
// Create callbacks
DEBUG_ONLY(CreateDebugCallback());
}
static void SelectPhysicalDevice()
{
std::vector<vk::PhysicalDevice> physicalDevices = State().instance.enumeratePhysicalDevices();
//DEBUG_ONLY(VkDebug::PrintDeviceInfo(physicalDevices));
if (GpuId >= physicalDevices.size())
GpuId = 0;
State().physicalDevice = physicalDevices[GpuId];
printf("Using GPU %d\n", GpuId);
}
static void SelectPhysicalDevice(vk::SurfaceKHR surface)
{
std::vector<vk::PhysicalDevice> physicalDevices = State().instance.enumeratePhysicalDevices();
//DEBUG_ONLY(VkDebug::PrintDeviceInfo(physicalDevices));
int k = 0;
for (auto physDevice : physicalDevices)
{
for (size_t i = 0; i < physDevice.getQueueFamilyProperties().size(); i++)
{
if (physDevice.getSurfaceSupportKHR((uint32_t)i, surface))
{
State().physicalDevice = physDevice;
GpuId = k;
printf("Using GPU %d\n", GpuId);
return;
}
}
k++;
}
}
static void CreateDevice()
{
// Initialize Queues
CoreLib::List<float> renderQueuePriorities;
CoreLib::List<float> transferQueuePriorities;
renderQueuePriorities.Add(1.0f);
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = PhysicalDevice().getQueueFamilyProperties();
MaxThreadCount = Math::Min(MaxThreadCount, (int)queueFamilyProperties[0].queueCount);
for (int i = 0; i < MaxThreadCount - 1; i++)
{
renderQueuePriorities.Add(1.0f);
}
//transferQueuePriorities.Add(1.0f);
//TODO: improve
int renderQueueFamilyIndex = 0;
int transferQueueFamilyIndex = 0;
//NOTE: When changing this, resources created by the transferQueue will also need to have
// their ownership transferred to the renderQueue, if they are created with
// vk::SharingMode::eExclusive. https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html#resources-sharing
CoreLib::List<vk::DeviceQueueCreateInfo> deviceQueueInfoVec;
deviceQueueInfoVec.Add(
vk::DeviceQueueCreateInfo()
.setQueueFamilyIndex(renderQueueFamilyIndex)
.setQueueCount(renderQueuePriorities.Count())
.setPQueuePriorities(renderQueuePriorities.Buffer())
);
//deviceQueueInfoVec.Add(
// vk::DeviceQueueCreateInfo()
// .setQueueFamilyIndex(transferQueueFamilyIndex)
// .setQueueCount(transferQueuePriorities.Count())
// .setPQueuePriorities(transferQueuePriorities.Buffer())
//);
// Lambda to check if layer is present and then add it
auto AddLayer = [](CoreLib::List<const char*>& enabledDeviceLayers, const char* layerName)
{
for (auto layer : State().physicalDevice.enumerateDeviceLayerProperties())
{
if (!strcmp(layerName, layer.layerName))
{
enabledDeviceLayers.Add(layerName);
return;
}
}
printf("Layer %s not supported\n", layerName);
};
CoreLib::List<const char*> enabledDeviceLayers;
#if USE_VALIDATION_LAYER
DEBUG_ONLY(AddLayer(enabledDeviceLayers, "VK_LAYER_LUNARG_standard_validation"));
#endif
// Lambda to check if extension is present and then add it
auto AddExtension = [](CoreLib::List<const char*>& enabledDeviceExtensions, const char* extensionName)
{
for (auto extension : State().physicalDevice.enumerateDeviceExtensionProperties())
{
if (!strcmp(extensionName, extension.extensionName))
{
enabledDeviceExtensions.Add(extensionName);
return;
}
}
printf("Extension %s not supported\n", extensionName);
};
CoreLib::List<const char*> enabledDeviceExtensions;
AddExtension(enabledDeviceExtensions, VK_KHR_SWAPCHAIN_EXTENSION_NAME);
AddExtension(enabledDeviceExtensions, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
DEBUG_ONLY(AddExtension(enabledDeviceExtensions, VK_EXT_DEBUG_MARKER_EXTENSION_NAME));
// Device Features
vk::PhysicalDeviceFeatures enabledDeviceFeatures = State().physicalDevice.getFeatures();
vk::DeviceCreateInfo deviceInfo = vk::DeviceCreateInfo()
.setQueueCreateInfoCount(deviceQueueInfoVec.Count())
.setPQueueCreateInfos(deviceQueueInfoVec.Buffer())
.setEnabledLayerCount(enabledDeviceLayers.Count())
.setPpEnabledLayerNames(enabledDeviceLayers.Buffer())
.setEnabledExtensionCount(enabledDeviceExtensions.Count())
.setPpEnabledExtensionNames(enabledDeviceExtensions.Buffer())
.setPEnabledFeatures(&enabledDeviceFeatures);
State().device = State().physicalDevice.createDevice(deviceInfo);
// Load device level function pointers
volkLoadDevice((VkDevice)(State().device));
State().presentQueue = State().device.getQueue(renderQueueFamilyIndex, 0);
State().renderQueues.SetSize(MaxThreadCount);
for (int i = 0; i < renderQueuePriorities.Count(); i++)
{
State().renderQueues[i] = State().device.getQueue(renderQueueFamilyIndex, i);
}
State().transferQueue = State().device.getQueue(transferQueueFamilyIndex, renderQueuePriorities.Count() - 1);//TODO: Change the index if changing family
}
static void CreateCommandPool()
{
vk::CommandPoolCreateInfo commandPoolCreateInfo = vk::CommandPoolCreateInfo()
.setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer)
.setQueueFamilyIndex(State().renderQueueIndex);
State().swapchainCommandPool = State().device.createCommandPool(commandPoolCreateInfo);
//TODO: multiple pools for multiple threads
vk::CommandPoolCreateInfo renderCommandPoolCreateInfo = vk::CommandPoolCreateInfo()
.setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer)
.setQueueFamilyIndex(State().renderQueueIndex);
State().renderCommandPools.SetSize(MaxThreadCount);
for (int i = 0; i < MaxThreadCount; i++)
State().renderCommandPools[i] = State().device.createCommandPool(renderCommandPoolCreateInfo);
State().renderCommandBufferPools.SetSize(MaxThreadCount);
for (int i = 0; i < MaxThreadCount; i++)
State().renderCommandBufferPools[i] = new List<List<vk::CommandBuffer>>();
}
static void CreateDescriptorPoolChain()
{
State().descriptorPoolChains.SetSize(MaxThreadCount);
for (int i = 0; i < MaxThreadCount; i++)
{
State().descriptorPoolChains[i] = new CoreLib::List<DescriptorPoolObject*>();
}
}
// This function encapsulates all device-specific initialization
static void InitDevice()
{
CreateDevice();
CreateCommandPool();
CreateDescriptorPoolChain();
List<unsigned char> initialData;
if (File::Exists(State().pipelineCacheLocation))
{
initialData = File::ReadAllBytes(State().pipelineCacheLocation);
}
vk::PipelineCacheCreateInfo createInfo = vk::PipelineCacheCreateInfo()
.setInitialDataSize(initialData.Count())
.setPInitialData(initialData.Buffer());
State().pipelineCache = State().device.createPipelineCache(createInfo);
}
static void Init()
{
if (State().initialized)
return;
renderThreadId = 0;
State().initialized = true;
if (volkInitialize() != VK_SUCCESS)
{
printf("Fatal error: Vulkan driver not found on the current system.\n");
exit(-1);
}
CreateInstance();
SelectPhysicalDevice();
InitDevice();
vk::DescriptorSetLayoutCreateInfo descLayoutCreateInfo;
descLayoutCreateInfo.setBindingCount(0);
State().emptyDescriptorSetLayout = State().device.createDescriptorSetLayout(descLayoutCreateInfo);
State().emptyDescriptorSet = AllocateDescriptorSet(State().emptyDescriptorSetLayout).second;
}
static void DestroyDevice()
{
State().device.destroyDescriptorSetLayout(State().emptyDescriptorSetLayout);
State().device.destroy();
}
static void DestroyInstance()
{
DEBUG_ONLY(State().instance.destroyDebugReportCallbackEXT(State().callback));
State().instance.destroy();
}
static void DestroyCommandPool()
{
for (int i = 0; i < MaxThreadCount; i++)
State().device.destroyCommandPool(State().renderCommandPools[i]);
State().device.destroyCommandPool(State().swapchainCommandPool);
for (auto & pool : State().renderCommandBufferPools)
pool = nullptr;
}
static void DestroyDescriptorPoolChain()
{
for (auto & chain : State().descriptorPoolChains)
{
for (auto& descriptorPool : *chain)
delete descriptorPool;
chain = nullptr;
}
}
// This function encapsulates all device-specific destruction
static void UninitDevice()
{
State().device.waitIdle();
if (State().pipelineCacheLocation.Length())
{
const size_t maxPipelineCacheSize = (64 << 20); // limit cache size to 64MB
size_t size = 0;
vkGetPipelineCacheData(State().device, State().PipelineCache(), &size, nullptr);
if (size > maxPipelineCacheSize)
size = maxPipelineCacheSize;
List<unsigned char> buffer;
buffer.SetSize((int)size);
vkGetPipelineCacheData(State().device, State().PipelineCache(), &size, buffer.Buffer());
File::WriteAllBytes(State().pipelineCacheLocation, buffer.Buffer(), (size_t)buffer.Count());
}
State().device.destroyPipelineCache(State().pipelineCache);
DestroyDescriptorPoolChain();
DestroyCommandPool();
DestroyDevice();
}
static void Destroy()
{
if (!State().initialized)
return;
UninitDevice();
DestroyInstance();
State().SetPipelineCacheLocation(String());
State().initialized = false;
};
static void DeviceLost()
{
UninitDevice();
SelectPhysicalDevice();
InitDevice();
//TODO: send message to user of engine that signals to recreate resources
}
public:
RendererState(RendererState const&) = delete;
void operator=(RendererState const&) = delete;
~RendererState()
{
Destroy();//TODO: Does this need to be here?
}
// Const reference access to class variables
static const vk::Instance& Instance()
{
return State().instance;
}
static vk::DescriptorSet GetEmptyDescriptorSet()
{
return State().emptyDescriptorSet;
}
static const vk::PhysicalDevice& PhysicalDevice()
{
return State().physicalDevice;
}
static const vk::Device& Device()
{
return State().device;
}
static void Init(int versionCount)
{
auto & state = State();
for (int i = 0; i < MaxThreadCount; i++)
state.renderCommandBufferPools[i]->SetSize(versionCount);
}
static void ResetTempBufferVersion(int version)
{
auto & state = State();
state.currentBufferVersions[renderThreadId] = version;
state.renderCommandBufferAllocPtrs[renderThreadId] = 0;
}
static const vk::CommandPool& SwapchainCommandPool()
{
//TODO: do I want to expose these command pools?
return State().swapchainCommandPool;
}
static const vk::CommandPool& TransferCommandPool()
{
return RenderCommandPool();
}
static const vk::CommandPool& RenderCommandPool()
{
return State().renderCommandPools[renderThreadId];
}
static vk::CommandBuffer GetTempTransferCommandBuffer()
{
return GetTempRenderCommandBuffer();
}
static vk::CommandBuffer GetTempRenderCommandBuffer()
{
return GetTempCommandBuffer(State().renderCommandPools[renderThreadId], *State().renderCommandBufferPools[renderThreadId], State().renderCommandBufferAllocPtrs[renderThreadId]);
}
static const vk::Queue& TransferQueue()
{
return RenderQueue();
}
static const vk::Queue& RenderQueue()
{
return State().renderQueues[renderThreadId];
}
static const vk::Queue& PresentQueue()
{
return State().presentQueue;
}
static const vk::PipelineCache& PipelineCache()
{
return State().pipelineCache;
}
static const vk::DescriptorPool& DescriptorPool()
{
if (State().descriptorPoolChains[renderThreadId]->Count() == 0)
State().descriptorPoolChains[renderThreadId]->Add(new DescriptorPoolObject());
return State().descriptorPoolChains[renderThreadId]->Last()->pool;
}
static std::pair<vk::DescriptorPool, vk::DescriptorSet> AllocateDescriptorSet(vk::DescriptorSetLayout layout, bool canTryAgain = true)
{
//TODO: add counter mechanism to DescriptorPoolObject so we know when to destruct
std::pair<vk::DescriptorPool, vk::DescriptorSet> res;
res.first = State().DescriptorPool();
// Create Descriptor Set
vk::DescriptorSetAllocateInfo descriptorSetAllocateInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(res.first)
.setDescriptorSetCount(1)
.setPSetLayouts(&layout);
auto err = RendererState::Device().allocateDescriptorSets(&descriptorSetAllocateInfo, &res.second);
if (err != vk::Result::eSuccess)
{
if (canTryAgain)
{
RendererState::State().descriptorPoolChains[renderThreadId]->Add(new DescriptorPoolObject());
return AllocateDescriptorSet(layout, false);
}
else CORELIB_ABORT("Couldn't allocate descriptor set.");
}
else return res;
}
static void SetPipelineCacheLocation(String loc)
{
State().pipelineCacheLocation = loc;
}
// Bookkeeping for multiple instances of HardwareRenderer
static void AddRenderer()
{
if (!State().initialized)
Init();
State().rendererCount++;
}
static void RemRenderer()
{
State().rendererCount--;
if (RendererCount() == 0)
Destroy();//TODO: Should I destroy the state here?
}
static int RendererCount()
{
return State().rendererCount;
}
// Resource creation functions
static vk::SurfaceKHR CreateSurface(WindowHandle windowHandle)
{
// Create the surface.
vk::SurfaceKHR surface;
#if _WIN32
vk::Win32SurfaceCreateInfoKHR surfaceCreateInfo = vk::Win32SurfaceCreateInfoKHR()
.setHwnd((HWND)windowHandle)
.setHinstance(GetModuleHandle(NULL));
surface = State().instance.createWin32SurfaceKHR(surfaceCreateInfo);
#elif __linux__
vk::XlibSurfaceCreateInfoKHR surfaceCreateInfo = vk::XlibSurfaceCreateInfoKHR()
.setWindow(windowHandle.window)
.setDpy((Display*)windowHandle.display);
surface = State().instance.createXlibSurfaceKHR(surfaceCreateInfo);
#elif __ANDROID__
vk::AndroidSurfaceCreateInfoKHR surfaceCreateInfo = vk::AndroidSurfaceCreaetInfoKHR()
.setWindow((ANativeWindow*)window);
surface = State().instance.createAndroidSurfaceKHR(surfaceCreateInfo);
#endif
// Check to see if the current physical device supports the surface
bool supported = false;
for (unsigned int i = 0; i < State().physicalDevice.getQueueFamilyProperties().size(); i++)
{
if (State().physicalDevice.getSurfaceSupportKHR(i, surface))
{
supported = true;
break;
}
}
// If not supported, recreate logical device with a compatible physical device
if (!supported)
{
printf("GPU %d does not support current surface\n", GpuId);
UninitDevice();
SelectPhysicalDevice(surface);
InitDevice();
//TODO: Notify user to recreate any resources they have created prior to this point
}
return surface;
}
//TODO: I should probably wrap command buffers in a class that contain both the handle and a reference to the command pool created from
static vk::CommandBuffer CreateCommandBuffer(vk::CommandPool commandPool, vk::CommandBufferLevel level = vk::CommandBufferLevel::ePrimary)
{
vk::CommandBufferAllocateInfo commandBufferAllocateInfo = vk::CommandBufferAllocateInfo()
.setCommandPool(commandPool)
.setLevel(level)
.setCommandBufferCount(1);
vk::CommandBuffer commandBuffer;
//TODO: lock mutex on commandPool or allocate commandPool per thread
commandBuffer = State().device.allocateCommandBuffers(commandBufferAllocateInfo).front();
//TODO: unlock mutex on commandPool
return commandBuffer;
}
static vk::CommandBuffer DestroyCommandBuffer(vk::CommandPool commandPool, vk::CommandBuffer commandBuffer)
{
//TODO: lock mutex on commandPool
State().device.freeCommandBuffers(commandPool, commandBuffer);
//TODO: unlock mutex on commandPool
return commandBuffer;
}
};
DescriptorPoolObject::DescriptorPoolObject() {
CoreLib::List<vk::DescriptorPoolSize> poolSizes;
poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eSampler, 200));
poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eSampledImage, 20000));
poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 5000));
poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eStorageBuffer, 2500));
poolSizes.Add(vk::DescriptorPoolSize(vk::DescriptorType::eStorageImage, 32));
vk::DescriptorPoolCreateInfo poolCreateInfo = vk::DescriptorPoolCreateInfo()
.setFlags(vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet)
.setMaxSets(5000)
.setPoolSizeCount(poolSizes.Count())
.setPPoolSizes(poolSizes.Buffer());
pool = RendererState::Device().createDescriptorPool(poolCreateInfo);
}
DescriptorPoolObject::~DescriptorPoolObject()
{
if (pool) RendererState::Device().destroyDescriptorPool(pool);
}
/*
* Interface to Vulkan translation functions
*/
vk::Format TranslateStorageFormat(StorageFormat format)
{
switch (format)
{
case StorageFormat::R_F16: return vk::Format::eR16Sfloat;
case StorageFormat::R_F32: return vk::Format::eR32Sfloat;
case StorageFormat::R_I8: return vk::Format::eR8Uint;
case StorageFormat::R_I16: return vk::Format::eR16Uint;
case StorageFormat::R_8: return vk::Format::eR8Unorm;
case StorageFormat::R_16: return vk::Format::eR16Unorm;
case StorageFormat::Int32_Raw: return vk::Format::eR32Sint;//
case StorageFormat::RG_F16: return vk::Format::eR16G16Sfloat;
case StorageFormat::RG_F32: return vk::Format::eR32G32Sfloat;
case StorageFormat::RG_I8: return vk::Format::eR8G8Uint;
case StorageFormat::RG_8: return vk::Format::eR8G8Unorm;
case StorageFormat::RG_16: return vk::Format::eR16G16Unorm;
case StorageFormat::RG_I16: return vk::Format::eR16G16Uint;
case StorageFormat::RG_I32_Raw: return vk::Format::eR32G32Sint;//
case StorageFormat::RGBA_F16: return vk::Format::eR16G16B16A16Sfloat;
case StorageFormat::RGBA_F32: return vk::Format::eR32G32B32A32Sfloat;
case StorageFormat::RGBA_8: return vk::Format::eR8G8B8A8Unorm;
case StorageFormat::RGBA_8_SRGB: return vk::Format::eR8G8B8A8Srgb;
case StorageFormat::RGBA_16: return vk::Format::eR16G16B16A16Snorm;
case StorageFormat::RGBA_I8: return vk::Format::eR8G8B8A8Uint;
case StorageFormat::RGBA_I16: return vk::Format::eR16G16B16A16Uint;
case StorageFormat::RGBA_I32_Raw: return vk::Format::eR32G32B32A32Sint;//
case StorageFormat::BC1: return vk::Format::eBc1RgbUnormBlock;//
case StorageFormat::BC1_SRGB: return vk::Format::eBc1RgbSrgbBlock;//
case StorageFormat::BC5: return vk::Format::eBc5UnormBlock;
case StorageFormat::BC3: return vk::Format::eBc3UnormBlock;
case StorageFormat::BC6H: return vk::Format::eBc6HUfloatBlock;
case StorageFormat::RGBA_Compressed: return vk::Format::eBc7UnormBlock;//
case StorageFormat::R11F_G11F_B10F: return vk::Format::eB10G11R11UfloatPack32; // need to swizzle?
case StorageFormat::RGB10_A2: return vk::Format::eA2R10G10B10UnormPack32;//
case StorageFormat::Depth24: return vk::Format::eX8D24UnormPack32;
case StorageFormat::Depth32: return vk::Format::eD32Sfloat;
case StorageFormat::Depth24Stencil8: return vk::Format::eD24UnormS8Uint;
default: CORELIB_NOT_IMPLEMENTED("TranslateStorageFormat");
}
};
vk::BufferUsageFlags TranslateUsageFlags(BufferUsage usage)
{
switch (usage)
{
case BufferUsage::ArrayBuffer: return vk::BufferUsageFlagBits::eVertexBuffer;
case BufferUsage::IndexBuffer: return vk::BufferUsageFlagBits::eIndexBuffer;
case BufferUsage::StorageBuffer: return vk::BufferUsageFlagBits::eStorageBuffer;
case BufferUsage::UniformBuffer: return vk::BufferUsageFlagBits::eUniformBuffer;
default: CORELIB_NOT_IMPLEMENTED("TranslateUsageFlags");
}
}
vk::Format TranslateVertexAttribute(VertexAttributeDesc attribute)
{
switch (attribute.Type)
{
case DataType::Byte:
return attribute.Normalized ? vk::Format::eR8Unorm : vk::Format::eR8Uint;
case DataType::Char:
return attribute.Normalized ? vk::Format::eR8Snorm : vk::Format::eR8Sint;
case DataType::Byte2:
return attribute.Normalized ? vk::Format::eR8G8Unorm : vk::Format::eR8G8Uint;
case DataType::Char2:
return attribute.Normalized ? vk::Format::eR8G8Snorm : vk::Format::eR8G8Sint;
case DataType::Byte3:
return attribute.Normalized ? vk::Format::eR8G8B8Unorm : vk::Format::eR8G8B8Uint;
case DataType::Char3:
return attribute.Normalized ? vk::Format::eR8G8B8Snorm : vk::Format::eR8G8B8Sint;
case DataType::Byte4:
return attribute.Normalized ? vk::Format::eR8G8B8A8Unorm : vk::Format::eR8G8B8A8Uint;
case DataType::Char4:
return attribute.Normalized ? vk::Format::eR8G8B8A8Snorm : vk::Format::eR8G8B8A8Sint;
case DataType::Short:
return attribute.Normalized ? vk::Format::eR16Snorm : vk::Format::eR16Sint;
case DataType::UShort:
return attribute.Normalized ? vk::Format::eR16Unorm : vk::Format::eR16Uint;
case DataType::Half:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16Sfloat;//
case DataType::Short2:
return attribute.Normalized ? vk::Format::eR16G16Snorm : vk::Format::eR16G16Sint;
case DataType::UShort2:
return attribute.Normalized ? vk::Format::eR16G16Unorm : vk::Format::eR16G16Uint;
case DataType::Half2:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16G16Sfloat;//
case DataType::Short3:
return attribute.Normalized ? vk::Format::eR16G16B16Snorm : vk::Format::eR16G16B16Sint;
case DataType::UShort3:
return attribute.Normalized ? vk::Format::eR16G16B16Unorm : vk::Format::eR16G16B16Uint;
case DataType::Half3:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR16G16B16Sfloat;//
case DataType::Short4:
return attribute.Normalized ? vk::Format::eR16G16B16A16Snorm : vk::Format::eR16G16B16A16Sint;
case DataType::UShort4:
return attribute.Normalized ? vk::Format::eR16G16B16A16Unorm : vk::Format::eR16G16B16A16Uint;
case DataType::Half4:
return attribute.Normalized ? vk::Format::eR16G16B16A16Snorm : vk::Format::eR16G16B16A16Sfloat;//
case DataType::Int:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Sint;
case DataType::UInt:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Uint;
case DataType::Float:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32Sfloat;
case DataType::Int2:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32Sint;
case DataType::Float2:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32Sfloat;
case DataType::Int3:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sint;
case DataType::Float3:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sfloat;
case DataType::Int4:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32A32Sint;
case DataType::UInt4_10_10_10_2:
throw HardwareRendererException("Unsupported data type.");
case DataType::Float4:
return attribute.Normalized ? throw HardwareRendererException("Unsupported data type.") : vk::Format::eR32G32B32Sfloat;
default:
throw HardwareRendererException("Unimplemented data type.");
}
}
vk::DescriptorType TranslateBindingType(BindingType bindType)
{
switch (bindType)
{
case BindingType::Texture:
return vk::DescriptorType::eSampledImage;
case BindingType::StorageTexture:
return vk::DescriptorType::eStorageImage;
case BindingType::Sampler:
return vk::DescriptorType::eSampler;
case BindingType::UniformBuffer:
return vk::DescriptorType::eUniformBuffer;
case BindingType::StorageBuffer:
return vk::DescriptorType::eStorageBuffer;
case BindingType::RWStorageBuffer:
return vk::DescriptorType::eStorageBuffer;
case BindingType::Unused:
throw HardwareRendererException("Attempting to use unused binding");
default:
CORELIB_NOT_IMPLEMENTED("TranslateBindingType");
}
}
vk::ShaderStageFlags TranslateStageFlags(StageFlags flag)
{
switch (flag)
{
case StageFlags::sfVertex: return vk::ShaderStageFlagBits::eVertex;
case StageFlags::sfFragment: return vk::ShaderStageFlagBits::eFragment;
case StageFlags::sfGraphics:return vk::ShaderStageFlagBits::eAllGraphics;
case StageFlags::sfCompute: return vk::ShaderStageFlagBits::eCompute;
case StageFlags::sfGraphicsAndCompute: return vk::ShaderStageFlagBits::eCompute | vk::ShaderStageFlagBits::eAllGraphics;
default: CORELIB_NOT_IMPLEMENTED("TranslateStageFlags");
}
}
vk::ImageLayout LayoutFromUsage(TextureUsage usage)
{
//TODO: fix this function to deal with the mask correctly
switch (usage)
{
case TextureUsage::ColorAttachment:
case TextureUsage::SampledColorAttachment:
return vk::ImageLayout::eColorAttachmentOptimal;
case TextureUsage::DepthAttachment:
case TextureUsage::SampledDepthAttachment:
return vk::ImageLayout::eDepthStencilAttachmentOptimal;
case TextureUsage::Sampled:
return vk::ImageLayout::eShaderReadOnlyOptimal;
case TextureUsage::Storage:
case TextureUsage::SampledStorage:
return vk::ImageLayout::eGeneral;
default: CORELIB_NOT_IMPLEMENTED("LayoutFromUsage");
}
}
vk::CompareOp TranslateCompareFunc(CompareFunc compareFunc)
{
switch (compareFunc)
{
case CompareFunc::Disabled: return vk::CompareOp::eNever;
case CompareFunc::Equal: return vk::CompareOp::eEqual;
case CompareFunc::Less: return vk::CompareOp::eLess;
case CompareFunc::Greater: return vk::CompareOp::eGreater;
case CompareFunc::LessEqual: return vk::CompareOp::eLessOrEqual;
case CompareFunc::GreaterEqual: return vk::CompareOp::eGreaterOrEqual;
case CompareFunc::NotEqual: return vk::CompareOp::eNotEqual;
case CompareFunc::Always: return vk::CompareOp::eAlways;
case CompareFunc::Never: return vk::CompareOp::eNever;
default: CORELIB_NOT_IMPLEMENTED("TranslateCompareFunc");
}
}
vk::StencilOp TranslateStencilOp(StencilOp stencilOp)
{
switch (stencilOp)
{
case StencilOp::Keep: return vk::StencilOp::eKeep;
case StencilOp::Zero: return vk::StencilOp::eZero;
case StencilOp::Replace: return vk::StencilOp::eReplace;
case StencilOp::Increment: return vk::StencilOp::eIncrementAndClamp;
case StencilOp::IncrementWrap: return vk::StencilOp::eIncrementAndWrap;
case StencilOp::Decrement: return vk::StencilOp::eDecrementAndClamp;
case StencilOp::DecrementWrap: return vk::StencilOp::eDecrementAndWrap;
case StencilOp::Invert: return vk::StencilOp::eInvert;
default: CORELIB_NOT_IMPLEMENTED("TranslateStencilOp");
}
}
vk::CullModeFlags TranslateCullMode(CullMode mode)
{
switch (mode)
{
case CullMode::CullBackFace: return vk::CullModeFlagBits::eBack;
case CullMode::CullFrontFace: return vk::CullModeFlagBits::eFront;
case CullMode::Disabled: return vk::CullModeFlagBits::eNone;
default: throw CoreLib::NotImplementedException("TranslateCullMode");
}
}
vk::PrimitiveTopology TranslatePrimitiveTopology(PrimitiveType ptype)
{
switch (ptype)
{
case PrimitiveType::Triangles: return vk::PrimitiveTopology::eTriangleList;
case PrimitiveType::Points: return vk::PrimitiveTopology::ePointList;
case PrimitiveType::Lines: return vk::PrimitiveTopology::eLineList;
case PrimitiveType::TriangleStrips: return vk::PrimitiveTopology::eTriangleStrip;
case PrimitiveType::LineStrips: return vk::PrimitiveTopology::eLineStrip;
default: CORELIB_NOT_IMPLEMENTED("TranslatePrimitiveTopology");
}
}
vk::AttachmentLoadOp TranslateLoadOp(LoadOp op)
{
switch (op)
{
case LoadOp::Load: return vk::AttachmentLoadOp::eLoad;
case LoadOp::Clear: return vk::AttachmentLoadOp::eClear;
case LoadOp::DontCare: return vk::AttachmentLoadOp::eDontCare;
default: CORELIB_NOT_IMPLEMENTED("TranslateLoadOp");
}
}
vk::AttachmentStoreOp TranslateStoreOp(StoreOp op)
{
switch (op)
{
case StoreOp::Store: return vk::AttachmentStoreOp::eStore;
case StoreOp::DontCare: return vk::AttachmentStoreOp::eDontCare;
default: CORELIB_NOT_IMPLEMENTED("TranslateStoreOp");
}
}
/*
* Vulkan helper functions
*/
vk::AccessFlags LayoutFlags(vk::ImageLayout layout)
{
switch (layout)
{
case vk::ImageLayout::eUndefined:
return vk::AccessFlags();
case vk::ImageLayout::eGeneral:
return vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eInputAttachmentRead |
vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead |
vk::AccessFlagBits::eTransferWrite;
case vk::ImageLayout::eColorAttachmentOptimal:
return vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eInputAttachmentRead;
case vk::ImageLayout::eDepthStencilAttachmentOptimal:
return vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
case vk::ImageLayout::eDepthStencilReadOnlyOptimal:
return vk::AccessFlagBits::eDepthStencilAttachmentRead;
case vk::ImageLayout::eShaderReadOnlyOptimal:
return vk::AccessFlagBits::eShaderRead;
case vk::ImageLayout::eTransferSrcOptimal:
return vk::AccessFlagBits::eTransferRead;
case vk::ImageLayout::eTransferDstOptimal:
return vk::AccessFlagBits::eTransferWrite;
case vk::ImageLayout::ePreinitialized:
return vk::AccessFlagBits::eHostWrite;
case vk::ImageLayout::ePresentSrcKHR:
return vk::AccessFlagBits::eMemoryRead;
default:
CORELIB_ABORT("Invalid ImageLayout");
}
}
vk::SampleCountFlagBits SampleCount(int samples)
{
if (samples <= 0 || (samples & (samples - 1)) != 0)
CORELIB_ABORT("samples must be a power of 2");
return (vk::SampleCountFlagBits)samples;
}
int32_t GetMemoryType(uint32_t memoryTypeBits, vk::MemoryPropertyFlags memoryPropertyFlags)
{
int32_t memoryTypeIndex = 0;
auto memProperties = RendererState::PhysicalDevice().getMemoryProperties();
for (uint32_t k = 0; k < 32; k++)
{
if ((memoryTypeBits & 1) == 1)
{
if ((memProperties.memoryTypes[k].propertyFlags & memoryPropertyFlags) == memoryPropertyFlags)
{
memoryTypeIndex = k;
return memoryTypeIndex;
}
}
memoryTypeBits >>= 1;
}
CORELIB_ABORT("Could not find a valid memory type index.");
}
vk::ShaderStageFlagBits ShaderStage(ShaderType stage)
{
switch (stage)
{
case ShaderType::VertexShader: return vk::ShaderStageFlagBits::eVertex;
case ShaderType::FragmentShader: return vk::ShaderStageFlagBits::eFragment;
case ShaderType::ComputeShader: return vk::ShaderStageFlagBits::eCompute;
default: CORELIB_NOT_IMPLEMENTED("ShaderStageFlagBits");
}
}
class Texture : public CoreLib::Object
{
public:
StorageFormat format;
TextureUsage usage;
int width;
int height;
int depth;
int mipLevels;
int arrayLayers;
int numSamples;
bool isCubeArray = false;
vk::Image image;
CoreLib::List<vk::ImageView> views;
vk::DeviceMemory memory;
uint32_t lastLayoutCheckTaskId = 0;
CoreLib::List<vk::ImageLayout> currentSubresourceLayouts;
Texture(String name, TextureUsage usage, int width, int height, int depth, int mipLevels, int arrayLayers, int numSamples, StorageFormat format,
bool isArray,
vk::ImageCreateFlags createFlags = vk::ImageCreateFlags())
{
this->usage = usage;
this->format = format;
this->width = width;
this->height = height;
this->depth = depth;
this->mipLevels = mipLevels;
this->arrayLayers = arrayLayers;
this->numSamples = numSamples;
this->currentSubresourceLayouts.SetSize(arrayLayers * mipLevels);
for (auto& currentLayout : this->currentSubresourceLayouts)
currentLayout = vk::ImageLayout::eUndefined;
// Create texture resources
vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor;
vk::ImageUsageFlags usageFlags;
if (!!(this->usage & TextureUsage::ColorAttachment))
{
aspectFlags = vk::ImageAspectFlagBits::eColor;
usageFlags = vk::ImageUsageFlagBits::eColorAttachment;
}
else if (!!(this->usage & TextureUsage::DepthAttachment))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
usageFlags = vk::ImageUsageFlagBits::eDepthStencilAttachment;
if (this->format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
if (!!(this->usage & TextureUsage::Sampled))
{
usageFlags |= vk::ImageUsageFlagBits::eSampled;
}
if (!!(this->usage & TextureUsage::Storage))
{
usageFlags |= vk::ImageUsageFlagBits::eStorage;
}
vk::ImageCreateInfo imageCreateInfo = vk::ImageCreateInfo()
.setFlags(createFlags)
.setImageType(depth == 1 ? vk::ImageType::e2D : vk::ImageType::e3D)
.setFormat(TranslateStorageFormat(this->format))
.setExtent(vk::Extent3D(width, height, depth))
.setMipLevels(mipLevels)
.setArrayLayers(arrayLayers)
.setSamples(SampleCount(numSamples))
.setTiling(vk::ImageTiling::eOptimal)
.setUsage(vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst | usageFlags)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr)
.setInitialLayout(vk::ImageLayout::eUndefined);
image = RendererState::Device().createImage(imageCreateInfo);
vk::MemoryRequirements imageMemoryRequirements = RendererState::Device().getImageMemoryRequirements(image);
vk::MemoryAllocateInfo imageAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(imageMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(imageMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal));
memory = RendererState::Device().allocateMemory(imageAllocateInfo);
RendererState::Device().bindImageMemory(image, memory, 0);
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(mipLevels)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageViewType viewType = vk::ImageViewType::e2D;
if (depth == 1)
{
if (createFlags & vk::ImageCreateFlagBits::eCubeCompatible)
{
if (isArray)
viewType = vk::ImageViewType::eCubeArray;
else
viewType = vk::ImageViewType::eCube;
}
else if (isArray)
viewType = vk::ImageViewType::e2DArray;
}
else viewType = vk::ImageViewType::e3D;
vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(image)
.setViewType(viewType)
.setFormat(imageCreateInfo.format)
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))//
.setSubresourceRange(imageSubresourceRange);
views.Add(RendererState::Device().createImageView(imageViewCreateInfo));
if (isDepthFormat(this->format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(image)
.setViewType(viewType)
.setFormat(imageCreateInfo.format)
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR))//
.setSubresourceRange(imageSubresourceRange);
views.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
if (this->format == StorageFormat::Depth24Stencil8)
{
aspectFlags = vk::ImageAspectFlagBits::eStencil;
imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(image)
.setViewType(viewType)
.setFormat(imageCreateInfo.format)
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eR))//
.setSubresourceRange(imageSubresourceRange);
views.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
#ifdef _DEBUG
if (vkDebugMarkerSetObjectNameEXT)
{
vk::DebugMarkerObjectNameInfoEXT nameInfo = vk::DebugMarkerObjectNameInfoEXT()
.setObject((uint64_t)(VkImage)image)
.setObjectType(vk::DebugReportObjectTypeEXT::eImage)
.setPObjectName(name.Buffer());
vkDebugMarkerSetObjectNameEXT(RendererState::Device(), &(VkDebugMarkerObjectNameInfoEXT&)nameInfo);
}
#else
CORELIB_UNUSED(name);
#endif
}
~Texture()
{
if (memory) RendererState::Device().freeMemory(memory);
for (auto view : views) RendererState::Device().destroyImageView(view);
if (image) RendererState::Device().destroyImage(image);
}
void TransferLayout(vk::ImageLayout targetLayout, List<vk::ImageMemoryBarrier>& imageBarriers)
{
struct LayoutTransferOp
{
vk::ImageSubresourceRange subresourceRange;
vk::ImageLayout oldLayout;
};
CoreLib::ShortList<LayoutTransferOp> transferOps;
vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer();
vk::ImageAspectFlags aspectFlags;
if (isDepthFormat(format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
// Record command buffer
transferOps.Clear();
for (int i = 0; i < arrayLayers; i++)
{
for (int j = 0; j < mipLevels; j++)
{
int subresourceIndex = i * mipLevels + j;
if (currentSubresourceLayouts[subresourceIndex] != targetLayout)
{
vk::ImageSubresourceRange range = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(j)
.setLevelCount(1)
.setBaseArrayLayer(i)
.setLayerCount(1);
if (transferOps.Count())
{
auto& last = transferOps.Last();
if (last.subresourceRange.baseArrayLayer == (uint32_t)i &&
last.oldLayout == currentSubresourceLayouts[subresourceIndex] &&
last.subresourceRange.baseMipLevel + last.subresourceRange.levelCount == (uint32_t)j)
{
last.subresourceRange.levelCount++;
if (transferOps.Count() > 1)
{
auto& last2 = transferOps[transferOps.Count() - 2];
if (last2.oldLayout == last.oldLayout &&
last2.subresourceRange.baseArrayLayer + last2.subresourceRange.layerCount == (uint32_t)i &&
last2.subresourceRange.baseMipLevel == last.subresourceRange.baseMipLevel &&
last2.subresourceRange.levelCount == last.subresourceRange.levelCount)
{
last2.subresourceRange.layerCount++;
transferOps.SetSize(transferOps.Count() - 1);
}
}
continue;
}
}
transferOps.Add(LayoutTransferOp{ range, currentSubresourceLayouts[subresourceIndex] });
}
}
}
for (int i = 0; i < transferOps.Count(); i++)
{
vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(transferOps[i].oldLayout))
.setDstAccessMask(LayoutFlags(targetLayout))
.setOldLayout(transferOps[i].oldLayout)
.setNewLayout(targetLayout)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(transferOps[i].subresourceRange);
imageBarriers.Add(textureUsageBarrier);
}
for (auto& currentLayout : currentSubresourceLayouts)
currentLayout = targetLayout;
}
DataType GetDataTypeElementType(DataType type)
{
return (DataType)((int)(type)&(~3));
}
void SetData(int level, int layer, int xOffset, int yOffset, int zOffset, int pwidth, int pheight, int pdepth, int layerCount, DataType inputType, void* data)
{
CORELIB_ASSERT(numSamples == 1 && "samples must be equal to 1");
CORELIB_ASSERT(this->mipLevels > level && "Attempted to set mipmap data for invalid level");
CORELIB_ASSERT(this->mipLevels > level && "Attempted to set layer data for invalid layer");
vk::ImageAspectFlags aspectFlags;
if (isDepthFormat(format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
int dataTypeSize = DataTypeSize(inputType);
List<unsigned short> translatedBuffer;
if (data && (format == StorageFormat::R_F16 || format == StorageFormat::RG_F16 || format == StorageFormat::RGBA_F16)
&& (GetDataTypeElementType(inputType) != DataType::Half))
{
// transcode f32 to f16
int channelCount = 1;
switch (format)
{
case StorageFormat::RG_F16:
channelCount = 2;
break;
case StorageFormat::RGBA_F16:
channelCount = 4;
break;
default:
channelCount = 1;
break;
}
translatedBuffer.SetSize(pwidth * pheight * pdepth * layerCount * channelCount);
float * src = (float*)data;
for (int i = 0; i < translatedBuffer.Count(); i++)
translatedBuffer[i] = FloatToHalf(src[i]);
dataTypeSize >>= 1;
data = (void*)translatedBuffer.Buffer();
}
// Set up staging buffer and copy data to new image
int bufferSize = pwidth * pheight * pdepth * layerCount * dataTypeSize;
if (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB|| format == StorageFormat::BC5 || format == StorageFormat::BC3 || format == StorageFormat::BC6H)
{
int blocks = (int)(ceil(pwidth / 4.0f) * ceil(pheight / 4.0f));
bufferSize = (format == StorageFormat::BC1||format == StorageFormat::BC1_SRGB) ? blocks * 8 : blocks * 16;
bufferSize *= layerCount;
}
vk::BufferCreateInfo stagingBufferCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(bufferSize)
.setUsage(vk::BufferUsageFlagBits::eTransferSrc)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingBufferCreateInfo);
vk::MemoryRequirements stagingBufferMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer);
vk::MemoryAllocateInfo bufferAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(stagingBufferMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(stagingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible));
vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(bufferAllocateInfo);
RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0);
void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
if (data)
{
memcpy(stagingMappedMemory, data, bufferSize);
}
else
{
memset(stagingMappedMemory, 0, bufferSize);
}
RendererState::Device().flushMappedMemoryRanges(vk::MappedMemoryRange(stagingMemory, 0, VK_WHOLE_SIZE));
RendererState::Device().unmapMemory(stagingMemory);
// Create buffer image copy information
vk::BufferImageCopy stagingCopy = vk::BufferImageCopy()
.setBufferOffset(0)
.setBufferRowLength(0)
.setBufferImageHeight(0)
.setImageSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(level).setBaseArrayLayer(layer).setLayerCount(layerCount))
.setImageOffset(vk::Offset3D(xOffset, yOffset, zOffset))
.setImageExtent(vk::Extent3D(pwidth, pheight, pdepth));
// Create command buffer
//TODO: Use CommandBuffer class?
vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer();
// Record command buffer
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
transferCommandBuffer.begin(transferBeginInfo);
List<vk::ImageMemoryBarrier> barriers;
barriers.Clear();
for (int i = 0; i < mipLevels; i++)
{
vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(i)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageMemoryBarrier textureCopyBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setOldLayout(vk::ImageLayout::eUndefined)
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureSubresourceRange);
barriers.Add(textureCopyBarrier);
}
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eTransfer,
vk::DependencyFlags(),
nullptr,
nullptr,
vk::ArrayProxy<const vk::ImageMemoryBarrier>(barriers.Count(), barriers.Buffer())
);
transferCommandBuffer.copyBufferToImage(
stagingBuffer,
this->image,
vk::ImageLayout::eTransferDstOptimal,
stagingCopy
);
barriers.Clear();
for (int i = 0; i < mipLevels; i++)
{
vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(i)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setDstAccessMask(LayoutFlags(LayoutFromUsage(this->usage)))
.setOldLayout(vk::ImageLayout::eTransferDstOptimal)
.setNewLayout(LayoutFromUsage(this->usage))
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureSubresourceRange);
for (int l = 0; l < arrayLayers; l++)
{
int subresourceIndex = l * mipLevels + i;
currentSubresourceLayouts[subresourceIndex] = LayoutFromUsage(this->usage);
}
barriers.Add(textureUsageBarrier);
}
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
vk::ArrayProxy<const vk::ImageMemoryBarrier>(barriers.Count(), barriers.Buffer())
);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
RendererState::TransferQueue().waitIdle();
// Destroy staging resources
RendererState::Device().freeMemory(stagingMemory);
RendererState::Device().destroyBuffer(stagingBuffer);
for (auto& currentLayout : currentSubresourceLayouts)
currentLayout = LayoutFromUsage(this->usage);
}
void GetData(int mipLevel, int arrayLayer, void* data, int bufSize)
{
CORELIB_UNUSED(bufSize);
// Set up staging buffer and copy data to new image
int bufferSize = 0;
if (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB || format == StorageFormat::BC5 || format == StorageFormat::BC3)
{
int blocks = (int)(ceil(width / 4.0f) * ceil(height / 4.0f));
bufferSize = (format == StorageFormat::BC1 || format == StorageFormat::BC1_SRGB) ? blocks * 8 : blocks * 16;
}
else
{
bufferSize = width * height * StorageFormatSize(format);
}
CORELIB_ASSERT(bufferSize <= bufSize && "buffer size is too small");
vk::BufferCreateInfo stagingBufferCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(bufferSize)
.setUsage(vk::BufferUsageFlagBits::eTransferDst)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingBufferCreateInfo);
vk::MemoryRequirements stagingBufferMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer);
vk::MemoryAllocateInfo bufferAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(stagingBufferMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(stagingBufferMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible));
vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(bufferAllocateInfo);
RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0);
// Get image aspect flags
vk::ImageAspectFlags aspectFlags = vk::ImageAspectFlagBits::eColor;
if (!!(usage & TextureUsage::ColorAttachment))
{
aspectFlags = vk::ImageAspectFlagBits::eColor;
}
else if (!!(usage & TextureUsage::DepthAttachment))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
// Create buffer image copy information
vk::BufferImageCopy stagingCopy = vk::BufferImageCopy()
.setBufferOffset(0)
.setBufferRowLength(0)
.setBufferImageHeight(0)
.setImageSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(mipLevel).setBaseArrayLayer(arrayLayer).setLayerCount(1))
.setImageOffset(vk::Offset3D())
.setImageExtent(vk::Extent3D(Math::Max(1, width >> mipLevel), Math::Max(1, height >> mipLevel), 1));
// Create command buffer
//TODO: Use CommandBuffer class?
vk::CommandBuffer transferCommandBuffer = RendererState::CreateCommandBuffer(RendererState::TransferCommandPool());
// Record command buffer
vk::ImageSubresourceRange textureSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(mipLevels)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
int subresourceIndex = arrayLayer * mipLevels + mipLevel;
vk::ImageMemoryBarrier textureCopyBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(currentSubresourceLayouts[subresourceIndex]))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setOldLayout(currentSubresourceLayouts[subresourceIndex])
.setNewLayout(vk::ImageLayout::eTransferSrcOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureSubresourceRange);
vk::ImageMemoryBarrier textureUsageBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setDstAccessMask(LayoutFlags(currentSubresourceLayouts[subresourceIndex]))
.setOldLayout(vk::ImageLayout::eTransferSrcOptimal)
.setNewLayout(currentSubresourceLayouts[subresourceIndex])
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureSubresourceRange);
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
transferCommandBuffer.begin(transferBeginInfo);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eTransfer,
vk::DependencyFlags(),
nullptr,
nullptr,
textureCopyBarrier
);
transferCommandBuffer.copyImageToBuffer(
this->image,
vk::ImageLayout::eTransferSrcOptimal,
stagingBuffer,
stagingCopy
);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureUsageBarrier
);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
RendererState::TransferQueue().waitIdle();
RendererState::DestroyCommandBuffer(RendererState::TransferCommandPool(), transferCommandBuffer);
// Map memory and copy
assert(bufSize >= bufferSize);
float* stagingMappedMemory = (float*)RendererState::Device().mapMemory(stagingMemory, 0, bufferSize, vk::MemoryMapFlags());
memcpy(data, stagingMappedMemory, bufferSize);
RendererState::Device().unmapMemory(stagingMemory);
// Destroy staging resources
RendererState::Device().freeMemory(stagingMemory);
RendererState::Device().destroyBuffer(stagingBuffer);
}
void BuildMipmaps()
{
vk::ImageAspectFlags aspectFlags;
if (isDepthFormat(format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
// Create command buffer
vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer();
vk::Filter blitFilter = vk::Filter::eLinear;
switch (format)
{
case StorageFormat::R_I8:
case StorageFormat::R_I16:
case StorageFormat::Int32_Raw:
case StorageFormat::RG_I8:
case StorageFormat::RG_I16:
case StorageFormat::RG_I32_Raw:
case StorageFormat::RGBA_I8:
case StorageFormat::RGBA_I16:
case StorageFormat::RGBA_I32_Raw:
blitFilter = vk::Filter::eNearest;
default:
break;
}
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
transferCommandBuffer.begin(transferBeginInfo);
vk::ImageSubresourceRange level0SubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageMemoryBarrier textureSrcBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(currentSubresourceLayouts[0]))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setOldLayout(currentSubresourceLayouts[0])
.setNewLayout(vk::ImageLayout::eTransferSrcOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(level0SubresourceRange);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureSrcBarrier
);
for (int i = 1; i < mipLevels; i++)
{
// Record command buffer
vk::ImageSubresourceRange textureSrcSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(i - 1)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageSubresourceRange textureDstSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(i)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageMemoryBarrier textureDstBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setOldLayout(vk::ImageLayout::eUndefined)
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureDstSubresourceRange);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureDstBarrier
);
vk::ImageBlit blitRegion;
blitRegion.setSrcSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(i - 1).setBaseArrayLayer(0).setLayerCount(arrayLayers))
.setSrcOffsets(std::array<vk::Offset3D, 2>{vk::Offset3D(0, 0, 0), vk::Offset3D(Math::Max(1, width >> (i - 1)), Math::Max(1, height >> (i - 1)), Math::Max(1, depth >> (i - 1)))})
.setDstSubresource(vk::ImageSubresourceLayers().setAspectMask(aspectFlags).setMipLevel(i).setBaseArrayLayer(0).setLayerCount(arrayLayers))
.setDstOffsets(std::array<vk::Offset3D, 2>{vk::Offset3D(0, 0, 0), vk::Offset3D(Math::Max(1, width >> i), Math::Max(1, height >> i), Math::Max(1, depth >> i))});
// Blit texture to each mip level
transferCommandBuffer.blitImage(
image, vk::ImageLayout::eTransferSrcOptimal,
image, vk::ImageLayout::eTransferDstOptimal,
blitRegion,
blitFilter
);
vk::ImageMemoryBarrier textureDstFinishBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setOldLayout(vk::ImageLayout::eTransferDstOptimal)
.setNewLayout(vk::ImageLayout::eTransferSrcOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(textureDstSubresourceRange);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureDstFinishBarrier
);
}
vk::ImageSubresourceRange allSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(mipLevels)
.setBaseArrayLayer(0)
.setLayerCount(arrayLayers);
vk::ImageMemoryBarrier textureDstFinishBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setDstAccessMask(LayoutFlags(currentSubresourceLayouts[0]))
.setOldLayout(vk::ImageLayout::eTransferSrcOptimal)
.setNewLayout(LayoutFromUsage(this->usage))
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(this->image)
.setSubresourceRange(allSubresourceRange);
transferCommandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureDstFinishBarrier
);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
for (auto& currentLayout : currentSubresourceLayouts)
currentLayout = LayoutFromUsage(this->usage);
}
void* Ptr()
{
return this;
}
};
class Texture2D : public VK::Texture, public GameEngine::Texture2D
{
//TODO: Need some way of determining layouts and performing transitions properly.
public:
Texture2D(String name, TextureUsage usage, int width, int height, int mipLevelCount, StorageFormat format)
: VK::Texture(name, usage, width, height, 1, mipLevelCount, 1, 1, format, false) {};
void GetSize(int& pwidth, int& pheight) override
{
pwidth = width;
pheight = height;
}
virtual bool IsDepthStencilFormat() override
{
return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32;
}
void SetData(int level, int pwidth, int pheight, int /*numSamples*/, DataType inputType, void* data) override
{
VK::Texture::SetData(level, 0, 0, 0, 0, pwidth, pheight, 1, 1, inputType, data);
}
void SetData(int pwidth, int pheight, int /*numSamples*/, DataType inputType, void* data) override
{
VK::Texture::SetData(0, 0, 0, 0, 0, pwidth, pheight, 1, 1, inputType, data);
}
void BuildMipmaps() override
{
VK::Texture::BuildMipmaps();
}
void GetData(int mipLevel, void * data, int bufSize) override
{
VK::Texture::GetData(mipLevel, 0, data, bufSize);
}
void* GetInternalPtr() override
{
return VK::Texture::Ptr();
}
};
class Texture2DArray : public VK::Texture, public GameEngine::Texture2DArray
{
public:
Texture2DArray(String name, TextureUsage usage, int width, int height, int mipLevels, int arrayLayers, StorageFormat newFormat)
: VK::Texture(name, usage, width, height, 1, mipLevels, arrayLayers, 1, newFormat, true) {};
virtual void GetSize(int& pwidth, int& pheight, int& players) override
{
pwidth = this->width;
pheight = this->height;
players = this->arrayLayers;
}
virtual bool IsDepthStencilFormat() override
{
return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32;
}
virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void * data) override
{
VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data);
}
virtual void BuildMipmaps() override
{
VK::Texture::BuildMipmaps();
}
void* GetInternalPtr() override
{
return VK::Texture::Ptr();
}
};
class TextureCube : public VK::Texture, public GameEngine::TextureCube
{
public:
TextureCube(String name, TextureUsage usage, int psize, int mipLevels, StorageFormat format)
: VK::Texture(name, usage, psize, psize, 1, mipLevels, 6, 1, format, false, vk::ImageCreateFlagBits::eCubeCompatible), size(psize)
{
List<float> zeroMem;
zeroMem.SetSize(psize * psize * 6 * 4);
for (int i = 0; i < zeroMem.Count(); i++)
zeroMem[i] = 0.0f;
for (int i = 0; i < mipLevels; i++)
VK::Texture::SetData(i, 0, 0, 0, 0, psize >> i, psize >> i, 1, 6, DataType::Float4, zeroMem.Buffer());
};
int size = 0;
virtual void GetSize(int & psize) override
{
psize = size;
}
virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void* data) override
{
VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data);
}
virtual bool IsDepthStencilFormat() override
{
return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32;
}
void* GetInternalPtr() override
{
return VK::Texture::Ptr();
}
};
class TextureCubeArray : public VK::Texture, public GameEngine::TextureCubeArray
{
public:
int count;
TextureCubeArray(String name, TextureUsage usage, int cubeCount, int psize, int mipLevels, StorageFormat format)
: VK::Texture(name, usage, psize, psize, 1, mipLevels, cubeCount * 6, 1, format, true, vk::ImageCreateFlagBits::eCubeCompatible), size(psize)
{
this->isCubeArray = true;
List<float> zeroMem;
zeroMem.SetSize(psize * psize * 6 * 4 * cubeCount);
for (int i = 0; i < zeroMem.Count(); i++)
zeroMem[i] = 0.0f;
for (int i = 0; i < mipLevels; i++)
VK::Texture::SetData(i, 0, 0, 0, 0, psize >> i, psize >> i, 1, cubeCount * 6, DataType::Float4, zeroMem.Buffer());
count = cubeCount;
};
int size = 0;
virtual void GetSize(int & psize, int &pCount) override
{
psize = size;
pCount = count;
}
virtual void SetData(int mipLevel, int xOffset, int yOffset, int layerOffset, int pwidth, int pheight, int layerCount, DataType inputType, void* data) override
{
VK::Texture::SetData(mipLevel, layerOffset, xOffset, yOffset, 0, pwidth, pheight, 1, layerCount, inputType, data);
}
virtual bool IsDepthStencilFormat() override
{
return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32;
}
void* GetInternalPtr() override
{
return VK::Texture::Ptr();
}
};
class Texture3D : public VK::Texture, public GameEngine::Texture3D
{
public:
Texture3D(String name, TextureUsage usage, int width, int height, int depth, int mipLevels, StorageFormat newFormat)
: VK::Texture(name, usage, width, height, depth, mipLevels, 1, 1, newFormat, false) {};
virtual void GetSize(int& pwidth, int& pheight, int& pdepth) override
{
pwidth = this->width;
pheight = this->height;
pdepth = this->depth;
}
virtual void SetData(int mipLevel, int xOffset, int yOffset, int zOffset, int pwidth, int pheight, int pdepth, DataType inputType, void * data) override
{
VK::Texture::SetData(mipLevel, 0, xOffset, yOffset, zOffset, pwidth, pheight, pdepth, 1, inputType, data);
}
virtual bool IsDepthStencilFormat() override
{
return this->format == StorageFormat::Depth24 || this->format == StorageFormat::Depth24Stencil8 || this->format == StorageFormat::Depth32;
}
void* GetInternalPtr() override
{
return VK::Texture::Ptr();
}
};
class TextureSampler : public GameEngine::TextureSampler
{
public:
vk::Sampler sampler;
TextureFilter filter = TextureFilter::Nearest;
WrapMode wrap = WrapMode::Repeat;
CompareFunc op = CompareFunc::Disabled;
void CreateSampler()
{
DestroySampler();
// Default sampler create info
vk::SamplerCreateInfo samplerCreateInfo = vk::SamplerCreateInfo()
.setFlags(vk::SamplerCreateFlags())
.setMinFilter(vk::Filter::eNearest)
.setMagFilter(vk::Filter::eNearest)
.setMipmapMode(vk::SamplerMipmapMode::eNearest)
.setAddressModeU(vk::SamplerAddressMode::eRepeat)
.setAddressModeV(vk::SamplerAddressMode::eRepeat)
.setAddressModeW(vk::SamplerAddressMode::eRepeat)
.setMipLodBias(0.0f)
.setAnisotropyEnable(VK_FALSE)
.setMaxAnisotropy(1.0f)
.setCompareEnable(op != CompareFunc::Disabled)
.setCompareOp(TranslateCompareFunc(op))
.setMinLod(0.0f)
.setMaxLod(0.0f)
.setBorderColor(vk::BorderColor::eFloatTransparentBlack)
.setUnnormalizedCoordinates(VK_FALSE);
// Modify create info based on parameters
switch (filter)
{
case TextureFilter::Nearest:
samplerCreateInfo.setMinFilter(vk::Filter::eNearest);
samplerCreateInfo.setMagFilter(vk::Filter::eNearest);
break;
case TextureFilter::Linear:
samplerCreateInfo.setMinFilter(vk::Filter::eLinear);
samplerCreateInfo.setMagFilter(vk::Filter::eLinear);
break;
case TextureFilter::Trilinear:
samplerCreateInfo.setMinFilter(vk::Filter::eLinear);
samplerCreateInfo.setMagFilter(vk::Filter::eLinear);
samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear);
samplerCreateInfo.setMaxLod(15.0f);
break;
case TextureFilter::Anisotropic4x:
samplerCreateInfo.setMinFilter(vk::Filter::eLinear);
samplerCreateInfo.setMagFilter(vk::Filter::eLinear);
samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear);
samplerCreateInfo.setMaxLod(15.0f);
samplerCreateInfo.setAnisotropyEnable(VK_TRUE);
samplerCreateInfo.setMaxAnisotropy(4.0f);
break;
case TextureFilter::Anisotropic8x:
samplerCreateInfo.setMinFilter(vk::Filter::eLinear);
samplerCreateInfo.setMagFilter(vk::Filter::eLinear);
samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear);
samplerCreateInfo.setMaxLod(15.0f);
samplerCreateInfo.setAnisotropyEnable(VK_TRUE);
samplerCreateInfo.setMaxAnisotropy(8.0f);
break;
case TextureFilter::Anisotropic16x:
samplerCreateInfo.setMinFilter(vk::Filter::eLinear);
samplerCreateInfo.setMagFilter(vk::Filter::eLinear);
samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear);
samplerCreateInfo.setMaxLod(15.0f);
samplerCreateInfo.setAnisotropyEnable(VK_TRUE);
samplerCreateInfo.setMaxAnisotropy(16.0f);
break;
}
switch (wrap)
{
case WrapMode::Clamp:
samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eClampToEdge);
samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eClampToEdge);
samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eClampToEdge);
break;
case WrapMode::Repeat:
samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eRepeat);
samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eRepeat);
samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eRepeat);
break;
case WrapMode::Mirror:
samplerCreateInfo.setAddressModeU(vk::SamplerAddressMode::eMirroredRepeat);
samplerCreateInfo.setAddressModeV(vk::SamplerAddressMode::eMirroredRepeat);
samplerCreateInfo.setAddressModeW(vk::SamplerAddressMode::eMirroredRepeat);
break;
}
sampler = RendererState::Device().createSampler(samplerCreateInfo);
}
void DestroySampler()
{
if (sampler) RendererState::Device().destroySampler(sampler);
}
public:
TextureSampler()
{
CreateSampler();
}
~TextureSampler()
{
DestroySampler();
}
TextureFilter GetFilter()
{
return filter;
}
void SetFilter(TextureFilter pfilter)
{
filter = pfilter;
// If anisotropy is not supported and we want anisotropic filtering, make trilinear filter
if (!RendererState::PhysicalDevice().getFeatures().samplerAnisotropy)
{
if (filter == TextureFilter::Anisotropic4x ||
filter == TextureFilter::Anisotropic8x ||
filter == TextureFilter::Anisotropic16x)
{
CoreLib::Diagnostics::Debug::WriteLine("Anisotropic filtering is not supported. Changing to trilinear.");
filter = TextureFilter::Trilinear;
}
}
else
{
TextureFilter oldFilter = filter;
float maxAnisotropy = RendererState::PhysicalDevice().getProperties().limits.maxSamplerAnisotropy;
switch (filter)
{
case TextureFilter::Anisotropic16x:
if (maxAnisotropy < 16.0f) filter = TextureFilter::Anisotropic8x;
// Fall through
case TextureFilter::Anisotropic8x:
if (maxAnisotropy < 8.0f) filter = TextureFilter::Anisotropic4x;
// Fall through
case TextureFilter::Anisotropic4x:
if (maxAnisotropy < 4.0f) filter = TextureFilter::Trilinear;
// Fall through
default:
break;
}
if (oldFilter != filter)
{
CoreLib::Diagnostics::Debug::Write("Max supported anisotropy is ");
CoreLib::Diagnostics::Debug::WriteLine(maxAnisotropy);
}
}
CreateSampler();
}
WrapMode GetWrapMode()
{
return wrap;
}
void SetWrapMode(WrapMode pwrap)
{
this->wrap = pwrap;
CreateSampler();
}
CompareFunc GetCompareFunc()
{
return op;
}
void SetDepthCompare(CompareFunc pop)
{
this->op = pop;
CreateSampler();
}
};
class BufferObject : public GameEngine::Buffer
{
friend class HardwareRenderer;
public:
vk::Buffer buffer;
vk::DeviceMemory memory;
vk::BufferUsageFlags usage;
vk::MemoryPropertyFlags location;
int mapOffset = 0;
int mapSize = -1;
int size = 0;
public:
BufferObject(vk::BufferUsageFlags usage, int psize, vk::MemoryPropertyFlags location)
{
//TODO: Should pass as input a requiredLocation and an optimalLocation?
this->location = location;
this->usage = usage;
this->size = psize;
// If we can't map the buffer, we need to specify it will be a transfer dest
if (!(this->location & vk::MemoryPropertyFlagBits::eHostVisible))
this->usage |= vk::BufferUsageFlagBits::eTransferDst;
// Create a buffer with the requested size
vk::BufferCreateInfo bufferCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(this->size)
.setUsage(this->usage)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
this->buffer = RendererState::Device().createBuffer(bufferCreateInfo);
// Check to see how much memory we actually require
vk::MemoryRequirements memoryRequirements = RendererState::Device().getBufferMemoryRequirements(this->buffer);
int backingSize = (int)memoryRequirements.size;
// If we allocate more memory than requested, recreate buffer to backing size
if (this->size != backingSize)
{
this->size = backingSize;
vk::BufferCreateInfo fullsizeBufferCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(this->size)
.setUsage(this->usage)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
RendererState::Device().destroyBuffer(this->buffer);
this->buffer = RendererState::Device().createBuffer(fullsizeBufferCreateInfo);
}
// Allocate memory for the buffer
vk::MemoryRequirements fullsizeMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(this->buffer);
vk::MemoryAllocateInfo fullsizeMemoryAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(fullsizeMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(fullsizeMemoryRequirements.memoryTypeBits, this->location));
this->memory = RendererState::Device().allocateMemory(fullsizeMemoryAllocateInfo);
RendererState::Device().bindBufferMemory(this->buffer, this->memory, 0);
}
~BufferObject()
{
if (this->buffer) RendererState::Device().destroyBuffer(this->buffer);
if (this->memory) RendererState::Device().freeMemory(this->memory);
}
void SetDataAsync(int offset, void* data, int psize)
{
if (psize == 0)
return;
// If the buffer is mappable, map and memcpy
if (location & vk::MemoryPropertyFlagBits::eHostVisible)
{
//TODO: Should memcpy + flush in chunks?
void* mappedMemory = Map(offset, psize);
memcpy(mappedMemory, data, psize);
Flush();
Unmap();
}
// Otherwise, we need to use command buffers
else
{
// Create command buffer
vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer();
assert(psize % 4 == 0);
assert(offset % 4 == 0);
// Record command buffer
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
// Transfer the data in chunks of <= 65536 bytes
transferCommandBuffer.begin(transferBeginInfo);
int remainingSize = psize;
int dataOffset = 0;
while (remainingSize > 65536)
{
transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, 65536, static_cast<char*>(data) + dataOffset);
remainingSize -= 65536;
dataOffset += 65536;
}
transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, remainingSize, static_cast<char*>(data) + dataOffset);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
}
}
void SetData(int offset, void* data, int psize)
{
CORELIB_ASSERT(data && "Initialize buffer with size preferred.");
// If the buffer is mappable, map and memcpy
if (location & vk::MemoryPropertyFlagBits::eHostVisible)
{
//TODO: Should memcpy + flush in chunks?
void* mappedMemory = Map(offset, psize);
memcpy(mappedMemory, data, psize);
Flush();
Unmap();
}
// Otherwise, we need to use command buffers
else
{
// Create command buffer
//TODO: Should this use a global buffer? How to handle thread safety?
vk::CommandBuffer transferCommandBuffer = RendererState::GetTempTransferCommandBuffer();
//TODO: Improve switching logic
bool staging = psize > (1 << 18);
if (staging)
{
// Create staging buffer
vk::BufferCreateInfo stagingCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(psize)
.setUsage(vk::BufferUsageFlagBits::eTransferSrc)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingCreateInfo);
vk::MemoryRequirements stagingMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer);
vk::MemoryAllocateInfo stagingMemoryAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(stagingMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(stagingMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible));
vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(stagingMemoryAllocateInfo);
RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0);
// Copy data to staging buffer
void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
memcpy(stagingMappedMemory, data, psize);
RendererState::Device().unmapMemory(stagingMemory);
// Create copy region description
vk::BufferCopy transferRegion = vk::BufferCopy()
.setSrcOffset(0)
.setDstOffset(offset)
.setSize(psize);
// Record command buffer
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
transferCommandBuffer.begin(transferBeginInfo);
transferCommandBuffer.copyBuffer(stagingBuffer, this->buffer, transferRegion);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
RendererState::TransferQueue().waitIdle(); //TODO: Remove
// Destroy staging resources
RendererState::Device().freeMemory(stagingMemory);
RendererState::Device().destroyBuffer(stagingBuffer);
}
else
{
assert(psize % 4 == 0);
assert(offset % 4 == 0);
// Record command buffer
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
// Transfer the data in chunks of <= 65536 bytes
transferCommandBuffer.begin(transferBeginInfo);
int remainingSize = psize;
int dataOffset = 0;
while (remainingSize > 65536)
{
transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, 65536, static_cast<char*>(data) + dataOffset);
remainingSize -= 65536;
dataOffset += 65536;
}
transferCommandBuffer.updateBuffer(this->buffer, offset + dataOffset, remainingSize, static_cast<char*>(data) + dataOffset);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::TransferQueue().submit(transferSubmitInfo, vk::Fence());
RendererState::TransferQueue().waitIdle(); //TODO: Remove
}
}
}
void SetData(void* data, int psize)
{
SetData(0, data, psize);
}
void GetData(void * pBuffer, int offset, int psize)
{
//TODO: Implement
// If the buffer is mappable, map and memcpy
if (location & vk::MemoryPropertyFlagBits::eHostVisible)
{
//TODO: Should memcpy + flush in chunks?
void* mappedMemory = Map(offset, psize);
memcpy(pBuffer, mappedMemory, psize);
Unmap();
}
else
{
vk::CommandBuffer transferCommandBuffer = RendererState::CreateCommandBuffer(RendererState::TransferCommandPool());
// Create staging buffer
vk::BufferCreateInfo stagingCreateInfo = vk::BufferCreateInfo()
.setFlags(vk::BufferCreateFlags())
.setSize(psize)
.setUsage(vk::BufferUsageFlagBits::eTransferDst)
.setSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(nullptr);
vk::Buffer stagingBuffer = RendererState::Device().createBuffer(stagingCreateInfo);
vk::MemoryRequirements stagingMemoryRequirements = RendererState::Device().getBufferMemoryRequirements(stagingBuffer);
vk::MemoryAllocateInfo stagingMemoryAllocateInfo = vk::MemoryAllocateInfo()
.setAllocationSize(stagingMemoryRequirements.size)
.setMemoryTypeIndex(GetMemoryType(stagingMemoryRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible));
vk::DeviceMemory stagingMemory = RendererState::Device().allocateMemory(stagingMemoryAllocateInfo);
RendererState::Device().bindBufferMemory(stagingBuffer, stagingMemory, 0);
// Create copy region description
vk::BufferCopy transferRegion = vk::BufferCopy()
.setSrcOffset(0)
.setDstOffset(offset)
.setSize(psize);
// Record command buffer
vk::CommandBufferBeginInfo transferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
transferCommandBuffer.begin(transferBeginInfo);
transferCommandBuffer.copyBuffer(this->buffer, stagingBuffer, transferRegion);
transferCommandBuffer.end();
// Submit to queue
vk::SubmitInfo transferSubmitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&transferCommandBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::RenderQueue().submit(transferSubmitInfo, vk::Fence());
RendererState::RenderQueue().waitIdle(); //TODO: Remove
// map memory and copy
void* stagingMappedMemory = RendererState::Device().mapMemory(stagingMemory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
memcpy(pBuffer, stagingMappedMemory, psize);
RendererState::Device().unmapMemory(stagingMemory);
RendererState::DestroyCommandBuffer(RendererState::TransferCommandPool(), transferCommandBuffer);
// Destroy staging resources
RendererState::Device().freeMemory(stagingMemory);
RendererState::Device().destroyBuffer(stagingBuffer);
}
}
int GetSize()
{
return size;
}
void* Map(int offset, int psize)
{
//TEMP
assert(buffer);
assert(this->mapSize == -1);
//ENDTEMP
// Buffer must have host visible flag to be mappable
if (!(location & vk::MemoryPropertyFlagBits::eHostVisible))
return nullptr;
//TODO: We need to guarantee that all previous commands writing to this range have completed
// Can probably do this by associating each buffer with a fence, and waiting on the fence
//TODO: Lock mutex for memory
this->mapOffset = offset;
this->mapSize = psize;
return RendererState::Device().mapMemory(memory, offset, psize, vk::MemoryMapFlags());
}
void* Map()
{
return Map(0, this->size);
}
// If the buffer is not host coherent, we need to flush to guarantee writes visible to device
void Flush(int offset, int psize)
{
assert(this->mapSize >= 0);
// We only need to flush if not host coherent
if (!(location & vk::MemoryPropertyFlagBits::eHostCoherent))
{
//TEMP
assert(offset >= this->mapOffset);
assert(offset % (RendererState::PhysicalDevice().getProperties().limits.nonCoherentAtomSize) == 0);
assert(psize % (RendererState::PhysicalDevice().getProperties().limits.nonCoherentAtomSize) == 0);
assert(psize <= this->mapSize || (this->mapSize == -1 && psize <= (this->size - offset)));
//TODO: Round down offset and round up size?
//ENDTEMP
//TODO: We need to make sure we do this before command buffers using the memory are submitted
vk::MappedMemoryRange memoryRange = vk::MappedMemoryRange()
.setMemory(this->memory)
.setOffset(offset)
.setSize(psize);
RendererState::Device().flushMappedMemoryRanges(memoryRange);
}
}
void Flush()
{
Flush(this->mapOffset, this->mapSize);
}
void Unmap()
{
assert(this->mapSize >= 0);
RendererState::Device().unmapMemory(memory);
this->mapSize = -1;
this->mapOffset = 0;
//TODO: unlock mutex
}
};
class Shader : public GameEngine::Shader
{
public:
ShaderType stage;
vk::ShaderModule module;
Shader() {}
~Shader()
{
Destroy();
}
void Create(ShaderType pstage, const char* data, int size)
{
Destroy();
this->stage = pstage;
vk::ShaderModuleCreateInfo createInfo(vk::ShaderModuleCreateFlags(), (size_t)size, (const uint32_t*)data);
this->module = RendererState::Device().createShaderModule(createInfo);
}
void Destroy()
{
if (module) RendererState::Device().destroyShaderModule(module);
module = vk::ShaderModule();
}
};
class RenderTargetLayout : public GameEngine::RenderTargetLayout
{
public:
CoreLib::List<vk::AttachmentReference> colorReferences;
vk::AttachmentReference depthReference;
vk::RenderPass renderPass, renderPassClear;
private:
void Resize(CoreLib::List<vk::AttachmentDescription> &descriptions, int size)
{
if (descriptions.Count() < size)
descriptions.SetSize(size);
}
void SetColorAttachment(CoreLib::List<vk::AttachmentDescription> & descriptions, int binding, StorageFormat format,
bool ignoreInitialContent, LoadOp loadOp = LoadOp::Load, StoreOp storeOp = StoreOp::Store)
{
Resize(descriptions, binding + 1);
if (ignoreInitialContent && loadOp == LoadOp::Load)
loadOp = LoadOp::DontCare;
descriptions[binding] = vk::AttachmentDescription()
.setFlags(vk::AttachmentDescriptionFlags())
.setFormat(TranslateStorageFormat(format))//
.setInitialLayout(ignoreInitialContent ? vk::ImageLayout::eUndefined : vk::ImageLayout::eColorAttachmentOptimal)//
.setFinalLayout(vk::ImageLayout::eColorAttachmentOptimal)//
.setSamples(SampleCount(1))
.setLoadOp(TranslateLoadOp(loadOp))
.setStoreOp(TranslateStoreOp(storeOp))
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)//
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);//
//if (samples > 1)
//{
// //TODO: need to resolve?
//}
}
void SetDepthAttachment(CoreLib::List<vk::AttachmentDescription> &descriptions, int binding, StorageFormat format,
bool ignoreInitialContent, LoadOp loadOp = LoadOp::Load, StoreOp storeOp = StoreOp::Store)
{
CORELIB_ASSERT(depthReference.layout == vk::ImageLayout::eUndefined && "Only 1 depth/stencil attachment allowed.");
Resize(descriptions, binding + 1);
if (ignoreInitialContent && loadOp == LoadOp::Load)
loadOp = LoadOp::DontCare;
descriptions[binding] = vk::AttachmentDescription()
.setFlags(vk::AttachmentDescriptionFlags())
.setFormat(TranslateStorageFormat(format))
.setInitialLayout(ignoreInitialContent ? vk::ImageLayout::eUndefined : vk::ImageLayout::eDepthStencilAttachmentOptimal)
.setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)
.setSamples(SampleCount(1))
.setLoadOp(TranslateLoadOp(loadOp))
.setStoreOp(TranslateStoreOp(storeOp))
.setStencilLoadOp(TranslateLoadOp(loadOp))
.setStencilStoreOp(TranslateStoreOp(storeOp));
}
public:
RenderTargetLayout() {};
RenderTargetLayout(CoreLib::ArrayView<AttachmentLayout> bindings, bool ignoreInitialContent)
{
depthReference.attachment = VK_ATTACHMENT_UNUSED;
List<vk::AttachmentDescription> descriptions, descriptionsClear;
int location = 0;
for (auto binding : bindings)
{
switch (binding.Usage)
{
case TextureUsage::ColorAttachment:
case TextureUsage::SampledColorAttachment:
SetColorAttachment(descriptions, location, binding.ImageFormat, ignoreInitialContent);
SetColorAttachment(descriptionsClear, location, binding.ImageFormat, ignoreInitialContent, LoadOp::Clear);
break;
case TextureUsage::DepthAttachment:
case TextureUsage::SampledDepthAttachment:
SetDepthAttachment(descriptions, location, binding.ImageFormat, ignoreInitialContent);
SetDepthAttachment(
descriptionsClear, location, binding.ImageFormat, ignoreInitialContent, LoadOp::Clear);
break;
case TextureUsage::Unused:
break;
default:
throw HardwareRendererException("Unsupported attachment usage");
}
location++;
}
int binding = 0;
for (auto description : descriptions)
{
if (description.finalLayout == vk::ImageLayout::eColorAttachmentOptimal)
colorReferences.Add(vk::AttachmentReference(binding, vk::ImageLayout::eColorAttachmentOptimal));
else if (description.finalLayout == vk::ImageLayout::eDepthStencilAttachmentOptimal)
depthReference = vk::AttachmentReference(binding, vk::ImageLayout::eDepthStencilAttachmentOptimal);
binding++;
}
// Create Subpass Descriptions
//TODO: Subpasses need to be implemented
CoreLib::List<vk::SubpassDescription> subpassDescriptions;
subpassDescriptions.Add(
vk::SubpassDescription()
.setFlags(vk::SubpassDescriptionFlags())
.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
.setInputAttachmentCount(0)
.setPInputAttachments(nullptr)
.setColorAttachmentCount(colorReferences.Count())
.setPColorAttachments(colorReferences.Buffer())
.setPResolveAttachments(nullptr)
.setPDepthStencilAttachment(&depthReference)
.setPreserveAttachmentCount(0)
.setPPreserveAttachments(nullptr)
);
// Create RenderPass
vk::RenderPassCreateInfo renderPassCreateInfo = vk::RenderPassCreateInfo()
.setFlags(vk::RenderPassCreateFlags())
.setAttachmentCount(descriptions.Count())
.setPAttachments(descriptions.Buffer())
.setSubpassCount(subpassDescriptions.Count())
.setPSubpasses(subpassDescriptions.Buffer())
.setDependencyCount(0)
.setPDependencies(nullptr);
this->renderPass = RendererState::Device().createRenderPass(renderPassCreateInfo);
renderPassCreateInfo.setPAttachments(descriptionsClear.Buffer());
this->renderPassClear = RendererState::Device().createRenderPass(renderPassCreateInfo);
}
~RenderTargetLayout()
{
if (renderPass) RendererState::Device().destroyRenderPass(renderPass);
if (renderPassClear)
RendererState::Device().destroyRenderPass(renderPassClear);
}
virtual GameEngine::FrameBuffer* CreateFrameBuffer(const RenderAttachments& renderAttachments) override;
};
class FrameBuffer : public GameEngine::FrameBuffer
{
public:
int width;
int height;
vk::Framebuffer framebuffer, framebufferClear;
CoreLib::RefPtr<RenderTargetLayout> renderTargetLayout;
RenderAttachments renderAttachments;
CoreLib::Array<vk::ClearValue, 10> clearValues;
CoreLib::List<vk::ImageView> attachmentImageViews;
FrameBuffer() {};
~FrameBuffer()
{
if (framebuffer) RendererState::Device().destroyFramebuffer(framebuffer);
if (framebufferClear)
RendererState::Device().destroyFramebuffer(framebufferClear);
for (auto view : attachmentImageViews)
RendererState::Device().destroyImageView(view);
}
virtual RenderAttachments& GetRenderAttachments() override
{
return renderAttachments;
}
};
GameEngine::FrameBuffer* RenderTargetLayout::CreateFrameBuffer(const RenderAttachments& renderAttachments)
{
#if _DEBUG
// Ensure the RenderAttachments are compatible with this RenderTargetLayout
for (auto colorReference : colorReferences)
{
TextureUsage usage = TextureUsage::ColorAttachment;
if (renderAttachments.attachments[colorReference.attachment].handle.tex2D)
usage = dynamic_cast<Texture2D*>(renderAttachments.attachments[colorReference.attachment].handle.tex2D)->usage;
else if (renderAttachments.attachments[colorReference.attachment].handle.tex2DArray)
usage = dynamic_cast<Texture2DArray*>(renderAttachments.attachments[colorReference.attachment].handle.tex2DArray)->usage;
if (!(usage & TextureUsage::ColorAttachment))
throw HardwareRendererException("Incompatible RenderTargetLayout and RenderAttachments");
}
if (depthReference.layout != vk::ImageLayout::eUndefined)
{
TextureUsage usage = TextureUsage::ColorAttachment;
if (renderAttachments.attachments[depthReference.attachment].handle.tex2D)
usage = dynamic_cast<Texture2D*>(renderAttachments.attachments[depthReference.attachment].handle.tex2D)->usage;
else if (renderAttachments.attachments[depthReference.attachment].handle.tex2DArray)
usage = dynamic_cast<Texture2DArray*>(renderAttachments.attachments[depthReference.attachment].handle.tex2DArray)->usage;
if (!(usage & TextureUsage::DepthAttachment))
throw HardwareRendererException("Incompatible RenderTargetLayout and RenderAttachments");
}
#endif
FrameBuffer* result = new FrameBuffer();
result->renderTargetLayout = this;
result->renderAttachments = renderAttachments;
result->attachmentImageViews.Clear();
for (auto attachment : renderAttachments.attachments)
{
vk::ImageAspectFlags aspectFlags;
if (attachment.handle.tex2D)
{
auto tex = dynamic_cast<Texture2D*>(attachment.handle.tex2D);
if (isDepthFormat(tex->format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (tex->format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(1);
vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(tex->image)
.setViewType(vk::ImageViewType::e2D)
.setFormat(TranslateStorageFormat(tex->format))
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))//
.setSubresourceRange(imageSubresourceRange);
result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
else if (attachment.handle.tex2DArray)
{
auto tex = dynamic_cast<Texture2DArray*>(attachment.handle.tex2DArray);
if (isDepthFormat(tex->format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (tex->format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(attachment.layer)
.setLayerCount(1);
vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(tex->image)
.setViewType(vk::ImageViewType::e2D)
.setFormat(TranslateStorageFormat(tex->format))
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))//
.setSubresourceRange(imageSubresourceRange);
result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
else if (attachment.handle.texCube)
{
auto tex = dynamic_cast<TextureCube*>(attachment.handle.texCube);
if (isDepthFormat(tex->format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (tex->format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(attachment.level)
.setLevelCount(1)
.setBaseArrayLayer((int)attachment.face)
.setLayerCount(1);
vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(tex->image)
.setViewType(vk::ImageViewType::e2D)
.setFormat(TranslateStorageFormat(tex->format))
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))//
.setSubresourceRange(imageSubresourceRange);
result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
else if (attachment.handle.texCubeArray)
{
auto tex = dynamic_cast<TextureCubeArray*>(attachment.handle.texCubeArray);
if (isDepthFormat(tex->format))
{
aspectFlags = vk::ImageAspectFlagBits::eDepth;
if (tex->format == StorageFormat::Depth24Stencil8)
aspectFlags |= vk::ImageAspectFlagBits::eStencil;
}
else
aspectFlags = vk::ImageAspectFlagBits::eColor;
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(aspectFlags)
.setBaseMipLevel(attachment.level)
.setLevelCount(1)
.setBaseArrayLayer((int)attachment.face + attachment.layer * 6)
.setLayerCount(1);
vk::ImageViewCreateInfo imageViewCreateInfo = vk::ImageViewCreateInfo()
.setFlags(vk::ImageViewCreateFlags())
.setImage(tex->image)
.setViewType(vk::ImageViewType::e2D)
.setFormat(TranslateStorageFormat(tex->format))
.setComponents(vk::ComponentMapping(vk::ComponentSwizzle::eR, vk::ComponentSwizzle::eG, vk::ComponentSwizzle::eB, vk::ComponentSwizzle::eA))//
.setSubresourceRange(imageSubresourceRange);
result->attachmentImageViews.Add(RendererState::Device().createImageView(imageViewCreateInfo));
}
if (aspectFlags == vk::ImageAspectFlagBits::eColor)
{
result->clearValues.Add(vk::ClearValue(vk::ClearColorValue()));
}
else
{
result->clearValues.Add(vk::ClearDepthStencilValue(1.0f, 0U));
}
}
vk::FramebufferCreateInfo framebufferCreateInfo = vk::FramebufferCreateInfo()
.setFlags(vk::FramebufferCreateFlags())
.setRenderPass(renderPass)
.setAttachmentCount(result->attachmentImageViews.Count())
.setPAttachments(result->attachmentImageViews.Buffer())
.setWidth(renderAttachments.width)
.setHeight(renderAttachments.height)
.setLayers(1);
result->framebuffer = RendererState::Device().createFramebuffer(framebufferCreateInfo);
framebufferCreateInfo.setRenderPass(renderPassClear);
result->framebufferClear = RendererState::Device().createFramebuffer(framebufferCreateInfo);
result->width = renderAttachments.width;
result->height = renderAttachments.height;
return result;
}
class DescriptorSetLayout : public GameEngine::DescriptorSetLayout
{
public:
CoreLib::List<vk::DescriptorSetLayoutBinding> layoutBindings;
vk::DescriptorSetLayout layout;
#if _DEBUG
CoreLib::ArrayView<GameEngine::DescriptorLayout> descriptors;
#endif
DescriptorSetLayout(CoreLib::ArrayView<GameEngine::DescriptorLayout> descriptors)
{
#if _DEBUG
this->descriptors = descriptors;
CoreLib::Array<int, 32> usedDescriptors;
usedDescriptors.SetSize(32);
for (auto& desc : usedDescriptors)
desc = false;
#endif
for (auto& desc : descriptors)
{
#if _DEBUG
if (usedDescriptors[desc.Location] != false)
throw HardwareRendererException("Descriptor location already in use.");
usedDescriptors[desc.Location] = true;
#endif
layoutBindings.Add(
vk::DescriptorSetLayoutBinding()
.setBinding(desc.Location)
.setDescriptorType(TranslateBindingType(desc.Type))
.setDescriptorCount(desc.ArraySize)
.setStageFlags(TranslateStageFlags(desc.Stages))
.setPImmutableSamplers(nullptr)
);
}
vk::DescriptorSetLayoutCreateInfo createInfo = vk::DescriptorSetLayoutCreateInfo()
.setFlags(vk::DescriptorSetLayoutCreateFlags())
.setBindingCount(layoutBindings.Count())
.setPBindings(layoutBindings.Buffer());
layout = RendererState::Device().createDescriptorSetLayout(createInfo);
}
~DescriptorSetLayout()
{
RendererState::Device().destroyDescriptorSetLayout(layout);
}
};
struct TextureUse
{
VK::Texture* texture;
vk::ImageLayout targetLayout;
};
class DescriptorSet : public GameEngine::DescriptorSet
{
public:
//TODO: previous implementation in PipelineInstance would keep track of
// previously bound descriptors and then create new imageInfo/bufferInfo
// and swap them with the old one, as well as only updating the descriptors
// that had changed. Should this do that too?
vk::DescriptorSet descriptorSet;
vk::DescriptorPool descriptorPool;
CoreLib::RefPtr<DescriptorSetLayout> descriptorSetLayout;
CoreLib::List<vk::DescriptorImageInfo> imageInfo;
CoreLib::List<vk::DescriptorBufferInfo> bufferInfo;
CoreLib::List<vk::WriteDescriptorSet> writeDescriptorSets;
CoreLib::List<CoreLib::List<TextureUse>> textureUses;
public:
DescriptorSet() {}
DescriptorSet(DescriptorSetLayout* layout)
{
// We need to keep a ref pointer to the layout because we need to have
// the layout available when we call vkUpdateDescriptorSets (2.3.1)
descriptorSetLayout = layout;
std::pair<vk::DescriptorPool, vk::DescriptorSet> res = RendererState::AllocateDescriptorSet(layout->layout);
descriptorPool = res.first;
descriptorSet = res.second;
}
~DescriptorSet()
{
if (descriptorSet) RendererState::Device().freeDescriptorSets(descriptorPool, descriptorSet);
}
virtual void BeginUpdate() override
{
imageInfo.Clear();
bufferInfo.Clear();
writeDescriptorSets.Clear();
}
virtual void Update(int location, ArrayView<GameEngine::Texture*> textures, TextureAspect aspect) override
{
int imageInfoStart = imageInfo.Count();
if (textureUses.Count() <= location)
textureUses.SetSize(location + 1);
textureUses[location].Clear();
for (auto texture : textures)
{
if (texture)
{
VK::Texture* internalTexture = dynamic_cast<VK::Texture*>(texture);
if (internalTexture->usage != TextureUsage::Sampled)
{
// Track layout of this texture
textureUses[location].Add(TextureUse{ internalTexture, vk::ImageLayout::eShaderReadOnlyOptimal });
}
vk::ImageView view = internalTexture->views[0];
if (isDepthFormat(internalTexture->format)/* && aspect == TextureAspect::Depth*/)
view = internalTexture->views[1];
if (internalTexture->format == StorageFormat::Depth24Stencil8 && aspect == TextureAspect::Stencil)
view = internalTexture->views[2];
imageInfo.Add(
vk::DescriptorImageInfo()
.setSampler(vk::Sampler())
.setImageView(view)
.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal)
);
}
else
imageInfo.Add(
vk::DescriptorImageInfo()
.setSampler(vk::Sampler())
.setImageView(vk::ImageView())
.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal)
);
}
writeDescriptorSets.Add(
vk::WriteDescriptorSet()
.setDstSet(this->descriptorSet)
.setDstBinding(location)
.setDstArrayElement(0)
.setDescriptorCount(textures.Count())
.setDescriptorType(vk::DescriptorType::eSampledImage)
.setPImageInfo(imageInfo.Buffer() + imageInfoStart)
.setPBufferInfo(nullptr)
.setPTexelBufferView(nullptr)
);
}
virtual void UpdateStorageImage(int location, ArrayView<GameEngine::Texture*> textures, TextureAspect aspect) override
{
int imageInfoStart = imageInfo.Count();
if (textureUses.Count() <= location)
textureUses.SetSize(location + 1);
textureUses[location].Clear();
for (auto texture : textures)
{
if (texture)
{
VK::Texture* internalTexture = dynamic_cast<VK::Texture*>(texture);
// Track layout of this texture
textureUses[location].Add(TextureUse{ internalTexture, vk::ImageLayout::eGeneral });
vk::ImageView view = internalTexture->views[0];
if (isDepthFormat(internalTexture->format) /*&& aspect == TextureAspect::Depth*/)
view = internalTexture->views[1];
if (internalTexture->format == StorageFormat::Depth24Stencil8 && aspect == TextureAspect::Stencil)
view = internalTexture->views[2];
imageInfo.Add(
vk::DescriptorImageInfo()
.setSampler(vk::Sampler())
.setImageView(view)
.setImageLayout(vk::ImageLayout::eGeneral)//
);
}
else
imageInfo.Add(
vk::DescriptorImageInfo()
.setSampler(vk::Sampler())
.setImageView(vk::ImageView())
.setImageLayout(vk::ImageLayout::eGeneral)//
);
}
writeDescriptorSets.Add(
vk::WriteDescriptorSet()
.setDstSet(this->descriptorSet)
.setDstBinding(location)
.setDstArrayElement(0)
.setDescriptorCount(textures.Count())
.setDescriptorType(vk::DescriptorType::eStorageImage)
.setPImageInfo(imageInfo.Buffer() + imageInfoStart)
.setPBufferInfo(nullptr)
.setPTexelBufferView(nullptr)
);
}
virtual void Update(int location, GameEngine::Texture* texture, TextureAspect aspect) override
{
Update(location, MakeArrayView(texture), aspect);
}
virtual void Update(int location, GameEngine::TextureSampler* sampler) override
{
VK::TextureSampler* internalSampler = reinterpret_cast<VK::TextureSampler*>(sampler);
imageInfo.Add(
vk::DescriptorImageInfo()
.setSampler(internalSampler->sampler)
.setImageView(vk::ImageView())
.setImageLayout(vk::ImageLayout::eUndefined)
);
writeDescriptorSets.Add(
vk::WriteDescriptorSet()
.setDstSet(this->descriptorSet)
.setDstBinding(location)
.setDstArrayElement(0)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eSampler)
.setPImageInfo(&imageInfo.Last())
.setPBufferInfo(nullptr)
.setPTexelBufferView(nullptr)
);
}
virtual void Update(int location, GameEngine::Buffer* buffer, int offset = 0, int length = -1) override
{
VK::BufferObject* internalBuffer = reinterpret_cast<VK::BufferObject*>(buffer);
vk::DescriptorType descriptorType;
if (internalBuffer->usage & vk::BufferUsageFlagBits::eUniformBuffer)
descriptorType = vk::DescriptorType::eUniformBuffer;
else
descriptorType = vk::DescriptorType::eStorageBuffer;
int range = (length == -1) ? internalBuffer->size : length;
bufferInfo.Add(
vk::DescriptorBufferInfo()
.setBuffer(internalBuffer->buffer)
.setOffset(offset)
.setRange(range)
);
writeDescriptorSets.Add(
vk::WriteDescriptorSet()
.setDstSet(this->descriptorSet)
.setDstBinding(location)
.setDstArrayElement(0)
.setDescriptorCount(1)
.setDescriptorType(descriptorType)
.setPImageInfo(nullptr)
.setPBufferInfo(&bufferInfo.Last())
.setPTexelBufferView(nullptr)
);
}
virtual void EndUpdate() override
{
if (writeDescriptorSets.Count() > 0)
RendererState::Device().updateDescriptorSets(
vk::ArrayProxy<const vk::WriteDescriptorSet>(writeDescriptorSets.Count(), writeDescriptorSets.Buffer()),
nullptr);
}
};
class PipelineBuilder;
class Pipeline : public GameEngine::Pipeline
{
public:
#if _DEBUG
CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> descriptorSets;
bool isGraphics = true;
#endif
int descSetCount = 0;
vk::PipelineLayout pipelineLayout;
vk::Pipeline pipeline;
vk::PipelineBindPoint pipelineBindPoint;
public:
Pipeline() = default;
Pipeline(RenderTargetLayout* renderTargetLayout, PipelineBuilder* pipelineBuilder);
~Pipeline()
{
if (pipeline) RendererState::Device().destroyPipeline(pipeline);
if (pipelineLayout) RendererState::Device().destroyPipelineLayout(pipelineLayout);
}
};
class PipelineBuilder : public GameEngine::PipelineBuilder
{
public:
#if _DEBUG
CoreLib::String debugName;
CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> descriptorSets;
#endif
CoreLib::List<vk::DescriptorSetLayout> setLayouts;
CoreLib::List<vk::PushConstantRange> pushConstantRanges;//TODO:
CoreLib::List<vk::PipelineShaderStageCreateInfo> shaderStages;
CoreLib::List<vk::VertexInputBindingDescription> vertexBindingDescriptions;
CoreLib::List<vk::VertexInputAttributeDescription> vertexAttributeDescriptions;
public:
virtual void SetShaders(CoreLib::ArrayView<GameEngine::Shader*> shaders) override
{
shaderStages.Clear();
#if _DEBUG
bool vertPresent = false;
bool tescControlPresent = false;
bool tescEvalPresent = false;
bool geometryPresent = false;
bool fragPresent = false;
#endif
for (auto shader : shaders)
{
#if _DEBUG
// Ensure that the device supports requested shader stages
if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eGeometry)
assert(RendererState::PhysicalDevice().getFeatures().geometryShader);
if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eTessellationControl)
assert(RendererState::PhysicalDevice().getFeatures().tessellationShader);
if (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage) == vk::ShaderStageFlagBits::eTessellationEvaluation)
assert(RendererState::PhysicalDevice().getFeatures().tessellationShader);
// Ensure only one of any shader stage is present in the requested shader stage
switch (ShaderStage(dynamic_cast<VK::Shader*>(shader)->stage))
{
case vk::ShaderStageFlagBits::eVertex:
assert(vertPresent == false);
vertPresent = true;
break;
case vk::ShaderStageFlagBits::eTessellationControl:
assert(tescControlPresent == false);
tescControlPresent = true;
break;
case vk::ShaderStageFlagBits::eTessellationEvaluation:
assert(tescEvalPresent == false);
tescEvalPresent = true;
break;
case vk::ShaderStageFlagBits::eGeometry:
assert(geometryPresent == false);
geometryPresent = true;
break;
case vk::ShaderStageFlagBits::eFragment:
assert(fragPresent == false);
fragPresent = true;
break;
case vk::ShaderStageFlagBits::eCompute:
throw HardwareRendererException("Can't use compute shader in graphics pipeline");
break;
default:
throw HardwareRendererException("Unknown shader stage");
}
#endif
shaderStages.Add(
vk::PipelineShaderStageCreateInfo()
.setFlags(vk::PipelineShaderStageCreateFlagBits())
.setStage(ShaderStage(reinterpret_cast<VK::Shader*>(shader)->stage))
.setModule(reinterpret_cast<VK::Shader*>(shader)->module)
.setPName("main")
.setPSpecializationInfo(nullptr)
);
}
}
virtual void SetVertexLayout(VertexFormat vertexFormat) override
{
//TODO: Improve
int location = 0;
int maxOffset = -1;
int stride = 0;
vertexAttributeDescriptions.Clear();
vertexBindingDescriptions.Clear();
for (auto attribute : vertexFormat.Attributes)
{
vertexAttributeDescriptions.Add(
vk::VertexInputAttributeDescription()
.setLocation(attribute.Location)
.setBinding(0)
.setFormat(TranslateVertexAttribute(attribute))
.setOffset(attribute.StartOffset)
);
location++;
if (attribute.StartOffset > maxOffset)
{
maxOffset = attribute.StartOffset;
stride = maxOffset + DataTypeSize(attribute.Type);
}
}
if (vertexAttributeDescriptions.Count() > 0)
{
vertexBindingDescriptions.Add(
vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(stride)
.setInputRate(vk::VertexInputRate::eVertex)//TODO: per instance data?
);
}
}
virtual void SetBindingLayout(CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> pDescriptorSets) override
{
#if _DEBUG
this->descriptorSets = pDescriptorSets;
#endif
for (auto& set : pDescriptorSets)
{
if (set) //TODO: ?
setLayouts.Add(reinterpret_cast<VK::DescriptorSetLayout*>(set)->layout);
}
}
virtual void SetDebugName(CoreLib::String name) override
{
#if _DEBUG
debugName = name;
#endif
}
virtual Pipeline* ToPipeline(GameEngine::RenderTargetLayout* renderTargetLayout) override
{
return new Pipeline(reinterpret_cast<RenderTargetLayout*>(renderTargetLayout), this);
}
virtual Pipeline* CreateComputePipeline(CoreLib::ArrayView<GameEngine::DescriptorSetLayout*> pDescriptorSets, GameEngine::Shader* shader) override
{
Pipeline * result = new Pipeline();
#if _DEBUG
result->descriptorSets = pDescriptorSets;
#endif
result->pipelineBindPoint = vk::PipelineBindPoint::eCompute;
List<vk::DescriptorSetLayout> descSetLayouts;
for (auto& set : pDescriptorSets)
{
if (set)
descSetLayouts.Add(reinterpret_cast<VK::DescriptorSetLayout*>(set)->layout);
}
// Create Pipeline Layout
vk::PipelineLayoutCreateInfo layoutCreateInfo = vk::PipelineLayoutCreateInfo()
.setFlags(vk::PipelineLayoutCreateFlags())
.setSetLayoutCount(pDescriptorSets.Count())
.setPSetLayouts(descSetLayouts.Buffer())
.setPushConstantRangeCount(0)
.setPPushConstantRanges(nullptr);
#ifdef _DEBUG
result->isGraphics = false;
#endif
result->descSetCount = descSetLayouts.Count();
result->pipelineLayout = RendererState::Device().createPipelineLayout(layoutCreateInfo);
vk::ComputePipelineCreateInfo createInfo;
createInfo.setLayout(result->pipelineLayout)
.stage.setModule(reinterpret_cast<VK::Shader*>(shader)->module)
.setStage(vk::ShaderStageFlagBits::eCompute)
.setPName("main");
result->pipeline = RendererState::Device().createComputePipeline(RendererState::PipelineCache(), createInfo);
return result;
}
};
vk::PolygonMode TranslatePolygonMode(PolygonMode mode)
{
switch (mode)
{
case PolygonMode::Fill:
return vk::PolygonMode::eFill;
case PolygonMode::Line:
return vk::PolygonMode::eLine;
case PolygonMode::Point:
return vk::PolygonMode::ePoint;
default:
return vk::PolygonMode::eFill;
}
}
Pipeline::Pipeline(RenderTargetLayout* renderTargetLayout, PipelineBuilder* pipelineBuilder)
{
#if _DEBUG
this->descriptorSets = pipelineBuilder->descriptorSets;
#endif
// Create Pipeline Layout
vk::PipelineLayoutCreateInfo layoutCreateInfo = vk::PipelineLayoutCreateInfo()
.setFlags(vk::PipelineLayoutCreateFlags())
.setSetLayoutCount(pipelineBuilder->setLayouts.Count())
.setPSetLayouts(pipelineBuilder->setLayouts.Buffer())
.setPushConstantRangeCount(pipelineBuilder->pushConstantRanges.Count())
.setPPushConstantRanges(pipelineBuilder->pushConstantRanges.Buffer());
this->descSetCount = pipelineBuilder->setLayouts.Count();
this->pipelineLayout = RendererState::Device().createPipelineLayout(layoutCreateInfo);
// Vertex Input Description
vk::PipelineVertexInputStateCreateInfo vertexInputCreateInfo = vk::PipelineVertexInputStateCreateInfo()
.setFlags(vk::PipelineVertexInputStateCreateFlags())
.setVertexBindingDescriptionCount(pipelineBuilder->vertexBindingDescriptions.Count())
.setPVertexBindingDescriptions(pipelineBuilder->vertexBindingDescriptions.Buffer())
.setVertexAttributeDescriptionCount(pipelineBuilder->vertexAttributeDescriptions.Count())
.setPVertexAttributeDescriptions(pipelineBuilder->vertexAttributeDescriptions.Buffer());
// Create Input Assembly Description
vk::PipelineInputAssemblyStateCreateInfo inputAssemblyCreateInfo = vk::PipelineInputAssemblyStateCreateInfo()
.setFlags(vk::PipelineInputAssemblyStateCreateFlags())
.setTopology(TranslatePrimitiveTopology(pipelineBuilder->FixedFunctionStates.PrimitiveTopology))
.setPrimitiveRestartEnable(pipelineBuilder->FixedFunctionStates.PrimitiveRestartEnabled);
// Create Viewport Description
vk::PipelineViewportStateCreateInfo viewportCreateInfo = vk::PipelineViewportStateCreateInfo()
.setFlags(vk::PipelineViewportStateCreateFlags())
.setViewportCount(1)
.setPViewports(nullptr)
.setScissorCount(1)
.setPScissors(nullptr);
// Create Rasterization Description
vk::PipelineRasterizationStateCreateInfo rasterizationCreateInfo = vk::PipelineRasterizationStateCreateInfo()
.setFlags(vk::PipelineRasterizationStateCreateFlags())
.setDepthClampEnable(VK_FALSE)
.setRasterizerDiscardEnable(VK_FALSE)
.setPolygonMode(TranslatePolygonMode(pipelineBuilder->FixedFunctionStates.PolygonFillMode))
.setCullMode(TranslateCullMode(pipelineBuilder->FixedFunctionStates.cullMode))
.setFrontFace(vk::FrontFace::eClockwise)
.setDepthBiasEnable(pipelineBuilder->FixedFunctionStates.EnablePolygonOffset)
.setDepthBiasConstantFactor(pipelineBuilder->FixedFunctionStates.PolygonOffsetUnits)
.setDepthBiasClamp(0.0f)
.setDepthBiasSlopeFactor(pipelineBuilder->FixedFunctionStates.PolygonOffsetFactor)
.setLineWidth(1.0f);
VkPipelineRasterizationConservativeStateCreateInfoEXT conservativeRasterStateCI{};
if (pipelineBuilder->FixedFunctionStates.ConsevativeRasterization)
{
conservativeRasterStateCI.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT;
conservativeRasterStateCI.conservativeRasterizationMode = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT;
rasterizationCreateInfo.pNext = &conservativeRasterStateCI;
}
// Create Multisampling Description
//TODO: Implement multisampling
vk::PipelineMultisampleStateCreateInfo multisampleCreateInfo = vk::PipelineMultisampleStateCreateInfo()
.setFlags(vk::PipelineMultisampleStateCreateFlags())
.setRasterizationSamples(vk::SampleCountFlagBits::e1)
.setSampleShadingEnable(VK_FALSE)
.setMinSampleShading(1.0f)
.setPSampleMask(nullptr)
.setAlphaToCoverageEnable(VK_FALSE)
.setAlphaToOneEnable(VK_FALSE);
// Create Depth Stencil Description
vk::PipelineDepthStencilStateCreateInfo depthStencilCreateInfo = vk::PipelineDepthStencilStateCreateInfo()
.setFlags(vk::PipelineDepthStencilStateCreateFlags())
.setDepthTestEnable(pipelineBuilder->FixedFunctionStates.DepthCompareFunc != CompareFunc::Disabled)
.setDepthWriteEnable(pipelineBuilder->FixedFunctionStates.DepthCompareFunc != CompareFunc::Disabled)
.setDepthCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.DepthCompareFunc))
.setDepthBoundsTestEnable(VK_FALSE)
.setMinDepthBounds(0.0f)
.setMaxDepthBounds(1.0f)
.setStencilTestEnable(pipelineBuilder->FixedFunctionStates.StencilCompareFunc != CompareFunc::Disabled)
.setFront(vk::StencilOpState()
.setCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.StencilCompareFunc))
.setPassOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthPassOp))
.setFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilFailOp))
.setDepthFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthFailOp))
.setCompareMask(pipelineBuilder->FixedFunctionStates.StencilMask)
.setWriteMask(pipelineBuilder->FixedFunctionStates.StencilMask)
.setReference(pipelineBuilder->FixedFunctionStates.StencilReference))
.setBack(vk::StencilOpState()
.setCompareOp(TranslateCompareFunc(pipelineBuilder->FixedFunctionStates.StencilCompareFunc))
.setPassOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthPassOp))
.setFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilFailOp))
.setDepthFailOp(TranslateStencilOp(pipelineBuilder->FixedFunctionStates.StencilDepthFailOp))
.setCompareMask(pipelineBuilder->FixedFunctionStates.StencilMask)
.setWriteMask(pipelineBuilder->FixedFunctionStates.StencilMask)
.setReference(pipelineBuilder->FixedFunctionStates.StencilReference));
// Create Blending Description
CoreLib::List<vk::PipelineColorBlendAttachmentState> colorBlendAttachments;
for (int i = 0; i<renderTargetLayout->colorReferences.Count(); i++)
{
colorBlendAttachments.Add(
vk::PipelineColorBlendAttachmentState()
.setBlendEnable(pipelineBuilder->FixedFunctionStates.blendMode != BlendMode::Replace)
.setSrcColorBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eOne)
.setDstColorBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eOneMinusSrcAlpha : vk::BlendFactor::eZero)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eOne)
.setDstAlphaBlendFactor(pipelineBuilder->FixedFunctionStates.blendMode == BlendMode::AlphaBlend ? vk::BlendFactor::eSrcAlpha : vk::BlendFactor::eZero)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)
);
}
vk::PipelineColorBlendStateCreateInfo colorBlendCreateInfo = vk::PipelineColorBlendStateCreateInfo()
.setFlags(vk::PipelineColorBlendStateCreateFlags())
.setLogicOpEnable(VK_FALSE)
.setLogicOp(vk::LogicOp::eCopy)
.setAttachmentCount(colorBlendAttachments.Count())
.setPAttachments(colorBlendAttachments.Count() > 0 ? colorBlendAttachments.Buffer() : nullptr)
.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
// Create Dynamic Description
CoreLib::Array<vk::DynamicState,2> dynamicStates;
dynamicStates.Add(vk::DynamicState::eViewport);
dynamicStates.Add(vk::DynamicState::eScissor);
vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo = vk::PipelineDynamicStateCreateInfo()
.setFlags(vk::PipelineDynamicStateCreateFlags())
.setDynamicStateCount(dynamicStates.Count())
.setPDynamicStates(dynamicStates.Buffer());
// Create Pipeline Create Info
vk::GraphicsPipelineCreateInfo pipelineCreateInfo = vk::GraphicsPipelineCreateInfo()
.setFlags(vk::PipelineCreateFlags())
.setStageCount(pipelineBuilder->shaderStages.Count())
.setPStages(pipelineBuilder->shaderStages.Buffer())
.setPVertexInputState(&vertexInputCreateInfo)
.setPInputAssemblyState(&inputAssemblyCreateInfo)
.setPTessellationState(nullptr)
.setPViewportState(&viewportCreateInfo)
.setPRasterizationState(&rasterizationCreateInfo)
.setPMultisampleState(&multisampleCreateInfo)
.setPDepthStencilState(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->depthReference.layout == vk::ImageLayout::eUndefined ? nullptr : &depthStencilCreateInfo)
.setPColorBlendState(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->colorReferences.Count() == 0 ? nullptr : &colorBlendCreateInfo)
.setPDynamicState(&dynamicStateCreateInfo)
.setLayout(pipelineLayout)
.setRenderPass(reinterpret_cast<VK::RenderTargetLayout*>(renderTargetLayout)->renderPass)
.setSubpass(0)
.setBasePipelineHandle(vk::Pipeline())
.setBasePipelineIndex(-1);
this->pipeline = RendererState::Device().createGraphicsPipelines(RendererState::PipelineCache(), pipelineCreateInfo)[0];
this->pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
//#if _DEBUG
// vk::DebugMarkerObjectNameInfoEXT nameInfo = vk::DebugMarkerObjectNameInfoEXT()
// .setObjectType(vk::DebugReportObjectTypeEXT::ePipeline)
// .setObject(pipeline.operator VkPipeline)
// .setPObjectName(pipelineBuilder->debugName.Buffer());
//
// RendererState::Device().debugMarkerSetObjectNameEXT(&nameInfo);
//#endif
}
class Fence : public GameEngine::Fence
{
public:
vk::Fence assocFence;
public:
Fence()
{
vk::FenceCreateInfo createInfo;
createInfo.setFlags(vk::FenceCreateFlagBits::eSignaled);
assocFence = RendererState::Device().createFence(createInfo);
}
~Fence()
{
RendererState::Device().destroyFence(assocFence);
}
virtual void Reset() override
{
RendererState::Device().resetFences(assocFence);
}
virtual void Wait() override
{
static int waitCounter = 0;
while (RendererState::Device().waitForFences(
assocFence,
VK_TRUE,
1
) != vk::Result::eSuccess) {
waitCounter++;
};
/*if (waitCounter > 10)
Print("waited %d\n", waitCounter);*/
}
};
class CommandBuffer : public GameEngine::CommandBuffer
{
public:
const vk::CommandPool& pool;
vk::CommandBuffer buffer;
Pipeline* curPipeline = nullptr;
CoreLib::Array<vk::DescriptorSet, 32> pendingDescSets;
CoreLib::List<VK::DescriptorSet*> descSets;
CommandBuffer(const vk::CommandPool& commandPool) : pool(commandPool)
{
pendingDescSets.SetSize(32);
buffer = RendererState::CreateCommandBuffer(pool, vk::CommandBufferLevel::eSecondary);
}
CommandBuffer() : CommandBuffer(RendererState::RenderCommandPool()) {}
~CommandBuffer()
{
RendererState::DestroyCommandBuffer(pool, buffer);
}
Buffer* lastVertBuffer = nullptr;
int lastVertBufferOffset = 0;
Buffer * lastIndexBuffer = nullptr;
int lastIndexBufferOffset = 0;
void ResetInternalState()
{
curPipeline = nullptr;
lastVertBuffer = nullptr;
lastIndexBuffer = nullptr;
lastVertBufferOffset = 0;
lastIndexBufferOffset = 0;
descSets.Clear();
}
virtual void SetEventMarker(const char * /*name*/, uint32_t /*color*/) override
{
}
virtual void BeginRecording(GameEngine::FrameBuffer *frameBuffer) override
{
vk::RenderPass renderPass;
if (frameBuffer)
{
renderPass = reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->renderTargetLayout->renderPass;
}
ResetInternalState();
for (int k = 0; k < pendingDescSets.Count(); k++)
pendingDescSets[k] = vk::DescriptorSet();
vk::CommandBufferInheritanceInfo inheritanceInfo =
vk::CommandBufferInheritanceInfo()
.setRenderPass(renderPass)
.setSubpass(0)
.setOcclusionQueryEnable(VK_FALSE)
.setQueryFlags(vk::QueryControlFlags())
.setPipelineStatistics(vk::QueryPipelineStatisticFlags());
vk::CommandBufferBeginInfo commandBufferBeginInfo =
vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse |
vk::CommandBufferUsageFlagBits::eRenderPassContinue)
.setPInheritanceInfo(&inheritanceInfo);
buffer.begin(commandBufferBeginInfo);
}
virtual void EndRecording() override
{
buffer.end();
}
virtual void BindVertexBuffer(Buffer* vertexBuffer, int byteOffset) override
{
if (byteOffset != lastVertBufferOffset || vertexBuffer != lastVertBuffer)
{
buffer.bindVertexBuffers(0, reinterpret_cast<VK::BufferObject*>(vertexBuffer)->buffer, { (vk::DeviceSize)byteOffset });
lastVertBuffer = vertexBuffer;
lastVertBufferOffset = byteOffset;
}
}
virtual void BindIndexBuffer(Buffer* indexBuffer, int byteOffset) override
{
if (byteOffset != lastIndexBufferOffset || indexBuffer != lastIndexBuffer)
{
buffer.bindIndexBuffer(reinterpret_cast<VK::BufferObject*>(indexBuffer)->buffer,
(vk::DeviceSize)byteOffset, vk::IndexType::eUint32);
lastIndexBuffer = indexBuffer;
lastIndexBufferOffset = byteOffset;
}
}
virtual void BindDescriptorSet(int binding, GameEngine::DescriptorSet* descSet) override
{
VK::DescriptorSet* internalDescriptorSet = reinterpret_cast<VK::DescriptorSet*>(descSet);
descSets.Add(internalDescriptorSet);
if (descSet == nullptr)
pendingDescSets[binding] = RendererState::GetEmptyDescriptorSet();
else
pendingDescSets[binding] = (internalDescriptorSet->descriptorSet);
}
virtual void BindPipeline(GameEngine::Pipeline* pipeline) override
{
auto newPipeline = reinterpret_cast<VK::Pipeline*>(pipeline);
if (curPipeline != newPipeline)
{
curPipeline = newPipeline;
buffer.bindPipeline(newPipeline->pipelineBindPoint, newPipeline->pipeline);
}
}
virtual void SetViewport(Viewport viewport) override
{
vk::Viewport vkViewport;
vkViewport.x = viewport.x;
vkViewport.y = viewport.y;
vkViewport.width = viewport.w;
vkViewport.height = viewport.h;
vkViewport.minDepth = viewport.minZ;
vkViewport.maxDepth = viewport.maxZ;
buffer.setViewport(0, 1, &vkViewport);
vk::Rect2D scissorRect = vk::Rect2D(
vk::Offset2D((int)viewport.x, (int)viewport.y), vk::Extent2D((int)viewport.w, (int)viewport.h));
buffer.setScissor(0, 1, &scissorRect);
}
virtual void DispatchCompute(int groupCountX, int groupCountY, int groupCountZ) override
{
buffer.bindDescriptorSets(
curPipeline->pipelineBindPoint,
curPipeline->pipelineLayout,
0,
curPipeline->descSetCount,
pendingDescSets.Buffer(),
0, nullptr);
buffer.dispatch(groupCountX, groupCountY, groupCountZ);
}
virtual void Draw(int firstVertex, int vertexCount) override
{
buffer.bindDescriptorSets(
curPipeline->pipelineBindPoint,
curPipeline->pipelineLayout,
0,
curPipeline->descSetCount,
pendingDescSets.Buffer(),
0, nullptr);
buffer.draw(vertexCount, 1, firstVertex, 0);
}
virtual void DrawInstanced(int numInstances, int firstVertex, int vertexCount) override
{
buffer.bindDescriptorSets(
curPipeline->pipelineBindPoint,
curPipeline->pipelineLayout,
0,
curPipeline->descSetCount,
pendingDescSets.Buffer(),
0, nullptr);
buffer.draw(vertexCount, numInstances, firstVertex, 0);
}
virtual void DrawIndexed(int firstIndex, int indexCount) override
{
buffer.bindDescriptorSets(
curPipeline->pipelineBindPoint,
curPipeline->pipelineLayout,
0,
curPipeline->descSetCount,
pendingDescSets.Buffer(),
0, nullptr);
buffer.drawIndexed(indexCount, 1, firstIndex, 0, 0);
}
virtual void DrawIndexedInstanced(int numInstances, int firstIndex, int indexCount) override
{
buffer.bindDescriptorSets(
curPipeline->pipelineBindPoint,
curPipeline->pipelineLayout,
0,
curPipeline->descSetCount,
pendingDescSets.Buffer(),
0, nullptr);
buffer.drawIndexed(indexCount, numInstances, firstIndex, 0, 0);
}
};
class VkWindowSurface : public GameEngine::WindowSurface
{
public:
WindowHandle handle = {};
int width = -1;
int height = -1;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
CoreLib::List<vk::Image> images; //alternatively could call getSwapchainImages each time
CoreLib::List<vk::CommandBuffer> presentCommandBuffers, clearCommandBuffers;
CoreLib::List<vk::Fence> presentCommandBufferFences;
vk::Semaphore imageAvailableSemaphore, renderFinishedSemaphore;
VkWindowSurface(WindowHandle windowHandle, int w, int h)
{
handle = windowHandle;
width = w;
height = h;
if (windowHandle)
surface = RendererState::CreateSurface(windowHandle);
CreateSwapchain();
CreateSemaphores();
Clear();
}
~VkWindowSurface()
{
UnbindWindow();
}
void Present(GameEngine::Texture2D * srcImage)
{
if (images.Count() == 0) return;
uint32_t nextImage = 0;
try
{
nextImage = RendererState::Device().acquireNextImageKHR(swapchain, UINT64_MAX, imageAvailableSemaphore, vk::Fence()).value;
}
catch (vk::OutOfDateKHRError)
{
CreateSwapchain();
return;
}
static int frameId = 0;
frameId++;
vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(1);
vk::ImageMemoryBarrier postPresentBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setOldLayout(vk::ImageLayout::eUndefined)
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(images[nextImage])
.setSubresourceRange(imageSubresourceRange);
vk::ImageMemoryBarrier prePresentBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::ePresentSrcKHR))
.setOldLayout(vk::ImageLayout::eTransferDstOptimal)
.setNewLayout(vk::ImageLayout::ePresentSrcKHR)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(images[nextImage])
.setSubresourceRange(imageSubresourceRange);
int cmdBufId = frameId % presentCommandBuffers.Count();
auto cmdBuffer = presentCommandBuffers[cmdBufId];
RendererState::Device().waitForFences(1, &presentCommandBufferFences[cmdBufId], true, 0);
RendererState::Device().resetFences(1, &presentCommandBufferFences[cmdBufId]);
cmdBuffer.begin(commandBufferBeginInfo); // start recording
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
postPresentBarrier
);
if (srcImage == nullptr)
{
// If no source image, clear to debug purple
cmdBuffer.clearColorImage(
images[nextImage],
vk::ImageLayout::eTransferDstOptimal,
vk::ClearColorValue(std::array<float, 4>{ 1.0f, 0.0f, 1.0f, 0.0f }),
imageSubresourceRange
);
}
else
{
auto srcTexture = dynamic_cast<Texture2D*>(srcImage);
vk::ImageMemoryBarrier textureTransferBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(srcTexture->currentSubresourceLayouts[0]))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setOldLayout(srcTexture->currentSubresourceLayouts[0])
.setNewLayout(vk::ImageLayout::eTransferSrcOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(srcTexture->image)
.setSubresourceRange(imageSubresourceRange);
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
textureTransferBarrier
);
srcTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferSrcOptimal;
// Blit
vk::ImageSubresourceLayers subresourceLayers = vk::ImageSubresourceLayers()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setMipLevel(0)
.setBaseArrayLayer(0)
.setLayerCount(1);
std::array<vk::Offset3D, 2> srcOffsets;
srcOffsets[0] = vk::Offset3D(0, 0, 0);
srcOffsets[1] = vk::Offset3D(dynamic_cast<VK::Texture2D*>(srcImage)->width, dynamic_cast<VK::Texture2D*>(srcImage)->height, 1);
std::array<vk::Offset3D, 2> dstOffsets;
dstOffsets[0] = vk::Offset3D(0, 0, 0);
dstOffsets[1] = vk::Offset3D(width, height, 1);
vk::ImageBlit blitRegions = vk::ImageBlit()
.setSrcSubresource(subresourceLayers)
.setSrcOffsets(srcOffsets)
.setDstSubresource(subresourceLayers)
.setDstOffsets(dstOffsets);
cmdBuffer.blitImage(
dynamic_cast<VK::Texture2D*>(srcImage)->image,
vk::ImageLayout::eTransferSrcOptimal,
images[nextImage],
vk::ImageLayout::eTransferDstOptimal,
blitRegions,
vk::Filter::eNearest
);
}
cmdBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(),
nullptr,
nullptr,
prePresentBarrier
);
cmdBuffer.end(); // stop recording
vk::PipelineStageFlags waitDstStageMask = vk::PipelineStageFlags(vk::PipelineStageFlagBits::eTransfer);
vk::SubmitInfo submitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(1)
.setPWaitSemaphores(&imageAvailableSemaphore)
.setPWaitDstStageMask(&waitDstStageMask)
.setCommandBufferCount(1)
.setPCommandBuffers(&cmdBuffer)
.setSignalSemaphoreCount(1)
.setPSignalSemaphores(&renderFinishedSemaphore);
RendererState::RenderQueue().submit(submitInfo, presentCommandBufferFences[cmdBufId]);
vk::PresentInfoKHR presentInfo = vk::PresentInfoKHR()
.setWaitSemaphoreCount(1)
.setPWaitSemaphores(&renderFinishedSemaphore)
.setSwapchainCount(1)
.setPSwapchains(&swapchain)
.setPImageIndices(&nextImage)
.setPResults(nullptr);
try
{
RendererState::RenderQueue().presentKHR(presentInfo);
}
catch (vk::OutOfDateKHRError)
{
CreateSwapchain();
}
}
void CreateSwapchain()
{
if (!surface)
return;
vkDeviceWaitIdle(RendererState::Device());
std::vector<vk::SurfaceFormatKHR> surfaceFormats = RendererState::PhysicalDevice().getSurfaceFormatsKHR(surface);
vk::Format format;
vk::ColorSpaceKHR colorSpace = surfaceFormats.at(0).colorSpace;
if ((surfaceFormats.size() == 1) && (surfaceFormats.at(0).format == vk::Format::eUndefined))
format = vk::Format::eB8G8R8A8Unorm;
else
format = surfaceFormats.at(0).format;
// Select presentation mode
vk::PresentModeKHR presentMode = vk::PresentModeKHR::eFifo; // Fifo presentation mode is guaranteed
for (auto & mode : RendererState::PhysicalDevice().getSurfacePresentModesKHR(surface))
{
// If we can use mailbox, use it.
if (mode == vk::PresentModeKHR::eMailbox)
{
presentMode = mode;
break;
}
}
vk::SurfaceCapabilitiesKHR surfaceCapabilities = RendererState::PhysicalDevice().getSurfaceCapabilitiesKHR(surface);
unsigned int desiredSwapchainImages = 2;
if (desiredSwapchainImages < surfaceCapabilities.minImageCount)
{
desiredSwapchainImages = surfaceCapabilities.minImageCount;
}
if (surfaceCapabilities.maxImageCount > 0
&& desiredSwapchainImages > surfaceCapabilities.maxImageCount)
{
desiredSwapchainImages = surfaceCapabilities.maxImageCount;
}
vk::Extent2D swapchainExtent = {};
if (surfaceCapabilities.currentExtent.width == -1)
{
swapchainExtent.width = this->width;
swapchainExtent.height = this->height;
}
else
{
swapchainExtent = surfaceCapabilities.currentExtent;
this->width = swapchainExtent.width;
this->height = swapchainExtent.height;
}
// Select swapchain pre-transform
// (Can be useful on tablets, etc.)
vk::SurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform;
if (surfaceCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
// Select identity transform if we can
preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
}
vk::SwapchainKHR oldSwapchain = swapchain;
vk::SwapchainCreateInfoKHR swapchainCreateInfo = vk::SwapchainCreateInfoKHR()
.setMinImageCount(desiredSwapchainImages)
.setSurface(surface)
.setImageFormat(format)
.setImageColorSpace(colorSpace)
.setImageExtent(swapchainExtent)
.setImageArrayLayers(1)
.setImageUsage(vk::ImageUsageFlagBits::eTransferDst) // we only draw to screen by blit
.setImageSharingMode(vk::SharingMode::eExclusive)
.setQueueFamilyIndexCount(0)
.setPQueueFamilyIndices(VK_NULL_HANDLE)
.setPreTransform(preTransform)
.setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eOpaque)
.setPresentMode(presentMode)
.setClipped(VK_TRUE)
.setOldSwapchain(oldSwapchain);
swapchain = RendererState::Device().createSwapchainKHR(swapchainCreateInfo);
DestroySwapchain(oldSwapchain);
auto vkImages = RendererState::Device().getSwapchainImagesKHR(swapchain);
images.SetSize((int)vkImages.size());
memcpy(images.Buffer(), &vkImages[0], vkImages.size() * sizeof(vk::Image));
CreateCommandBuffers();
}
void CreateCommandBuffers()
{
DestroyCommandBuffers();
vk::CommandBufferAllocateInfo commandBufferAllocateInfo = vk::CommandBufferAllocateInfo()
.setCommandPool(RendererState::SwapchainCommandPool())
.setLevel(vk::CommandBufferLevel::ePrimary)
.setCommandBufferCount((uint32_t)images.Count() * 2);
presentCommandBuffers.SetSize(commandBufferAllocateInfo.commandBufferCount);
RendererState::Device().allocateCommandBuffers(&commandBufferAllocateInfo, presentCommandBuffers.Buffer());
clearCommandBuffers.SetSize(commandBufferAllocateInfo.commandBufferCount);
RendererState::Device().allocateCommandBuffers(&commandBufferAllocateInfo, clearCommandBuffers.Buffer());
presentCommandBufferFences.SetSize(presentCommandBuffers.Count());
vk::FenceCreateInfo fenceCreateInfo;
fenceCreateInfo.setFlags(vk::FenceCreateFlagBits::eSignaled);
for (int i = 0; i < presentCommandBuffers.Count(); i++)
presentCommandBufferFences[i] = RendererState::Device().createFence(fenceCreateInfo);
// record clear command buffers
for (int image = 0; image < images.Count(); image++)
{
//TODO: see if following line is beneficial
//commandBuffers[image].reset(vk::CommandBufferResetFlags()); // implicitly done by begin
vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(1);
vk::ImageMemoryBarrier postPresentBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(vk::AccessFlags())
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setOldLayout(vk::ImageLayout::eUndefined)
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(images[image])
.setSubresourceRange(imageSubresourceRange);
vk::ImageMemoryBarrier prePresentBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::ePresentSrcKHR))
.setOldLayout(vk::ImageLayout::eTransferDstOptimal)
.setNewLayout(vk::ImageLayout::ePresentSrcKHR)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(images[image])
.setSubresourceRange(imageSubresourceRange);
clearCommandBuffers[image].begin(commandBufferBeginInfo); // start recording
clearCommandBuffers[image].pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eTransfer,
vk::DependencyFlags(),
nullptr,
nullptr,
postPresentBarrier
);
clearCommandBuffers[image].clearColorImage(
images[image],
vk::ImageLayout::eTransferDstOptimal,
vk::ClearColorValue(std::array<float, 4>{ 0.467f, 0.725f, 0.0f, 0.0f }),
imageSubresourceRange
);
clearCommandBuffers[image].pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eBottomOfPipe,
vk::DependencyFlags(),
nullptr,
nullptr,
prePresentBarrier
);
clearCommandBuffers[image].end(); // stop recording
}
// record present command buffers
}
void CreateSemaphores()
{
DestroySemaphores();
vk::SemaphoreCreateInfo semaphoreCreateInfo;
imageAvailableSemaphore = RendererState::Device().createSemaphore(semaphoreCreateInfo);
renderFinishedSemaphore = RendererState::Device().createSemaphore(semaphoreCreateInfo);
}
void DestroySemaphores()
{
if (imageAvailableSemaphore) RendererState::Device().destroySemaphore(imageAvailableSemaphore);
if (renderFinishedSemaphore) RendererState::Device().destroySemaphore(renderFinishedSemaphore);
}
void DestroyCommandBuffers()
{
if (presentCommandBufferFences.Count())
RendererState::Device().waitForFences(presentCommandBufferFences.Count(), presentCommandBufferFences.Buffer(), true, 0);
for (auto fence : presentCommandBufferFences)
RendererState::Device().destroyFence(fence);
for (auto commandBuffer : presentCommandBuffers)
RendererState::Device().freeCommandBuffers(RendererState::SwapchainCommandPool(), commandBuffer);
for (auto commandBuffer : clearCommandBuffers)
RendererState::Device().freeCommandBuffers(RendererState::SwapchainCommandPool(), commandBuffer);
presentCommandBufferFences.Clear();
}
void DestroySwapchain()
{
RendererState::Device().waitIdle();
if (swapchain)
DestroySwapchain(swapchain);
}
void DestroySwapchain(vk::SwapchainKHR pswapchain)
{
if (pswapchain) RendererState::Device().destroySwapchainKHR(pswapchain);// shouldn't need this if, but nvidia driver is broken.
}
void UnbindWindow()
{
DestroySemaphores();
DestroyCommandBuffers();
DestroySwapchain();
if (surface) RendererState::Instance().destroySurfaceKHR(surface);
handle = WindowHandle();
}
void Clear()
{
}
virtual void Resize(int pwidth, int pheight) override
{
if (!handle) return;
if (width != pwidth || height != pheight)
{
this->width = pwidth;
this->height = pheight;
CreateSwapchain();
}
}
virtual void GetSize(int & w, int & h) override
{
w = this->width;
h = this->height;
}
virtual WindowHandle GetWindowHandle() override
{
return this->handle;
}
};
class HardwareRenderer : public GameEngine::HardwareRenderer
{
private:
List<vk::Semaphore> transferSemaphores;
CoreLib::Array<vk::CommandBuffer, MaxRenderThreads> jobSubmissionBuffers;
List<vk::ImageMemoryBarrier> imageMemoryBarriers;
uint32_t taskId = 0;
std::mutex queueMutex;
public:
virtual TargetShadingLanguage GetShadingLanguage() override
{
return TargetShadingLanguage::SPIRV;
}
public:
HardwareRenderer(String pipelineCacheLocation)
{
RendererState::SetPipelineCacheLocation(pipelineCacheLocation);
RendererState::AddRenderer();
jobSubmissionBuffers.SetSize(MaxRenderThreads);
};
~HardwareRenderer()
{
RendererState::Device().waitIdle();
for (auto & sem : transferSemaphores)
RendererState::Device().destroySemaphore(sem);
RendererState::RemRenderer();
}
virtual void ThreadInit(int threadId) override
{
renderThreadId = threadId;
}
virtual void Init(int versionCount) override
{
RendererState::Init(versionCount);
}
virtual void ResetTempBufferVersion(int version) override
{
RendererState::ResetTempBufferVersion(version);
}
virtual WindowSurface* CreateSurface(WindowHandle windowHandle, int pwidth, int pheight) override
{
VkWindowSurface * rs = new VkWindowSurface(windowHandle, pwidth, pheight);
return rs;
}
virtual void BeginJobSubmission() override
{
// Create command buffer begin info
vk::CommandBufferBeginInfo primaryBeginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)
.setPInheritanceInfo(nullptr);
jobSubmissionBuffers[renderThreadId] = RendererState::GetTempRenderCommandBuffer();
jobSubmissionBuffers[renderThreadId].begin(primaryBeginInfo);
}
virtual void EndJobSubmission(GameEngine::Fence* fence) override
{
auto primaryBuffer = jobSubmissionBuffers[renderThreadId];
primaryBuffer.end();
vk::SubmitInfo submitInfo = vk::SubmitInfo()
.setWaitSemaphoreCount(0)
.setPWaitSemaphores(nullptr)
.setPWaitDstStageMask(nullptr)
.setCommandBufferCount(1)
.setPCommandBuffers(&primaryBuffer)
.setSignalSemaphoreCount(0)
.setPSignalSemaphores(nullptr);
RendererState::RenderQueue().submit(submitInfo, fence ? ((VK::Fence*)fence)->assocFence : nullptr);
}
void QueuePipelineBarrier(vk::CommandBuffer cmdBuffer, PipelineBarriers barriers)
{
if (barriers == PipelineBarriers::Memory || barriers == PipelineBarriers::MemoryAndImage)
{
auto memBarrier = vk::MemoryBarrier()
.setSrcAccessMask(vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eHostWrite)
.setDstAccessMask(vk::AccessFlagBits::eShaderRead);
cmdBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(), 1, &memBarrier, 0, nullptr, imageMemoryBarriers.Count(), imageMemoryBarriers.Buffer());
}
else if (barriers == PipelineBarriers::ExecutionOnly)
{
cmdBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eAllCommands,
vk::DependencyFlags(), 0, nullptr, 0, nullptr, 0, nullptr);
}
}
virtual void QueueComputeTask(GameEngine::Pipeline* computePipeline, GameEngine::DescriptorSet* descriptorSet,
int x, int y, int z, PipelineBarriers barriers) override
{
std::lock_guard<std::mutex> lock(queueMutex);
taskId++;
imageMemoryBarriers.Clear();
if (barriers == PipelineBarriers::MemoryAndImage)
{
auto vkDescSet = (VK::DescriptorSet*)descriptorSet;
for (auto& textureUseList : vkDescSet->textureUses)
{
for (auto textureUse : textureUseList)
{
if (textureUse.texture->lastLayoutCheckTaskId == taskId)
continue;
textureUse.texture->lastLayoutCheckTaskId = taskId;
textureUse.texture->TransferLayout(textureUse.targetLayout, imageMemoryBarriers);
}
}
}
auto primaryBuffer = jobSubmissionBuffers[renderThreadId];
QueuePipelineBarrier(primaryBuffer, barriers);
auto pipeline = dynamic_cast<VK::Pipeline*>(computePipeline);
auto descSet = dynamic_cast<VK::DescriptorSet*>(descriptorSet);
primaryBuffer.bindPipeline(pipeline->pipelineBindPoint, pipeline->pipeline);
primaryBuffer.bindDescriptorSets(pipeline->pipelineBindPoint, pipeline->pipelineLayout, 0, 1, &descSet->descriptorSet, 0, nullptr);
primaryBuffer.dispatch(x, y, z);
}
virtual void QueueRenderPass(GameEngine::FrameBuffer *frameBuffer, bool clearFrameBuffer,
CoreLib::ArrayView<GameEngine::CommandBuffer *> commands,
PipelineBarriers barriers) override
{
std::lock_guard<std::mutex> lock(queueMutex);
taskId++;
imageMemoryBarriers.Clear();
auto vkframeBuffer = (VK::FrameBuffer*)frameBuffer;
if (barriers == PipelineBarriers::MemoryAndImage)
{
// Determine texture layout transfer ops that are necessary
Array<GameEngine::Texture*, 8> attachmentTextures;
vkframeBuffer->renderAttachments.GetTextures(attachmentTextures);
for (auto texture : attachmentTextures)
{
auto vkTexture = dynamic_cast<VK::Texture*>(texture);
if (vkTexture->lastLayoutCheckTaskId == taskId)
continue;
vkTexture->lastLayoutCheckTaskId = taskId;
if (texture->IsDepthStencilFormat())
vkTexture->TransferLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal, imageMemoryBarriers);
else
vkTexture->TransferLayout(vk::ImageLayout::eColorAttachmentOptimal, imageMemoryBarriers);
}
for (auto cmdBuf : commands)
{
auto vkCmdBuf = (VK::CommandBuffer*)cmdBuf;
for (auto descSet : vkCmdBuf->descSets)
{
for (auto& textureUseList : descSet->textureUses)
for (auto textureUse : textureUseList)
{
if (textureUse.texture->lastLayoutCheckTaskId == taskId)
continue;
textureUse.texture->lastLayoutCheckTaskId = taskId;
textureUse.texture->TransferLayout(textureUse.targetLayout, imageMemoryBarriers);
}
}
}
}
// Create render pass begin info
vk::RenderPassBeginInfo renderPassBeginInfo =
vk::RenderPassBeginInfo()
.setRenderPass(clearFrameBuffer ? vkframeBuffer->renderTargetLayout->renderPassClear
: vkframeBuffer->renderTargetLayout->renderPass)
.setFramebuffer(clearFrameBuffer ? vkframeBuffer->framebufferClear : vkframeBuffer->framebuffer)
.setRenderArea(vk::Rect2D()
.setOffset(vk::Offset2D(0, 0))
.setExtent(vk::Extent2D(reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->width,
reinterpret_cast<VK::FrameBuffer *>(frameBuffer)->height)))
.setClearValueCount(vkframeBuffer->clearValues.Count())
.setPClearValues(vkframeBuffer->clearValues.Buffer());
// Aggregate secondary command buffers
CoreLib::List<vk::CommandBuffer> renderPassCommandBuffers;
for (auto& buffer : commands)
{
auto internalBuffer = static_cast<VK::CommandBuffer*>(buffer);
renderPassCommandBuffers.Add(internalBuffer->buffer);
}
// Record primary command buffer
auto primaryBuffer = jobSubmissionBuffers[renderThreadId];
QueuePipelineBarrier(primaryBuffer, barriers);
if (renderPassCommandBuffers.Count() > 0)
{
primaryBuffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eSecondaryCommandBuffers);
primaryBuffer.executeCommands(renderPassCommandBuffers.Count(), renderPassCommandBuffers.Buffer());
primaryBuffer.endRenderPass();
}
}
virtual void Wait() override
{
RendererState::Device().waitIdle();
}
virtual void Blit(GameEngine::Texture2D *dstImage, GameEngine::Texture2D *srcImage, VectorMath::Vec2i dstOffset,
SourceFlipMode flipSrc) override
{
auto primaryBuffer = jobSubmissionBuffers[renderThreadId];
vk::ImageSubresourceRange imageSubresourceRange = vk::ImageSubresourceRange()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setBaseMipLevel(0)
.setLevelCount(1)
.setBaseArrayLayer(0)
.setLayerCount(1);
auto dstTexture = dynamic_cast<VK::Texture*>(dstImage);
vk::ImageMemoryBarrier preBlitBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eUndefined))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferDstOptimal))
.setOldLayout(dstTexture->currentSubresourceLayouts[0])
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(dstTexture->image)
.setSubresourceRange(imageSubresourceRange);
dstTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferDstOptimal;
auto srcTexture = dynamic_cast<Texture2D*>(srcImage);
vk::ImageMemoryBarrier textureTransferBarrier = vk::ImageMemoryBarrier()
.setSrcAccessMask(LayoutFlags(vk::ImageLayout::eColorAttachmentOptimal))
.setDstAccessMask(LayoutFlags(vk::ImageLayout::eTransferSrcOptimal))
.setOldLayout(srcTexture->currentSubresourceLayouts[0])
.setNewLayout(vk::ImageLayout::eTransferSrcOptimal)
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.setImage(srcTexture->image)
.setSubresourceRange(imageSubresourceRange);
primaryBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eTransfer,
vk::DependencyFlags(),
0, nullptr,
0, nullptr,
2, MakeArray(preBlitBarrier, textureTransferBarrier).Buffer());
// Blit
vk::ImageSubresourceLayers subresourceLayers = vk::ImageSubresourceLayers()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setMipLevel(0)
.setBaseArrayLayer(0)
.setLayerCount(1);
int srcWidth, srcHeight, destWidth, destHeight;
dynamic_cast<VK::Texture2D*>(srcImage)->GetSize(srcWidth, srcHeight);
dynamic_cast<VK::Texture2D*>(dstImage)->GetSize(destWidth, destHeight);
std::array<vk::Offset3D, 2> srcOffsets;
if (flipSrc != SourceFlipMode::None)
{
srcOffsets[0] = vk::Offset3D(0, srcHeight, 0);
srcOffsets[1] = vk::Offset3D(srcWidth, 0, 1);
}
else
{
srcOffsets[0] = vk::Offset3D(0, 0, 0);
srcOffsets[1] = vk::Offset3D(srcWidth, srcHeight, 1);
}
std::array<vk::Offset3D, 2> dstOffsets;
dstOffsets[0] = vk::Offset3D(dstOffset.x, dstOffset.y, 0);
dstOffsets[1] = vk::Offset3D(dstOffset.x + srcWidth, dstOffset.y + srcHeight, 1);
int wFix = 0, hFix = 0;
if (dstOffsets[1].x > destWidth)
wFix = destWidth - dstOffsets[1].x;
if (dstOffsets[1].y > destHeight)
hFix = destHeight - dstOffsets[1].y;
dstOffsets[1].x += wFix;
dstOffsets[1].y += hFix;
srcOffsets[1].x += wFix;
srcOffsets[1].y += hFix;
vk::ImageBlit blitRegions = vk::ImageBlit()
.setSrcSubresource(subresourceLayers)
.setSrcOffsets(srcOffsets)
.setDstSubresource(subresourceLayers)
.setDstOffsets(dstOffsets);
primaryBuffer.blitImage(
srcTexture->image,
vk::ImageLayout::eTransferSrcOptimal,
dstTexture->image,
vk::ImageLayout::eTransferDstOptimal,
blitRegions,
vk::Filter::eNearest
);
srcTexture->currentSubresourceLayouts[0] = vk::ImageLayout::eTransferSrcOptimal;
}
virtual void Present(GameEngine::WindowSurface *surface, GameEngine::Texture2D* srcImage) override
{
((VkWindowSurface*)surface)->Present(srcImage);
}
virtual BufferObject* CreateBuffer(BufferUsage usage, int size, const BufferStructureInfo* structInfo) override
{
CORELIB_UNUSED(structInfo);
return new BufferObject(TranslateUsageFlags(usage) | vk::BufferUsageFlagBits::eTransferSrc, size, vk::MemoryPropertyFlagBits::eDeviceLocal);
}
virtual BufferObject* CreateMappedBuffer(BufferUsage usage, int size, const BufferStructureInfo* structInfo) override
{
CORELIB_UNUSED(structInfo);
return new BufferObject(TranslateUsageFlags(usage), size, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
}
Texture2D* CreateTexture2D(CoreLib::String name, int pwidth, int pheight, StorageFormat format, DataType dataType, void* data) override
{
TextureUsage usage;
usage = TextureUsage::Sampled;
int mipLevelCount = (int)Math::Log2Floor(Math::Max(pwidth, pheight)) + 1;
Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format);
res->SetData(pwidth, pheight, 1, dataType, data);
res->BuildMipmaps();
return res;
}
Texture2D* CreateTexture2D(CoreLib::String name, TextureUsage usage, int pwidth, int pheight, int mipLevelCount, StorageFormat format) override
{
Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format);
return res;
}
Texture2D* CreateTexture2D(CoreLib::String name, TextureUsage usage, int pwidth, int pheight, int mipLevelCount, StorageFormat format, DataType dataType, CoreLib::ArrayView<void*> mipLevelData) override
{
Texture2D* res = new Texture2D(name, usage, pwidth, pheight, mipLevelCount, format);
for (int level = 0; level < mipLevelCount; level++)
res->SetData(level, Math::Max(pwidth >> level, 1), Math::Max(pheight >> level, 1), 1, dataType, mipLevelData[level]);
return res;
}
Texture2DArray* CreateTexture2DArray(CoreLib::String name, TextureUsage usage, int w, int h, int layers, int mipLevelCount, StorageFormat format) override
{
Texture2DArray* res = new Texture2DArray(name, usage, w, h, mipLevelCount, layers, format);
return res;
}
TextureCube* CreateTextureCube(CoreLib::String name, TextureUsage usage, int size, int mipLevelCount, StorageFormat format) override
{
TextureCube* res = new TextureCube(name, usage, size, mipLevelCount, format);
return res;
}
virtual TextureCubeArray* CreateTextureCubeArray(CoreLib::String name, TextureUsage usage, int size, int mipLevelCount, int cubemapCount, StorageFormat format) override
{
TextureCubeArray * rs = new TextureCubeArray(name, usage, cubemapCount, size, mipLevelCount, format);
return rs;
}
Texture3D* CreateTexture3D(CoreLib::String name, TextureUsage usage, int w, int h, int d, int mipLevelCount, StorageFormat format) override
{
Texture3D* res = new Texture3D(name, usage, w, h, d, mipLevelCount, format);
return res;
}
TextureSampler* CreateTextureSampler() override
{
return new TextureSampler();
}
Shader* CreateShader(ShaderType stage, const char* data, int size) override
{
Shader* result = new Shader();
result->Create(stage, data, size);
return result;
}
virtual RenderTargetLayout* CreateRenderTargetLayout(CoreLib::ArrayView<AttachmentLayout> bindings, bool ignoreInitialContent) override
{
return new RenderTargetLayout(bindings, ignoreInitialContent);
}
virtual PipelineBuilder* CreatePipelineBuilder() override
{
return new PipelineBuilder();
}
virtual DescriptorSetLayout* CreateDescriptorSetLayout(CoreLib::ArrayView<DescriptorLayout> descriptors) override
{
return new DescriptorSetLayout(descriptors);
}
virtual DescriptorSet * CreateDescriptorSet(GameEngine::DescriptorSetLayout* layout) override
{
return new DescriptorSet(reinterpret_cast<VK::DescriptorSetLayout*>(layout));
}
Fence* CreateFence() override
{
return new Fence();
}
CommandBuffer* CreateCommandBuffer() override
{
return new CommandBuffer();
}
virtual int UniformBufferAlignment() override
{
return (int)RendererState::PhysicalDevice().getProperties().limits.minUniformBufferOffsetAlignment;
}
virtual int StorageBufferAlignment() override
{
return (int)RendererState::PhysicalDevice().getProperties().limits.minStorageBufferOffsetAlignment;
}
virtual String GetRendererName() override
{
return RendererState::PhysicalDevice().getProperties().deviceName;
}
virtual bool IsImageSpaceYAxisInverted() override
{
return true;
}
};
}
HardwareRenderer* GameEngine::CreateVulkanHardwareRenderer(int gpuId, String pipelineCacheLocation)
{
VK::GpuId = gpuId;
return new VK::HardwareRenderer(pipelineCacheLocation);
} | 37.630362 | 204 | 0.709493 | csyonghe |
c453e694b608ec8aaf75c2c292ce965af3712fc3 | 1,740 | cpp | C++ | compiled/cpp_stl_11/expr_io_pos.cpp | smarek/ci_targets | c5edee7b0901fd8e7f75f85245ea4209b38e0cb3 | [
"MIT"
] | 4 | 2017-04-08T12:55:11.000Z | 2020-12-05T21:09:31.000Z | compiled/cpp_stl_11/expr_io_pos.cpp | smarek/ci_targets | c5edee7b0901fd8e7f75f85245ea4209b38e0cb3 | [
"MIT"
] | 7 | 2018-04-23T01:30:33.000Z | 2020-10-30T23:56:14.000Z | compiled/cpp_stl_11/expr_io_pos.cpp | smarek/ci_targets | c5edee7b0901fd8e7f75f85245ea4209b38e0cb3 | [
"MIT"
] | 6 | 2017-04-08T11:41:14.000Z | 2020-10-30T22:47:31.000Z | // This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
#include "expr_io_pos.h"
expr_io_pos_t::expr_io_pos_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, expr_io_pos_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = this;
m_substream1 = nullptr;
m__io__raw_substream1 = nullptr;
m_substream2 = nullptr;
m__io__raw_substream2 = nullptr;
_read();
}
void expr_io_pos_t::_read() {
m__raw_substream1 = m__io->read_bytes(16);
m__io__raw_substream1 = std::unique_ptr<kaitai::kstream>(new kaitai::kstream(m__raw_substream1));
m_substream1 = std::unique_ptr<all_plus_number_t>(new all_plus_number_t(m__io__raw_substream1.get(), this, m__root));
m__raw_substream2 = m__io->read_bytes(14);
m__io__raw_substream2 = std::unique_ptr<kaitai::kstream>(new kaitai::kstream(m__raw_substream2));
m_substream2 = std::unique_ptr<all_plus_number_t>(new all_plus_number_t(m__io__raw_substream2.get(), this, m__root));
}
expr_io_pos_t::~expr_io_pos_t() {
_clean_up();
}
void expr_io_pos_t::_clean_up() {
}
expr_io_pos_t::all_plus_number_t::all_plus_number_t(kaitai::kstream* p__io, expr_io_pos_t* p__parent, expr_io_pos_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
_read();
}
void expr_io_pos_t::all_plus_number_t::_read() {
m_my_str = kaitai::kstream::bytes_to_str(m__io->read_bytes_term(0, false, true, true), std::string("UTF-8"));
m_body = m__io->read_bytes(((_io()->size() - _io()->pos()) - 2));
m_number = m__io->read_u2le();
}
expr_io_pos_t::all_plus_number_t::~all_plus_number_t() {
_clean_up();
}
void expr_io_pos_t::all_plus_number_t::_clean_up() {
}
| 35.510204 | 152 | 0.73046 | smarek |
c4553de6373a9657acb50c651dc4c0b91d3cef5e | 3,529 | hpp | C++ | qtgui/soda_comboboxes.hpp | kb1vc/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 14 | 2017-10-27T16:01:05.000Z | 2021-03-16T08:12:42.000Z | qtgui/soda_comboboxes.hpp | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 11 | 2017-09-16T03:13:11.000Z | 2020-12-11T09:11:35.000Z | qtgui/soda_comboboxes.hpp | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 6 | 2017-09-13T12:47:43.000Z | 2020-12-02T20:54:25.000Z | /*
Copyright (c) 2017 Matthew H. Reilly (kb1vc)
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.
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
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SODA_WFALL_COMBO_BOXES_H
#define SODA_WFALL_COMBO_BOXES_H
#include <QWidget>
#include <QComboBox>
#include <QString>
#include <vector>
#include <map>
#include <cmath>
#include <iostream>
namespace GUISoDa {
class ValComboBox : public QComboBox {
Q_OBJECT
public:
explicit ValComboBox(QWidget * parent = 0) : QComboBox(parent) {
clear();
connect(this, &QComboBox::currentTextChanged, this, &ValComboBox::textChanged);
}
double value() {
return valmap[currentText()];
}
public slots:
void addValue(QString lab, double val);
void setValue(double v);
signals:
void valueChanged(double v);
protected:
void textChanged(const QString & txt);
std::map<QString, double> valmap;
};
class WFallDynRangeComboBox : public ValComboBox {
Q_OBJECT
public:
WFallDynRangeComboBox(QWidget * parent = 0) : ValComboBox(parent) {
addValue("50", 50.0);
addValue("45", 45.0);
addValue("40", 40.0);
addValue("35", 35.0);
addValue("30", 30.0);
addValue("25", 25.0);
addValue("15", 15.0);
addValue("10", 10.0);
addValue("5", 5.0);
setValue(25.0);
}
};
class WFallSpanComboBox : public ValComboBox {
Q_OBJECT
public:
WFallSpanComboBox(QWidget * parent = 0) : ValComboBox(parent) {
addValue("200", 200.0);
addValue("100", 100.0);
addValue("50", 50.0);
addValue("25", 25.0);
addValue("10", 10.0);
setValue(200.0);
}
};
class IntValComboBox : public QComboBox {
Q_OBJECT
public:
explicit IntValComboBox(QWidget * parent = 0) : QComboBox(parent) {
clear();
connect(this, &QComboBox::currentTextChanged, this, &IntValComboBox::textChanged);
}
int value() {
return valmap[currentText()];
}
public slots:
void addValue(QString lab, int val);
void setValue(int v);
void setValue(const QString & s);
signals:
void valueChanged(int v);
protected:
void textChanged(const QString & txt);
std::map<QString, int> valmap;
};
}
#endif
| 27.356589 | 90 | 0.672428 | kb1vc |
c45750110fd1766af0cb80565f33cf45b2902093 | 1,118 | cpp | C++ | Phoebe-core/src/ph/debug/PerformanceInfo.cpp | JRBonilla/Slate | 9bcb3befced30d8f9ffb2dcce0a0209ba76093e4 | [
"MIT"
] | 1 | 2017-02-26T23:37:37.000Z | 2017-02-26T23:37:37.000Z | Phoebe-core/src/ph/debug/PerformanceInfo.cpp | JRBonilla/Slate | 9bcb3befced30d8f9ffb2dcce0a0209ba76093e4 | [
"MIT"
] | null | null | null | Phoebe-core/src/ph/debug/PerformanceInfo.cpp | JRBonilla/Slate | 9bcb3befced30d8f9ffb2dcce0a0209ba76093e4 | [
"MIT"
] | null | null | null | #include "PerformanceInfo.h"
#include "ph/app/Application.h"
namespace ph { namespace debug {
using namespace math;
using namespace renderer;
PerformanceInfo::PerformanceInfo()
: Layer2D(ShaderManager::Get("Font"), Mat4::Orthographic(-16.0f, 16.0f, -9.0f, 9.0f, -1.0f, 1.0f)) {
}
PerformanceInfo::~PerformanceInfo() {
}
void PerformanceInfo::Init() {
Layer2D::Init();
m_FPSLabel = new Label("", 14.5f, 8.3f, FontManager::Get("Default"), Vec4(1.0f, 1.0f, 1.0f, 1.0f));
this->Add(m_FPSLabel);
m_UPSLabel = new Label("", 14.5f, 7.8f, FontManager::Get("Default"), Vec4(1.0f, 1.0f, 1.0f, 1.0f));
this->Add(m_UPSLabel);
m_FrameTimeLabel = new Label("", 13.0f, 7.3f, FontManager::Get("Default"), Vec4(1.0f, 1.0f, 1.0f, 1.0f));
this->Add(m_FrameTimeLabel);
}
void PerformanceInfo::Update() {
m_FPSLabel->SetText(std::to_string(Application::GetApplication().GetFPS()) + " FPS");
m_UPSLabel->SetText(std::to_string(Application::GetApplication().GetUPS()) + " UPS");
m_FrameTimeLabel->SetText(std::to_string(Application::GetApplication().GetFrameTime()).substr(0, 5) + " ms/frame");
}
}} | 31.942857 | 117 | 0.676208 | JRBonilla |
c4577e5ca14344a5247089b2e3adaa0551c37da3 | 2,299 | hpp | C++ | hw4/sdb.hpp | ss8651twtw/Unix-Programming | bf6f132e03d1c57ee901dcba2104db102051052e | [
"MIT"
] | 19 | 2019-10-20T09:02:12.000Z | 2022-03-28T20:07:06.000Z | hw4/sdb.hpp | ss8651twtw/Unix-Programming | bf6f132e03d1c57ee901dcba2104db102051052e | [
"MIT"
] | null | null | null | hw4/sdb.hpp | ss8651twtw/Unix-Programming | bf6f132e03d1c57ee901dcba2104db102051052e | [
"MIT"
] | 3 | 2021-05-27T03:20:34.000Z | 2021-06-18T07:35:38.000Z | #pragma once
#include <string>
#include <sstream>
#include <vector>
#define PB push_back
#define NOLOAD 0
#define LOADED 1
#define RUNNING 2
#define MAXASM 0x100
using namespace std;
typedef vector<string> VS;
typedef long long LL;
typedef unsigned char UC;
struct breakpoint {
int id;
LL addr;
UC ori;
bool isfix;
breakpoint(int _i = -1, LL _a = 0, UC _o = '\0', bool _f = false)
: id(_i), addr(_a), ori(_o), isfix(_f) {
}
};
VS split(const string &s, const char d = '\0') {
VS res;
stringstream ss(s);
string item;
if (d)
while (getline(ss, item, d)) res.PB(item);
else
while (ss >> item) res.PB(item);
return res;
}
string get_byte(const UC *byte) {
stringstream ss;
ss << hex << setfill('0') << setw(2) << (int) *byte;
string tmp;
ss >> tmp;
return tmp;
}
string get_bytes(const UC *bytes, int n) {
string out = "";
bool fir = true;
for (int i = 0; i < n; i++) {
if (!fir) out += " ";
fir = false;
out += get_byte(bytes + i);
}
return out;
}
string get_printable(const string &s) {
string out = "|";
for (auto &x : s) {
int tmp = x;
if (tmp < 32 || tmp > 126) out += ".";
else out += x;
}
out += "|";
return out;
}
string flags2rwx(const LL flags) {
string per = "xwr", tmp = "";
for (int i = 2; i >= 0; i--) {
if (flags & (1 << i)) tmp += per[i];
else tmp += "-";
}
return tmp;
}
LL str2ll(const string &s) {
if (s.find("0x") == 0 || s.find("0X") == 0) {
return stoll(s, NULL, 16);
}
else if (s.find("0") == 0) {
return stoll(s, NULL, 8);
}
else {
return stoll(s);
}
}
void get_code();
void get_regs();
string get_mem(const LL addr);
void print_reg(const string &name);
UC patch_byte(const LL addr, UC c);
bool isintext(const LL addr);
bool chkat(const auto &x, unsigned int at, bool p);
int chkst();
string disone(UC *pos, LL &addr);
void bp(const LL addr);
void cont();
void del(int id);
void disasm();
void dump(int sz = 80);
void quit();
void get(const string ®);
void getregs();
void help();
void list();
void load();
void run();
void vmmap();
void set(const string ®, LL val);
void si();
void start();
| 19.649573 | 69 | 0.552414 | ss8651twtw |
c45bf601ddc8ca5628cb190857128f9a5577812f | 1,794 | cpp | C++ | liftoff-physics/liftoff-physics/driven_body.cpp | AgentTroll/liftoff | d300cbc716c811dca036527b99c0537ed1a6dbf6 | [
"Apache-2.0"
] | 1 | 2021-10-30T05:59:36.000Z | 2021-10-30T05:59:36.000Z | liftoff-physics/liftoff-physics/driven_body.cpp | caojohnny/liftoff | d300cbc716c811dca036527b99c0537ed1a6dbf6 | [
"Apache-2.0"
] | null | null | null | liftoff-physics/liftoff-physics/driven_body.cpp | caojohnny/liftoff | d300cbc716c811dca036527b99c0537ed1a6dbf6 | [
"Apache-2.0"
] | null | null | null | #include "driven_body.h"
namespace liftoff {
driven_body::driven_body(double body_mass, d_idx_t db_driver_idx, int body_derivatives, double db_time_step) :
body(body_mass, body_derivatives), driver_idx(db_driver_idx), time_step(db_time_step) {
for (int i = 0; i < body_derivatives; ++i) {
prev_state.emplace_back();
}
}
void driven_body::set_component(d_idx_t derivative, const vector &component) {
if (d_mot.size() <= derivative) {
return;
}
body::set_component(derivative, component);
if (!initial) {
drive_derivatives(derivative);
}
}
void driven_body::drive_derivatives(d_idx_t root_driver) {
vector time_v{time_step};
for (d_idx_t i = root_driver + 1; i < d_mot.size(); ++i) {
const vector &prev_driving_vec{prev_state[i - 1]};
const vector &cur_driving_vec{d_mot[i - 1]};
d_mot[i].set(cur_driving_vec).sub(prev_driving_vec).div(time_v);
}
}
void driven_body::drive_integrals(d_idx_t root_driver) {
if (root_driver == 0) {
return;
}
vector time_v{time_step};
std::vector<vector> adjusted_mot;
for (const auto &vec : d_mot) {
adjusted_mot.push_back(vector{vec}.mul(time_v));
}
d_idx_t i = root_driver;
do {
i--;
const vector cur_driving_vec{adjusted_mot[i + 1]};
d_mot[i].add(cur_driving_vec);
} while (i != 0);
}
void driven_body::compute_motion() {
drive_integrals(driver_idx);
}
void driven_body::post_compute() {
for (d_idx_t i = 0; i < d_mot.size(); ++i) {
prev_state[i].set(d_mot[i]);
}
}
}
| 28.03125 | 114 | 0.576923 | AgentTroll |
c45cccdafbadfaeff80917ea46b7c84afd239ef4 | 15,287 | cc | C++ | gazebo/physics/ModelState.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-04-06T16:17:36.000Z | 2015-04-06T16:17:36.000Z | gazebo/physics/ModelState.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | gazebo/physics/ModelState.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2015 Open Source Robotics Foundation
*
* 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 "gazebo/common/Exception.hh"
#include "gazebo/physics/Model.hh"
#include "gazebo/physics/Link.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/physics/ModelState.hh"
using namespace gazebo;
using namespace physics;
/////////////////////////////////////////////////
ModelState::ModelState()
: State()
{
}
/////////////////////////////////////////////////
ModelState::ModelState(const ModelPtr _model, const common::Time &_realTime,
const common::Time &_simTime, const uint64_t _iterations)
: State(_model->GetName(), _realTime, _simTime, _iterations)
{
this->pose = _model->GetWorldPose();
// Copy all the links
const Link_V links = _model->GetLinks();
for (Link_V::const_iterator iter = links.begin(); iter != links.end(); ++iter)
{
this->linkStates.insert(std::make_pair((*iter)->GetName(),
LinkState(*iter, _realTime, _simTime, _iterations)));
}
// Copy all the joints
/*const Joint_V joints = _model->GetJoints();
for (Joint_V::const_iterator iter = joints.begin();
iter != joints.end(); ++iter)
{
this->jointStates.insert(std::make_pair((*iter)->GetName(),
JointState(*iter, _realTime, _simTime, _iterations)));
}*/
}
/////////////////////////////////////////////////
ModelState::ModelState(const ModelPtr _model)
: State(_model->GetName(), _model->GetWorld()->GetRealTime(),
_model->GetWorld()->GetSimTime(), _model->GetWorld()->GetIterations())
{
this->pose = _model->GetWorldPose();
// Copy all the links
const Link_V links = _model->GetLinks();
for (Link_V::const_iterator iter = links.begin(); iter != links.end(); ++iter)
{
this->linkStates.insert(std::make_pair((*iter)->GetName(),
LinkState((*iter))));
}
// Copy all the joints
/*const Joint_V joints = _model->GetJoints();
for (Joint_V::const_iterator iter = joints.begin();
iter != joints.end(); ++iter)
{
this->jointStates.insert(std::make_pair((*iter)->GetName(),
JointState(*iter)));
}*/
}
/////////////////////////////////////////////////
ModelState::ModelState(const sdf::ElementPtr _sdf)
: State()
{
this->Load(_sdf);
}
/////////////////////////////////////////////////
ModelState::~ModelState()
{
}
/////////////////////////////////////////////////
void ModelState::Load(const ModelPtr _model, const common::Time &_realTime,
const common::Time &_simTime, const uint64_t _iterations)
{
this->name = _model->GetName();
this->wallTime = common::Time::GetWallTime();
this->realTime = _realTime;
this->simTime = _simTime;
this->iterations = _iterations;
this->pose = _model->GetWorldPose();
// Load all the links
const Link_V links = _model->GetLinks();
for (Link_V::const_iterator iter = links.begin(); iter != links.end(); ++iter)
{
this->linkStates[(*iter)->GetName()].Load(*iter, _realTime, _simTime,
_iterations);
}
// Remove links that no longer exist. We determine this by check the time
// stamp on each link.
for (LinkState_M::iterator iter = this->linkStates.begin();
iter != this->linkStates.end();)
{
if (iter->second.GetRealTime() != this->realTime)
this->linkStates.erase(iter++);
else
++iter;
}
// Copy all the joints
/*const Joint_V joints = _model->GetJoints();
for (Joint_V::const_iterator iter = joints.begin();
iter != joints.end(); ++iter)
{
this->jointStates[(*iter)->GetName()].Load(*iter, _realTime, _simTime,
_iterations);
}
// Remove joints that no longer exist. We determine this by check the time
// stamp on each joint.
for (JointState_M::iterator iter = this->jointStates.begin();
iter != this->jointStates.end();)
{
if (iter->second.GetRealTime() != this->realTime)
this->jointStates.erase(iter++);
else
++iter;
}*/
}
/////////////////////////////////////////////////
void ModelState::Load(const sdf::ElementPtr _elem)
{
// Set the name
this->name = _elem->Get<std::string>("name");
// Set the model pose
if (_elem->HasElement("pose"))
this->pose = _elem->Get<math::Pose>("pose");
else
this->pose.Set(0, 0, 0, 0, 0, 0);
// Set all the links
this->linkStates.clear();
if (_elem->HasElement("link"))
{
sdf::ElementPtr childElem = _elem->GetElement("link");
while (childElem)
{
this->linkStates.insert(std::make_pair(
childElem->Get<std::string>("name"), LinkState(childElem)));
childElem = childElem->GetNextElement("link");
}
}
// Set all the joints
/*this->jointStates.clear();
if (_elem->HasElement("joint"))
{
sdf::ElementPtr childElem = _elem->GetElement("joint");
while (childElem)
{
this->jointStates.insert(std::make_pair(childElem->Get<std::string>("name"),
JointState(childElem)));
childElem = childElem->GetNextElement("joint");
}
}*/
}
/////////////////////////////////////////////////
const math::Pose &ModelState::GetPose() const
{
return this->pose;
}
/////////////////////////////////////////////////
bool ModelState::IsZero() const
{
bool result = true;
for (LinkState_M::const_iterator iter = this->linkStates.begin();
iter != this->linkStates.end() && result; ++iter)
{
result = result && iter->second.IsZero();
}
/*for (JointState_M::const_iterator iter = this->jointStates.begin();
iter != this->jointStates.end() && result; ++iter)
{
result = result && iter->second.IsZero();
}*/
return result && this->pose == math::Pose::Zero;
}
/////////////////////////////////////////////////
unsigned int ModelState::GetLinkStateCount() const
{
return this->linkStates.size();
}
/////////////////////////////////////////////////
LinkState_M ModelState::GetLinkStates(const boost::regex &_regex) const
{
LinkState_M result;
// Search for matching link names
for (LinkState_M::const_iterator iter = this->linkStates.begin();
iter != this->linkStates.end(); ++iter)
{
if (boost::regex_match(iter->first, _regex))
result.insert(std::make_pair(iter->first, iter->second));
}
return result;
}
/////////////////////////////////////////////////
JointState_M ModelState::GetJointStates(const boost::regex &_regex) const
{
JointState_M result;
// Search for matching link names
for (JointState_M::const_iterator iter = this->jointStates.begin();
iter != this->jointStates.end(); ++iter)
{
if (boost::regex_match(iter->second.GetName(), _regex))
result.insert(std::make_pair(iter->first, iter->second));
}
return result;
}
/////////////////////////////////////////////////
LinkState ModelState::GetLinkState(const std::string &_linkName) const
{
// Search for the link name
LinkState_M::const_iterator iter = this->linkStates.find(_linkName);
if (iter != this->linkStates.end())
return iter->second;
gzthrow("Invalid link name[" + _linkName + "]");
return LinkState();
}
/////////////////////////////////////////////////
bool ModelState::HasLinkState(const std::string &_linkName) const
{
// Search for the link name
LinkState_M::const_iterator iter = this->linkStates.find(_linkName);
if (iter != this->linkStates.end())
return true;
return false;
}
/////////////////////////////////////////////////
const LinkState_M &ModelState::GetLinkStates() const
{
return this->linkStates;
}
/////////////////////////////////////////////////
unsigned int ModelState::GetJointStateCount() const
{
return this->jointStates.size();
}
/////////////////////////////////////////////////
JointState ModelState::GetJointState(unsigned int _index) const
{
if (_index < this->jointStates.size())
{
JointState_M::const_iterator iter = this->jointStates.begin();
std::advance(iter, _index);
return iter->second;
}
gzthrow("Index is out of range");
return JointState();
}
/////////////////////////////////////////////////
JointState ModelState::GetJointState(const std::string &_jointName) const
{
JointState_M::const_iterator iter = this->jointStates.find(_jointName);
if (iter != this->jointStates.end())
return iter->second;
gzthrow("Invalid joint name[" + _jointName + "]");
return JointState();
}
/////////////////////////////////////////////////
bool ModelState::HasJointState(const std::string &_jointName) const
{
JointState_M::const_iterator iter = this->jointStates.find(_jointName);
if (iter != this->jointStates.end())
return true;
return false;
}
/////////////////////////////////////////////////
const JointState_M &ModelState::GetJointStates() const
{
return this->jointStates;
}
/////////////////////////////////////////////////
ModelState &ModelState::operator=(const ModelState &_state)
{
State::operator=(_state);
// Copy the pose
this->pose = _state.pose;
// Clear the link and joint states.
this->linkStates.clear();
this->jointStates.clear();
// Copy the link states.
for (LinkState_M::const_iterator iter =
_state.linkStates.begin(); iter != _state.linkStates.end(); ++iter)
{
this->linkStates.insert(std::make_pair(iter->first, iter->second));
}
// Copy the joint states.
// for (JointState_M::const_iterator iter =
// _state.jointStates.begin(); iter != _state.jointStates.end(); ++iter)
// {
// this->jointStates.insert(std::make_pair(iter->first, iter->second));
// }
return *this;
}
/////////////////////////////////////////////////
ModelState ModelState::operator-(const ModelState &_state) const
{
ModelState result;
result.name = this->name;
result.pose.pos = this->pose.pos - _state.pose.pos;
result.pose.rot = _state.pose.rot.GetInverse() * this->pose.rot;
// Insert the link state diffs.
for (LinkState_M::const_iterator iter =
this->linkStates.begin(); iter != this->linkStates.end(); ++iter)
{
try
{
if (_state.HasLinkState(iter->second.GetName()))
{
LinkState state = iter->second - _state.GetLinkState(
iter->second.GetName());
if (!state.IsZero())
result.linkStates.insert(std::make_pair(state.GetName(), state));
}
}
catch(common::Exception &)
{
// Ignore exception, which is just the fact that a link state may not
// have been recorded.
}
}
// Insert the joint state diffs.
/*for (JointState_M::const_iterator iter =
this->jointStates.begin(); iter != this->jointStates.end(); ++iter)
{
try
{
if (_state.HasJointState(iter->second.GetName()))
{
JointState state = iter->second -
_state.GetJointState(iter->second.GetName());
if (!state.IsZero())
result.jointStates.insert(std::make_pair(state.GetName(), state));
}
}
catch(common::Exception &)
{
// Ignore exception, which is just the fact that a joint state may not
// have been recorded.
}
}*/
return result;
}
/////////////////////////////////////////////////
ModelState ModelState::operator+(const ModelState &_state) const
{
ModelState result;
result.name = this->name;
result.pose.pos = this->pose.pos + _state.pose.pos;
result.pose.rot = _state.pose.rot * this->pose.rot;
// Insert the link state diffs.
for (LinkState_M::const_iterator iter =
this->linkStates.begin(); iter != this->linkStates.end(); ++iter)
{
try
{
if (_state.HasLinkState(iter->second.GetName()))
{
LinkState state = iter->second + _state.GetLinkState(
iter->second.GetName());
result.linkStates.insert(std::make_pair(state.GetName(), state));
}
}
catch(common::Exception &)
{
// Ignore exception, which is just the fact that a link state may not
// have been recorded.
}
}
// Insert the joint state diffs.
for (JointState_M::const_iterator iter =
this->jointStates.begin(); iter != this->jointStates.end(); ++iter)
{
try
{
if (_state.HasJointState(iter->second.GetName()))
{
JointState state = iter->second +
_state.GetJointState(iter->second.GetName());
result.jointStates.insert(std::make_pair(state.GetName(), state));
}
}
catch(common::Exception &)
{
// Ignore exception, which is just the fact that a joint state may not
// have been recorded.
}
}
return result;
}
/////////////////////////////////////////////////
void ModelState::FillSDF(sdf::ElementPtr _sdf)
{
_sdf->ClearElements();
_sdf->GetAttribute("name")->Set(this->name);
_sdf->GetElement("pose")->Set(this->pose);
for (LinkState_M::iterator iter = this->linkStates.begin();
iter != this->linkStates.end(); ++iter)
{
sdf::ElementPtr elem = _sdf->AddElement("link");
iter->second.FillSDF(elem);
}
for (JointState_M::iterator iter = this->jointStates.begin();
iter != this->jointStates.end(); ++iter)
{
sdf::ElementPtr elem = _sdf->AddElement("joint");
iter->second.FillSDF(elem);
}
}
/////////////////////////////////////////////////
void ModelState::SetWallTime(const common::Time &_time)
{
State::SetWallTime(_time);
for (LinkState_M::iterator iter = this->linkStates.begin();
iter != this->linkStates.end(); ++iter)
{
iter->second.SetWallTime(_time);
}
for (JointState_M::iterator iter = this->jointStates.begin();
iter != this->jointStates.end(); ++iter)
{
iter->second.SetWallTime(_time);
}
}
/////////////////////////////////////////////////
void ModelState::SetRealTime(const common::Time &_time)
{
State::SetRealTime(_time);
for (LinkState_M::iterator iter = this->linkStates.begin();
iter != this->linkStates.end(); ++iter)
{
iter->second.SetRealTime(_time);
}
for (JointState_M::iterator iter = this->jointStates.begin();
iter != this->jointStates.end(); ++iter)
{
iter->second.SetRealTime(_time);
}
}
/////////////////////////////////////////////////
void ModelState::SetSimTime(const common::Time &_time)
{
State::SetSimTime(_time);
for (LinkState_M::iterator iter = this->linkStates.begin();
iter != this->linkStates.end(); ++iter)
{
iter->second.SetSimTime(_time);
}
for (JointState_M::iterator iter = this->jointStates.begin();
iter != this->jointStates.end(); ++iter)
{
iter->second.SetSimTime(_time);
}
}
/////////////////////////////////////////////////
void ModelState::SetIterations(const uint64_t _iterations)
{
State::SetIterations(_iterations);
for (auto &linkState : this->linkStates)
linkState.second.SetIterations(_iterations);
for (auto &jointState : this->jointStates)
jointState.second.SetIterations(_iterations);
}
| 27.744102 | 82 | 0.596127 | harderthan |
c46026e88d71cf275f6bd0d46af96202541d9c9f | 3,448 | hpp | C++ | src/frovedis/matrix/cir_array_list.hpp | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 63 | 2018-06-21T14:11:59.000Z | 2022-03-30T11:24:36.000Z | src/frovedis/matrix/cir_array_list.hpp | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 5 | 2018-09-22T14:01:53.000Z | 2021-12-27T16:11:05.000Z | src/frovedis/matrix/cir_array_list.hpp | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 12 | 2018-08-23T15:59:44.000Z | 2022-02-20T06:47:22.000Z | #ifndef _C_ARRAY_LIST_HPP_
#define _C_ARRAY_LIST_HPP_
#include <vector>
#include "../core/exceptions.hpp"
#include <boost/lexical_cast.hpp>
#define ITOS boost::lexical_cast<std::string>
namespace frovedis {
template <class T>
struct cir_array_list {
explicit cir_array_list(size_t size=10):
rear(-1), front(-1), totActiveElements(0), len(size)
{ val.resize(size); }
cir_array_list(const cir_array_list& l) {
val = l.val;
rear = l.rear;
front = l.front;
len = l.len;
totActiveElements = l.totActiveElements;
}
cir_array_list(cir_array_list&& l) {
val.swap(l.val);
rear = l.rear;
front = l.front;
len = l.len;
totActiveElements = l.totActiveElements;
l.reset();
}
cir_array_list& operator=(const cir_array_list& l) {
val = l.val;
rear = l.rear;
front = l.front;
len = l.len;
totActiveElements = l.totActiveElements;
return *this;
}
cir_array_list& operator=(cir_array_list&& l) {
val.swap(l.val);
rear = l.rear;
front = l.front;
len = l.len;
totActiveElements = l.totActiveElements;
l.reset();
return *this;
}
bool isFull() const {
return (totActiveElements == len);
}
bool isEmpty() const {
return (totActiveElements == 0);
}
size_t size() const {
return len;
}
void debug_print() const {
for (size_t i = 0; i < totActiveElements; ++i) {
std::cout << "[" << i << "] " << operator[](i) << "\n";
}
std::cout << std::endl;
}
void reset() {
rear = front = -1;
len = totActiveElements = 0;
val.clear();
}
void push_back_impl() {
if(isEmpty()) {
rear = front = 0;
}
else if (isFull()) { // insertion is possible, even if list is full
rear = (rear+1) % len;
front = (front+1) % len;
}
else {
front = (front+1) % len;
}
totActiveElements = (totActiveElements < len) ? totActiveElements + 1 : len;
}
// inserts data after last active element in the list (at front)
void push_back(const T& data);
void push_back(T&& data);
// removes oldest active data from the list (from rear) and returns it
T pop_front();
// returns the ith active element from the list
const T& operator[](size_t index) const;
T& operator[](size_t index);
std::vector<T> val;
size_t rear, front, totActiveElements, len;
SERIALIZE(val,rear,front,totActiveElements,len)
};
template <class T>
void cir_array_list<T>::push_back(const T& data) {
push_back_impl();
val[front] = data;
}
template <class T>
void cir_array_list<T>::push_back(T&& data) {
push_back_impl();
val[front] = std::move(data);
}
template <class T>
T cir_array_list<T>::pop_front() {
if(isEmpty()) REPORT_ERROR(USER_ERROR,"Invalid operation: Empty list!\n");
T ret = val[rear];
if (rear == front) {rear = front = -1;}
else rear = (rear + 1) % len;
totActiveElements--;
return ret;
}
template <class T>
const T& cir_array_list<T>::operator[] (size_t index) const {
std::string msg = ITOS(index) + ": Invalid index!\n";
if(index >= totActiveElements) REPORT_ERROR(USER_ERROR,msg);
size_t a_index = (rear + index) % len;
return val[a_index];
}
template <class T>
T& cir_array_list<T>::operator[] (size_t index) {
std::string msg = ITOS(index) + ": Invalid index!\n";
if(index >= totActiveElements) REPORT_ERROR(USER_ERROR,msg);
size_t a_index = (rear + index) % len;
return val[a_index];
}
}
#endif
| 24.985507 | 80 | 0.632251 | XpressAI |
c465c8d17760be36b0247edede5e4117f865bfaa | 1,578 | cc | C++ | src/media_factory_sdl.cc | Jaween/september | 17b712a1a278d159e69cb5134109255472e11098 | [
"Apache-2.0"
] | null | null | null | src/media_factory_sdl.cc | Jaween/september | 17b712a1a278d159e69cb5134109255472e11098 | [
"Apache-2.0"
] | null | null | null | src/media_factory_sdl.cc | Jaween/september | 17b712a1a278d159e69cb5134109255472e11098 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include "media_factory_sdl.hpp"
#include "image_sdl.hpp"
#include "window_manager_sdl.hpp"
MediaFactorySdl::MediaFactorySdl() {
initialiseSdl();
}
MediaFactorySdl::~MediaFactorySdl() {
Mix_FreeMusic(music_);
music_ = NULL;
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
WindowManager* MediaFactorySdl::createWindowManager() {
WindowManager* window_manager = new WindowManagerSdl();
window_managers.push_back(window_manager);
return window_manager;
}
Image* MediaFactorySdl::createImage(unsigned int width, unsigned int height, unsigned int words_per_pixel) {
Image* image = new ImageSdl(width, height, words_per_pixel);
images.push_back(image);
return image;
}
bool MediaFactorySdl::initialiseSdl() {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) == -1) {
std::cerr << "Failed to initialise SDL" << std::endl;
return false;
}
int flags = IMG_INIT_PNG;
if ((IMG_Init(flags) & flags) == -1) {
std::cerr << "Failed to initialise SDL_image" << std::endl;
return false;
}
if ((Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1)) {
std::cerr << "Failed to initialise SDL_mixer" << std::endl;
return false;
}
return true;
}
void MediaFactorySdl::playAudio(std::string filename, bool loop) {
music_ = Mix_LoadMUS(filename.c_str());
if (music_ == NULL) {
std::cerr << "Could not open " << filename << std::endl;
}
if (loop) {
Mix_PlayMusic(music_, -1);
} else {
Mix_PlayMusic(music_, 1);
}
} | 23.909091 | 108 | 0.688213 | Jaween |
c465cfdf9a8e67089fa4a6fd52040316b1aea520 | 3,956 | cpp | C++ | Competitive Programming/Practice(Div.2 A)/TreeAndQueries_CF_375D.cpp | Brabec/Hacktoberfest2020 | d3a85850a462ab24abf59d68b5142e0b61b5ce37 | [
"MIT"
] | null | null | null | Competitive Programming/Practice(Div.2 A)/TreeAndQueries_CF_375D.cpp | Brabec/Hacktoberfest2020 | d3a85850a462ab24abf59d68b5142e0b61b5ce37 | [
"MIT"
] | null | null | null | Competitive Programming/Practice(Div.2 A)/TreeAndQueries_CF_375D.cpp | Brabec/Hacktoberfest2020 | d3a85850a462ab24abf59d68b5142e0b61b5ce37 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define int long long int
#define ll long long
#define quickie ios_base::sync_with_stdio(false); cin.tie(NULL);
#define rep(i, a, b) for(int i=a; i<b; i++)
#define rep1(i, a, b) for(int i=a; i<=b; i++)
#define repp(i, a, b) for(int i=b-1; i>=a; i--)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define db double
#define mi map<int, int>
#define vi vector<int>
#define qi queue<int>
#define MI(x) power(x, mod-2)
#define test int t; cin >> t;
#define all(a) a.begin(),a.e()
#define mod 1000000007
#define pi 3.141592653589
#define fact(n) rep(i, 1, n+1)ft.pb((ft[i-1]*i)%mod) ;
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// template<typename T>
// using ordered_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
// template<typename T>
// using ordered_multiset = tree<T,null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;
//(*****FOR USING ORDERED SET CHANGE INT*******)
const int maxN = 100001 ;
int BLK = 2000 ;
vi v[maxN] ;
int a[maxN], start[maxN], e[maxN], timer, ft[2*maxN] ;
int nodeF[maxN], eleF[maxN], FF[maxN] = {0}, ans[maxN] ;
int bucket[maxN], n, q, sz ;
struct query {
int l, r, ind, k ;
};
query Q[maxN] ;
int getBLK(int n) {
return (n+BLK-1)/BLK ;
}
void dfs(int n, int p) {
ft[timer] = n ;
start[n] = timer ;
timer++ ;
for(auto i : v[n]) {
if(i != p) {
dfs(i, n) ;
}
}
e[n] = timer ;
ft[timer] = n ;
timer++ ;
}
void add(int inx) {
int node = ft[inx] ;
int col = a[node] ;
nodeF[node]++ ;
if(nodeF[node] == 2) {
eleF[col]++ ;
FF[eleF[col]]++ ;
bucket[getBLK(eleF[col])]++ ;
FF[eleF[col]-1]-- ;
bucket[getBLK(eleF[col]-1)]-- ;
}
}
void remove(int inx) {
int node = ft[inx] ;
int col = a[node] ;
nodeF[node]-- ;
if(nodeF[node] == 1) {
eleF[col]-- ;
FF[eleF[col]]++ ;
bucket[getBLK(eleF[col])]++ ;
FF[eleF[col]+1]-- ;
bucket[getBLK(eleF[col]+1)]-- ;
}
}
bool comp(query a, query b) {
if(a.l/BLK != b.l/BLK) {
return a.l/BLK < b.l/BLK ;
}
if(a.l/BLK % 2)
return a.r < b.r ;
else
return a.r > b.r ;
}
int getans(int k, int n) {
int ans = 0 ;
int L = getBLK(k) ;
int R = getBLK(n) ;
if(L == R) {
rep(i, k, n+1) ans += FF[i] ;
return ans ;
}
rep1(i, k, L*BLK) {
ans += FF[i] ;
}
rep(i, L+1, R) ans += bucket[i] ;
rep(i, R*BLK+1, n+1) ans += FF[i] ;
return ans ;
}
signed main() {
quickie
cin >> n >> q ;
rep(i, 1, n+1) cin >> a[i] ;
rep(i, 0, n-1) {
int a, b ;
cin >> a >> b ;
v[a].pb(b) ;
v[b].pb(a) ;
}
timer = 1 ;
dfs(1, -1) ;
rep1(i, 1, q) {
int a, k;
cin >> a >> k;
Q[i].l = start[a] ;
Q[i].r = e[a] ;
Q[i].k = k ;
Q[i].ind = i ;
}
sort(Q+1, Q+q+1, comp) ;
int ML = 0, MR = -1 ;
rep(i, 1, q+1) {
int L = Q[i].l ;
int R = Q[i].r ;
int ind = Q[i].ind ;
int k = Q[i].k ;
while(ML > L) {
ML-- ;
add(ML) ;
}
while(MR < R) {
MR++ ;
add(MR) ;
}
while(ML < L) {
remove(ML) ;
ML++ ;
}
while(MR > R) {
remove(MR) ;
MR-- ;
}
ans[ind] = getans(k, n) ;
}
rep(i, 1, q+1) cout << ans[i] << "\n" ;
}
int power(int x, int y) {
int res = 1; x %= mod;
while (y > 0) {
if (y & 1)
res = (res*x) % mod;
y = y>>1;
x = (x*x) % mod;
}
return res%mod;
}
int gcd(int a,int b){
if(a==0) return b;
return gcd(b%a,a);
}
| 21.15508 | 106 | 0.471183 | Brabec |
c466dadaccef19813483ba8370f6b329ac159cbb | 711 | cpp | C++ | GEAR_CORE/src/Core/Timer.cpp | AndrewRichards-Code/GEAR_CORE | 4d4e77bf643dc9b98de9f38445eae690290e1895 | [
"MIT"
] | 3 | 2020-12-13T19:53:17.000Z | 2021-12-29T14:53:35.000Z | GEAR_CORE/src/Core/Timer.cpp | AndrewRichards-Code/GEAR_CORE | 4d4e77bf643dc9b98de9f38445eae690290e1895 | [
"MIT"
] | 1 | 2021-10-06T09:36:34.000Z | 2021-10-09T03:46:37.000Z | GEAR_CORE/src/Core/Timer.cpp | AndrewRichards-Code/GEAR | c08dfce35ccaa4bde046eb5b9e94d53eb65e7586 | [
"MIT"
] | null | null | null | #include "gear_core_common.h"
#include "Timer.h"
using namespace gear;
using namespace core;
Timer::Timer()
{
m_StartTimePoint = std::chrono::system_clock::now();
m_NowTimePoint = std::chrono::system_clock::now();
}
Timer::~Timer()
{
}
void Timer::Update()
{
GetDeltaTime();
}
double Timer::GetTime()
{
m_NowTimePoint = std::chrono::system_clock::now();
m_ElapsedDuration = m_NowTimePoint - m_StartTimePoint;
return m_ElapsedDuration.count();
}
double Timer::GetElapsedTime()
{
m_ElapsedTime = GetTime();
return m_ElapsedTime;
}
double Timer::GetDeltaTime()
{
GetElapsedTime();
m_DeltaTime = m_ElapsedTime - m_PreviousElapsedTime;
m_PreviousElapsedTime = m_ElapsedTime;
return m_DeltaTime;
}
| 16.928571 | 55 | 0.739803 | AndrewRichards-Code |
c466dcdd1f20af1289d978da91deb2db339b9179 | 2,811 | cpp | C++ | Project 19-/26 Compute Shader Beginning/GameApp.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | 3 | 2018-05-29T12:18:08.000Z | 2018-06-20T16:14:13.000Z | Project 19-/26 Compute Shader Beginning/GameApp.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | Project 19-/26 Compute Shader Beginning/GameApp.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | #include "GameApp.h"
using namespace DirectX;
GameApp::GameApp(HINSTANCE hInstance)
: D3DApp(hInstance)
{
}
GameApp::~GameApp()
{
}
bool GameApp::Init()
{
if (!D3DApp::Init())
return false;
if (!InitResource())
return false;
return true;
}
void GameApp::Compute()
{
assert(m_pd3dImmediateContext);
//#if defined(DEBUG) | defined(_DEBUG)
// ComPtr<IDXGraphicsAnalysis> graphicsAnalysis;
// HR(DXGIGetDebugInterface1(0, __uuidof(graphicsAnalysis.Get()), reinterpret_cast<void**>(graphicsAnalysis.GetAddressOf())));
// graphicsAnalysis->BeginCapture();
//#endif
m_pd3dImmediateContext->CSSetShaderResources(0, 1, m_pTextureInputA.GetAddressOf());
m_pd3dImmediateContext->CSSetShaderResources(1, 1, m_pTextureInputB.GetAddressOf());
m_pd3dImmediateContext->CSSetShader(m_pTextureMul_CS.Get(), nullptr, 0);
m_pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, m_pTextureOutputUAV.GetAddressOf(), nullptr);
m_pd3dImmediateContext->Dispatch(32, 32, 1);
//#if defined(DEBUG) | defined(_DEBUG)
// graphicsAnalysis->EndCapture();
//#endif
SaveDDSTextureToFile(m_pd3dImmediateContext.Get(), m_pTextureOutput.Get(), L"..\\Texture\\flareoutput.dds");
MessageBox(nullptr, L"请打开..\\Texture文件夹观察输出文件flareoutput.dds", L"运行结束", MB_OK);
}
bool GameApp::InitResource()
{
CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"..\\Texture\\flare.dds",
nullptr, m_pTextureInputA.GetAddressOf());
CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"..\\Texture\\flarealpha.dds",
nullptr, m_pTextureInputB.GetAddressOf());
// DXGI_FORMAT | RWTexture2D<T>
// --------------------------------+------------------
// DXGI_FORMAT_R8G8B8A8_UNORM | unorm float4
// DXGI_FORMAT_R16G16B16A16_UNORM | unorm float4
// DXGI_FORMAT_R8G8B8A8_SNORM | snorm float4
// DXGI_FORMAT_R16G16B16A16_SNORM | snorm float4
// DXGI_FORMAT_R16G16B16A16_FLOAT | float4 或 half4?
// DXGI_FORMAT_R32G32B32A32_FLOAT | float4
DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
CD3D11_TEXTURE2D_DESC texDesc(format, 512, 512, 1, 1,
D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS);
m_pd3dDevice->CreateTexture2D(&texDesc, nullptr, m_pTextureOutput.GetAddressOf());
// 创建无序访问视图
CD3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc(D3D11_UAV_DIMENSION_TEXTURE2D, format);
m_pd3dDevice->CreateUnorderedAccessView(m_pTextureOutput.Get(), &uavDesc,
m_pTextureOutputUAV.GetAddressOf());
// 创建计算着色器
ComPtr<ID3DBlob> blob;
D3DReadFileToBlob(L"Shaders\\TextureMul_CS.cso", blob.GetAddressOf());
m_pd3dDevice->CreateComputeShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pTextureMul_CS.GetAddressOf());
return true;
}
| 31.943182 | 129 | 0.708645 | MKXJun |
c467869984f55a64d01d2ba3444c5246a1b017b0 | 2,048 | hpp | C++ | src/librcl/scene_encoder.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 17 | 2019-03-12T14:52:22.000Z | 2021-11-09T01:16:23.000Z | src/librcl/scene_encoder.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | null | null | null | src/librcl/scene_encoder.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 2 | 2019-08-11T12:53:07.000Z | 2021-06-22T10:08:08.000Z | /* Copyright Institute of Sound and Vibration Research - All rights reserved */
#ifndef VISR_LIBRCL_SCENE_ENCODER_HPP_INCLUDED
#define VISR_LIBRCL_SCENE_ENCODER_HPP_INCLUDED
#include "export_symbols.hpp"
#include <libvisr/atomic_component.hpp>
#include <libvisr/constants.hpp>
#include <libvisr/parameter_input.hpp>
#include <libvisr/parameter_output.hpp>
#include <libpml/message_queue_protocol.hpp>
#include <libpml/object_vector.hpp>
#include <libpml/shared_data_protocol.hpp>
#include <libpml/string_parameter.hpp>
#include <memory> // for std::unique_ptr
#include <vector>
namespace visr
{
namespace rcl
{
/**
* Component to encode audio objects to JSON messages (typically to be sent over a network).
* This component has neither audio inputs or outputs.
*/
class VISR_RCL_LIBRARY_SYMBOL SceneEncoder: public AtomicComponent
{
public:
/**
* Constructor.
* @param context Configuration object containing basic execution parameters.
* @param name The name of the component. Must be unique within the containing composite component (if there is one).
* @param parent Pointer to a containing component if there is one. Specify \p nullptr in case of a top-level component.
*/
explicit SceneEncoder( SignalFlowContext const & context,
char const * name,
CompositeComponent * parent = nullptr );
/**
* Disabled (deleted) copy constructor
*/
SceneEncoder( SceneEncoder const & ) = delete;
/**
* Destructor.
*/
~SceneEncoder();
/**
* Transform the incoming object vector into a JSON message.
* @warning At the moment, a message is created in each process call.
* @todo Create a triggering/timing method to control the output rate.
*/
void process() override;
private:
ParameterInput< pml::SharedDataProtocol, pml::ObjectVector> mObjectInput;
ParameterOutput< pml::MessageQueueProtocol, pml::StringParameter > mDatagramOutput;
};
} // namespace rcl
} // namespace visr
#endif // #ifndef VISR_LIBRCL_SCENE_ENCODER_HPP_INCLUDED
| 29.257143 | 122 | 0.737305 | s3a-spatialaudio |
c467b7e1d8f23903c808048aaf4e21c7effcd1c6 | 1,104 | cpp | C++ | Languages/C++/all_possible_permutations_for_n_numbers.cpp | anujjain5699/Hacktoberfest | 05a2a8f813e301012240b14d729d015b35fbded7 | [
"MIT"
] | null | null | null | Languages/C++/all_possible_permutations_for_n_numbers.cpp | anujjain5699/Hacktoberfest | 05a2a8f813e301012240b14d729d015b35fbded7 | [
"MIT"
] | null | null | null | Languages/C++/all_possible_permutations_for_n_numbers.cpp | anujjain5699/Hacktoberfest | 05a2a8f813e301012240b14d729d015b35fbded7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
#define fast ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
/*n=3
3
1 3 6
1 3 6
1 6 3
3 1 6
3 6 1
6 1 3
6 3 1
*/
vector<vector<int>> permute(vector<int> &num)
{
if(num.size()<=1)
return {num};
vector<vector<int>> result;
for(int i=0;i<num.size();i++)
{
vector<int>v(num.begin(),num.end());
v.erase(v.begin()+i);
auto res=permute(v);
for(int j=0;j<res.size();j++)
{
vector<int> _v=res[j];
_v.insert(_v.begin(),num[i]);
result.push_back(_v);
}
}
return result;
}
int32_t main(){
fast
int n;
cin>>n;
vector<int> v;
rep(i,n)
{
int num;
cin>>num;
v.push_back(num);
}
vector<vector<int>> res=permute(v);
for (int i = 0; i < res.size();i++) {
for (auto it = res[i].begin();it != res[i].end(); it++)
cout << *it << " ";
cout << endl;
}
return 0;
}
| 18.098361 | 84 | 0.48913 | anujjain5699 |
c469ae0d20e412b6b651b03d9b5b605532924a60 | 3,075 | hpp | C++ | llarp/net/net_addr.hpp | tewinget/loki-network | 556277a2609dfc7417a67a61c1a5e3951640c764 | [
"Zlib"
] | 1 | 2021-02-10T03:41:22.000Z | 2021-02-10T03:41:22.000Z | llarp/net/net_addr.hpp | tzf-key/loki-network | 01b3c0363caa746abf0fa52d27ffef1c84141cc3 | [
"Zlib"
] | 2 | 2019-12-19T15:37:07.000Z | 2020-01-31T19:42:28.000Z | llarp/net/net_addr.hpp | tzf-key/loki-network | 01b3c0363caa746abf0fa52d27ffef1c84141cc3 | [
"Zlib"
] | null | null | null | #ifndef LLARP_NET_ADDR_HPP
#define LLARP_NET_ADDR_HPP
#include <net/address_info.hpp>
#include <net/net.h>
#include <net/net.hpp>
#include <util/string_view.hpp>
#include <net/net_int.hpp>
#include <string>
namespace llarp
{
// real work
struct Addr
{
// network order
sockaddr_in6 _addr;
sockaddr_in _addr4; // why do we even have this? favor cpu over memory
~Addr();
Addr();
Addr(const Addr& other);
void
port(uint16_t port);
in6_addr*
addr6();
in_addr*
addr4();
const in6_addr*
addr6() const;
const in_addr*
addr4() const;
Addr(const std::string str);
Addr(const std::string str, const uint16_t p_port);
Addr(string_view addr_str, string_view port_str);
bool
from_char_array(const char* str);
Addr(const char* str);
bool
from_4int(const uint8_t one, const uint8_t two, const uint8_t three,
const uint8_t four);
Addr(const uint8_t one, const uint8_t two, const uint8_t three,
const uint8_t four);
Addr(const uint8_t one, const uint8_t two, const uint8_t three,
const uint8_t four, const uint16_t p_port);
Addr(const AddressInfo& other);
Addr(const sockaddr_in& other);
Addr(const sockaddr_in6& other);
Addr(const sockaddr& other);
std::string
ToString() const;
friend std::ostream&
operator<<(std::ostream& out, const Addr& a);
operator const sockaddr*() const;
operator sockaddr*() const;
void
CopyInto(sockaddr* other) const;
int
af() const;
uint16_t
port() const;
bool
operator<(const Addr& other) const;
bool
operator==(const Addr& other) const;
Addr&
operator=(const sockaddr& other);
inline uint32_t
tohl() const
{
return ntohl(addr4()->s_addr);
}
inline huint32_t
xtohl() const
{
return huint32_t{ntohl(addr4()->s_addr)};
}
inline uint32_t
ton() const
{
return addr4()->s_addr;
}
inline nuint32_t
xtonl() const
{
return nuint32_t{addr4()->s_addr};
}
bool
sameAddr(const Addr& other) const;
bool
operator!=(const Addr& other) const;
inline uint32_t
getHostLong()
{
in_addr_t addr = this->addr4()->s_addr;
uint32_t byte = ntohl(addr);
return byte;
}
bool
isTenPrivate(uint32_t byte);
bool
isOneSevenPrivate(uint32_t byte);
bool
isOneNinePrivate(uint32_t byte);
/// return true if our ipv4 address is a bogon
/// TODO: ipv6
bool
IsBogon() const;
socklen_t
SockLen() const;
bool
isPrivate() const;
bool
isLoopback() const;
struct Hash
{
std::size_t
operator()(Addr const& a) const noexcept
{
if(a.af() == AF_INET)
{
return a.port() ^ a.addr4()->s_addr;
}
static const uint8_t empty[16] = {0};
return (a.af() + memcmp(a.addr6(), empty, 16)) ^ a.port();
}
};
}; // end struct
} // namespace llarp
#endif
| 17.877907 | 75 | 0.602276 | tewinget |
c46a08da8a12a35a95113790233bd223db6b80b4 | 376 | cpp | C++ | ACM-ICPC/2455.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/2455.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/2455.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
using namespace std;
int x, y;
int station[4];
int main() {
// 조건에 맞게 실행하면 된다
for (int i = 0; i < 4; i++) {
scanf("%d %d", &x, &y);
station[i] = station[i - 1] - x;
station[i] = station[i] + y;
}
printf("%d\n", max(station[0], max(station[1], max(station[2], station[3]))));
} | 20.888889 | 83 | 0.489362 | KimBoWoon |
c46ac87562bbd364481c80a2db80feb7f61e5bcc | 504 | cpp | C++ | src/main.cpp | DannyHavenith/SimpleProjectSkeleton | 163e1973eeecf845be308c6c58fc4a03c7057de9 | [
"BSL-1.0"
] | null | null | null | src/main.cpp | DannyHavenith/SimpleProjectSkeleton | 163e1973eeecf845be308c6c58fc4a03c7057de9 | [
"BSL-1.0"
] | null | null | null | src/main.cpp | DannyHavenith/SimpleProjectSkeleton | 163e1973eeecf845be308c6c58fc4a03c7057de9 | [
"BSL-1.0"
] | null | null | null | /**
* 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 <iostream>
#include <exception>
void error( const std::string &what)
{
throw std::runtime_error( what);
}
int main(int argc, char* argv[])
{
try
{
std::cout << "It's working!\n";
}
catch (std::exception &e)
{
std::cerr << "something went wrong: " << e.what() << '\n';
}
return 0;
}
| 15.75 | 66 | 0.595238 | DannyHavenith |
c46bafdebaa88d95ca854cbed10fd83fd8e896ab | 2,431 | cc | C++ | src/chrome/app/breakpad_field_trial_win.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/app/breakpad_field_trial_win.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | chrome/app/breakpad_field_trial_win.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/breakpad_field_trial_win.h"
#include "base/lazy_instance.h"
#include "base/string_util.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "breakpad/src/client/windows/common/ipc_protocol.h"
#include "chrome/app/breakpad_win.h"
#include "chrome/common/child_process_logging.h"
// Sets the breakpad experiment chunks for crash reporting. |chunks| is an
// array of C strings of size |chunk_size| containing the values to set, where
// each entry may contain multiple experiment tuples, with the total number of
// experiments indicated by |experiments_chunks|.
// Note that this is suffixed with "3" due to parameter changes that were made
// to the predecessor functions. If the signature changes again, use a new name.
extern "C" void __declspec(dllexport) __cdecl SetExperimentList3(
const wchar_t** chunks,
size_t chunks_size,
size_t experiments_count) {
// Make sure the offset was initialized before storing the data.
if (breakpad_win::g_experiment_chunks_offset == 0)
return;
// Store up to |kMaxReportedVariationChunks| chunks.
const size_t number_of_chunks_to_report =
std::min(chunks_size, kMaxReportedVariationChunks);
for (size_t i = 0; i < number_of_chunks_to_report; ++i) {
const size_t entry_index = breakpad_win::g_experiment_chunks_offset + i;
(*breakpad_win::g_custom_entries)[entry_index].set_value(chunks[i]);
}
// Make note of the total number of experiments, which may be greater than
// what was able to fit in |kMaxReportedVariationChunks|. This is useful when
// correlating stability with the number of experiments running
// simultaneously.
base::wcslcpy(
(*breakpad_win::g_custom_entries)[
breakpad_win::g_num_of_experiments_offset].value,
base::StringPrintf(
L"%d", static_cast<int>(experiments_count)).c_str(),
google_breakpad::CustomInfoEntry::kValueMaxLength);
}
namespace testing {
void SetExperimentChunks(const std::vector<string16>& chunks,
size_t experiments_count) {
std::vector<const wchar_t*> cstrings;
StringVectorToCStringVector(chunks, &cstrings);
::SetExperimentList3(&cstrings[0], cstrings.size(), experiments_count);
}
} // namespace testing
| 41.20339 | 80 | 0.744961 | jxjnjjn |
c46bb90f4171afb1b290cd9bcaf163f5c6ba264e | 6,586 | cpp | C++ | src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/retail/native/fabrichost/FabricActivatorService.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace ServiceModel;
using namespace Common;
using namespace Transport;
using namespace Hosting2;
using namespace FabricHost;
RealConsole console;
const StringLiteral TraceType("FabricHost");
FabricActivatorService::FabricActivatorService(
bool runAsService,
bool activateHidden,
bool skipFabricSetup)
: ServiceBase(FabricHost::Constants::ServiceName),
runAsService_(runAsService),
activateHidden_(activateHidden),
skipFabricSetup_(skipFabricSetup),
stopping_(false),
activationManager_()
{
}
void FabricActivatorService::OnStart(Common::StringCollection const &)
{
Trace.WriteInfo(TraceType, "FabricActivatorService starting ...");
if (runAsService_)
{
ServiceModeStartWait();
}
else
{
ConsoleModeStartWait();
}
}
#if !defined(PLATFORM_UNIX)
void FabricActivatorService::OnPreshutdown()
{
Trace.WriteInfo(TraceType, "Received Preshutdown notification, stopping ...");
if (Hosting2::FabricHostConfig::GetConfig().EnableRestartManagement && runAsService_)
{
SetServiceState(SERVICE_STOP_PENDING, 4, 30000);
Threadpool::Post([this]()
{
this->DisableNode();
});
}
else
{
OnStop(false);
}
}
#endif
void FabricActivatorService::OnStop(bool shutdown)
{
Trace.WriteInfo(TraceType, "service stopping (shutdown = {0}) ...", shutdown);
if(stopping_)
{
Trace.WriteInfo(TraceType, "service is already in stopping process");
return;
}
stopping_ = true;
if (runAsService_)
{
ServiceModeStopWait();
}
else
{
ConsoleModeStopWait();
}
}
void FabricActivatorService::OnPause()
{
Assert::CodingError("{0} does not support pause", FabricHost::Constants::ServiceName);
}
void FabricActivatorService::OnContinue()
{
Assert::CodingError("{0} does not support continue", FabricHost::Constants::ServiceName);
}
void FabricActivatorService::ServiceModeStartWait()
{
StartActivationManager();
}
void FabricActivatorService::ConsoleModeStartWait()
{
StartActivationManager();
}
void FabricActivatorService::ServiceModeStopWait()
{
StopActivationManager();
}
void FabricActivatorService::ConsoleModeStopWait()
{
console.WriteLine(StringResource::Get(IDS_FABRICHOST_CLOSING));
StopActivationManager();
console.WriteLine(StringResource::Get(IDS_FABRICHOST_CLOSED));
}
void FabricActivatorService::OnOpenComplete(AsyncOperationSPtr operation)
{
ErrorCode error = activationManager_->EndOpen(operation);
Trace.WriteTrace(error.ToLogLevel(),
TraceType,
"FabricActivatorManager open returned {0}",
error);
if(!error.IsSuccess())
{
::ExitProcess(1);
}
}
void FabricActivatorService::CreateAndOpen(AutoResetEvent & openEvent)
{
activationManager_ = make_shared<FabricActivationManager>(activateHidden_, skipFabricSetup_);
activationManager_->BeginOpen(Hosting2::FabricHostConfig::GetConfig().StartTimeout,
[&openEvent, this] (AsyncOperationSPtr const& operation)
{
this->OnOpenComplete(operation);
openEvent.Set();
},
activationManager_->CreateAsyncOperationRoot()
);
}
void FabricActivatorService::StartActivationManager()
{
AutoResetEvent openEvent;
Threadpool::Post([this, &openEvent]()
{
this->CreateAndOpen(openEvent);
});
openEvent.WaitOne();
}
void FabricActivatorService::OnCloseCompleted(AsyncOperationSPtr operation)
{
ErrorCode error = activationManager_->EndClose(operation);
Trace.WriteTrace(
error.ToLogLevel(),
TraceType,
"FabricActivatorManager close returned {0}",
error);
}
void FabricActivatorService::Close(AutoResetEvent & closeEvent)
{
Trace.WriteInfo(
TraceType,
"FabricActivatorService close with timeout {0} ",
Hosting2::FabricHostConfig::GetConfig().StopTimeout);
activationManager_->BeginClose(Hosting2::FabricHostConfig::GetConfig().StopTimeout,
[&closeEvent, this](AsyncOperationSPtr operation)
{
this->OnCloseCompleted(operation);
closeEvent.Set();
},
activationManager_->CreateAsyncOperationRoot());
}
void FabricActivatorService::StopActivationManager()
{
Trace.WriteInfo(
TraceType,
"FabricActivatorService StopActivationManager called {0}",
Hosting2::FabricHostConfig::GetConfig().StopTimeout);
AutoResetEvent closeEvent;
Threadpool::Post([this, &closeEvent]()
{
this->Close(closeEvent);
});
closeEvent.WaitOne();
}
#if !defined(PLATFORM_UNIX)
void FabricActivatorService::DisableNode()
{
AutoResetEvent disableEvent;
int checkpoint = 5;
SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000);
Trace.WriteInfo(
TraceType,
"FabricActivatorService DisableNode called with timeout {0}",
FabricHost::Constants::NodeDisableWaitTimeInMinutes);
Threadpool::Post([this, &disableEvent]()
{
auto asyncPtr = activationManager_->FabricRestartManagerObj->BeginNodeDisable(
TimeSpan::FromMinutes(FabricHost::Constants::NodeDisableWaitTimeInMinutes),
[&disableEvent, this](AsyncOperationSPtr operation)
{
this->activationManager_->FabricRestartManagerObj->EndNodeDisable(operation);
disableEvent.Set();
},
activationManager_->CreateAsyncOperationRoot());
if (asyncPtr->CompletedSynchronously)
{
this->activationManager_->FabricRestartManagerObj->EndNodeDisable(asyncPtr);
disableEvent.Set();
}
});
SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000);
while (!disableEvent.WaitOne(TimeSpan::FromSeconds(15)))
{
Trace.WriteInfo(TraceType, "FabricActivatorService DisableNode, Still Waiting {0}", checkpoint);
SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000);
}
Trace.WriteInfo(TraceType, "Node disabled:{0}", checkpoint);
SetServiceState(SERVICE_STOP_PENDING, checkpoint++, 30000);
OnStop(false);
Trace.WriteInfo(TraceType, "Stopping service...");
SetServiceState(SERVICE_STOPPED, checkpoint++);
}
#endif
| 27.90678 | 104 | 0.684482 | AnthonyM |
c46ce61033da4da5bcced60f1ac8e2280f66df5b | 355 | hpp | C++ | ddbtoaster/experiments/src/tpch/query12.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 38 | 2017-09-29T08:12:31.000Z | 2022-03-31T03:56:20.000Z | ddbtoaster/experiments/src/tpch/query12.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 33 | 2018-04-05T02:42:39.000Z | 2022-02-18T02:13:57.000Z | ddbtoaster/experiments/src/tpch/query12.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 17 | 2017-09-29T08:16:00.000Z | 2022-02-18T04:22:29.000Z | #define USE_TPCH_ORDERS
#define USE_TPCH_LINEITEM
#ifdef BATCH_MODE
#include "codegen_batch/Tpch12VCpp.hpp"
#else
#include "codegen/Tpch12VCpp.hpp"
#endif
namespace dbtoaster
{
class data_t;
void print_result(data_t& data)
{
std::cout << "HIGH_LINE_COUNT: " << data.get_HIGH_LINE_COUNT().count() << std::endl;
}
}
| 16.904762 | 96 | 0.676056 | szarnyasg |
c47023396d2b11a6e4bc5eec694d80d879aca542 | 631 | cpp | C++ | samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | samples/hello_ar_c/app/src/main/gef_abertay/maths/vector2.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | #include <maths/vector2.h>
#include <math.h>
namespace gef
{
const Vector2 Vector2::kZero(0.0f, 0.0f);
const Vector2 Vector2::kOne(1.0f, 1.0f);
void Vector2::Normalise()
{
float length = Length();
x /= length;
y /= length;
}
float Vector2::LengthSqr() const
{
return (x*x + y*y);
}
float Vector2::Length() const
{
return sqrtf(x*x + y*y);
}
Vector2 Vector2::Rotate(float angle)
{
Vector2 result;
result.x = x*cosf(angle) - y*sinf(angle);
result.y = x*sinf(angle) + y*cosf(angle);
return result;
}
float Vector2::DotProduct(const Vector2& _vec) const
{
return x*_vec.x + y*_vec.y;
}
} | 14.674419 | 53 | 0.630745 | JD1305 |
c4704897edbdc6505338ba35d372c032016f8987 | 3,329 | cc | C++ | src/geometry/test/test_Mesh1D.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/geometry/test/test_Mesh1D.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/geometry/test/test_Mesh1D.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*----------------------------------//
/*!
* \file test_Mesh1D.cc
* \author Jeremy Roberts
* \date Apr 1, 2012
* \brief Test of Mesh1D class.
* \note Copyright (C) 2012 Jeremy Roberts.
*/
//---------------------------------------------------------------------------//
// LIST OF TEST FUNCTIONS
#define TEST_LIST \
FUNC(test_Mesh1D) \
FUNC(test_Mesh1D_serialize)
// Detran headers
#include "TestDriver.hh"
#include "Mesh1D.hh"
// System headers
#include <fstream>
// Setup
#include "mesh_fixture.hh"
using namespace detran_geometry;
using namespace detran_utilities;
using namespace detran_test;
using namespace std;
int main(int argc, char *argv[])
{
RUN(argc, argv);
}
//----------------------------------------------//
// TEST DEFINITIONS
//----------------------------------------------//
int test_Mesh1D(int argc, char *argv[])
{
// Get the mesh
SP_mesh mesh = mesh_1d_fixture();
// Mesh properties:
// cm = [ 0.0 5.0 10.0]
// fm = [ 5 5 ]
// mt = [ 0 1 ]
// Basic mesh things.
TEST(mesh->number_cells() == 10);
TEST(mesh->number_cells_x() == 10);
TEST(mesh->number_cells_y() == 1);
TEST(mesh->number_cells_z() == 1);
TEST(mesh->dx(0) == 1.0);
TEST(mesh->dy(0) == 1.0);
TEST(mesh->dz(0) == 1.0);
TEST(mesh->dimension() == 1);
int cell = 5;
TEST(mesh->index(5) == cell);
TEST(mesh->cell_to_i(cell) == 5);
TEST(mesh->cell_to_j(cell) == 0);
TEST(mesh->cell_to_k(cell) == 0);
TEST(mesh->volume(cell) == 1.0);
vec_int mat_map = mesh->mesh_map("MATERIAL");
TEST(mat_map[0] == 0);
TEST(mat_map[5] == 1);
TESTFALSE(mesh->mesh_map_exists("SHOULDNOTEXIST"));
return 0;
}
int test_Mesh1D_serialize(int argc, char *argv[])
{
#ifdef DETRAN_ENABLE_BOOST
{
// Get the mesh and pack it
SP_mesh mesh = mesh_1d_fixture();
mesh->display();
std::ofstream ofs("mesh1d.archive");
boost::archive::binary_oarchive oa(ofs);
oa << mesh;
ofs.close();
}
{
// Unpack
SP_mesh mesh;
std::ifstream ifs("mesh1d.archive");
boost::archive::binary_iarchive ia(ifs);
ia >> mesh;
ifs.close();
mesh->display();
// Test
TEST(mesh->number_cells() == 10);
TEST(mesh->number_cells_x() == 10);
TEST(mesh->number_cells_y() == 1);
TEST(mesh->number_cells_z() == 1);
TEST(mesh->dx(0) == 1.0);
TEST(mesh->dy(0) == 1.0);
TEST(mesh->dz(0) == 1.0);
TEST(mesh->dimension() == 1);
int cell = 5;
TEST(mesh->index(5) == cell);
TEST(mesh->cell_to_i(cell) == 5);
TEST(mesh->cell_to_j(cell) == 0);
TEST(mesh->cell_to_k(cell) == 0);
TEST(mesh->volume(cell) == 1.0);
vec_int mat_map = mesh->mesh_map("MATERIAL");
TEST(mat_map[0] == 0);
TEST(mat_map[5] == 1);
TESTFALSE(mesh->mesh_map_exists("SHOULDNOTEXIST"));
}
#endif
return 0;
}
//---------------------------------------------------------------------------//
// end of test_Mesh3D.cc
//---------------------------------------------------------------------------//
| 26.420635 | 79 | 0.479423 | RLReed |
c4709fa177c376c60cb488f07a8d73a95f86c4d4 | 6,522 | cpp | C++ | source/core/fluid-solver.cpp | linusmossberg/fluid-simulator | 629301987fff9e82cf1f1cc99b010b5f8619136b | [
"MIT"
] | 24 | 2021-03-16T13:22:08.000Z | 2022-02-20T12:43:35.000Z | source/core/fluid-solver.cpp | linusmossberg/fluid-simulator | 629301987fff9e82cf1f1cc99b010b5f8619136b | [
"MIT"
] | null | null | null | source/core/fluid-solver.cpp | linusmossberg/fluid-simulator | 629301987fff9e82cf1f1cc99b010b5f8619136b | [
"MIT"
] | 4 | 2021-03-16T16:38:54.000Z | 2022-01-17T17:31:55.000Z | #include "fluid-solver.hpp"
#include <iostream>
#include "util.hpp"
#include "../gl-util/fbo.hpp"
#include "../gl-util/shader.hpp"
#include "../gl-util/quad.hpp"
#include "../shaders/screen.vert"
#include "../shaders/stencil.vert"
#include "../shaders/fluid-solver/advect.frag"
#include "../shaders/fluid-solver/force.frag"
#include "../shaders/fluid-solver/jacobi-diffusion.frag"
#include "../shaders/fluid-solver/jacobi-pressure.frag"
#include "../shaders/fluid-solver/divergence.frag"
#include "../shaders/fluid-solver/curl.frag"
#include "../shaders/fluid-solver/vorticity.frag"
#include "../shaders/fluid-solver/gradient-subtract.frag"
#include "../shaders/fluid-solver/speed.frag"
FluidSolver::FluidSolver(const std::shared_ptr<Config>& cfg) : cfg(cfg)
{
setSize(glm::ivec2(128));
}
void FluidSolver::step()
{
glViewport(0, 0, grid_cells.x, grid_cells.y);
glScissor(0, 0, grid_cells.x, grid_cells.y);
dx = cfg->sim_width / grid_cells.x;
if (clear_velocity)
{
velocity->clear(glm::vec4(0.0f));
pressure->clear(glm::vec4(0.0f));
clear_velocity = false;
}
Quad::bind();
applyForce();
applyVorticityConfinement();
advect(velocity, temp_fbo);
diffuseVelocity();
subtractPressureGradient();
computeSpeed();
}
void FluidSolver::advect(std::unique_ptr<FBO>& quantity, std::unique_ptr<FBO>& temp_quantity)
{
static const Shader advect_shader(screen_vert, advect_frag, "advect");
temp_quantity->bind();
advect_shader.use();
glUniform1f(advect_shader.getLocation("dt"), cfg->dt);
glm::vec2 world2tx = 1.0f / ((float)cfg->sim_width * glm::vec2(1.0f, y_aspect));
glUniform2fv(advect_shader.getLocation("world2tx"), 1, &world2tx[0]);
velocity->bindTexture(0, GL_LINEAR);
quantity->bindTexture(1, GL_LINEAR);
Quad::draw();
std::swap(quantity, temp_quantity);
}
void FluidSolver::diffuseVelocity()
{
static const Shader jacobi_diffusion_shader(stencil_vert, jacobi_diffusion_frag, "jacobi-diffusion");
float nu = cfg->mu / cfg->rho;
// Solver approaches unchanged velocity when dx2_nudt
// approaches infinity, so this should be correct.
if (nu <= 0.0f) return;
jacobi_diffusion_shader.use();
float dx2_nudt = std::pow(dx, 2) / (nu * cfg->dt);
glUniform2fv(jacobi_diffusion_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(jacobi_diffusion_shader.getLocation("dx2_nudt"), dx2_nudt);
temp_fbo2->bind();
velocity->bindTexture(0);
velocity->bindTexture(1);
Quad::draw();
for (int i = 0; i < cfg->viscosity_iterations - 1.0f; i++)
{
temp_fbo->bind();
temp_fbo2->bindTexture(0);
Quad::draw();
std::swap(temp_fbo2, temp_fbo);
}
std::swap(velocity, temp_fbo2);
}
void FluidSolver::applyForce()
{
static const Shader force_shader(screen_vert, force_frag, "force");
temp_fbo->bind();
force_shader.use();
velocity->bindTexture(0);
glm::vec2 force = (float)cfg->F * glm::vec2(std::cos(cfg->F_angle), std::sin(cfg->F_angle));
glUniform2fv(force_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform2fv(force_shader.getLocation("pos"), 1, &force_pos[0]);
glUniform2fv(force_shader.getLocation("force"), 1, &force[0]);
glUniform1f(force_shader.getLocation("dt"), cfg->dt);
Quad::draw();
std::swap(velocity, temp_fbo);
}
void FluidSolver::computeCurl()
{
static const Shader curl_shader(stencil_vert, curl_frag, "curl");
curl->bind();
curl_shader.use();
velocity->bindTexture(0);
glUniform2fv(curl_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(curl_shader.getLocation("half_inv_dx"), 0.5f / dx);
Quad::draw();
}
void FluidSolver::applyVorticityConfinement()
{
static const Shader vorticity_shader(stencil_vert, vorticity_frag, "vorticity");
computeCurl();
if (cfg->vorticity < 1e-6f) return;
temp_fbo->bind();
vorticity_shader.use();
velocity->bindTexture(0);
curl->bindTexture(1);
glUniform2fv(vorticity_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(vorticity_shader.getLocation("half_inv_dx"), 0.5f / dx);
glUniform1f(vorticity_shader.getLocation("dt"), cfg->dt);
glUniform1f(vorticity_shader.getLocation("vorticity_scale"), cfg->vorticity);
Quad::draw();
std::swap(temp_fbo, velocity);
}
void FluidSolver::computeDivergence()
{
static const Shader divergence_shader(stencil_vert, divergence_frag, "divergence");
divergence->bind();
divergence_shader.use();
velocity->bindTexture(0);
glUniform2fv(divergence_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(divergence_shader.getLocation("half_inv_dx"), 0.5f / dx);
Quad::draw();
}
void FluidSolver::computePressure()
{
static const Shader jacobi_pressure_shader(stencil_vert, jacobi_pressure_frag, "jacobi-pressure");
computeDivergence();
if (clear_pressure) pressure->clear(glm::vec4(0.0f));
jacobi_pressure_shader.use();
glUniform2fv(jacobi_pressure_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(jacobi_pressure_shader.getLocation("dx2"), std::pow(dx, 2));
divergence->bindTexture(1);
for (int i = 0; i < cfg->pressure_iterations; i++)
{
temp_fbo->bind();
pressure->bindTexture(0);
Quad::draw();
std::swap(temp_fbo, pressure);
}
}
void FluidSolver::subtractPressureGradient()
{
static const Shader gradient_subtract_shader(stencil_vert, gradient_subtract_frag, "gradient");
computePressure();
temp_fbo->bind();
gradient_subtract_shader.use();
pressure->bindTexture(0);
velocity->bindTexture(1);
glUniform2fv(gradient_subtract_shader.getLocation("tx_size"), 1, &cell_size[0]);
glUniform1f(gradient_subtract_shader.getLocation("half_inv_dx"), 0.5f / dx);
Quad::draw();
std::swap(temp_fbo, velocity);
}
void FluidSolver::computeSpeed()
{
static const Shader speed_shader(screen_vert, speed_frag, "speed");
speed->bind();
speed_shader.use();
velocity->bindTexture(0);
Quad::draw();
}
void FluidSolver::setSize(const glm::ivec2& grid_cells_)
{
grid_cells = grid_cells_;
cell_size = 1.0f / glm::vec2(grid_cells);
y_aspect = grid_cells.y / (float)grid_cells.x;
for (auto& fbo : { &temp_fbo, &temp_fbo2, &velocity, &pressure, &divergence, &curl, &speed })
{
*fbo = std::make_unique<FBO>(grid_cells);
}
}
| 25.778656 | 105 | 0.679853 | linusmossberg |
c470ab62adc02621ce365f085edd2d3ecd22735e | 170 | cpp | C++ | solutions/beecrowd/1959/1959.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1959/1959.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1959/1959.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | #include <cstdint>
#include <iostream>
int main() {
uint32_t n, l;
while (std::cin >> n >> l) {
std::cout << n * l << std::endl;
}
return 0;
}
| 13.076923 | 40 | 0.482353 | deniscostadsc |
c4746985d107bc2f5bbec86fa80042245f0952ec | 5,554 | cpp | C++ | tests/test-hdr/set/hdr_splitlist_set_dhp.cpp | simple555a/libcds | d05a0909402369d4a79eb82aed1742a7b227548b | [
"BSD-2-Clause"
] | 2 | 2016-12-03T22:09:50.000Z | 2021-08-31T12:44:24.000Z | tests/test-hdr/set/hdr_splitlist_set_dhp.cpp | TatyanaBerlenko/libcds | 3f4dfab2aea72d70ce44e7fbc02da9a6908f0781 | [
"BSD-2-Clause"
] | null | null | null | tests/test-hdr/set/hdr_splitlist_set_dhp.cpp | TatyanaBerlenko/libcds | 3f4dfab2aea72d70ce44e7fbc02da9a6908f0781 | [
"BSD-2-Clause"
] | 2 | 2018-05-26T19:27:12.000Z | 2021-08-31T12:44:28.000Z | //$$CDS-header$$
#include "set/hdr_set.h"
#include <cds/container/michael_list_dhp.h>
#include <cds/container/split_list_set.h>
namespace set {
namespace {
struct DHP_cmp_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef HashSetHdrTest::hash_int hash;
typedef HashSetHdrTest::simple_item_counter item_counter;
typedef cc::opt::v::relaxed_ordering memory_model;
enum { dynamic_bucket_table = false };
struct ordered_list_traits: public cc::michael_list::traits
{
typedef HashSetHdrTest::cmp<HashSetHdrTest::item> compare;
};
};
struct DHP_less_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef HashSetHdrTest::hash_int hash;
typedef HashSetHdrTest::simple_item_counter item_counter;
typedef cc::opt::v::sequential_consistent memory_model;
enum { dynamic_bucket_table = false };
struct ordered_list_traits: public cc::michael_list::traits
{
typedef HashSetHdrTest::less<HashSetHdrTest::item> less;
};
};
struct DHP_cmpmix_traits: public cc::split_list::traits
{
typedef cc::michael_list_tag ordered_list;
typedef HashSetHdrTest::hash_int hash;
typedef HashSetHdrTest::simple_item_counter item_counter;
struct ordered_list_traits: public cc::michael_list::traits
{
typedef HashSetHdrTest::cmp<HashSetHdrTest::item> compare;
typedef HashSetHdrTest::less<HashSetHdrTest::item> less;
};
};
struct DHP_cmpmix_stat_traits : public DHP_cmpmix_traits
{
typedef cc::split_list::stat<> stat;
};
}
void HashSetHdrTest::Split_DHP_cmp()
{
// traits-based version
typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmp_traits > set;
test_int< set >();
// option-based version
typedef cc::SplitListSet< cds::gc::DHP, item,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::michael_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::opt::memory_model< cc::opt::v::relaxed_ordering >
,cc::split_list::dynamic_bucket_table< true >
,cc::split_list::ordered_list_traits<
cc::michael_list::make_traits<
cc::opt::compare< cmp<item> >
>::type
>
>::type
> opt_set;
test_int< opt_set >();
}
void HashSetHdrTest::Split_DHP_less()
{
// traits-based version
typedef cc::SplitListSet< cds::gc::DHP, item, DHP_less_traits > set;
test_int< set >();
// option-based version
typedef cc::SplitListSet< cds::gc::DHP, item,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::michael_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::opt::memory_model< cc::opt::v::sequential_consistent >
,cc::split_list::dynamic_bucket_table< false >
,cc::split_list::ordered_list_traits<
cc::michael_list::make_traits<
cc::opt::less< less<item> >
>::type
>
>::type
> opt_set;
test_int< opt_set >();
}
void HashSetHdrTest::Split_DHP_cmpmix()
{
// traits-based version
typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmpmix_traits > set;
test_int< set >();
// option-based version
typedef cc::SplitListSet< cds::gc::DHP, item,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::michael_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::split_list::ordered_list_traits<
cc::michael_list::make_traits<
cc::opt::less< less<item> >
,cc::opt::compare< cmp<item> >
>::type
>
>::type
> opt_set;
test_int< opt_set >();
}
void HashSetHdrTest::Split_DHP_cmpmix_stat()
{
// traits-based version
typedef cc::SplitListSet< cds::gc::DHP, item, DHP_cmpmix_stat_traits > set;
test_int< set >();
// option-based version
typedef cc::SplitListSet< cds::gc::DHP, item,
cc::split_list::make_traits<
cc::split_list::ordered_list<cc::michael_list_tag>
,cc::opt::hash< hash_int >
,cc::opt::item_counter< simple_item_counter >
,cc::split_list::ordered_list_traits<
cc::michael_list::make_traits<
cc::opt::less< less<item> >
,cc::opt::compare< cmp<item> >
>::type
>
,cds::opt::stat< cc::split_list::stat<> >
>::type
> opt_set;
test_int< opt_set >();
}
} // namespace set
| 35.151899 | 83 | 0.53547 | simple555a |
c47970c86327841ab6ac5370fb8a4c301bc6a496 | 22,935 | cpp | C++ | src/CrossValidation.cpp | wfondrie/percolator | bd29e37399f2ed58385287a97b555bb06642ff18 | [
"Apache-2.0"
] | null | null | null | src/CrossValidation.cpp | wfondrie/percolator | bd29e37399f2ed58385287a97b555bb06642ff18 | [
"Apache-2.0"
] | null | null | null | src/CrossValidation.cpp | wfondrie/percolator | bd29e37399f2ed58385287a97b555bb06642ff18 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se>
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 "CrossValidation.h"
// number of folds for cross validation
const unsigned int CrossValidation::numFolds_ = 3u;
#ifdef _OPENMP
#include <algorithm>
#include <omp.h>
const unsigned int CrossValidation::numAlgInObjects_ = CrossValidation::numFolds_;
#else
const unsigned int CrossValidation::numAlgInObjects_ = 1u;
#endif
// checks cross validation convergence in case of quickValidation_
const double CrossValidation::requiredIncreaseOver2Iterations_ = 0.01;
CrossValidation::CrossValidation(bool quickValidation,
bool reportPerformanceEachIteration, double testFdr, double selectionFdr,
double initialSelectionFdr, double selectedCpos, double selectedCneg, unsigned int niter, bool usePi0,
unsigned int nestedXvalBins, bool trainBestPositive, unsigned int numThreads, bool skipNormalizeScores) :
quickValidation_(quickValidation), usePi0_(usePi0),
reportPerformanceEachIteration_(reportPerformanceEachIteration),
testFdr_(testFdr), selectionFdr_(selectionFdr), initialSelectionFdr_(initialSelectionFdr),
selectedCpos_(selectedCpos), selectedCneg_(selectedCneg), niter_(niter),
nestedXvalBins_(nestedXvalBins), trainBestPositive_(trainBestPositive),
numThreads_(numThreads), skipNormalizeScores_(skipNormalizeScores) {}
CrossValidation::~CrossValidation() {
for (unsigned int set = 0; set < numFolds_ * nestedXvalBins_; ++set) {
if (svmInputs_[set]) {
delete svmInputs_[set];
}
svmInputs_[set] = NULL;
}
}
/**
* Sets up the SVM classifier:
* - divide dataset into training and test sets for each fold
* - set parameters (fdr, soft margin)
* @param w_ vector of SVM weights
* @return number of positives for initial setup
*/
int CrossValidation::preIterationSetup(Scores& fullset, SanityCheck* pCheck,
Normalizer* pNorm, FeatureMemoryPool& featurePool) {
assert(nestedXvalBins_ >= 1u);
// initialize weights vector for all folds
w_ = vector<vector<double> >(numFolds_,
vector<double> (FeatureNames::getNumFeatures() + 1));
// One input set, to be reused multiple times
for (unsigned int set = 0; set < numFolds_ * nestedXvalBins_; ++set) {
svmInputs_.push_back(new AlgIn(fullset.size(), static_cast<int>(FeatureNames::getNumFeatures()) + 1));
assert( svmInputs_.back() );
}
trainScores_.resize(numFolds_, Scores(usePi0_));
testScores_.resize(numFolds_, Scores(usePi0_));
fullset.createXvalSetsBySpectrum(trainScores_, testScores_, numFolds_, featurePool);
if (selectionFdr_ <= 0.0) {
selectionFdr_ = testFdr_;
}
if (selectedCpos_ > 0) {
candidatesCpos_.push_back(selectedCpos_);
} else {
candidatesCpos_.push_back(10);
candidatesCpos_.push_back(1);
candidatesCpos_.push_back(0.1);
if (VERB > 0) {
cerr << "Selecting Cpos by cross-validation." << endl;
}
}
if (selectedCpos_ > 0 && selectedCneg_ > 0) {
candidatesCfrac_.push_back(selectedCneg_ / selectedCpos_);
} else {
candidatesCfrac_.push_back(1.0 * fullset.getTargetDecoySizeRatio());
candidatesCfrac_.push_back(3.0 * fullset.getTargetDecoySizeRatio());
candidatesCfrac_.push_back(10.0 * fullset.getTargetDecoySizeRatio());
if (VERB > 0) {
cerr << "Selecting Cneg by cross-validation." << endl;
}
}
int numPositive = pCheck->getInitDirection(testScores_, trainScores_, pNorm, w_,
testFdr_, initialSelectionFdr_);
// Form cpos, cneg pairs per nested CV fold
candidateCposCfrac cpCnFold;
for (unsigned int set = 0; set < numFolds_; ++set) {
for (int nestedSet = 0; nestedSet < nestedXvalBins_; nestedSet++) {
if(!quickValidation_) {
std::vector<double>::const_iterator itCpos = candidatesCpos_.begin();
for ( ; itCpos != candidatesCpos_.end(); ++itCpos) {
double cpos = *itCpos;
std::vector<double>::const_iterator itCfrac = candidatesCfrac_.begin();
for ( ; itCfrac != candidatesCfrac_.end(); ++itCfrac) {
double cfrac = *itCfrac;
cpCnFold.cpos = cpos;
cpCnFold.cfrac = cfrac;
cpCnFold.set = set;
cpCnFold.nestedSet = nestedSet;
cpCnFold.tp = 0;
for (int i = static_cast<int>(FeatureNames::getNumFeatures()) + 1; i--;) {
cpCnFold.ww.push_back(0);
}
classWeightsPerFold_.push_back(cpCnFold);
}
}
} else {
cpCnFold.cpos = 1;
cpCnFold.cfrac = 1;
cpCnFold.set = set;
cpCnFold.nestedSet = nestedSet;
cpCnFold.tp = 0;
for (int i = static_cast<int>(FeatureNames::getNumFeatures()) + 1; i--;) {
cpCnFold.ww.push_back(0);
}
classWeightsPerFold_.push_back(cpCnFold);
}
}
}
if (DataSet::getCalcDoc()) {
for (std::size_t set = 0; set < numFolds_; ++set) {
trainScores_[set].calcScores(w_[set], selectionFdr_);
}
#pragma omp parallel for schedule(dynamic, 1)
for (int set = 0; set < numFolds_; ++set) {
trainScores_[set].recalculateDescriptionOfCorrect(selectionFdr_);
testScores_[set].getDOC().copyDOCparameters(trainScores_[set].getDOC());
testScores_[set].setDOCFeatures(pNorm);
}
}
return numPositive;
}
/**
* Train the SVM using several cross validation iterations
* @param pNorm Normalization object
*/
void CrossValidation::train(Normalizer* pNorm) {
if (VERB > 0) {
cerr << "---Training with Cpos";
if (selectedCpos_ > 0) {
cerr << "=" << selectedCpos_;
} else {
cerr << " selected by cross validation";
}
cerr << ", Cneg";
if (selectedCneg_ > 0) {
cerr << "=" << selectedCneg_;
} else {
cerr << " selected by cross validation";
}
cerr << ", initial_fdr=" << initialSelectionFdr_;
cerr << ", fdr=" << selectionFdr_ << endl;
}
// iterate
int foundPositivesOldOld = 0, foundPositivesOld = 0, foundPositives = 0;
for (unsigned int i = 0; i < niter_; i++) {
if (VERB > 1) {
cerr << "Iteration " << i + 1 << ":\t";
}
bool updateDOC = true;
double selectionFdr = selectionFdr_;
if (i == 0u) {
selectionFdr = initialSelectionFdr_;
}
foundPositives = doStep(updateDOC, pNorm, selectionFdr);
if (reportPerformanceEachIteration_) {
int foundTestPositives = 0;
for (size_t set = 0; set < numFolds_; ++set) {
foundTestPositives += testScores_[set].calcScores(w_[set], testFdr_);
}
if (VERB > 1) {
std::cerr << "Found " << foundTestPositives << " test set PSMs with q<"
<< testFdr_ << endl;
}
} else if (VERB > 1) {
cerr << "Estimated " << foundPositives << " PSMs with q<" << testFdr_ << endl;
}
if (VERB > 2) {
printAllWeightsColumns(cerr);
}
if (VERB > 3) {
printAllRawWeightsColumns(cerr, pNorm);
}
if (foundPositives > 0 && foundPositivesOldOld > 0 && quickValidation_ &&
(static_cast<double>(foundPositives - foundPositivesOldOld) <=
foundPositivesOldOld * requiredIncreaseOver2Iterations_)) {
if (VERB > 0) {
std::cerr << "Performance increase over the last two iterations " <<
"indicate that the algorithm has converged\n" <<
"(" << foundPositives << " vs " << foundPositivesOldOld << ")" <<
std::endl;
}
break;
}
foundPositivesOldOld = foundPositivesOld;
foundPositivesOld = foundPositives;
}
if (VERB == 2) {
printAllWeightsColumns(cerr);
}
if (VERB == 3) {
printAllRawWeightsColumns(cerr, pNorm);
}
foundPositives = 0;
for (size_t set = 0; set < numFolds_; ++set) {
foundPositives += testScores_[set].calcScores(w_[set], testFdr_);
}
if (VERB > 0) {
std::cerr << "Found " << foundPositives <<
" test set PSMs with q<" << testFdr_ << "." << std::endl;
}
}
/**
* Executes a cross validation step
* @param w_ list of the bins' normal vectors (in linear algebra sense) of the
* hyperplane from SVM
* @param updateDOC boolean deciding to recalculate retention features
* @see DescriptionOfCorrect
* @return Estimation of number of true positives
*/
int CrossValidation::doStep(bool updateDOC, Normalizer* pNorm, double selectionFdr) {
// Setup
options pOptions;
pOptions.lambda = 1.0;
pOptions.lambda_u = 1.0;
pOptions.epsilon = EPSILON;
pOptions.cgitermax = CGITERMAX;
pOptions.mfnitermax = MFNITERMAX;
int estTruePos = 0;
// for determining an appropriate positive training set, the decoys+1 in the
// FDR estimates is too restrictive for small datasets
bool skipDecoysPlusOne = true;
for (std::size_t set = 0; set < numFolds_; ++set) {
trainScores_[set].calcScores(w_[set], selectionFdr, skipDecoysPlusOne);
}
if (DataSet::getCalcDoc() && updateDOC) {
#pragma omp parallel for schedule(dynamic, 1)
for (int set = 0; set < numFolds_; ++set) {
trainScores_[set].recalculateDescriptionOfCorrect(selectionFdr);
testScores_[set].getDOC().copyDOCparameters(trainScores_[set].getDOC());
testScores_[set].setDOCFeatures(pNorm);
}
}
// Below implements the series of speedups detailed in the following:
// ////////////////////////////////
// Speeding Up Percolator
// John T. Halloran, Hantian Zhang, Kaan Kara, Cédric Renggli, Matthew The, Ce Zhang, David M. Rocke, Lukas Käll, and William Stafford Noble
// Journal of Proteome Research 2019 18 (9), 3353-3359
// ////////////////////////////////
// Note that the implementation further improves on the speedups in the paper by:
// -implementing a single threadpool using OMP for SVM training per each cpos,cneg pair per nested CV fold
// -has a much smaller memory footprint by fixing memory leaks in L2_SVM_MFN and more efficient validation of the learned SVM parameters
// ////
// Create SVM input data for parallelization
std::vector<AlgIn*> svmInputsVec;
std::vector< std::vector< Scores > > nestedTestScoresVec;
for (std::size_t set = 0; set < numFolds_; ++set) {
std::vector<Scores> nestedTrainScores(nestedXvalBins_, usePi0_), nestedTestScores(nestedXvalBins_, usePi0_);
if (nestedXvalBins_ > 1) {
FeatureMemoryPool featurePool;
trainScores_[set].createXvalSetsBySpectrum(nestedTrainScores, nestedTestScores, nestedXvalBins_, featurePool);
} else {
// sub-optimal cross validation
nestedTrainScores[0] = trainScores_[set];
nestedTestScores[0] = trainScores_[set];
}
nestedTestScoresVec.push_back(nestedTestScores);
// Set SVM input data for L2-SVM-MFN
for (std::size_t nestedFold = 0; nestedFold < nestedXvalBins_; ++nestedFold)
{
AlgIn* svmInput = svmInputs_[set * nestedXvalBins_ + nestedFold];
if ((VERB > 2) && (nestedFold==0)){
cerr << "Split " << set + 1 << ": Training with "
<< svmInput->positives << " positives and "
<< svmInput->negatives << " negatives" << std::endl;
}
nestedTrainScores[nestedFold].generateNegativeTrainingSet(*svmInput, 1.0);
nestedTrainScores[nestedFold].generatePositiveTrainingSet(*svmInput, selectionFdr, 1.0, trainBestPositive_);
svmInputsVec.push_back(svmInput);
}
}
#pragma omp parallel for schedule(dynamic, 1) ordered
for (int pairIdx = 0; pairIdx < classWeightsPerFold_.size(); pairIdx++){
candidateCposCfrac* cpCnFold = &classWeightsPerFold_[pairIdx];
AlgIn* svmInput = svmInputsVec[cpCnFold->set * nestedXvalBins_ +
static_cast<unsigned int>(cpCnFold->nestedSet)];
trainCpCnPair(*cpCnFold, pOptions,svmInput);
}
estTruePos = mergeCpCnPairs(selectionFdr, pOptions, nestedTestScoresVec, candidatesCpos_,
candidatesCfrac_);
return estTruePos;
}
/**
* Train SVM over a single (cpos, cneg) pair
* @param cpCnFold contains cpos, cneg pair and SVM learned weights
* @param pOptions options for the SVM algorithm
* @param svmInput training data for this particular nested CV fold
*/
void CrossValidation::trainCpCnPair(candidateCposCfrac& cpCnFold,
options& pOptions, AlgIn* svmInput) {
vector_double pWeights;
pWeights.d = static_cast<int>(FeatureNames::getNumFeatures()) + 1;
pWeights.vec = new double[pWeights.d];
double cpos = cpCnFold.cpos;
double cfrac = cpCnFold.cfrac;
// Create storage vector for SVM algorithm
vector_double Outputs;
size_t numInputs = static_cast<std::size_t>(svmInput->positives + svmInput->negatives);
Outputs.vec = new double[numInputs];
Outputs.d = static_cast<int>(numInputs);
if (VERB > 3) cerr << "- cross-validation with Cpos=" << cpos
<< ", Cneg=" << cfrac * cpos << endl;
for (int ix = 0; ix < pWeights.d; ix++) {
pWeights.vec[ix] = 0;
}
for (int ix = 0; ix < Outputs.d; ix++) {
Outputs.vec[ix] = 0;
}
// Call SVM algorithm (see ssl.cpp)
L2_SVM_MFN(*svmInput, pOptions, pWeights, Outputs, cpos, cfrac * cpos);
for (std::size_t i = FeatureNames::getNumFeatures() + 1; i--;) {
cpCnFold.ww[i] = pWeights.vec[i];
}
}
/**
* Validate and merge weights learned per cpos,cneg pairs per nested CV fold per CV fold
* @param pWeights results vector from the SVM algorithm
* @param pOptions options for the SVM algorithm
* @param nestedTestScoresVec 2D vector, test sets per nested CV fold per CV fold
*/
int CrossValidation::mergeCpCnPairs(double selectionFdr,
options& pOptions, vector< vector<Scores> >& nestedTestScoresVec,
const vector<double>& cposCandidates, const vector<double>& cfracCandidates) {
// for determining the number of positives, the decoys+1 in the FDR estimates
// is too restrictive for small datasets
bool skipDecoysPlusOne = true;
vector<int> bestTruePoses(numFolds_, 0);
vector<double> bestCposes(numFolds_, 1);
vector<double> bestCfracs(numFolds_, 1);
int set = 0;
// Validate learned parameters per (cpos,cneg) pair per nested CV fold
// Note: this cannot be done in trainCpCnPair without setting a critical pragma, due to the
// scoring calculation in calcScores.
unsigned int numCpCnPairsPerSet = static_cast<unsigned int>(classWeightsPerFold_.size() / numFolds_);
#pragma omp parallel for schedule(dynamic, 1) ordered
for (set = 0; set < numFolds_; ++set) {
unsigned int a = set * numCpCnPairsPerSet;
unsigned int b = (set+1) * numCpCnPairsPerSet;
int tp = 0;
std::vector<candidateCposCfrac>::iterator itCpCnPair;
std::map<std::pair<double, double>, int> intermediateResults;
for (itCpCnPair = classWeightsPerFold_.begin() + a; itCpCnPair < classWeightsPerFold_.begin() + b; itCpCnPair++) {
tp = nestedTestScoresVec[set][static_cast<std::size_t>(itCpCnPair->nestedSet)].calcScores(itCpCnPair->ww, testFdr_, skipDecoysPlusOne);
intermediateResults[std::make_pair(itCpCnPair->cpos, itCpCnPair->cfrac)] += tp;
itCpCnPair->tp = tp;
if (nestedXvalBins_ <= 1) {
if(tp >= bestTruePoses[set]){
bestTruePoses[set] = tp;
w_[set] = itCpCnPair->ww;
bestCposes[set] = itCpCnPair->cpos;
bestCfracs[set] = itCpCnPair->cfrac;
}
}
}
if (nestedXvalBins_ > 1) { // Check nestedXvalBins, which collapse (accumulate) tp estimated for each CV bin
// Now check which achieved best performance among cpos, cneg pairs
std::vector<double>::const_iterator itCpos = cposCandidates.begin();
for ( ; itCpos != cposCandidates.end(); ++itCpos) {
double cpos = *itCpos;
std::vector<double>::const_iterator itCfrac = cfracCandidates.begin();
for ( ; itCfrac != cfracCandidates.end(); ++itCfrac) {
double cfrac = *itCfrac;
tp = intermediateResults[std::make_pair(cpos, cfrac)];
if(tp >= bestTruePoses[set]){
bestTruePoses[set] = tp;
bestCposes[set] = cpos;
bestCfracs[set] = cfrac;
}
}
}
}
}
if (nestedXvalBins_ > 1) {
#pragma omp parallel for schedule(dynamic, 1) ordered
for (set = 0; set < numFolds_; ++set) {
vector_double pWeights;
pWeights.d = static_cast<int>(FeatureNames::getNumFeatures()) + 1;
pWeights.vec = new double[pWeights.d];
AlgIn* svmInput = svmInputs_[set * nestedXvalBins_];
trainScores_[set].generateNegativeTrainingSet(*svmInput, 1.0);
trainScores_[set].generatePositiveTrainingSet(*svmInput, selectionFdr, 1.0, trainBestPositive_);
// Create storage vector for SVM algorithm
vector_double Outputs;
size_t numInputs = static_cast<std::size_t>(svmInput->positives + svmInput->negatives);
Outputs.vec = new double[numInputs];
Outputs.d = static_cast<int>(numInputs);
for (int ix = 0; ix < pWeights.d; ix++) {
pWeights.vec[ix] = 0;
}
for (int ix = 0; ix < Outputs.d; ix++) {
Outputs.vec[ix] = 0;
}
// Call SVM algorithm (see ssl.cpp)
L2_SVM_MFN(*svmInput, pOptions, pWeights, Outputs, bestCposes[set], bestCposes[set] * bestCfracs[set]);
for (std::size_t i = FeatureNames::getNumFeatures() + 1; i--;) {
w_[set][i] = pWeights.vec[i];
}
}
}
double bestTruePos = 0;
for (set = 0; set < numFolds_; ++set) {
bestTruePos += trainScores_[set].calcScores(w_[set], testFdr_);
}
return static_cast<int>(bestTruePos / (numFolds_ - 1));
}
void CrossValidation::postIterationProcessing(Scores& fullset,
SanityCheck* pCheck) {
if (!pCheck->validateDirection(w_)) {
for (std::size_t set = 0; set < numFolds_; ++set) {
testScores_[set].calcScores(w_[0], selectionFdr_);
}
}
if (DataSet::getCalcDoc()) {
// TODO: take the average instead of the first DOC model?
fullset.getDOC().copyDOCparameters(testScores_[0].getDOC());
}
fullset.merge(testScores_, selectionFdr_, skipNormalizeScores_);
}
/**
* Prints the weights of the normalized vector to a stream
* @param weightStream stream where the weights are written to
* @param w_ normal vector
*/
void CrossValidation::printSetWeights(ostream & weightStream, unsigned int set) {
weightStream << DataSet::getFeatureNames().getFeatureNames() <<
"\tm0" << std::endl;
weightStream.precision(3);
weightStream << w_[set][0];
for (unsigned int ix = 1; ix < FeatureNames::getNumFeatures() + 1; ix++) {
weightStream << "\t" << fixed << setprecision(4) << w_[set][ix];
}
weightStream << endl;
}
/**
* Prints the weights of the raw vector to a stream
* @param weightStream stream where the weights are written to
* @param w_ normal vector
*/
void CrossValidation::printRawSetWeights(ostream & weightStream, unsigned int set,
Normalizer * pNorm) {
vector<double> ww(FeatureNames::getNumFeatures() + 1);
pNorm->unnormalizeweight(w_[set], ww);
weightStream << ww[0];
for (unsigned int ix = 1; ix < FeatureNames::getNumFeatures() + 1; ix++) {
weightStream << "\t" << fixed << setprecision(4) << ww[ix];
}
weightStream << endl;
}
// used to save weights for reuse as weight input file
void CrossValidation::printAllWeights(ostream & weightStream,
Normalizer * pNorm) {
for (unsigned int ix = 0; ix < numFolds_; ++ix) {
printSetWeights(weightStream, ix);
printRawSetWeights(weightStream, ix, pNorm);
}
}
void CrossValidation::getAvgWeights(std::vector<double>& weights,
Normalizer * pNorm) {
vector<double> ww(FeatureNames::getNumFeatures() + 1);
weights.resize(FeatureNames::getNumFeatures() + 1);
for (size_t set = 0; set < w_.size(); ++set) {
pNorm->unnormalizeweight(w_[set], ww);
for (unsigned int ix = 0; ix < FeatureNames::getNumFeatures() + 1; ix++) {
weights[ix] += ww[ix] / static_cast<double>(w_.size());
}
}
}
void CrossValidation::printAllWeightsColumns(
std::vector< std::vector<double> > weightMatrix, ostream & outputStream) {
// write to intermediate stream to prevent the fixed precision from sticking
ostringstream weightStream;
for (unsigned int set = 0; set < numFolds_; ++set) {
weightStream << " Split" << set + 1 << '\t'; // right-align with weights
}
weightStream << "FeatureName" << std::endl;
size_t numRows = FeatureNames::getNumFeatures() + 1;
for (unsigned int ix = 0; ix < numRows; ix++) {
for (unsigned int set = 0; set < numFolds_; ++set) {
// align positive and negative weights
if (weightMatrix[set][ix] >= 0) weightStream << " ";
weightStream << fixed << setprecision(4) << weightMatrix[set][ix];
weightStream << "\t";
}
if (ix == numRows - 1) {
weightStream << "m0";
} else {
weightStream << DataSet::getFeatureNames().getFeatureName(ix);
}
weightStream << std::endl;
}
outputStream << weightStream.str();
}
void CrossValidation::printAllWeightsColumns(ostream & weightStream) {
std::cerr << "Learned normalized SVM weights for the " << numFolds_
<< " cross-validation splits:" << std::endl;
printAllWeightsColumns(w_, weightStream);
}
void CrossValidation::printAllRawWeightsColumns(ostream & weightStream,
Normalizer * pNorm) {
std::cerr << "Learned raw SVM weights for the " << numFolds_
<< " cross-validation splits:" << std::endl;
std::vector< std::vector<double> > ww = w_;
for (size_t set = 0; set < w_.size(); ++set) {
pNorm->unnormalizeweight(w_[set], ww[set]);
}
printAllWeightsColumns(ww, weightStream);
}
void CrossValidation::printDOC() {
cerr << "For the cross validation sets the average deltaMass are ";
for (size_t ix = 0; ix < testScores_.size(); ix++) {
cerr << testScores_[ix].getDOC().getAvgDeltaMass() << " ";
}
cerr << "and average pI are ";
for (size_t ix = 0; ix < testScores_.size(); ix++) {
cerr << testScores_[ix].getDOC().getAvgPI() << " ";
}
cerr << endl;
}
| 38.872881 | 142 | 0.648398 | wfondrie |
c47b6e6d60d3b8d1b15d6d00b83fac6f1b76f623 | 11,768 | cpp | C++ | src/hir2mpl/bytecode_input/dex/src/class_loader_context.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | 2 | 2019-09-06T07:02:41.000Z | 2019-09-09T12:24:46.000Z | src/hir2mpl/bytecode_input/dex/src/class_loader_context.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | src/hir2mpl/bytecode_input/dex/src/class_loader_context.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <android-base/file.h>
#include "dexfile_libdexfile.h"
#include "class_loader_context.h"
namespace maple {
const char ClassLoaderContext::kPathClassLoaderString[] = "PCL";
const char ClassLoaderContext::kDelegateLastClassLoaderString[] = "DLC";
const char ClassLoaderContext::kInMemoryDexClassLoaderString[] = "IMC";
const char ClassLoaderContext::kClassLoaderOpeningMark = '[';
const char ClassLoaderContext::kClassLoaderClosingMark = ']';
const char ClassLoaderContext::kClassLoaderSharedLibraryOpeningMark = '{';
const char ClassLoaderContext::kClassLoaderSharedLibraryClosingMark = '}';
const char ClassLoaderContext::kClassLoaderSharedLibrarySeparator = '#';
const char ClassLoaderContext::kClassLoaderSeparator = ';';
const char ClassLoaderContext::kClasspathSeparator = ',';
const char ClassLoaderContext::kSpecialSharedLib[] = "&";
size_t ClassLoaderContext::FindMatchingSharedLibraryCloseMarker(const std::string& spec,
size_t sharedLibraryOpenIndex) {
uint32_t counter = 1;
size_t stringIndex = sharedLibraryOpenIndex + 1;
size_t sharedLibraryClose = std::string::npos;
while (counter != 0) {
sharedLibraryClose = spec.find_first_of(kClassLoaderSharedLibraryClosingMark, stringIndex);
size_t sharedLibraryOpen = spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, stringIndex);
if (sharedLibraryClose == std::string::npos) {
break;
}
if ((sharedLibraryOpen == std::string::npos) ||
(sharedLibraryClose < sharedLibraryOpen)) {
--counter;
stringIndex = sharedLibraryClose + 1;
} else {
++counter;
stringIndex = sharedLibraryOpen + 1;
}
}
return sharedLibraryClose;
}
ClassLoaderType ClassLoaderContext::GetCLType(const std::string& clString) {
if (clString.compare(0, strlen(kPathClassLoaderString), kPathClassLoaderString) == 0) {
return kPathClassLoader;
} else if (clString.compare(0, strlen(kDelegateLastClassLoaderString), kDelegateLastClassLoaderString) == 0) {
return kDelegateLastClassLoader;
} else if (clString.compare(0, strlen(kInMemoryDexClassLoaderString), kInMemoryDexClassLoaderString) == 0) {
return kInMemoryDexClassLoader;
}
return kInvalidClassLoader;
}
const char* ClassLoaderContext::GetCLTypeName(ClassLoaderType type) const {
switch (type) {
case kPathClassLoader: {
return kPathClassLoaderString;
}
case kDelegateLastClassLoader: {
return kDelegateLastClassLoaderString;
}
case kInMemoryDexClassLoader: {
return kInMemoryDexClassLoaderString;
}
default: {
return nullptr;
}
}
}
ClassLoaderInfo *ClassLoaderContext::ParseClassLoaderSpec(const std::string &spec) {
ClassLoaderType classLoaderType = GetCLType(spec);
if (classLoaderType == kInvalidClassLoader) {
return nullptr;
}
if (classLoaderType == kInMemoryDexClassLoader) {
return nullptr;
}
const char* classLoaderTypeStr = GetCLTypeName(classLoaderType);
CHECK_FATAL(classLoaderTypeStr != nullptr, "classLoaderTypeStr return a nullptr!");
size_t typeStrZize = strlen(classLoaderTypeStr);
// Check the opening and closing markers.
if (spec[typeStrZize] != kClassLoaderOpeningMark) {
return nullptr;
}
if ((spec[spec.length() - 1] != kClassLoaderClosingMark) &&
(spec[spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
return nullptr;
}
size_t closingIndex = spec.find_first_of(kClassLoaderClosingMark);
std::string classpath = spec.substr(typeStrZize + 1, closingIndex - typeStrZize - 1);
ClassLoaderInfo *info = mp.New<ClassLoaderInfo>();
info->type = classLoaderType;
if (!OpenDexFiles(classpath, info->hexElements)) {
return nullptr;
};
if ((spec[spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
(spec[spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
size_t startIndex = spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
if (startIndex == std::string::npos) {
return nullptr;
}
std::string sharedLibrariesSpec = spec.substr(startIndex + 1, spec.length() - startIndex - 2);
if (!ParseSharedLibraries(sharedLibrariesSpec, *info)) {
return nullptr;
}
}
return info;
}
bool ClassLoaderContext::ParseSharedLibraries(std::string &sharedLibrariesSpec, ClassLoaderInfo &info) {
size_t cursor = 0;
while (cursor != sharedLibrariesSpec.length()) {
size_t sharedLibrarySeparator = sharedLibrariesSpec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
size_t sharedLibraryOpen = sharedLibrariesSpec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
std::string sharedLibrarySpec;
if (sharedLibrarySeparator == std::string::npos) {
sharedLibrarySpec = sharedLibrariesSpec.substr(cursor, sharedLibrariesSpec.length() - cursor);
cursor = sharedLibrariesSpec.length();
} else if ((sharedLibraryOpen == std::string::npos) || (sharedLibraryOpen > sharedLibrarySeparator)) {
sharedLibrarySpec = sharedLibrariesSpec.substr(cursor, sharedLibrarySeparator - cursor);
cursor = sharedLibrarySeparator + 1;
} else {
size_t closing_marker = FindMatchingSharedLibraryCloseMarker(sharedLibrariesSpec, sharedLibraryOpen);
if (closing_marker == std::string::npos) {
return false;
}
sharedLibrarySpec = sharedLibrariesSpec.substr(cursor, closing_marker + 1 - cursor);
cursor = closing_marker + 1;
if (cursor != sharedLibrariesSpec.length() &&
sharedLibrariesSpec[cursor] == kClassLoaderSharedLibrarySeparator) {
++cursor;
}
}
ClassLoaderInfo *sharedLibrary = ParseInternal(sharedLibrarySpec);
if (sharedLibrary == nullptr) {
return false;
}
info.sharedLibraries.push_back(sharedLibrary);
}
return true;
}
ClassLoaderInfo *ClassLoaderContext::ParseInternal(const std::string &spec) {
std::string remaining = spec;
ClassLoaderInfo *first = nullptr;
ClassLoaderInfo *previousIteration = nullptr;
while (!remaining.empty()) {
std::string currentSpec;
size_t classLoaderSeparator = remaining.find_first_of(kClassLoaderSeparator);
size_t sharedLibraryOpen = remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
if (classLoaderSeparator == std::string::npos) {
currentSpec = remaining;
remaining = "";
} else if ((sharedLibraryOpen == std::string::npos) || (sharedLibraryOpen > classLoaderSeparator)) {
currentSpec = remaining.substr(0, classLoaderSeparator);
remaining = remaining.substr(sharedLibraryOpen + 1, remaining.size() - classLoaderSeparator - 1);
} else {
size_t sharedLibraryClose = FindMatchingSharedLibraryCloseMarker(remaining, sharedLibraryOpen);
CHECK_FATAL(sharedLibraryClose != std::string::npos,
"Invalid class loader spec: %s", currentSpec.c_str());
currentSpec = remaining.substr(0, sharedLibraryClose + 1);
if (remaining.size() == sharedLibraryClose + 1) {
remaining = "";
} else if ((remaining.size() == sharedLibraryClose + 2) ||
(remaining.at(sharedLibraryClose + 1) != kClassLoaderSeparator)) {
CHECK_FATAL(false, "Invalid class loader spec: %s", currentSpec.c_str());
return nullptr;
} else {
remaining = remaining.substr(sharedLibraryClose + 2, remaining.size() - sharedLibraryClose - 2);
}
}
ClassLoaderInfo *info = ParseClassLoaderSpec(currentSpec);
CHECK_FATAL(info != nullptr, "Invalid class loader spec: %s", currentSpec.c_str());
if (first == nullptr) {
first = info;
previousIteration = first;
} else {
CHECK_NULL_FATAL(previousIteration);
previousIteration->parent = info;
previousIteration = previousIteration->parent;
}
}
return first;
}
// Process PCL/DLC string, and open the corresponding byte code file (dex/jar/apk)
bool ClassLoaderContext::Parse(const std::string &spec) {
if (spec.empty()) {
return false;
}
// Output to IFile, used by collision check when trying to load IFile.
if (spec.compare(kSpecialSharedLib) == 0) {
isSpecialSharedLib = true;
return false;
}
loaderChain = ParseInternal(spec);
return loaderChain != nullptr;
}
// PCL
ClassLoaderContext *ClassLoaderContext::Create(const std::string &spec, MemPool &mp) {
ClassLoaderContext *retv = mp.New<ClassLoaderContext>(mp);
if (retv->Parse(spec)) {
return retv;
} else {
return nullptr;
}
}
// compiled File
ClassLoaderInfo *ClassLoaderContext::CreateClassLoader(const std::string &spec) {
ClassLoaderInfo *classLoader = mp.New<ClassLoaderInfo>();
classLoader->type = kPathClassLoader;
classLoader->parent = loaderChain;
loaderChain = classLoader;
if (!OpenDexFiles(spec, classLoader->hexElements)) {
CHECK_FATAL(false, "Fail to Open Dex Files!");
};
return loaderChain;
}
bool ClassLoaderContext::OpenDexFiles(const std::string &spec,
std::vector<std::unique_ptr<bc::DexParser>> &openedFileParsers) {
if (spec.empty()) {
return false;
}
bool isSuccess = true;
const std::vector<std::string> &fileNames = FEUtils::Split(spec, kClasspathSeparator);
uint depFileIdx = UINT32_MAX;
for (const std::string &fileName : fileNames) {
const bool verifyChecksum = true;
const bool verify = true;
std::unique_ptr<std::string> content = std::make_unique<std::string>();
// If the file is not a .dex file, the function tries .zip/.jar/.apk files,
// all of which are Zip archives with "classes.dex" inside.
if (!android::base::ReadFileToString(fileName, content.get())) {
WARN(kLncErr, "%s ReadFileToString failed", fileName.c_str());
isSuccess = false;
continue;
}
// content size must > 0, otherwise previous step return false
const art::DexFileLoader dexFileLoader;
art::DexFileLoaderErrorCode errorCode;
std::string errorMsg;
std::vector<std::unique_ptr<const art::DexFile>> dexFiles;
if (!dexFileLoader.OpenAll(reinterpret_cast<const uint8_t*>(content->data()), content->size(), fileName, verify,
verifyChecksum, &errorCode, &errorMsg, &dexFiles)) {
// Display returned error message to user. Note that this error behavior
// differs from the error messages shown by the original Dalvik dexdump.
WARN(kLncErr, "%s open fialed, errorMsg: %s", fileName.c_str(), errorMsg.c_str());
isSuccess = false;
continue;
}
for (size_t i = 0; i < dexFiles.size(); ++i) {
std::unique_ptr<IDexFile> iDexFile = std::make_unique<LibDexFile>(
std::move(dexFiles[i]), std::move(content));
iDexFile->SetFileIdx(depFileIdx);
const std::list<std::string> &inputClassNames = {};
const std::string str = fileName + " (classes" + std::to_string(i + 1) + ")"; // mark dependent dexfile name
std::unique_ptr<bc::DexParser> bcParser = std::make_unique<bc::DexParser>(depFileIdx, str, inputClassNames);
bcParser->SetDexFile(std::move(iDexFile));
openedFileParsers.push_back(std::move(bcParser));
--depFileIdx;
}
}
return isSuccess;
}
}
| 41.730496 | 116 | 0.706237 | venshine |
c47b7ead145c3e58aa8d9672e76278c81ffb18e1 | 2,019 | cpp | C++ | WindowsInternals/ExceptionHandling/ExceptionHandling.cpp | alonf/Windows-Internals-Course-Materials | 591a84cfa349c17e66dc58d16e8b5f4662cad967 | [
"MIT"
] | 5 | 2017-04-28T10:30:36.000Z | 2019-08-26T05:53:55.000Z | WindowsInternals/ExceptionHandling/ExceptionHandling.cpp | alonf/Windows-Internals-Course-Materials | 591a84cfa349c17e66dc58d16e8b5f4662cad967 | [
"MIT"
] | null | null | null | WindowsInternals/ExceptionHandling/ExceptionHandling.cpp | alonf/Windows-Internals-Course-Materials | 591a84cfa349c17e66dc58d16e8b5f4662cad967 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------
// <copyright file="ExceptionHandling.cpp" company="CodeValue">
// Copyright (c) 2011 by CodeValue Ltd. All rights reserved
// </copyright>
//
// http://codevalue.com
// Licensed under the Educational Community License version 1.0 (http://www.opensource.org/licenses/ecl1)
// This example was written as a demonstration of principles only
//
// ------------------------------------------------------------------------
// ExceptionHandling.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <functional>
#include <iostream>
using namespace std;
void CheckException(int depth)
{
__try
{
if (depth == 0)
RaiseException(5, 0, 0, nullptr);
__try
{
CheckException(depth - 1);
}
__finally
{
wcout << L"Called in the finally statement, depth: " << depth << L" Abnormal Termination:" <<
(AbnormalTermination() ? L"True" : L"False") << endl;
}
wcout << L"*** This is never written" << endl;
}
__except (EXCEPTION_CONTINUE_SEARCH)
{
}
}
void Test(PWSTR message)
{
wcout << endl << endl;
wcout << "============================================" << endl;
wcout << "========= N E W T E S T =============" << endl;
wcout << "============================================" << endl;
__try
{
CheckException(10);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
wcout << L"Test, message:" << message << endl;;
}
}
LONG WINAPI VectoredHandler(_EXCEPTION_POINTERS *ExceptionInfo)
{
wcout << "Vectored Handler" << endl;
return EXCEPTION_EXECUTE_HANDLER;
}
int main()
{
__try
{
Test(L"First");
PVOID hHandler = AddVectoredExceptionHandler(2, VectoredHandler);
Test(L"After adding exception handler");
RemoveVectoredExceptionHandler(hHandler);
Test(L"Last");
}
__finally
{
wcout << L"Called in the finally statement of main. Abnormal Termination:" <<
(AbnormalTermination() ? L"True" : L"False") << endl;
}
return 0;
}
| 22.433333 | 105 | 0.583952 | alonf |
c4817c5bea747ea1744463c6b31413300f928cd8 | 7,261 | cpp | C++ | Task 3/src/main.cpp | Niapollab/Microprocessor-Architecture_5-semester | 6f7303ce85d45720ee7c847cb9969fc7cc5a1737 | [
"Apache-2.0"
] | 1 | 2021-12-20T04:44:23.000Z | 2021-12-20T04:44:23.000Z | Task 3/src/main.cpp | Niapollab/Microprocessor-Architecture_5-semester | 6f7303ce85d45720ee7c847cb9969fc7cc5a1737 | [
"Apache-2.0"
] | null | null | null | Task 3/src/main.cpp | Niapollab/Microprocessor-Architecture_5-semester | 6f7303ce85d45720ee7c847cb9969fc7cc5a1737 | [
"Apache-2.0"
] | null | null | null | #include <Arduino.h>
#ifdef __PLATFORMIO_BUILD_DEBUG__
#include <avr_debugger.h>
#endif
#include "Digit.h"
#include "State.h"
// FIXME: 5 or 7 != 0
#include <LiquidCrystal_I2C.h>
#include "LCDSerialUserInterface.h"
#include "NumberBuilder.h"
#include "Calculator.h"
#include "InterruptUtils.h"
#include <Keypad.h>
#include <EEPROM.h>
volatile bool need_redraw = false;
const int LCD_TYPE = 0x27;
const int LCD_WIDTH = 16;
const int LCD_HEIGHT = 2;
const int MAX_DIGITS_COUNT = 8;
const int KEYPAD_ROWS_COUNT = 4;
const int KEYPAD_COLUMNS_COUNT = 4;
State current_state = State::MAIN_MENU_CALCULATOR_SELECTED;
NumberBuilder numberBuilder(MAX_DIGITS_COUNT);
Calculator calculator;
int stored_value;
const int KEYPAD_ROWS[] = { 2, 3, 4, 5 };
const int KEYPAD_COLUMNS[] = { 6, 7, 8, 9 };
Keypad keypad(KEYPAD_ROWS, KEYPAD_ROWS_COUNT, KEYPAD_COLUMNS, KEYPAD_COLUMNS_COUNT);
const ButtonState* numpad_states[]
{
&keypad.get_last_state(3, 1), // 0
&keypad.get_last_state(0, 0), // 1
&keypad.get_last_state(0, 1), // 2
&keypad.get_last_state(0, 2), // 3
&keypad.get_last_state(1, 0), // 4
&keypad.get_last_state(1, 1), // 5
&keypad.get_last_state(1, 2), // 6
&keypad.get_last_state(2, 0), // 7
&keypad.get_last_state(2, 1), // 8
&keypad.get_last_state(2, 2) // 9
};
const ButtonState* additional_states[]
{
&keypad.get_last_state(0, 3), // D1
&keypad.get_last_state(1, 3), // D2
&keypad.get_last_state(2, 3), // D3
&keypad.get_last_state(3, 3) // D4
};
const ButtonState* star_state = &keypad.get_last_state(3, 0); // *
const ButtonState* sharp_state = &keypad.get_last_state(3, 2); // #
const ButtonState* calculator_backspace = additional_states[1];
const ButtonState* calculator_enter = additional_states[2];
const ButtonState* dialog_yes = additional_states[1];
const ButtonState* dialog_no = additional_states[2];
IUserInterface* ui = new LCDSerialUserInterface(LiquidCrystal_I2C(LCD_TYPE, LCD_WIDTH, LCD_HEIGHT));
void redraw()
{
switch (current_state)
{
case State::MAIN_MENU_CALCULATOR_SELECTED:
ui->draw_calculator_menu_item();
break;
case State::MAIN_MENU_MEMORY_SELECTED:
ui->draw_memory_menu_item(stored_value);
break;
case State::MAIN_MENU_CLEAR_SELECTED:
ui->draw_clear_menu_item();
break;
case State::CALCULATOR_INPUT_FIRST:
ui->draw_first_dialog(numberBuilder.number());
break;
case State::CALCULATOR_INPUT_SECOND:
ui->draw_second_dialog(numberBuilder.number());
break;
case State::CALCULATOR_RESULT:
ui->draw_result(calculator.calculate_or());
break;
case State::CALCULATOR_SAVE_RESULT_DIALOG:
ui->draw_save_dialog();
break;
case State::CLEAR_MEMORY_DIALOG:
ui->draw_clear_dialog();
break;
}
need_redraw = false;
}
void menu_down_handler()
{
const int SIZE = 3;
int next = (int)current_state + 1;
if (next >= SIZE)
next = 0;
current_state = (State)next;
need_redraw = true;
}
void menu_enter_handler()
{
if (current_state != State::MAIN_MENU_MEMORY_SELECTED)
{
switch (current_state)
{
case State::MAIN_MENU_CALCULATOR_SELECTED:
current_state = State::CALCULATOR_INPUT_FIRST;
stop_interrupt();
break;
case State::MAIN_MENU_CLEAR_SELECTED:
current_state = State::CLEAR_MEMORY_DIALOG;
stop_interrupt();
break;
default:
break;
}
need_redraw = true;
}
}
int restore_value_form_memory()
{
int restored_value = 0;
EEPROM.get(0, restored_value);
return restored_value;
}
void store_new_value(int value)
{
stored_value = value;
EEPROM.put(0, stored_value);
}
void setup()
{
#ifdef __PLATFORMIO_BUILD_DEBUG__
debug_init();
#endif
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
init_interrupt();
set_handler(0, menu_down_handler);
set_handler(1, menu_enter_handler);
start_interrupt();
ui->init();
stored_value = restore_value_form_memory();
need_redraw = true;
}
bool pressed_any_key(const ButtonState* states, int size)
{
for (int i = 0; i < size; ++i)
if (states[i].click_count() > 0)
return true;
return false;
}
bool is_clicked_or_pressed(const ButtonState& state)
{
return state.click_count() > 0 || state.is_on_pressed();
}
void main_menu_loop()
{
invoke_interrupts();
}
void internal_save_dialog(int saved_value)
{
keypad.update();
if (dialog_yes->click_count() > 0)
{
store_new_value(saved_value);
current_state = State::MAIN_MENU_CALCULATOR_SELECTED;
start_interrupt();
need_redraw = true;
} else if (dialog_no->click_count() > 0)
{
current_state = State::MAIN_MENU_CALCULATOR_SELECTED;
start_interrupt();
need_redraw = true;
}
}
void clear_dialog_loop()
{
internal_save_dialog(0);
}
void save_dialog_loop()
{
internal_save_dialog(calculator.calculate_or());
}
void calculator_loop()
{
const int DIGITS_COUNT = 10;
keypad.update();
if (current_state == State::CALCULATOR_RESULT)
{
if (pressed_any_key(keypad.get_last_states(), KEYPAD_ROWS_COUNT * KEYPAD_COLUMNS_COUNT))
{
current_state = State::CALCULATOR_SAVE_RESULT_DIALOG;
need_redraw = true;
}
return;
}
for (int i = 0; i < DIGITS_COUNT; ++i)
if (is_clicked_or_pressed(*numpad_states[i]))
{
if (!numberBuilder.can_add_digit())
break;
numberBuilder.add_digit((Digit)i);
need_redraw = true;
}
if (is_clicked_or_pressed(*calculator_backspace))
{
if (numberBuilder.can_backspace())
{
numberBuilder.backspace();
need_redraw = true;
}
} else if (calculator_enter->click_count() > 0)
{
switch (current_state)
{
case State::CALCULATOR_INPUT_FIRST:
calculator.op1() = numberBuilder.number();
break;
case State::CALCULATOR_INPUT_SECOND:
calculator.op2() = numberBuilder.number();
break;
default:
break;
}
numberBuilder.clear();
current_state = (State)((int)current_state + 1);
need_redraw = true;
}
}
void loop()
{
if (need_redraw)
redraw();
switch (current_state)
{
case State::MAIN_MENU_CALCULATOR_SELECTED:
case State::MAIN_MENU_MEMORY_SELECTED:
case State::MAIN_MENU_CLEAR_SELECTED:
main_menu_loop();
break;
case State::CALCULATOR_INPUT_FIRST:
case State::CALCULATOR_INPUT_SECOND:
case State::CALCULATOR_RESULT:
calculator_loop();
break;
case State::CALCULATOR_SAVE_RESULT_DIALOG:
save_dialog_loop();
case State::CLEAR_MEMORY_DIALOG:
clear_dialog_loop();
break;
}
} | 24.284281 | 100 | 0.628564 | Niapollab |
c48569951844b3364da391edfc422359933cc089 | 1,048 | cpp | C++ | MatchMaster/Classes/Jewel.cpp | Ghost233/MatchMaster | 03c5920e8dda487ccf1ecfdac9837a91c1e3763f | [
"MIT"
] | null | null | null | MatchMaster/Classes/Jewel.cpp | Ghost233/MatchMaster | 03c5920e8dda487ccf1ecfdac9837a91c1e3763f | [
"MIT"
] | null | null | null | MatchMaster/Classes/Jewel.cpp | Ghost233/MatchMaster | 03c5920e8dda487ccf1ecfdac9837a91c1e3763f | [
"MIT"
] | 1 | 2019-08-15T04:59:08.000Z | 2019-08-15T04:59:08.000Z | //
// Jewel.cpp
// MatchMaster
//
// Created by Ghost on 14-3-18.
//
//
#include "Jewel.h"
Jewel::Jewel():x(-1), y(-1)
{
}
Jewel::~Jewel()
{
}
bool Jewel::init()
{
return true;
}
bool Jewel::initWithJewelType(JewelType tempType)
{
if (!this->init()) return false;
type = tempType;
return true;
}
void Jewel::destroyAnimation()
{
auto action1 = FadeOut::create(0.5);
auto action2 = ScaleBy::create(0.5, 1.5);
auto action3 = Spawn::createWithTwoActions(action1, action2);
auto action4 = CallFunc::create(CC_CALLBACK_0(Jewel::finalRemove, this));
auto action5 = Sequence::createWithTwoActions(action3, action4);
this->runAction(action5);
}
void Jewel::finalRemove()
{
this->removeFromParentAndCleanup(true);
}
bool Jewel::fall(int targetX, int targetY)
{
if (y == targetY) return false;
float length = (y - targetY) * SPACEY;
auto action1 = MoveBy::create(length / FALL_SPEED_PER_SECOND, Point(0, -length));
y = targetY;
this->runAction(action1);
return true;
}
| 18.385965 | 85 | 0.647901 | Ghost233 |
c4867c8cb97824bd50616c96010b28aa6589a24b | 2,721 | cpp | C++ | src/modules/multigrid/test/MultigridBaseTest.cpp | ess-dmsc/event-formation-un | 62a2842ea7140162ab9625d22b96f6df369ec07c | [
"BSD-2-Clause"
] | 8 | 2017-12-02T09:20:26.000Z | 2022-03-28T08:17:40.000Z | src/modules/multigrid/test/MultigridBaseTest.cpp | ess-dmsc/event-formation-un | 62a2842ea7140162ab9625d22b96f6df369ec07c | [
"BSD-2-Clause"
] | 296 | 2017-10-24T09:06:10.000Z | 2022-03-31T07:31:06.000Z | src/modules/multigrid/test/MultigridBaseTest.cpp | ess-dmsc/event-formation-un | 62a2842ea7140162ab9625d22b96f6df369ec07c | [
"BSD-2-Clause"
] | 8 | 2018-04-08T15:35:50.000Z | 2021-04-12T05:06:15.000Z | /** Copyright (C) 2018 European Spallation Source ERIC */
/** @file
*
* \brief Unit tests.
*/
#include <common/testutils/TestBase.h>
#include <multigrid/MultigridBase.h>
#include <common/testutils/TestUDPServer.h>
// \todo use reference data instead
#include <multigrid/mesytec/test/TestData.h>
class MultigridBaseStandIn : public MultigridBase {
public:
MultigridBaseStandIn(BaseSettings Settings, MultigridSettings const &ReadoutSettings)
: MultigridBase(Settings, ReadoutSettings){};
~MultigridBaseStandIn() = default;
using Detector::Threads;
using MultigridBase::Counters;
};
class MultigridBaseTest : public TestBase {
public:
void SetUp() override {
LocalSettings.ConfigFile = TEST_JSON_PATH "ILL_mappings.json";
Settings.RxSocketBufferSize = 100000;
Settings.NoHwCheck = true;
}
void TearDown() override {}
BaseSettings Settings;
MultigridSettings LocalSettings;
};
TEST_F(MultigridBaseTest, Constructor) {
MultigridBaseStandIn Readout(Settings, LocalSettings);
EXPECT_EQ(Readout.Counters.rx_packets, 0);
EXPECT_EQ(Readout.Counters.rx_bytes, 0);
EXPECT_EQ(Readout.Counters.tx_bytes, 0);
}
TEST_F(MultigridBaseTest, DataReceive) {
MultigridBaseStandIn Readout(Settings, LocalSettings);
Readout.startThreads();
std::chrono::duration<std::int64_t, std::milli> InitSleepTime {300};
TestUDPServer Server(43126, Settings.DetectorPort,
&ws4[0], ws4.size());
std::this_thread::sleep_for(InitSleepTime);
Server.startPacketTransmission(1, 1000);
std::chrono::duration<std::int64_t, std::milli> SleepTime(1000);
std::this_thread::sleep_for(SleepTime);
Readout.stopThreads();
EXPECT_EQ(Readout.Counters.rx_packets, 1);
EXPECT_EQ(Readout.Counters.rx_bytes, ws4.size());
EXPECT_EQ(Readout.Counters.parser_discarded_bytes, 0);
EXPECT_EQ(Readout.Counters.parser_triggers, 36);
EXPECT_EQ(Readout.Counters.builder_glitch_rejects, 0);
EXPECT_EQ(Readout.Counters.builder_filter_rejects, 0);
EXPECT_EQ(Readout.Counters.builder_geometry_errors, 0);
EXPECT_EQ(Readout.Counters.hits_total, 54);
EXPECT_EQ(Readout.Counters.hits_bad_plane, 0);
EXPECT_EQ(Readout.Counters.hits_time_seq_err, 0);
EXPECT_EQ(Readout.Counters.hits_used, 44);
EXPECT_EQ(Readout.Counters.pulses, 0);
EXPECT_EQ(Readout.Counters.wire_clusters, 24);
EXPECT_EQ(Readout.Counters.grid_clusters, 26);
EXPECT_EQ(Readout.Counters.events_total, 23);
EXPECT_EQ(Readout.Counters.events_multiplicity_rejects, 1);
EXPECT_EQ(Readout.Counters.events_bad, 0);
EXPECT_EQ(Readout.Counters.events_geometry_err, 0);
EXPECT_EQ(Readout.Counters.tx_events, 22);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.182927 | 87 | 0.767365 | ess-dmsc |
c4890b4eefdcb2aa0ce94060079a7a1916c33d93 | 3,546 | cpp | C++ | src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | src/core/visual/win32/krmovie/ogg/OggStreamMapper.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | #include "oggstdafx.h"
#include "OggStreamMapper.h"
#include "OggDemuxFilter.h"
#include "OggDemuxOutputPin.h"
OggStreamMapper::OggStreamMapper(OggDemuxFilter* inParentFilter, CCritSec* inParentFilterLock):
mStreamState(STRMAP_READY),
mParentFilter(inParentFilter),
mParentFilterLock(inParentFilterLock),
mFishHeadPacket(NULL),
mSkeletonSerialNo(0)
{
}
OggStreamMapper::~OggStreamMapper(void)
{
for (size_t i = 0; i < mPins.size(); i++)
{
delete mPins[i];
}
}
OggDemuxOutputPin* OggStreamMapper::getPinByIndex(unsigned long inIndex)
{
if (inIndex < mPins.size())
{
return mPins[inIndex];
}
return NULL;
}
bool OggStreamMapper::acceptOggPage(OggPage* inOggPage)
{
switch (mStreamState)
{
case STRMAP_READY:
//WARNING::: Partial fall through
if (inOggPage->header()->isBOS())
{
mStreamState = STRMAP_PARSING_BOS_PAGES;
}
else
{
mStreamState = STRMAP_ERROR;
delete inOggPage;
return false;
}
//Partial fall through
case STRMAP_PARSING_BOS_PAGES:
//WARNING::: Partial fall through
if (!allStreamsReady())
{
if (inOggPage->header()->isBOS())
{
return addNewPin(inOggPage);
}
else
{
mStreamState = STRMAP_DATA;
}
}
//Partial fall through
case STRMAP_DATA:
{
// TODO: remove useless code
// if (mFishHeadPacket != NULL)
// {
// if (inOggPage->header()->StreamSerialNo() == mSkeletonSerialNo)
// {
// int x = 2;
// }
// }
OggDemuxOutputPin* locPin = getMatchingPin(inOggPage->header()->StreamSerialNo());
if (locPin != NULL)
{
return locPin->acceptOggPage(inOggPage);
}
else
{
//Ignore unknown streams
delete inOggPage;
return true;
}
}
break;
case STRMAP_FINISHED:
case STRMAP_ERROR:
default:
return false;
}
}
bool OggStreamMapper::allStreamsReady()
{
bool locAllReady = true;
//OggDemuxOutputPin* locPin = NULL;
for (size_t i = 0; i < mPins.size(); i++)
{
locAllReady = locAllReady && mPins[i]->IsStreamReady();
}
return locAllReady && (mPins.size() > 0);
}
bool OggStreamMapper::isFishHead(OggPage* inOggPage)
{
StampedOggPacket* locPacket = inOggPage->getStampedPacket(0);
if (locPacket == NULL)
{
return false;
}
else
{
if ((strncmp((const char*)locPacket->packetData(), "fishead\0", 8)) == 0)
{
return true;
}
}
return false;
}
bool OggStreamMapper::handleFishHead(OggPage* inOggPage)
{
mFishHeadPacket = inOggPage->getStampedPacket(0)->clone();
mSkeletonSerialNo = inOggPage->header()->StreamSerialNo();
delete inOggPage;
return true;
}
bool OggStreamMapper::addNewPin(OggPage* inOggPage)
{
//FISH::: Catch the fishead here.
if (isFishHead(inOggPage))
{
return handleFishHead(inOggPage);
}
else
{
OggDemuxOutputPin* locNewPin = new OggDemuxOutputPin(NAME("OggPageSourcePin"), mParentFilter, mParentFilterLock, inOggPage->getPacket(0)->clone(), inOggPage->header()->StreamSerialNo());
//locNewPin->AddRef();
delete inOggPage;
mPins.push_back(locNewPin);
return true;
}
}
OggDemuxOutputPin* OggStreamMapper::getMatchingPin(unsigned long inSerialNo)
{
OggDemuxOutputPin* locPin = NULL;
for (size_t i = 0; i < mPins.size(); i++)
{
locPin = mPins[i];
if (locPin->getSerialNo() == inSerialNo)
{
return locPin;
}
}
return NULL;
}
| 21.754601 | 188 | 0.632262 | miahmie |
c4899eee09beb6df36ed93266dd2fd1c24838d29 | 3,365 | cpp | C++ | Atif/src/source/volumefraction.cpp | jiangj-physchem/Interface_project | 36d17fc28dc1e3dec0b9c80575242b792eb9671b | [
"MIT"
] | 15 | 2021-01-16T04:49:08.000Z | 2022-02-22T14:17:35.000Z | Atif/program/src/volumefraction.cpp | leying-w/Atif | 7d4c4e0cc8fa159912e2f634056608023257f986 | [
"MIT"
] | null | null | null | Atif/program/src/volumefraction.cpp | leying-w/Atif | 7d4c4e0cc8fa159912e2f634056608023257f986 | [
"MIT"
] | 4 | 2021-01-16T08:16:57.000Z | 2022-03-24T05:18:51.000Z | //***********solve the possion equation****************//
#include "clibrary.h"
#include "volumefraction.h"
#include "simpsonintegration.h"
#include "constantnum.h"
extern double dr;
extern short nspecies;
extern int LLIM; //the minimum lower limit of intergral
extern int ngrid; //the number of grids
extern int ngrid_m; //the number of grids: the middle between two surfaces
void VolumeFraction(double eta_t,float* D,double* etar,double** rho)
{
short hspecies;
double eta0;
double* D3;
double* eta;
hspecies = nspecies - 1;
eta = new double[hspecies]();
D3 = new double[nspecies]();
for(short i=0; i<nspecies; ++i)
{
D3[i] = D[i]*D[i]*D[i]*Pi/6.0;
}
for(int k=LLIM; k<=ngrid_m; ++k)
{
for(short i=0; i<hspecies; ++i)
{
eta[i] = rho[i][k]*D3[i];
}
eta0 = 0;
for(short i=0; i<hspecies; ++i)
{
eta0 += eta[i];
}
if(eta0 > eta_t)
{
for(short i=0; i<hspecies; ++i)
{
if(eta[i] > etar[i])
{
rho[i][k] = rho[i][k]*etar[i]/eta[i];
rho[i][ngrid-k] = rho[i][k];
}
}
}
eta0= 0;
for(short i=0; i<hspecies; ++i)
{
eta0 += rho[i][k]*D3[i];
}
rho[hspecies][k] = (eta_t - eta0)/D3[hspecies];
rho[hspecies][ngrid-k] = rho[hspecies][k];
if(rho[hspecies][k] < 0)
{
std::cerr<<"Error in VolumeFraction.cpp: solvent concentration is negative"<<std::endl;
exit(0);
}
}
delete [] eta;
delete [] D3;
}
void VolumeFraction(int i,int* LLI,int* ULI,float* D,double** rho,double* eta)
{
//LLI: the lower limit of intergral: LLI[i]=round(D[i]*0.5/dr)
//ULI: the upper limit of intergral: ULI[i]=round((size-D[i]*0.5)/dr)
double* N3I;
double R,rin,rip,D2,temp;
int kin,kip,hspecies;
hspecies = nspecies - 1;
N3I = new double[hspecies]();
R = i*dr;
for(short j=0; j<hspecies; ++j)
{
rin = R - 0.5*D[j];
rip = R + 0.5*D[j];
kin = round(rin/dr);
kip = round(rip/dr);
D2 = D[j]*D[j]*0.25;
if(kin < LLI[j]) kin = LLI[j];
if(kip > ULI[j]) kip = ULI[j];
temp =SimpsonIntegration(rho[j],0,ngrid,kin,kip,D2,i);
N3I[j]=Pi*temp;
eta[j] = N3I[j];
}
delete [] N3I;
}
void VolumeFractionDFT(double eta_t,float* D,int* LLI,int* ULI,double* etar,double** rho)
{
short hspecies;
double eta0;
double* eta;
hspecies = nspecies - 1;
eta = new double[hspecies]();
for(int k=LLIM; k<=ngrid_m; ++k)
{
VolumeFraction(k,LLI,ULI,D,rho,eta);
eta0 = 0;
for(short i=0; i<hspecies; ++i)
{
eta0 += eta[i];
}
if(eta0 > eta_t)
{
for(short i=0; i<hspecies; ++i)
{
if(eta[i] > etar[i])
{
rho[i][k] = rho[i][k]*etar[i]/eta[i];
rho[i][ngrid-k] = rho[i][k];
}
}
}
}
delete [] eta;
}
| 23.047945 | 99 | 0.453195 | jiangj-physchem |
c48b85bae19a358d7910403bc2e1c2f37226976a | 12,349 | cpp | C++ | Code/main.cpp | Avramis/ClassificationByNumbers | 6c36aa4998173e3f78c4f27b27cfd66350b9ae07 | [
"MIT"
] | 1 | 2019-03-27T15:16:06.000Z | 2019-03-27T15:16:06.000Z | Code/main.cpp | Avramis/ClassificationByNumbers | 6c36aa4998173e3f78c4f27b27cfd66350b9ae07 | [
"MIT"
] | null | null | null | Code/main.cpp | Avramis/ClassificationByNumbers | 6c36aa4998173e3f78c4f27b27cfd66350b9ae07 | [
"MIT"
] | null | null | null | //
// main.cpp
// ClassificationTool
//
// Created by Avraam Tapinos
// Copyright © 2018 Avraam Tapinos. All rights reserved.
//
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include "ClassificationTree.hpp"
#include "ClassificationInitiation.hpp"
#include "InstructionsClass.hpp"
#include "Print_Time.hpp"
#include "TestFileExistance.hpp"
int main(int argc, const char * argv[]) {
ClassificationTree CVPT;
Print_Time PT;
TestFileExistance TE;
bool vptprov = false, faprov = false, rprov = false , outprov = false, pKNN = true, pRange = false, vpts = false, inddirprov = false, preporc = true, accu = false, znorm = false, ptd = false, repall = true, isen = false;
std::string fadir = "", vptdir = "", readsdir = "", outdir = "", rep = "Tetrahedron", tra = "DWT", indexdir = "", sapp = "DTW";
int kmer = 64, clvl = 4, knn = 5;
double range = 0.15;
clock_t start, stop;
size_t sidx = readsdir.find_last_of(".");
std::cout << readsdir.substr(0,sidx+1) << "\n";
std::cout << "#############################################################\n";
std::cout << "# #\n";
std::cout << "# CBN #\n";
std::cout << "# ClassificationByNumbers #\n";
std::cout << "# #\n";
std::cout << "#############################################################\n";
int civ = (argc - 1) % 2;
if (civ || argc - 1 == 0) {
for (int i = 1; i < argc; i++) {
if ((std::string) (argv[i]) == "-h"
|| (std::string) (argv[i]) == "-help"
|| (std::string) (argv[i]) == "-H"
|| (std::string) (argv[i]) == "-Help"
|| (std::string) (argv[i]) == "-HELP") {
InstructionsClass instructions(1);
return 1;
}
}
InstructionsClass instreuctions(0);
return 1;
}
else {
for (int i = 1; i < argc; i += 2) {
if ((std::string) (argv[i]) == "-h"
|| (std::string) (argv[i]) == "-help"
|| (std::string) (argv[i]) == "-H"
|| (std::string) (argv[i]) == "-Help"
|| (std::string) (argv[i]) == "-HELP") {
InstructionsClass instructions(0);
}
else if ((std::string) (argv[i]) == "-o") {
outdir = (std::string) (argv[i + 1]);
outprov = true;
}
else if ((std::string) (argv[i]) == "-r") {
readsdir = (std::string) (argv[i + 1]);
rprov = TE.exists_test(readsdir);
if (rprov == false){
std::cout << "> No such file or directory exist for the provided fastq file\n";
InstructionsClass instructions(0);
return 1;
}
}
else if ((std::string) (argv[i]) == "-fa"){
fadir = (std::string) (argv[i + 1]);
faprov = TE.exists_test(fadir);
if(faprov == false){
std::cout << "> No such file or directory exist for the provided fasta file\n";
InstructionsClass instructions(0);
return 1;
}
}
else if ((std::string) (argv[i]) == "-vpt_load"){
vptdir = (std::string) (argv[i + 1]);
size_t didx = vptdir.find(".vptstruct");
if(!(didx != std::string::npos)){
vptprov = TE.exists_test(vptdir+".vptstruct");
if(vptprov == true){
vptdir+=".vptstruct";
}
else{
std::cout << "> No such file or directory exist for the provided VPTree index file\n";
InstructionsClass instructions(1);
return 1;
}
}
else{
vptprov = TE.exists_test(vptdir);
if(vptprov == false){
std::cout << "> No such file or directory exist for the provided VPTree index file\n";
InstructionsClass instructions(1);
return 1;
}
}
}
else if ((std::string) (argv[i]) == "-kmer") {
kmer = std::stoi(argv[i + 1]);
}
else if ((std::string) (argv[i]) == "-rep") {
rep = (std::string) (argv[i + 1]);
}
else if ((std::string) (argv[i]) == "-tra") {
tra = (std::string) (argv[i + 1]);
}
else if ((std::string) (argv[i]) == "-clvl") {
clvl = std::stoi(argv[i + 1]);
}
else if ((std::string) (argv[i]) == "-knn") {
knn = std::stoi(argv[i + 1]);
pKNN = true;
pRange = false;
}
else if ((std::string) (argv[i]) == "-ra") {
range = std::stod(argv[i + 1]);
pKNN = false;
pRange = true;
}
else if ((std::string) (argv[i]) == "-s") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
vpts = true;
}
else{
vpts = false;
}
}
else if ((std::string) (argv[i]) == "-vpt_save") {
indexdir = (std::string) (argv[i + 1]);
inddirprov = true;
vpts = true;
}
else if((std::string) (argv[i]) == "-sen"){
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
isen = true;
}
else{
isen = false;
}
}
else if ((std::string) (argv[i]) == "-evs") {
if((std::string) (argv[i + 1]) == "s" ||(std::string) (argv[i + 1]) == "S" || (std::string) (argv[i + 1]) == "Slow" || (std::string) (argv[i + 1]) == "SLOW" || (std::string) (argv[i + 1]) == "slow"){
sapp = "SW";
}
else if((std::string) (argv[i + 1]) == "m" ||(std::string) (argv[i + 1]) == "M" || (std::string) (argv[i + 1]) == "Medium" || (std::string) (argv[i + 1]) == "MEDIUM" || (std::string) (argv[i + 1]) == "medium"){
sapp = "DTW";
}
else{
sapp = "ED";
}
}
else if ((std::string) (argv[i]) == "-proc") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
preporc = true;
}
else{
preporc = false;
}
}
else if ((std::string) (argv[i]) == "-accu") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
accu = true;
}
else{
accu = false;
}
}
else if ((std::string) (argv[i]) == "-znorm") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
znorm = true;
}
else{
znorm = false;
}
}
else if ((std::string) (argv[i]) == "-ptd") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
ptd = true;
}
else{
ptd = false;
}
}
else if ((std::string) (argv[i]) == "-repall") {
if((std::string) (argv[i + 1]) == "y" || (std::string) (argv[i + 1]) == "Y" || (std::string) (argv[i + 1]) == "Yes"){
repall = true;
}
else{
repall = false;
}
}
}
}
if( vptprov == false && faprov == false){
std::cout << "> No index file or fasta file reference file has been provided.\n";
std::cout << "> Process is termianted.\n";
InstructionsClass instructions(1);
}
if(rprov == false){
std::cout << "> No reads file has been provided.\n";
std::cout << "> Process is termianted.\n";
InstructionsClass instructions(1);
}
if(outprov == false){
size_t sidx = readsdir.find_last_of(".");
outdir = readsdir.substr(0,sidx);
if(pKNN == true){
outdir += "> KNN_Classification.txt";
}
else{
outdir += "> Range_Search_Classification.txt";
}
std::cout << "> No output directory has been provided for storing the classification results.\n";
std::cout << "> Results will be stored in:\n";
std::cout << "> " << outdir << "\n";
}
if (inddirprov == true){
vpts = true;
};
if(vpts == true){
if(vptprov == true){
std::cout << "> Indexing tree already exist in loaction:\n";
std::cout << "> " << vptdir << "n";
std::cout << "> Tree will not be saved.\n";
vpts = false;
}
else{
if(inddirprov == false){
size_t sidx = fadir.find_last_of(".");
indexdir = fadir.substr(0,sidx);
std::cout << "> No directory has been provided for storing the indexing tree.\n";
std::cout << "> Indexing tree will be storied in:\n";
std::cout << "> " << indexdir << "\n";
}
}
}
if(vptprov == true){
std::cout << "> Initiate loading indexing structure.\n";
start = clock();
CVPT.loadTree(vptdir);
stop = clock();
std::cout << "> Loading indexing structure completed.\n";
std::cout << "> Loading tree elapsed time: " << PT.returnTimestr(start, stop) << "\n";
}
else{
start = clock();
std::cout << "> Initiate building indexing structure.\n";
start = clock();
CVPT.BuildTree(fadir, kmer, rep, tra, clvl, accu, znorm);
stop = clock();
std::cout << "> Building indexing structure completed.\n";
std::cout << "> Building tree elapsed time: " << PT.returnTimestr(start, stop) << "\n";
}
if(ptd == true){
std::cout << "> Index tree contains " << CVPT.TreeNodesNum() << " nodes\n";
CVPT.TreeprintAllTau();
}
if(pKNN == true){
std::cout << "> Initiate KNN search.\n";
start = clock();
ClassificationInitiation CIKNN(&CVPT, readsdir, outdir, sapp, knn, preporc, repall, isen);
stop = clock();
std::cout << "> KNN search completed.\n";
std::cout << "> KNN search elapsed time: " << PT.returnTimestr(start, stop) << "\n";
}
else if(pRange == true){
std::cout << "> Initiate range search.\n";
start = clock();
ClassificationInitiation CIRange(&CVPT, readsdir, outdir ,sapp, range, preporc, repall);
stop = clock();
std::cout << "> Range search completed.\n";
std::cout << "> Range search elapsed time: " << PT.returnTimestr(start, stop) << "\n";
}
if(vpts == true){
std::cout << "> Initiate saving indexing structure.\n";
start = clock();
CVPT.saveTree(indexdir);
stop = clock();
std::cout << "> Saving indexing structure completed.\n";
std::cout << "> Saving indexing structure elapsed time: " << PT.returnTimestr(start, stop) << "\n";
}
std::cout << "#############################################################\n\n";
return 0;
}
| 40.224756 | 226 | 0.412746 | Avramis |
c48c2ee9e3197b16a27fe91445f6d9332d26960b | 1,532 | cpp | C++ | source/consumers/add_ons/Status.cpp | ess-dmsc/daquiri | f218d9a62cdf568b4a52454f1e35d87ec262391c | [
"BSD-2-Clause"
] | 2 | 2018-03-25T05:31:44.000Z | 2019-07-25T05:17:51.000Z | source/consumers/add_ons/Status.cpp | ess-dmsc/daquiri | f218d9a62cdf568b4a52454f1e35d87ec262391c | [
"BSD-2-Clause"
] | 158 | 2017-11-16T09:20:24.000Z | 2022-03-28T11:39:43.000Z | source/consumers/add_ons/Status.cpp | ess-dmsc/daquiri | f218d9a62cdf568b4a52454f1e35d87ec262391c | [
"BSD-2-Clause"
] | 2 | 2018-09-20T08:29:21.000Z | 2020-08-04T18:34:50.000Z | #include <consumers/add_ons/Status.h>
#include <core/util/logger.h>
namespace DAQuiri {
Status Status::extract(const Spill& spill)
{
Status ret;
ret.valid = true;
ret.type = spill.type;
ret.producer_time = spill.time;
ret.consumer_time = std::chrono::system_clock::now();
ret.timebase = spill.event_model.timebase;
Setting native_time = spill.state.find(Setting("native_time"));
if (native_time)
ret.stats["native_time"] = native_time;
auto live_time = spill.state.find(Setting("live_time"));
if (live_time)
ret.stats["live_time"] = live_time;
return ret;
}
// TODO: make this work with nanoseconds
hr_duration_t Status::calc_diff(const Status& from, const Status& to, std::string name)
{
if (!from.stats.count(name) || !to.stats.count(name))
return hr_duration_t();
auto diff = to.stats.at(name).get_number() - from.stats.at(name).get_number();
auto diff_us = to.timebase.to_microsec(diff);
return std::chrono::microseconds(static_cast<uint64_t>(diff_us));
}
hr_duration_t Status::total_elapsed(const std::vector<Status>& stats, std::string name)
{
hr_duration_t t {std::chrono::seconds(0)};
hr_duration_t ret {std::chrono::seconds(0)};
Status start = stats.front();
for (const auto& q : stats)
{
if (q.type == Spill::Type::start)
{
ret += t;
start = q;
}
else
{
t = calc_diff(start, q, name);
if (t == hr_duration_t())
return t;
}
}
if (stats.back().type != Spill::Type::start)
ret += t;
return ret;
}
} | 25.114754 | 87 | 0.66188 | ess-dmsc |
c49028d1192c300940990602f81a94e14d93b315 | 1,720 | hh | C++ | inc/EHttpProxyResponse.hh | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 7 | 2016-08-25T14:22:36.000Z | 2020-05-25T17:27:51.000Z | inc/EHttpProxyResponse.hh | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 1 | 2018-07-11T12:37:55.000Z | 2018-07-12T00:05:33.000Z | inc/EHttpProxyResponse.hh | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 2 | 2017-06-09T01:22:36.000Z | 2021-09-29T16:27:58.000Z | /*
* EHttpProxyResponse.hh
*
* Created on: 2016-6-16
* Author: cxxjava@lotuseed.com
*/
#ifndef EHTTPPROXYRESPONSE_HH_
#define EHTTPPROXYRESPONSE_HH_
#include "Efc.hh"
namespace efc {
namespace eio {
/**
* HttpProxyResponse.java - Wrapper class for HTTP requests.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
* @since MINA 2.0.0-M3
*/
class EHttpProxyResponse: public EObject {
public:
/**
* @return the HTTP response protocol version.
*/
const char* getHttpVersion();
/**
* @return the HTTP response status code.
*/
int getStatusCode();
/**
* @return the HTTP response status line.
*/
const char* getStatusLine();
/**
* @return the HTTP response body.
*/
const char* getBody();
/**
* Sets the HTTP response body.
*
* @param body The HTTP Body
*/
void setBody(const char* body);
/**
* @return the HTTP response headers.
*/
EMap<EString*, EList<EString*>*>* getHeaders();
/*protected:*/
/**
* Constructor of an HTTP proxy response.
*
* @param httpVersion the protocol version
* @param statusLine the response status line
* @param headers the response headers
*/
EHttpProxyResponse(const char* httpVersion, const char* statusLine,
EMap<EString*, EList<EString*>*>* headers);
private:
/**
* The HTTP response protocol version.
*/
EString httpVersion;
/**
* The HTTP response status line.
*/
EString statusLine;
/**
* The HTTP response status code;
*/
int statusCode;
/**
* The HTTP response headers.
*/
EHashMap<EString*, EList<EString*>* > headers;
/**
* The HTTP response body.
*/
EString body;
};
} /* namespace eio */
} /* namespace efc */
#endif /* EHTTPPROXYRESPONSE_HH_ */
| 17.55102 | 68 | 0.656977 | developkits |
c4929eabdecbf5c91d24efca9ac82ed4aa17b111 | 1,529 | cpp | C++ | src/core/notebook/bundlenotebook.cpp | lizhyumzi/vnote | 7c4d89b0272cf817902272e8733d56c2cddb797a | [
"MIT"
] | null | null | null | src/core/notebook/bundlenotebook.cpp | lizhyumzi/vnote | 7c4d89b0272cf817902272e8733d56c2cddb797a | [
"MIT"
] | null | null | null | src/core/notebook/bundlenotebook.cpp | lizhyumzi/vnote | 7c4d89b0272cf817902272e8733d56c2cddb797a | [
"MIT"
] | null | null | null | #include "bundlenotebook.h"
#include <QDebug>
#include <notebookconfigmgr/bundlenotebookconfigmgr.h>
#include <notebookconfigmgr/notebookconfig.h>
#include <utils/fileutils.h>
using namespace vnotex;
BundleNotebook::BundleNotebook(const NotebookParameters &p_paras,
QObject *p_parent)
: Notebook(p_paras, p_parent)
{
auto configMgr = getBundleNotebookConfigMgr();
auto config = configMgr->readNotebookConfig();
m_nextNodeId = config->m_nextNodeId;
}
BundleNotebookConfigMgr *BundleNotebook::getBundleNotebookConfigMgr() const
{
return dynamic_cast<BundleNotebookConfigMgr *>(getConfigMgr().data());
}
ID BundleNotebook::getNextNodeId() const
{
return m_nextNodeId;
}
ID BundleNotebook::getAndUpdateNextNodeId()
{
auto id = m_nextNodeId++;
getBundleNotebookConfigMgr()->writeNotebookConfig();
return id;
}
void BundleNotebook::updateNotebookConfig()
{
getBundleNotebookConfigMgr()->writeNotebookConfig();
}
void BundleNotebook::removeNotebookConfig()
{
getBundleNotebookConfigMgr()->removeNotebookConfig();
}
void BundleNotebook::remove()
{
// Remove all nodes.
removeNode(getRootNode());
// Remove notebook config.
removeNotebookConfig();
// Remove notebook root folder if it is empty.
if (!FileUtils::removeDirIfEmpty(getRootFolderAbsolutePath())) {
qInfo() << QString("root folder of notebook (%1) is not empty and needs manual clean up")
.arg(getRootFolderAbsolutePath());
}
}
| 25.065574 | 97 | 0.717462 | lizhyumzi |
c4934fc0ce7bf9cefa9ffea2b003ffb8525b07cc | 11,857 | cpp | C++ | src/taesooLib/BaseLib/motion/COM_IKsolver.cpp | jackthgu/K-AR_HYU_Deform_Simulation | e7c275c8948e1fe3e800ab37b17aa8406b147277 | [
"MIT"
] | null | null | null | src/taesooLib/BaseLib/motion/COM_IKsolver.cpp | jackthgu/K-AR_HYU_Deform_Simulation | e7c275c8948e1fe3e800ab37b17aa8406b147277 | [
"MIT"
] | null | null | null | src/taesooLib/BaseLib/motion/COM_IKsolver.cpp | jackthgu/K-AR_HYU_Deform_Simulation | e7c275c8948e1fe3e800ab37b17aa8406b147277 | [
"MIT"
] | null | null | null | \
#include "stdafx.h"
#include "../math/mathclass.h"
#include "../math/optimize.h"
#include "FullbodyIK_MotionDOF.h"
#include "Motion.h"
#include "MotionUtil.h"
#include "MotionLoader.h"
#include "MotionDOF.h"
#include "IKSolver.h"
#include "VRMLloader.h"
#include "COM_IKsolver.h"
//#define DEBUG_DRAW
#ifdef DEBUG_DRAW
#include "../../MainLib/OgreFltk/RE.h"
static void drawSphere(const char* name, const char* mat, double scale, vector3 const& pos)
{
Ogre::SceneNode* pNode=RE::createEntity(name,"sphere1010.mesh");
RE::setMaterialName(pNode, mat);
RE::moveEntity(pNode, vector3(scale, scale, scale),pos);
}
#endif
using namespace MotionUtil;
COM_IKsolver:: COM_IKsolver(VRMLloader const& skel, std::vector<Effector>& effectors, intvectorn const& knee_bone_indexes, vectorn const& axis_sign)
:Optimize(), mSkeleton(skel),mDofInfo(skel.dofInfo), mEffectors(effectors)
,cgmethod(10)
{
init(0.01, 3, 0.01, 0.005, cgmethod);
mHipBones.resize(mEffectors.size());
mKneeBones.resize(mEffectors.size());
mAnkleBones.resize(mEffectors.size());
mAxis.setSize(mEffectors.size());
currPose.Init(skel.numRotJoint(), skel.numTransJoint());
for(int i=0; i<mEffectors.size(); i++)
{
Msg::verify(mEffectors[i].bone->getRotationalChannels().length()==3, "rotc");
Bone const& knee=mSkeleton.bone(knee_bone_indexes[i]);
if(mEffectors[i].bone==knee.child())
{
mKneeBones[i]=&knee;
ASSERT(knee.getRotationalChannels().length()==1);
ASSERT(knee.parent()->getRotationalChannels().length()==3);
mHipBones[i]=knee.parent();
mAnkleBones[i]=mEffectors[i].bone;
mbAdjustLen=false;
}
else if(mEffectors[i].bone==knee.child()->child())
{
mKneeBones[i]=&knee;
ASSERT(knee.getRotationalChannels().length()==1);
ASSERT(knee.parent()->getRotationalChannels().length()==0);
ASSERT(knee.parent()->parent()->getRotationalChannels().length()==3);
mHipBones[i]=knee.parent()->parent();
mAnkleBones[i]=mEffectors[i].bone;
mbAdjustLen=true;
}
else
Msg::error("??");
switch(mKneeBones[i]->getRotationalChannels()[0])
{
case 'X':
mAxis[i]=vector3(1,0,0);
break;
case 'Y':
mAxis[i]=vector3(0,1,0);
break;
case 'Z':
mAxis[i]=vector3(0,0,1);
break;
}
mAxis[i]*=axis_sign[i];
}
}
static void rotateChildren(Bone& b, quater const& q)
{
b._getFrame().rotation.leftMult(q);
for(Bone* hc=b.child(); hc; hc=hc->sibling())
rotateChildren(*hc,q);
}
void COM_IKsolver::setSkeleton(vectorn & temp)
{
if(mbAdjustLen)
{
for(int c=0; c<mEffectors.size();c++)
{
// reset knee translations to 0.
temp[mDofInfo.startT(mKneeBones[c]->child()->treeIndex())]=0;
// reset hip translations to 0.
temp[mDofInfo.startT(mHipBones[c]->child()->treeIndex())]=0;
}
}
mSkeleton.setPose(mDofInfo.setDOF(temp));
}
void COM_IKsolver::_prepare(int c)
{
mHipBones[c]->parent()->getRotation(q0);
mHipBones[c]->getTranslation(sh);
mHipBones[c]->getRotation(q1);
mKneeBones[c]->getTranslation(elb);
mKneeBones[c]->getRotation(q2);
mAnkleBones[c]->getTranslation(wrist);
mKneeBones[c]->getOffset(v1);
mAnkleBones[c]->getOffset(v2);
// mAnkleBones[c]->getRotation(test);
// preserve original global ankle orientation.
mAnkleBones[c]->_getFrame().rotation=ankleGlobal[c];
hand=mAnkleBones[c]->getFrame().toGlobalPos(mEffectors[c].localpos);
v3.difference(sh, elb);
v4.difference(elb, mAnkleBones[c]->getTranslation());
}
void COM_IKsolver::_ikSolve(int c)
{
goal=con[c]-hand+wrist;
const bool useKneeDamping=false;
#ifdef DEBUG_DRAW
if(c==1)
{
double skinScale=100;
drawSphere("m0","red", 1, sh*skinScale );
drawSphere("m1","red", 1, elb*skinScale );
drawSphere("m2","red", 1, wrist*skinScale );
drawSphere("g2","green", 3, goal*skinScale );
RE::output("m0", "%s", sh.output().ptr());
RE::output("m1", "%s", elb.output().ptr());
RE::output("m2", "%s", wrist.output().ptr());
RE::output("q1", "%s %f", q1.output().ptr(), q1.length());
RE::output("v1","%s %s", v1.output().ptr(), (q1.inverse()*(elb-sh)).output().ptr());
RE::output("v2","%s %s", v2.output().ptr(), (q2.inverse()*(wrist-elb)).output().ptr());
RE::output("import","%f", importance[c]);
}
#endif
quater qo1=q1;
quater qo2=q2;
if(mbAdjustLen)
MotionUtil::limbIK_1DOFknee(goal, sh, v1, v2, v3, v4, q1, q2, mAxis[c], useKneeDamping,&r[c]);
else
MotionUtil::limbIK_1DOFknee(goal, sh, v1, v2, v3, v4, q1, q2, mAxis[c], useKneeDamping);
if(importance[c]!=1.0)
{
quater qt;
qt.difference(qo1, q1);
qt.scale(importance[c]);
q1=qt*qo1;
qt.difference(qo2, q2);
qt.scale(importance[c]);
q2=qt*qo2;
}
// q0
// q0l1=qq1
// q0l1l2=qq2
// q0l1l2l3=qq3
BoneForwardKinematics & fk=mSkeleton.fkSolver();
fk._local(*mHipBones[c]).rotation=q0.inverse()*q1;
fk._local(*mKneeBones[c]).rotation=q1.inverse()*q2;
fk._local(*mAnkleBones[c]).rotation=q2.inverse()*ankleGlobal[c];
if(mbAdjustLen) {
fk._local(*mHipBones[c]->child()).translation=vector3(0,r[c]*-1 ,0);
fk._local(*mKneeBones[c]->child()).translation=vector3(0,r[c]*-1 ,0);
}
mSkeleton.fkSolver().setChain(*mAnkleBones[c]);
#ifdef DEBUG_DRAW
if(c==1)
{
double skinScale=100;
drawSphere("ma0","green", 1, mHipBones[c]->getTranslation()*skinScale );
drawSphere("ma1","green", 1, mKneeBones[c]->getTranslation()*skinScale );
drawSphere("ma2","green", 1, mAnkleBones[c]->getTranslation()*skinScale );
}
#endif
}
void COM_IKsolver::_iksolve(vector3 const& newPelvisPos)
{
temp.setVec3(0, newPelvisPos);
setSkeleton(temp);
quater deltaHip[4];
for (int i=0; i<mEffectors.size(); i++)
deltaHip[i].identity();
// quater test;
r.setSize(mEffectors.size());
for (int i=0; i<mEffectors.size(); i++)
{
_prepare(i);
_ikSolve(i);
}
totalMass=0;
com.setValue(0,0,0);
vector3 bcom;
for(int b=1; b<mSkeleton.numBone(); b++){
VRMLTransform& bone=mSkeleton.VRMLbone(b);
totalMass+=bone.mass();
bcom=bone.getFrame().toGlobalPos(bone.localCOM())*bone.mass();
com+=bcom;
}
com/=totalMass;
}
void COM_IKsolver::calcPelvisPos(vectorn& origRootTF_, quater const& currRotY, transf const& newRootTF, quaterN const& delta_foot, vector3N const& _con, vectorn const& _importance,vector3 const& _desiredCOM, vector3& pelvisPos)
{
con=_con;
desiredCom=_desiredCOM;
importance=_importance;
transf origRootTF=MotionDOF::rootTransformation(origRootTF_);
{
quater rotY, offset;
origRootTF.rotation.decompose(rotY, offset);
origRootTF.rotation.mult(currRotY, offset);
}
temp.assign(origRootTF_);
MotionDOF::setRootTransformation(temp, origRootTF);
setSkeleton(temp);
for(int c=0; c<mEffectors.size();c++)
ankleGlobal[c]=delta_foot[c]*mAnkleBones[c]->getFrame().rotation;
MotionDOF::setRootTransformation(temp, newRootTF);
_iksolve(newRootTF.translation);
vectorn initialPos(3);
initialPos.setVec3(0,newRootTF.translation);
optimize(initialPos);
pelvisPos=getResult().toVector3(0);
if( pelvisPos.x!=pelvisPos.x)
{
printf("?\n");
pelvisPos=newRootTF.translation;
}
}
void COM_IKsolver::IKsolve(vectorn& origRootTF_, quater const& currRotY, transf const& newRootTF, quaterN const& delta_foot, vector3N const& _con, vectorn const& _importance, vector3 const& _desiredCOM)
{
vector3 pelvisPos;
calcPelvisPos(origRootTF_, currRotY, newRootTF, delta_foot, _con, _importance, _desiredCOM, pelvisPos);
_iksolve(pelvisPos);
//printf("pelvisPos %s\n", pelvisPos.output().ptr());
mSkeleton.fkSolver().getPoseFromLocal(tempp);
//printf("ankleHeight %s %s %s %f %f\n", pelvisPos.output().ptr(), tempp.m_aTranslations[0].output().ptr(), mAnkleBones[0]->NameId,_con[0].y, mAnkleBones[0]->getFrame().translation.x);
//printf("pelvisPos2 %s\n", tempp.m_aTranslations[0].output().ptr());
/* mSkeleton.setPose(tempp);
quater tt1,tt2,tt3;
int c=mEffectors.size()-1;
tt1=mHipBones[c]->_getFrame().rotation;
tt2=mKneeBones[c]->_getFrame().rotation;
tt3=mAnkleBones[c]->_getFrame().rotation;*/
mDofInfo.getDOF(tempp, origRootTF_);
}
m_real COM_IKsolver::objectiveFunction(vectorn const& x)
{
_iksolve(x.toVector3(0));
double e=com.distance(desiredCom);
return e;
}
void COM_IKsolver::IKsolve2(vectorn & temp, quater const& currRotY, transf const& newRootTF, quaterN const& delta_foot, vector3N const& con)
{
Msg::msgBox("not implemented yet!");
transf origRootTF=MotionDOF::rootTransformation(temp);
{
quater rotY, offset;
origRootTF.rotation.decompose(rotY, offset);
origRootTF.rotation.mult(currRotY, offset);
}
MotionDOF::setRootTransformation(temp, origRootTF);
setSkeleton(temp);
quater ankleGlobal[4];
for(int c=0; c<mEffectors.size();c++)
ankleGlobal[c]=delta_foot[c]*mAnkleBones[c]->getFrame().rotation;
MotionDOF::setRootTransformation(temp, newRootTF);
setSkeleton(temp);
quater deltaHip[4];
for(int c=0; c<mEffectors.size();c++)
deltaHip[c].identity();
// quater test;
vector3 goal, sh, elb, v1, v2, v3, v4, wrist,hand;
quater q1, q2;
vectorn r(mEffectors.size());
for(int c=0; c<mEffectors.size();c++)
{
mHipBones[c]->getTranslation(sh);
mHipBones[c]->getRotation(q1);
mKneeBones[c]->getTranslation(elb);
mKneeBones[c]->getRotation(q2);
mKneeBones[c]->getOffset(v1);
mAnkleBones[c]->getOffset(v2);
mAnkleBones[c]->getTranslation(wrist);
// mAnkleBones[c]->getRotation(test);
// preserve original global ankle orientation.
mAnkleBones[c]->_getFrame().rotation=ankleGlobal[c];
hand=mAnkleBones[c]->getFrame().toGlobalPos(mEffectors[c].localpos);
goal=con[c]-hand+wrist;
v3.difference(sh, elb);
v4.difference(elb, mAnkleBones[c]->getTranslation());
const bool useKneeDamping=true;
if(mbAdjustLen)
MotionUtil::limbIK_1DOFknee(goal, sh, v1, v2, v3, v4, q1, q2, mAxis[c], useKneeDamping,&r[c]);
else
MotionUtil::limbIK_1DOFknee(goal, sh, v1, v2, v3, v4, q1, q2, mAxis[c], useKneeDamping);
/*
if(useKneeDamping)
IKSolver::limbIK(goal, sh, v1, v2, q1, q2, 1.0, mAxis[c], &v3, &v4);
else
IKSolver::limbIK(goal, sh, v1, v2, q1, q2, 1.0, mAxis[c]);
*/
///mHipBones[c]->_getFrame().rotation=q1;
///mKneeBones[c]->_getFrame().rotation=q2;
//if(mbAdjustLen)
//{
// // update global orientations of translation joints too,
// // so that getPoseFromGlobal(...) works.
// mHipBones[c]->child()->_getFrame().rotation=q1;
// mKneeBones[c]->child()->_getFrame().rotation=q2;
//}
mHipBones[c]->_getLocalFrame().rotation=q0.inverse()*q1;
mKneeBones[c]->_getLocalFrame().rotation=q1.inverse()*q2;
mAnkleBones[c]->_getLocalFrame().rotation=q2.inverse()*ankleGlobal[c];
if(mbAdjustLen)
mSkeleton.fkSolver().setChain(*mAnkleBones[c]->child());
else
mSkeleton.fkSolver().setChain(*mAnkleBones[c]);
}
mSkeleton.getPose(tempp);
/* mSkeleton.setPose(tempp);
quater tt1,tt2,tt3;
int c=mEffectors.size()-1;
tt1=mHipBones[c]->_getFrame().rotation;
tt2=mKneeBones[c]->_getFrame().rotation;
tt3=mAnkleBones[c]->_getFrame().rotation;*/
mDofInfo.getDOF(tempp, temp);
if(mbAdjustLen)
{
for(int c=0;c<mEffectors.size();c++)
{
temp[mDofInfo.startT(mHipBones[c]->child()->treeIndex())]=r[c]*-1;
temp[mDofInfo.startT(mKneeBones[c]->child()->treeIndex())]=r[c]*-1;
}
}
}
#ifdef USE_LUABIND
#include "../MainLib/WrapperLua/BaselibLUA.h"
#include "../MainLib/WrapperLua/MainlibLUA.h"
#include <luabind/luabind.hpp>
#include <luabind/operator.hpp>
#include <luabind/out_value_policy.hpp>
#include <luabind/adopt_policy.hpp>
#include <luabind/error.hpp>
using namespace luabind;
void registerCOM_IKsolver(lua_State* L)
{
luabind::module(L)
[
class_<COM_IKsolver>("COM_IKsolver")
.def(constructor<VRMLloader const&, std::vector<Effector>&, intvectorn const&, vectorn const&>() )
.def("IKsolve", &COM_IKsolver::IKsolve)
.def("IKsolve2", &COM_IKsolver::IKsolve2)
.def("calcPelvisPos", &COM_IKsolver::calcPelvisPos)
];
}
#endif
| 28.030733 | 227 | 0.6909 | jackthgu |
c49555699704ba251e7aa7e167445a0e0e1da0fe | 5,439 | cpp | C++ | thirdparty/box2d-optimized/src/dynamics/b2_contact_manager.cpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 113 | 2020-02-25T03:19:32.000Z | 2021-05-17T09:15:40.000Z | thirdparty/box2d-optimized/src/dynamics/b2_contact_manager.cpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 172 | 2020-02-21T08:56:42.000Z | 2021-05-12T03:18:40.000Z | thirdparty/box2d-optimized/src/dynamics/b2_contact_manager.cpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 62 | 2020-02-23T14:10:16.000Z | 2021-05-14T13:53:19.000Z | // MIT License
// Copyright (c) 2019 Erin Catto
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "box2d/b2_body.h"
#include "box2d/b2_contact.h"
#include "box2d/b2_contact_manager.h"
#include "box2d/b2_fixture.h"
#include "box2d/b2_world_callbacks.h"
b2ContactFilter b2_defaultFilter;
b2ContactManager::b2ContactManager() {
m_contactCount = 0;
m_contactFilter = &b2_defaultFilter;
m_contactListener = nullptr;
m_allocator = nullptr;
m_contactList = (b2Contact*) b2Alloc(1 * sizeof(b2Contact));
m_contactList->m_next = m_contactList;
m_contactList->m_prev = m_contactList;
m_contactList->m_fixtureA = nullptr;
m_contactList->m_fixtureB = nullptr;
}
b2ContactManager::~b2ContactManager() {
b2Free(m_contactList);
}
void b2ContactManager::Destroy(b2Contact* c) {
if (m_contactListener && c->IsTouching()) {
m_contactListener->EndContact(c);
}
b2Assert(c != m_contactList);
// Remove from the world.
c->m_prev->m_next = c->m_next;
c->m_next->m_prev = c->m_prev;
b2Contact::Destroy(c, m_allocator);
--m_contactCount;
}
// This is the top level collision call for the time step. Here
// all the narrow phase collision is processed for the world
// contact list.
void b2ContactManager::Collide() {
// Update awake contacts.
b2Contact* c = Start();
while (c != End()) {
b2Fixture* fixtureA = c->GetFixtureA();
b2Fixture* fixtureB = c->GetFixtureB();
b2Body* bodyA = fixtureA->GetBody();
b2Body* bodyB = fixtureB->GetBody();
// Is this contact flagged for filtering?
if (c->m_flags & b2Contact::e_filterFlag) {
// Should these bodies collide?
if (bodyB->ShouldCollide(bodyA) == false) {
b2Contact* cNuke = c;
c = cNuke->GetNext();
Destroy(cNuke);
continue;
}
// Check user filtering.
if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) {
b2Contact* cNuke = c;
c = cNuke->GetNext();
Destroy(cNuke);
continue;
}
}
// Clear the island flag; Prepare to build islands in b2World::Solve
// Clear the persist flag; Prepare to add/remove new contacts from the broadphase
// Clear the filtering flag
c->m_flags &= ~(b2Contact::e_islandFlag | b2Contact::e_persistFlag | b2Contact::e_filterFlag);
// TODO this checks can probably be removed with some extra code in b2_body
#ifdef ENABLE_SLEEPING
bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody;
bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody;
bool active = (activeA || activeB);
#else
bool active = (bodyA->m_type != b2_staticBody) || (bodyB->m_type != b2_staticBody);
#endif // ENABLE_SLEEPING
// At least one body must be awake and it must be dynamic or kinematic.
if (active) {
// The contact persists.
c->Update(m_contactListener);
}
c = c->GetNext();
}
}
void b2ContactManager::FindNewContacts() {
m_broadPhase.UpdateAndQuery(this);
RemoveDeadContacts();
}
void b2ContactManager::RemoveDeadContacts() {
b2Contact* c = Start();
while (c != End()) {
b2Contact* cNuke = c;
c = c->GetNext();
if ((cNuke->m_flags & b2Contact::e_persistFlag) == 0) {
Destroy(cNuke);
}
}
}
b2Contact* b2ContactManager::QueryCallback(b2Fixture* fixtureA, b2Fixture* fixtureB) {
b2Body* bodyA = fixtureA->GetBody();
b2Body* bodyB = fixtureB->GetBody();
// Are the fixtures on the same body?
if (bodyA == bodyB) {
return nullptr;
}
// Does a contact already exist?
for (int32 i = 0; i < bodyB->GetContactCount(); ++i) {
b2Contact* c = bodyB->GetContact(i);
b2Fixture* fA = c->GetFixtureA();
b2Fixture* fB = c->GetFixtureB();
if ((fA == fixtureA && fB == fixtureB) || (fA == fixtureB && fB == fixtureA)) {
// persist the contact
c->m_flags |= b2Contact::e_persistFlag;
return c;
}
}
// Does a joint override collision? Is at least one body dynamic?
if (bodyB->ShouldCollide(bodyA) == false) {
return nullptr;
}
// Check user filtering.
if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) {
return nullptr;
}
// Call the factory.
b2Contact* c = b2Contact::Create(fixtureA, fixtureB, m_allocator);
if (c == nullptr) {
return nullptr;
}
// Insert into the world.
c->m_prev = m_contactList;
c->m_next = m_contactList->m_next;
m_contactList->m_next->m_prev = c;
m_contactList->m_next = c;
bodyA->AddContact(c);
bodyB->AddContact(c);
++m_contactCount;
return c;
}
| 28.777778 | 96 | 0.702887 | rh101 |
c496dbaf648e776db621b9e232a872c94c9bbb9a | 1,759 | cpp | C++ | Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Player/GBox/State/States/State_GBox_PortalFalling.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "State_GBox_PortalFalling.h"
#include "Components/ArrowComponent.h"
#include "Kismet/KismetMathLibrary.h"
void UState_GBox_PortalFalling::Init(class UStateMng_GC* pMng)
{
Super::Init(pMng);
}
void UState_GBox_PortalFalling::Enter()
{
Super::Enter();
if (m_pStartPortal == nullptr)
{
ULOG(TEXT("StartPortal is Nullptr"));
return;
}
m_vStartLoc = m_pStartPortal->GetComponentLocation();
GetRootChar()->SetActorRotation(FRotator(0.0f, m_pStartPortal->GetComponentRotation().Yaw, 0.0f));
GetRootChar()->SetActorLocation(m_vStartLoc);
GetRootChar()->GetAnimationMng()->PlayAnimationSequnceBase(TEXT("Portal_Falling"), TEXT("DefaultSlot"), 0.0f, 0.2f, 1.0f);
m_bMotionEnd = false;
}
void UState_GBox_PortalFalling::Exit()
{
Super::Exit();
GetRootChar()->GetSpringArm()->CameraLagSpeed = 10.0f;
//GetRootChar()->GetSlowGage()->SetInit(GetRootChar(), GetRootChar()->m_vSlowGagePos);
m_pStartPortal = nullptr;
GetRootChar()->SetVisibleHUD(true);
GetRootChar()->GetAnimationMng()->StopAnimation_SequnceBaseSlot(TEXT("DefaultSlot"), 0.2f);
if (GetRootChar()->GetStick() != nullptr)
{
GetRootChar()->GetStick()->Control_Portal(false);
}
}
void UState_GBox_PortalFalling::Update(float fDeltaTime)
{
Super::Update(fDeltaTime);
if (m_pStartPortal == nullptr) return;
if (m_bMotionEnd == true)
{
ChangeState(static_cast<int32>(E_State_GBox::E_Idle));
return;
}
}
void UState_GBox_PortalFalling::StateMessage(FString StateMessage)
{
Super::StateMessage(StateMessage);
if (StateMessage == "MotionEnd")
{
m_bMotionEnd = true;
}
}
void UState_GBox_PortalFalling::SetPortal(UArrowComponent * pPortal)
{
m_pStartPortal = pPortal;
}
| 23.453333 | 123 | 0.744741 | Bornsoul |
c4980ab09e9d77dbb2c8d9831116c537b0f9c153 | 6,185 | cpp | C++ | src/resqml2/GridConnectionSetRepresentation.cpp | untereiner/fesapi | 98b00320a82c88b2fda0ae0654cedd80afce317d | [
"Apache-2.0"
] | null | null | null | src/resqml2/GridConnectionSetRepresentation.cpp | untereiner/fesapi | 98b00320a82c88b2fda0ae0654cedd80afce317d | [
"Apache-2.0"
] | null | null | null | src/resqml2/GridConnectionSetRepresentation.cpp | untereiner/fesapi | 98b00320a82c88b2fda0ae0654cedd80afce317d | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"; you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-----------------------------------------------------------------------*/
#include "GridConnectionSetRepresentation.h"
#include <algorithm>
#include <stdexcept>
#include <hdf5.h>
#include "../resqml2_0_1/FaultInterpretation.h"
#include "../common/AbstractHdfProxy.h"
#include "AbstractLocal3dCrs.h"
#include "../resqml2_0_1/UnstructuredGridRepresentation.h"
#include "../resqml2_0_1/AbstractIjkGridRepresentation.h"
#include "../resqml2_0_1/StructuralOrganizationInterpretation.h"
using namespace std;
using namespace RESQML2_NS;
using namespace gsoap_resqml2_0_1;
const char* GridConnectionSetRepresentation::XML_TAG = "GridConnectionSetRepresentation";
void GridConnectionSetRepresentation::pushBackSupportingGridRepresentation(AbstractGridRepresentation * supportingGridRep)
{
if (supportingGridRep == nullptr) {
throw invalid_argument("The supporting Grid Representation cannot be null.");
}
getRepository()->addRelationship(this, supportingGridRep);
pushBackXmlSupportingGridRepresentation(supportingGridRep);
}
void GridConnectionSetRepresentation::pushBackInterpretation(AbstractFeatureInterpretation* interp)
{
if (interp == nullptr) {
throw invalid_argument("The interpretation to push back cannot be null.");
}
getRepository()->addRelationship(this, interp);
pushBackXmlInterpretation(interp);
}
void GridConnectionSetRepresentation::loadTargetRelationships()
{
AbstractRepresentation::loadTargetRelationships();
// Supporting grid representation
unsigned int supportingGridCount = getSupportingGridRepresentationCount();
for (unsigned int i = 0; i < supportingGridCount; ++i) {
gsoap_resqml2_0_1::eml20__DataObjectReference* dor = getSupportingGridRepresentationDor(i);
RESQML2_NS::AbstractGridRepresentation* supportingGridRep = getRepository()->getDataObjectByUuid<RESQML2_NS::AbstractGridRepresentation>(dor->UUID);
if (supportingGridRep == nullptr) { // partial transfer
getRepository()->createPartial(dor);
supportingGridRep = getRepository()->getDataObjectByUuid<RESQML2_NS::AbstractGridRepresentation>(dor->UUID);
if (supportingGridRep == nullptr) {
throw invalid_argument("The DOR looks invalid.");
}
}
getRepository()->addRelationship(this, supportingGridRep);
}
if (isAssociatedToInterpretations()) {
unsigned int interpCount = getInterpretationCount();
for (unsigned int i = 0; i < interpCount; ++i) {
RESQML2_NS::AbstractFeatureInterpretation* interp = getRepository()->getDataObjectByUuid<AbstractFeatureInterpretation>(getInterpretationUuidFromIndex(i));
if (interp == nullptr) {
throw logic_error("The referenced interpretation is either not a resqml grid interpretation or it is partial and not implemented yet");
}
getRepository()->addRelationship(this, interp);
}
}
}
void GridConnectionSetRepresentation::setCellIndexPairs(ULONG64 cellIndexPairCount, ULONG64 * cellIndexPair, ULONG64 cellIndexPairNullValue, COMMON_NS::AbstractHdfProxy * proxy, unsigned short gridIndexPairNullValue, unsigned short * gridIndexPair)
{
if (cellIndexPairNullValue > static_cast<ULONG64>((std::numeric_limits<LONG64>::max)())) {
throw std::invalid_argument("The XML null value cannot be greater than a 64 bits signed integer cause of gsoap mappings");
}
if (proxy == nullptr) {
proxy = getRepository()->getDefaultHdfProxy();
if (proxy == nullptr) {
throw std::invalid_argument("A (default) HDF Proxy must be provided.");
}
}
const std::string uuid = getUuid();
setCellIndexPairsUsingExistingDataset(cellIndexPairCount, "/RESQML/" + uuid + "/CellIndexPairs", cellIndexPairNullValue, proxy, gridIndexPairNullValue, gridIndexPair != nullptr ? "/RESQML/" + getUuid() + "/GridIndexPairs" : "");
// ************ HDF ************
hsize_t numValues[] = { cellIndexPairCount, 2 };
proxy->writeArrayNd(uuid, "CellIndexPairs", H5T_NATIVE_ULLONG, cellIndexPair, numValues, 2);
if (gridIndexPair != nullptr) {
proxy->writeArrayNd(uuid, "GridIndexPairs", H5T_NATIVE_USHORT, gridIndexPair, numValues, 2);
}
}
ULONG64 GridConnectionSetRepresentation::getXyzPointCountOfPatch(const unsigned int &) const
{
throw logic_error("Not implemented yet");
}
void GridConnectionSetRepresentation::getXyzPointsOfPatch(const unsigned int &, double *) const
{
throw logic_error("Not implemented yet");
}
AbstractFeatureInterpretation * GridConnectionSetRepresentation::getInterpretationFromIndex(const unsigned int & interpretationIndex) const
{
return static_cast<AbstractFeatureInterpretation*>(repository->getDataObjectByUuid(getInterpretationUuidFromIndex(interpretationIndex)));
}
AbstractGridRepresentation* GridConnectionSetRepresentation::getSupportingGridRepresentation(unsigned int index) const
{
return static_cast<AbstractGridRepresentation*>(repository->getDataObjectByUuid(getSupportingGridRepresentationUuid(index)));
}
std::string GridConnectionSetRepresentation::getSupportingGridRepresentationUuid(unsigned int index) const
{
return getSupportingGridRepresentationDor(index)->UUID;
}
std::string GridConnectionSetRepresentation::getSupportingGridRepresentationTitle(unsigned int index) const
{
return getSupportingGridRepresentationDor(index)->Title;
}
std::string GridConnectionSetRepresentation::getSupportingGridRepresentationContentType(unsigned int index) const
{
return getSupportingGridRepresentationDor(index)->ContentType;
}
| 41.790541 | 248 | 0.778981 | untereiner |
7bca72dc0998bc5a01d85613d7788660c4674b5a | 2,835 | cpp | C++ | src/core/contract/Signable.cpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | src/core/contract/Signable.cpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | src/core/contract/Signable.cpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "stdafx.hpp"
#include "opentxs/core/contract/Signable.hpp"
#include "opentxs/core/Data.hpp"
#include "opentxs/core/Identifier.hpp"
#include "opentxs/core/Log.hpp"
namespace opentxs
{
Signable::Signable(const ConstNym& nym)
: alias_()
, id_(Identifier::Factory())
, nym_(nym)
, signatures_()
, version_()
, conditions_()
, lock_()
{
}
Signable::Signable(const ConstNym& nym, const std::uint32_t version)
: alias_()
, id_(Identifier::Factory())
, nym_(nym)
, signatures_()
, version_(version)
, conditions_()
, lock_()
{
}
Signable::Signable(
const ConstNym& nym,
const std::uint32_t version,
const std::string& conditions)
: alias_()
, id_(Identifier::Factory())
, nym_(nym)
, signatures_()
, version_(version)
, conditions_(conditions)
, lock_()
{
}
std::string Signable::Alias() const
{
Lock lock(lock_);
return alias_;
}
bool Signable::CalculateID(const Lock& lock)
{
id_ = Identifier::Factory(GetID(lock));
return true;
}
bool Signable::CheckID(const Lock& lock) const { return (GetID(lock) == id_); }
OTIdentifier Signable::id(const Lock& lock) const
{
OT_ASSERT(verify_write_lock(lock));
return id_;
}
OTIdentifier Signable::ID() const
{
Lock lock(lock_);
return id(lock);
}
ConstNym Signable::Nym() const { return nym_; }
void Signable::SetAlias(const std::string& alias)
{
Lock lock(lock_);
alias_ = alias;
}
const std::string& Signable::Terms() const
{
Lock lock(lock_);
return conditions_;
}
bool Signable::update_signature(const Lock& lock)
{
OT_ASSERT(verify_write_lock(lock));
if (!nym_) {
otErr << __FUNCTION__ << ": Missing nym." << std::endl;
return false;
}
return true;
}
bool Signable::Validate() const
{
Lock lock(lock_);
return validate(lock);
}
bool Signable::verify_write_lock(const Lock& lock) const
{
if (lock.mutex() != &lock_) {
otErr << __FUNCTION__ << ": Incorrect mutex." << std::endl;
return false;
}
if (false == lock.owns_lock()) {
otErr << __FUNCTION__ << ": Lock not owned." << std::endl;
return false;
}
return true;
}
bool Signable::verify_signature(const Lock& lock, const proto::Signature&) const
{
OT_ASSERT(verify_write_lock(lock));
if (!nym_) {
otErr << __FUNCTION__ << ": Missing nym." << std::endl;
return false;
}
return true;
}
const std::uint32_t& Signable::Version() const { return version_; }
} // namespace opentxs
| 18.9 | 80 | 0.635626 | nopdotcom |
7bcc1244e660d129d58a585782226d055037ca59 | 7,386 | cpp | C++ | sdk/cpp/tests/test_crud.cpp | ygorelik/pydk | 42ac7f2b33006c3ea99d07eb9f405346d35c6614 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/cpp/tests/test_crud.cpp | ygorelik/pydk | 42ac7f2b33006c3ea99d07eb9f405346d35c6614 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/cpp/tests/test_crud.cpp | ygorelik/pydk | 42ac7f2b33006c3ea99d07eb9f405346d35c6614 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* ----------------------------------------------------------------
Copyright 2016 Cisco Systems
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 <string.h>
#include <iostream>
#include "netconf_provider.hpp"
#include "crud_service.hpp"
#include "catch.hpp"
#include <ydk_ydktest/openconfig_bgp.hpp>
#include "config.hpp"
using namespace ydk;
using namespace std;
void config_bgp(openconfig_bgp::Bgp* bgp)
{
// Set the Global AS
bgp->global->config->as = 65001;
bgp->global->config->router_id = "1.2.3.4";
auto afi_safi = make_unique<openconfig_bgp::Bgp::Global::AfiSafis::AfiSafi>();
afi_safi->afi_safi_name = "openconfig-bgp-types:L3VPN_IPV4_UNICAST";
afi_safi->config->afi_safi_name = "openconfig-bgp-types:L3VPN_IPV4_UNICAST";
afi_safi->config->enabled = true;
afi_safi->parent = bgp->global->afi_safis.get();
bgp->global->afi_safis->afi_safi.push_back(move(afi_safi));
auto neighbor = make_unique<openconfig_bgp::Bgp::Neighbors::Neighbor>();
neighbor->neighbor_address = "6.7.8.9";
neighbor->config->neighbor_address = "6.7.8.9";
neighbor->config->enabled = true;
neighbor->config->peer_as = 65001;
neighbor->config->local_as = 65001;
neighbor->config->peer_group = "IBGP";
neighbor->config->peer_type = "INTERNAL";
neighbor->parent = bgp->neighbors.get();
bgp->neighbors->neighbor.push_back(move(neighbor));
auto peer_group = make_unique<openconfig_bgp::Bgp::PeerGroups::PeerGroup>();
peer_group->peer_group_name = "IBGP";
peer_group->config->peer_group_name = "IBGP";
peer_group->config->auth_password = "password";
peer_group->config->description = "test description";
peer_group->config->peer_as = 65001;
peer_group->config->local_as = 65001;
peer_group->config->peer_type = "INTERNAL";
peer_group->parent = bgp->peer_groups.get();
bgp->peer_groups->peer_group.push_back(move(peer_group));
}
TEST_CASE("bgp_create_delete")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp);
REQUIRE(reply);
config_bgp(bgp.get());
reply = crud.create(provider, *bgp);
REQUIRE(reply);
}
TEST_CASE("bgp_read_delete")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp_set = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp_set);
REQUIRE(reply);
config_bgp(bgp_set.get());
reply = crud.create(provider, *bgp_set);
REQUIRE(reply);
auto bgp_filter = make_unique<openconfig_bgp::Bgp>();
auto bgp_read = crud.read_config(provider, *bgp_filter);
REQUIRE(bgp_read!=nullptr);
openconfig_bgp::Bgp * bgp_read_ptr = dynamic_cast<openconfig_bgp::Bgp*>(bgp_read.get());
REQUIRE(bgp_read_ptr!=nullptr);
REQUIRE(*(bgp_read_ptr) == *(bgp_set));
CHECK(bgp_set->global->config->as == bgp_read_ptr->global->config->as);
CHECK(bgp_set->neighbors->neighbor[0]->neighbor_address == bgp_read_ptr->neighbors->neighbor[0]->neighbor_address);
CHECK(bgp_set->neighbors->neighbor[0]->config->local_as == bgp_read_ptr->neighbors->neighbor[0]->config->local_as);
CHECK(bgp_set->global->afi_safis->afi_safi[0]->afi_safi_name == bgp_read_ptr->global->afi_safis->afi_safi[0]->afi_safi_name);
CHECK(bgp_set->global->afi_safis->afi_safi[0]->config->afi_safi_name == bgp_read_ptr->global->afi_safis->afi_safi[0]->config->afi_safi_name);
reply = reply && (bgp_set->global->afi_safis->afi_safi[0]->config->enabled == bgp_read_ptr->global->afi_safis->afi_safi[0]->config->enabled);
REQUIRE(reply);
cout<<*bgp_set<<endl<<endl;
cout<<*bgp_read_ptr<<endl;
}
TEST_CASE("bgp_update_delete")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp);
REQUIRE(reply);
config_bgp(bgp.get());
reply = crud.create(provider, *bgp);
REQUIRE(reply);
auto bgp_update = make_unique<openconfig_bgp::Bgp>();
bgp_update->global->config->as = 65210;
reply = crud.update(provider, *bgp_update);
REQUIRE(reply);
}
TEST_CASE("bgp_set_leaf")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp);
REQUIRE(reply);
bgp->global->config->as = 65210;
reply = crud.update(provider, *bgp);
REQUIRE(reply);
}
TEST_CASE("bgp_read_create")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp_set = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp_set);
REQUIRE(reply);
bgp_set->global->config->as = 65001;
bgp_set->global->config->router_id = "1.2.3.4";
reply = crud.create(provider, *bgp_set);
REQUIRE(reply);
auto bgp_filter = make_unique<openconfig_bgp::Bgp>();
auto bgp_read = crud.read_config(provider, *bgp_filter);
REQUIRE(bgp_read!=nullptr);
openconfig_bgp::Bgp * bgp_read_ptr = dynamic_cast<openconfig_bgp::Bgp*>(bgp_read.get());
REQUIRE(bgp_read_ptr!=nullptr);
REQUIRE(*(bgp_read_ptr) == *(bgp_set));
bgp_read_ptr->global->config->as = 65210;
bgp_read_ptr->global->config->router_id = "6.7.8.9";
reply = crud.update(provider, *bgp_read_ptr);
REQUIRE(reply);
}
TEST_CASE("bgp_read_non_top")
{
ydk::path::Repository repo{TEST_HOME};
NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
CrudService crud{};
auto bgp_set = make_unique<openconfig_bgp::Bgp>();
bool reply = crud.delete_(provider, *bgp_set);
REQUIRE(reply);
bgp_set->global->config->as = 65001;
bgp_set->global->config->router_id = "1.2.3.4";
auto d = make_unique<openconfig_bgp::Bgp::Neighbors::Neighbor>();
d->neighbor_address = "1.2.3.4";
d->config->neighbor_address = "1.2.3.4";
d->parent = bgp_set->neighbors.get();
bgp_set->neighbors->neighbor.push_back(move(d));
auto q = make_unique<openconfig_bgp::Bgp::Neighbors::Neighbor>();
q->neighbor_address = "1.2.3.5";
q->config->neighbor_address = "1.2.3.5";
q->parent = bgp_set->neighbors.get();
bgp_set->neighbors->neighbor.push_back(move(q));
reply = crud.create(provider, *bgp_set);
REQUIRE(reply);
auto bgp_filter = make_unique<openconfig_bgp::Bgp>();
auto bgp_read = crud.read_config(provider, *(bgp_filter));
REQUIRE(bgp_read!=nullptr);
openconfig_bgp::Bgp * bgp_read_ptr = dynamic_cast<openconfig_bgp::Bgp*>(bgp_read.get());
REQUIRE(bgp_read_ptr!=nullptr);
cout<<*bgp_set<<endl<<endl;
cout<<*bgp_read_ptr<<endl;
REQUIRE(*(bgp_read_ptr) == *(bgp_set));
}
| 34.194444 | 143 | 0.710804 | ygorelik |
7bceb4b4391f4d47a51fa2ffaa23871c2b0e0154 | 1,251 | cpp | C++ | code/test2/3.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | 8 | 2022-03-13T10:25:33.000Z | 2022-03-30T08:26:00.000Z | code/test2/3.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | null | null | null | code/test2/3.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | 2 | 2022-03-20T12:09:52.000Z | 2022-03-21T03:43:01.000Z | #include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<string> vec;
void reload(string str){
for(int i = 0 ; i < str.size(); i++){
if(!isdigit(str[i])) vec.push_back(str.substr(i,1));
else{
int k = i;
while(k < str.size() && isdigit(str[k])){
k++;
}
vec.push_back(str.substr(i,k-i));
i = k - 1;
}
}
}
vector<int> conquer(int le,int ri){
if(le == ri){
vector<int> ret;
ret.push_back(stoi(vec[le]));
return ret;
}
vector<int> ret;
for(auto i = le + 1; i < ri; i+=2){
auto ans_le = conquer(le,i - 1);
auto ans_ri = conquer(i + 1, ri);
// i is '+' || '-' || '*'
for(auto l :ans_le){
for (auto r :ans_ri){
if(vec[i] == "+") ret.push_back(l+r);
else if (vec[i] == "-") ret.push_back(l-r);
else if (vec[i] == "*") ret.push_back(l*r);
}
}
}
return ret;
}
int main(){
string str;
cin >> str;
reload(str);
auto ret = conquer(0,vec.size()-1);
sort(ret.begin(),ret.end());
for(auto re : ret){
cout << re << endl;
}
return 0;
} | 23.603774 | 60 | 0.446843 | Bc-Gg |
7bd08ac1997b871c58ceed62d3596283bf8e1709 | 2,548 | cpp | C++ | core/stream/MediaClientSocketStream.cpp | fritzprix/MediaPipe | b52806abeb905efef3341244cdf1b9969c773a87 | [
"BSD-2-Clause"
] | 1 | 2016-03-18T11:33:51.000Z | 2016-03-18T11:33:51.000Z | core/stream/MediaClientSocketStream.cpp | fritzprix/MediaPipe | b52806abeb905efef3341244cdf1b9969c773a87 | [
"BSD-2-Clause"
] | null | null | null | core/stream/MediaClientSocketStream.cpp | fritzprix/MediaPipe | b52806abeb905efef3341244cdf1b9969c773a87 | [
"BSD-2-Clause"
] | 1 | 2022-02-08T05:11:20.000Z | 2022-02-08T05:11:20.000Z | /*
* MediaClientSocketStream.cpp
*
* Created on: Mar 24, 2016
* Author: innocentevil
*/
#include "MediaClientSocketStream.h"
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
static size_t READOUT_BUFFER_SIZE = 16;
namespace MediaPipe {
MediaClientSocketStream::MediaClientSocketStream(const char* host, int port) {
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
assert(!(sock_fd < 0));
struct hostent* resolved_host = gethostbyname(host);
assert(resolved_host);
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
::memcpy(&dest_addr.sin_addr,resolved_host->h_addr,sizeof(dest_addr.sin_addr));
}
MediaClientSocketStream::MediaClientSocketStream(int port)
{
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
assert(!(sock_fd < 0));
// setup loopback address
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
dest_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
}
MediaClientSocketStream::~MediaClientSocketStream() {
this->close();
}
int MediaClientSocketStream::open(void) {
assert(!(sock_fd < 0));
int res = connect(sock_fd, (const sockaddr*) &dest_addr, sizeof(sockaddr_in));
assert(!(res < 0));
return res;
}
ssize_t MediaClientSocketStream::read(void* rb, size_t sz) const {
assert(!(sock_fd < 0));
return recv(sock_fd, rb, sz,0);
}
uint8_t MediaClientSocketStream::read() const {
assert(!(sock_fd < 0));
uint8_t c = 0;
recv(sock_fd,&c,sizeof(uint8_t),0);
return c;
}
ssize_t MediaClientSocketStream::write(const void* wb, size_t sz) {
assert(!(sock_fd < 0));
return send(sock_fd, wb, sz, 0);
}
ssize_t MediaClientSocketStream::write(const uint8_t c) {
assert(!(sock_fd < 0));
return send(sock_fd, &c, sizeof(uint8_t),0);
}
ssize_t MediaClientSocketStream::skip(size_t sz) const
{
assert((sz > 0) && !(sock_fd < 0));
uint8_t buffer[READOUT_BUFFER_SIZE];
size_t res, rsz = sz;
while(rsz > READOUT_BUFFER_SIZE)
{
if((res = recv(sock_fd, buffer, READOUT_BUFFER_SIZE, 0)) < 0)
return res;
rsz -= res;
}
if((res = recv(sock_fd, buffer,rsz, 0)) < 0)
return res;
rsz -= res;
return (sz - rsz);
}
int MediaClientSocketStream::close() {
if(sock_fd < 0)
return EXIT_FAILURE;
::close(sock_fd);
sock_fd = -1;
return EXIT_SUCCESS;
}
} /* namespace MediaPipe */
| 22.156522 | 80 | 0.707221 | fritzprix |
7bd1cfc86febc7e5396c15b3672edf01a9161a05 | 719 | hpp | C++ | compilax/project_env.hpp | deqyra/CompilaX | a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf | [
"MIT"
] | null | null | null | compilax/project_env.hpp | deqyra/CompilaX | a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf | [
"MIT"
] | null | null | null | compilax/project_env.hpp | deqyra/CompilaX | a7ce9effdaf607bb1632ca39cb30b8c7ace83dbf | [
"MIT"
] | null | null | null | /* // \\
// \\
// \\
//WARNING\\
// \\
=============
DO NOT edit project_env.hpp, or your changes
will be OVERWRITTEN at the next run of CMake.
Instead, edit config/project_env.config.hpp.
*/
#ifndef RENDERBOI__PROJECT_ENV_HPP
#define RENDERBOI__PROJECT_ENV_HPP
#define PROJECT_NAME "CompilaX"
#define PROJECT_VERSION "1.0"
#define COPYRIGHT_NOTICE "2021 © François Brachais <deqyra@gmail.com>"
#define MIT_LICENSE_NOTICE "This software and its source code are subject to the "\
"MIT license.\nSee file LICENSE.md at https://github.com/deqyra/CompilaX. "
#define GL_CONTEXT_VERSION_MAJOR
#define GL_CONTEXT_VERSION_MINOR
#endif//RENDERBOI__PROJECT_ENV_HPP
| 28.76 | 83 | 0.69541 | deqyra |
7bd4b729890d17a0f9f607d9ae876845b809829d | 881 | cpp | C++ | contests/Codeforces Round #613 Div 2/Just_eat_it.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | 2 | 2020-08-27T18:21:04.000Z | 2020-08-30T13:24:39.000Z | contests/Codeforces Round #613 Div 2/Just_eat_it.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | null | null | null | contests/Codeforces Round #613 Div 2/Just_eat_it.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | null | null | null | // https://codeforces.com/contest/1285/problem/B
/**
* Idea:
* if any of the prefix-sum or suffix-sum is found to be non-positive,
* we can simply get rid of the reducing prefix/suffix(negative) to get a value
* that is greater(or equal) than the sum of all elements
*
*/
#include <iostream>
#include <vector>
#include <climits>
typedef long long ll;
using namespace std;
bool solve(vector<ll>& arr)
{
int n = int(arr.size());
ll sum = 0LL;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
if (sum <= 0)
return false;
}
sum = 0LL;
for (int i = n - 1; i >= 0; --i)
{
sum += arr[i];
if (sum <= 0)
return false;
}
return true;
}
int main()
{
int tc;
cin >> tc;
while (tc--)
{
ll n;
cin >> n;
vector<ll> arr(n);
for (int i = 0; i < n; ++i)
cin >> arr[i];
cout << (solve(arr) ? "Yes" : "No") << endl;
}
return 0;
} | 14.209677 | 81 | 0.557321 | Razdeep |
7bd5d27e7e74782ea76332989b3d7f1c904558e9 | 7,959 | cpp | C++ | gtsam/sfm/tests/testSfmData.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 1 | 2022-03-04T07:01:48.000Z | 2022-03-04T07:01:48.000Z | gtsam/sfm/tests/testSfmData.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | null | null | null | gtsam/sfm/tests/testSfmData.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 1 | 2022-03-21T06:58:34.000Z | 2022-03-21T06:58:34.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file TestSfmData.cpp
* @date January 2022
* @author Frank dellaert
* @brief tests for SfmData class and associated utilites
*/
#include <CppUnitLite/TestHarness.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/sfm/SfmData.h>
using namespace std;
using namespace gtsam;
using gtsam::symbol_shorthand::P;
namespace gtsam {
GTSAM_EXPORT std::string createRewrittenFileName(const std::string& name);
GTSAM_EXPORT std::string findExampleDataFile(const std::string& name);
} // namespace gtsam
/* ************************************************************************* */
TEST(dataSet, Balbianello) {
// The structure where we will save the SfM data
const string filename = findExampleDataFile("Balbianello");
SfmData sfmData = SfmData::FromBundlerFile(filename);
// Check number of things
EXPECT_LONGS_EQUAL(5, sfmData.numberCameras());
EXPECT_LONGS_EQUAL(544, sfmData.numberTracks());
const SfmTrack& track0 = sfmData.tracks[0];
EXPECT_LONGS_EQUAL(3, track0.numberMeasurements());
// Check projection of a given point
EXPECT_LONGS_EQUAL(0, track0.measurements[0].first);
const SfmCamera& camera0 = sfmData.cameras[0];
Point2 expected = camera0.project(track0.p),
actual = track0.measurements[0].second;
EXPECT(assert_equal(expected, actual, 1));
// We share *one* noiseModel between all projection factors
auto model = noiseModel::Isotropic::Sigma(2, 1.0); // one pixel in u and v
// Convert to NonlinearFactorGraph
NonlinearFactorGraph graph = sfmData.sfmFactorGraph(model);
EXPECT_LONGS_EQUAL(1419, graph.size()); // regression
// Get initial estimate
Values values = initialCamerasAndPointsEstimate(sfmData);
EXPECT_LONGS_EQUAL(549, values.size()); // regression
}
/* ************************************************************************* */
TEST(dataSet, readBAL_Dubrovnik) {
// The structure where we will save the SfM data
const string filename = findExampleDataFile("dubrovnik-3-7-pre");
SfmData sfmData = SfmData::FromBalFile(filename);
// Check number of things
EXPECT_LONGS_EQUAL(3, sfmData.numberCameras());
EXPECT_LONGS_EQUAL(7, sfmData.numberTracks());
const SfmTrack& track0 = sfmData.tracks[0];
EXPECT_LONGS_EQUAL(3, track0.numberMeasurements());
// Check projection of a given point
EXPECT_LONGS_EQUAL(0, track0.measurements[0].first);
const SfmCamera& camera0 = sfmData.cameras[0];
Point2 expected = camera0.project(track0.p),
actual = track0.measurements[0].second;
EXPECT(assert_equal(expected, actual, 12));
}
/* ************************************************************************* */
TEST(dataSet, openGL2gtsam) {
Vector3 rotVec(0.2, 0.7, 1.1);
Rot3 R = Rot3::Expmap(rotVec);
Point3 t = Point3(0.0, 0.0, 0.0);
Pose3 poseGTSAM = Pose3(R, t);
Pose3 expected = openGL2gtsam(R, t.x(), t.y(), t.z());
Point3 r1 = R.r1(), r2 = R.r2(), r3 = R.r3(); // columns!
Rot3 cRw(r1.x(), r2.x(), r3.x(), -r1.y(), -r2.y(), -r3.y(), -r1.z(), -r2.z(),
-r3.z());
Rot3 wRc = cRw.inverse();
Pose3 actual = Pose3(wRc, t);
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST(dataSet, gtsam2openGL) {
Vector3 rotVec(0.2, 0.7, 1.1);
Rot3 R = Rot3::Expmap(rotVec);
Point3 t = Point3(1.0, 20.0, 10.0);
Pose3 actual = Pose3(R, t);
Pose3 poseGTSAM = openGL2gtsam(R, t.x(), t.y(), t.z());
Pose3 expected = gtsam2openGL(poseGTSAM);
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST(dataSet, writeBAL_Dubrovnik) {
const string filenameToRead = findExampleDataFile("dubrovnik-3-7-pre");
SfmData readData = SfmData::FromBalFile(filenameToRead);
// Write readData to file filenameToWrite
const string filenameToWrite = createRewrittenFileName(filenameToRead);
CHECK(writeBAL(filenameToWrite, readData));
// Read what we wrote
SfmData writtenData = SfmData::FromBalFile(filenameToWrite);
// Check that what we read is the same as what we wrote
EXPECT_LONGS_EQUAL(readData.numberCameras(), writtenData.numberCameras());
EXPECT_LONGS_EQUAL(readData.numberTracks(), writtenData.numberTracks());
for (size_t i = 0; i < readData.numberCameras(); i++) {
PinholeCamera<Cal3Bundler> expectedCamera = writtenData.cameras[i];
PinholeCamera<Cal3Bundler> actualCamera = readData.cameras[i];
EXPECT(assert_equal(expectedCamera, actualCamera));
}
for (size_t j = 0; j < readData.numberTracks(); j++) {
// check point
SfmTrack expectedTrack = writtenData.tracks[j];
SfmTrack actualTrack = readData.tracks[j];
Point3 expectedPoint = expectedTrack.p;
Point3 actualPoint = actualTrack.p;
EXPECT(assert_equal(expectedPoint, actualPoint));
// check rgb
Point3 expectedRGB =
Point3(expectedTrack.r, expectedTrack.g, expectedTrack.b);
Point3 actualRGB = Point3(actualTrack.r, actualTrack.g, actualTrack.b);
EXPECT(assert_equal(expectedRGB, actualRGB));
// check measurements
for (size_t k = 0; k < actualTrack.numberMeasurements(); k++) {
EXPECT_LONGS_EQUAL(expectedTrack.measurements[k].first,
actualTrack.measurements[k].first);
EXPECT(assert_equal(expectedTrack.measurements[k].second,
actualTrack.measurements[k].second));
}
}
}
/* ************************************************************************* */
TEST(dataSet, writeBALfromValues_Dubrovnik) {
const string filenameToRead = findExampleDataFile("dubrovnik-3-7-pre");
SfmData readData = SfmData::FromBalFile(filenameToRead);
Pose3 poseChange =
Pose3(Rot3::Ypr(-M_PI / 10, 0., -M_PI / 10), Point3(0.3, 0.1, 0.3));
Values values;
for (size_t i = 0; i < readData.numberCameras(); i++) { // for each camera
Pose3 pose = poseChange.compose(readData.cameras[i].pose());
values.insert(i, pose);
}
for (size_t j = 0; j < readData.numberTracks(); j++) { // for each point
Point3 point = poseChange.transformFrom(readData.tracks[j].p);
values.insert(P(j), point);
}
// Write values and readData to a file
const string filenameToWrite = createRewrittenFileName(filenameToRead);
writeBALfromValues(filenameToWrite, readData, values);
// Read the file we wrote
SfmData writtenData = SfmData::FromBalFile(filenameToWrite);
// Check that the reprojection errors are the same and the poses are correct
// Check number of things
EXPECT_LONGS_EQUAL(3, writtenData.numberCameras());
EXPECT_LONGS_EQUAL(7, writtenData.numberTracks());
const SfmTrack& track0 = writtenData.tracks[0];
EXPECT_LONGS_EQUAL(3, track0.numberMeasurements());
// Check projection of a given point
EXPECT_LONGS_EQUAL(0, track0.measurements[0].first);
const SfmCamera& camera0 = writtenData.cameras[0];
Point2 expected = camera0.project(track0.p),
actual = track0.measurements[0].second;
EXPECT(assert_equal(expected, actual, 12));
Pose3 expectedPose = camera0.pose();
Pose3 actualPose = values.at<Pose3>(0);
EXPECT(assert_equal(expectedPose, actualPose, 1e-7));
Point3 expectedPoint = track0.p;
Point3 actualPoint = values.at<Point3>(P(0));
EXPECT(assert_equal(expectedPoint, actualPoint, 1e-6));
}
/* ************************************************************************* */
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */
| 37.018605 | 80 | 0.64204 | h-rover |
7bd95920884728e3b7eac3b62bb72ebae7d25242 | 5,652 | cpp | C++ | svntrunk/src/pk/globject/test/iv00.cpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/pk/globject/test/iv00.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/pk/globject/test/iv00.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* 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.
*
* 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 HOLDER 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.
*/
#define RUNTIME_TYPE_CHECKING // FOR GLOBJECT STUFF
//#include <pk/mpi.hpp>
//#include <pk/reactor.hpp>
#include <pk/platform.hpp>
#include <pk/fxlogger.hpp>
//#include "pkdebug.hpp"
#include <pk/globject.hpp>
class MyThing
{
public:
MyThing( int t )
{
BegLogLine(PKFXLOG_GLOBJECT)
<< " MyThing Constructed "
<< EndLogLine;
x = t;
}
int x, y, z;
};
// Declare the globalized type to the globject system.
///GLOBJECT_TYPE_DCL(MyThing);
GCM_TypeFreeBase * GCM< MyThing >::SingletonPtr = NULL; //A98 required NULL def.
static int
MainBackEnd(void *Msg )
{
GlobjectReference *ref = (GlobjectReference *) Msg;
BegLogLine( PKFXLOG_GLOBJECT )
<< " MainBackEnd Doing Fetch: "
<< " ref->HomeMemory "
<< ref->HomeMemory
<< " ref->TableIndex "
<< ref->TableKey
<< EndLogLine;
MyThing X = GCM<MyThing>::Fetch( *ref );
BegLogLine( PKFXLOG_GLOBJECT )
<< " MainBackEnd Done Fetch: "
<< " X.x "
<< X.x
<< " X.y "
<< X.y
<< " X.z "
<< X.z
<< EndLogLine;
return(0);
}
PkMain(int argc, char **argv, char **envp)
{
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " Before: Instantiation, assignment f X "
<< EndLogLine;
MyThing X( 142 );
X.x = 99; X.y = 999; X.z = 9999;
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " After: Instantiation, assignment X "
<< EndLogLine;
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " Before: X Enroll "
<< EndLogLine;
GlobjectReference Xref = GCM<MyThing>::Enroll( &X );
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " After: X Enroll "
<< EndLogLine;
for( int j = 0; j < Platform::Topology::GetAddressSpaceCount(); j++ )
{
X.z = j;
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " Before Trigger of Globject Fetch to be done on "
<< j
<< EndLogLine;
////////PkActiveMsgSubSys::Trigger( j, MainBackEnd, (void *) &Xref, sizeof( Xref ) );
Platform::Reactor::Trigger( j, MainBackEnd, (void *) &Xref, sizeof( Xref ) );
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " After Trigger of Globject Fetch to be done on "
<< j
<< EndLogLine;
sleep(1);
}
for(;;)
{
BegLogLine(PKFXLOG_GLOBJECT)
<< " Main[" << Platform::Topology::GetAddressSpaceId() << "] "
<< " dead waiting "
<< EndLogLine;
sleep(1);
}
return(0);
}
#if 0
void *
PhysicalThreadMain( void * arg )
{
int mpirc;
MPI_Status Status;
for(;;)
{
mpirc = MPI_Recv( RecvBufferSize,
RecvBufferArea,
MPI_CHAR,
MPI_ANY_SOURCE,
MyAddress.MpiType,
MPI_COMM_WORLD,
&Status);
int TrueLen;
MPI_Get_count( &Status, MPI_CHAR, &TrueLen );
}
return( NULL );
}
#endif
#if 0
ObjType *operator-> ()
{
if( CachedInst == NULL )
{
if( mRef.HomeMemory == ThisMemory() )
{
assert( mRef.UniqueNumber == ((Inst *) mRef)->Address.UniqueNumber );
CachedInst = (ObjType *) mRef.Address;
}
else
{
assert(0);
//static Cashed[1024];
if( 0 ) //object is still refed in cached, reuse )
{
//CachedInst = Cashed. Address;
}
else
{
//CachedInst = new Inst;
/MPI_Send( )
//MPI_Recv( Inst );
//update Cashe
}
}
}
return( CachedInst );
}
#endif
#if 0
typedef long long UniqueNumberType;
static inline
long long LLTime()
{
timebasestruct_t Now;
read_real_time( &Now, TIMEBASE_SZ );
time_base_to_time( &Now, TIMEBASE_SZ );
long long llNow = (long long)Now.tb_high * (long long)1000000000 + Now.tb_low ;
return( llNow );
}
#endif
| 27.980198 | 118 | 0.595718 | Bhaskers-Blu-Org1 |
7bda53c935b0e4f4ecfc7bd36fb9a8023239cad7 | 19,914 | hpp | C++ | src/common/kmer_iterators.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 16 | 2016-06-07T22:12:02.000Z | 2021-12-15T12:40:52.000Z | src/common/kmer_iterators.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 1 | 2017-11-13T20:59:33.000Z | 2018-12-14T16:40:01.000Z | src/common/kmer_iterators.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 7 | 2016-08-19T21:31:41.000Z | 2021-12-19T14:58:45.000Z | /*
* Copyright 2015 Georgia Institute of Technology
*
* 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.
*/
/**
* @file kmer_iterators.hpp
* @ingroup common
* @author Patrick Flick
* @author Tony Pan <tpan7@gatech.edu>
* @brief iterator to generate kmers from a sequence of characters in alphabet (DNA, etc)
* @details include support for Kmer and reverse Kmer (for reverse complement)
*
* These classes DO NOT perform translation from ASCII to selected alphabet.
* To handle that, use "bliss::utils::ASCII2<ALPHABET>" functor with a transform iterator
* e.g. bliss::iterator::transform_iterator, or boost's transform iterator
* then set the transform iterator as base iterator type for kmerGenerationIterators below.
*/
#ifndef BLISS_COMMON_KMER_ITERATORS_H
#define BLISS_COMMON_KMER_ITERATORS_H
// C std lib includes:
#include <cstdlib>
// C++ STL includes:
#include <iterator>
#include <type_traits>
// own includes
#include "common/base_types.hpp"
#include "common/padding.hpp"
#include "common/kmer.hpp"
#include "iterators/sliding_window_iterator.hpp"
// TODO: Need convenience functions to make start and end iterators (the true/false flags are not easy to remember.)
// TODO: Need convenience typedef to allow for reverse complement generation.
namespace bliss
{
namespace common
{
/**
* @brief The sliding window operator for k-mer generation from character data.
*
* @tparam BaseIterator Type of the underlying base iterator, which returns
* characters.
* @tparam Kmer The k-mer type, must be of type bliss::Kmer
*/
template <class BaseIterator, class Kmer>
class KmerSlidingWindow {};
template <typename BaseIterator, unsigned int KMER_SIZE,
typename ALPHABET, typename word_type>
class KmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> >
{
public:
/// The Kmer type (same as the `value_type` of this iterator)
typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type;
typedef BaseIterator base_iterator_type;
/// The value_type of the underlying iterator
typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;
/**
* @brief Initializes the sliding window.
*
* @param it[in|out] The current base iterator position. This will be set to
* the last read position.
*/
inline void init(BaseIterator& it)
{
kmer.fillFromChars(it, true);
}
/**
* @brief Slides the window by one character taken from the given iterator.
*
* This will read the current character of the iterator and then advance the
* iterator by one.
*
* @param it[in|out] The underlying iterator position, this will be read
* and then advanced.
*/
inline void next(BaseIterator& it)
{
kmer.nextFromChar(*it);
++it;
}
/**
* @brief Returns the value of the current sliding window, i.e., the current
* k-mer value.
*
* @return The current k-mer value.
*/
inline kmer_type getValue()
{
// return a copy of the current kmer
return this->kmer;
}
private:
/// The kmer buffer (i.e. the window of the sliding window)
kmer_type kmer;
};
/**
* @brief The sliding window operator for reverse k-mer generation from character data.
* @note to create reverse complement, use a transform iterator to change the char to complement
*
* @tparam BaseIterator Type of the underlying base iterator, which returns
* characters.
* @tparam Kmer The k-mer type, must be of type bliss::Kmer
*/
template <class BaseIterator, class Kmer>
class ReverseKmerSlidingWindow {};
template <typename BaseIterator, unsigned int KMER_SIZE,
typename ALPHABET, typename word_type>
class ReverseKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> >
{
public:
/// The Kmer type (same as the `value_type` of this iterator)
typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type;
typedef BaseIterator base_iterator_type;
/// The value_type of the underlying iterator
typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;
/**
* @brief Initializes the sliding window.
*
* @param it[in|out] The current base iterator position. This will be set to
* the last read position.
*/
inline void init(BaseIterator& it)
{
kmer.fillReverseFromChars(it, true);
}
/**
* @brief Slides the window by one character taken from the given iterator.
*
* This will read the current character of the iterator and then advance the
* iterator by one.
*
* @param it[in|out] The underlying iterator position, this will be read
* and then advanced.
*/
inline void next(BaseIterator& it)
{
kmer.nextReverseFromChar(*it);
++it;
}
/**
* @brief Returns the value of the current sliding window, i.e., the current
* k-mer value.
*
* @return The current k-mer value.
*/
inline kmer_type getValue()
{
// return a copy of the current kmer
return this->kmer;
}
private:
/// The kmer buffer (i.e. the window of the sliding window)
kmer_type kmer;
};
/**
* @brief Iterator that generates k-mers from character data.
*
* @tparam BaseIterator The underlying iterator of characters. E.g. a
* std::string::iterator. Any iterator yielding
* `char` works.
* @tparam Kmer The type of the Kmer, this has to be of type
* bliss::Kmer.
*/
template <class SlidingWindow>
class KmerGenerationIteratorBase
: public iterator::sliding_window_iterator<typename SlidingWindow::base_iterator_type, SlidingWindow >
{
protected:
typedef typename SlidingWindow::base_iterator_type BaseIterator;
/// The type of the base class
typedef iterator::sliding_window_iterator<BaseIterator, SlidingWindow >
base_class_t;
/// The difference_type of character offsets
typedef typename std::iterator_traits<base_class_t>::difference_type diff_type;
/// The type of the sliding window.
typedef SlidingWindow functor_t;
public:
/// Default constructor.
KmerGenerationIteratorBase() : base_class_t() {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first character of the
* sequence to be used for generating k-mers.
*/
KmerGenerationIteratorBase(const BaseIterator& baseBegin)
: base_class_t(baseBegin, true) {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first character of the
* sequence to be used for generating k-mers.
* @param initialze_window Whether to read the first `KMER_SIZE` characters
* to initialize the sliding window. This will
* have to be set to `false` for creating
* `end` style iterators which would otherwise
* read past the valid range.
*/
KmerGenerationIteratorBase(const BaseIterator& baseBegin, bool initialize_window)
: base_class_t(baseBegin, initialize_window) {}
protected:
/*****************************
* non public constructors *
*****************************/
// handleing of the `window` object instances is strictly hidden
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first character of the
* sequence to be used for generating k-mers.
* @param window The sliding window object used by the iterator.
*/
KmerGenerationIteratorBase(const BaseIterator& baseBegin, const functor_t& window)
: base_class_t(baseBegin, window, true) {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first character of the
* sequence to be used for generating k-mers.
* @param window The sliding window object used by the iterator.
* @param initialze_window Whether to read the first `KMER_SIZE` characters
* to initialize the sliding window. This will
* have to be set to `false` for creating
* `end` style iterators which would otherwise
* read past the valid range.
*/
KmerGenerationIteratorBase(const BaseIterator& baseBegin, const functor_t& window, bool initialize_window)
: base_class_t(baseBegin, window, initialize_window) {}
};
/// normal KmerGenerationIterator for generating kmers from a sequence of alphabet characters
template <class BaseIterator, class Kmer>
using KmerGenerationIterator = KmerGenerationIteratorBase<KmerSlidingWindow<BaseIterator, Kmer > >;
/// reverse KmerGenerationIterator for generating kmers from a sequence of alphabet characters. can be used for reverse complements.
template <class BaseIterator, class Kmer>
using ReverseKmerGenerationIterator = KmerGenerationIteratorBase<ReverseKmerSlidingWindow<BaseIterator, Kmer > >;
/**
* @brief The sliding window operator for k-mer generation from packed data.
*
* @tparam BaseIterator Type of the underlying base iterator, which returns
* elements of packed data.
* @tparam Kmer The k-mer type, must be of type bliss::Kmer
*/
template <class BaseIterator, class Kmer>
class PackedKmerSlidingWindow {};
template <typename BaseIterator, unsigned int KMER_SIZE,
typename ALPHABET, typename word_type>
class PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> >
{
public:
/// The Kmer type (same as the `value_type` of this iterator)
typedef bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> kmer_type;
/// The value_type of the underlying iterator
typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;
/// The padding traits of the underlying stream
typedef PackingTraits<base_value_type, bliss::common::AlphabetTraits<ALPHABET>::getBitsPerChar()> padtraits;
/**
* @brief Initializes the sliding window.
*
* @tparam offset_t The offset type.
* @param it[in|out] The current base iterator, this will be set
* to the last read position.
* @param offset[in|out] The current bit/character offset in the current position
* of the base iterator. This will be set to the
* position that was read last.
*/
template<typename offset_t>
inline void init(BaseIterator& it, offset_t& offset)
{
// there is no implementation yet to handle the case that the first
// k-mer starts from an offset != 0:
assert(offset == 0);
// fill kmer from the given packed and padded stream
// this leaves the iterator and the offset ON the last read position
// and NOT AFTER this (i.e. NOT on the position to be read NEXT)
offset = kmer.fillFromPackedStream(it, offset, true);
}
/**
* @brief Slides the window by one character, taken from the given iterator.
*
* This will read the current character of the iterator and then increase
* the (iterator, offset) position by one character.
*
* @tparam offset_t The offset type.
* @param it[in|out] The current base iterator, this will be set
* to the next position.
* @param offset[in|out] The current bit/character offset in the current position
* of the base iterator. This will be set to one
* character past the character read.
*/
template<typename offset_t>
inline void next(BaseIterator& it, offset_t& offset)
{
kmer.nextFromPackedStream(it, offset);
}
/**
* @brief Returns the value of the current sliding window, i.e., the current
* k-mer value.
*
* @return The current k-mer value.
*/
inline kmer_type getValue()
{
// return a copy of the current kmer
return this->kmer;
}
/**
* @brief Skips over `advance_by` characters in the current (iterator,
* offset) position.
*
* @tparam offset_t Type of the offset.
* @param it[in|out] The current iterator position. Will be modified to
* the position after skipping `advance_by` chars.
* @param offset The current offset position. Will be modified to
* the position after skipping `advance_by` chars.
* @param advance_by The number of characters to skip.
*/
template<typename offset_t>
// TODO: - [ ] separate offset types
// [ ] FIX: from any starting offset, not only from offset=0
//
void skip(BaseIterator& it, offset_t& offset, offset_t advance_by)
{
// get offset for underlying iterator
offset_t nWords = advance_by / padtraits::chars_per_word;
// get offset for bitwise offset
offset_t bit_offset = advance_by % padtraits::chars_per_word;
bit_offset *= padtraits::bits_per_char;
// add it to the base iterator
std::advance(it, nWords);
offset += bit_offset;
}
private:
/// The kmer buffer (i.e. the window of the sliding window)
kmer_type kmer;
};
/**
* @brief Iterator that generates k-mers from packed data.
*
* @tparam BaseIterator The underlying iterator, which supplies any integer
* type of packed character data.
* @tparam Kmer The type of the Kmer, this has to be of type
* bliss::Kmer.
*/
template <class BaseIterator, class Kmer>
class PackedKmerGenerationIterator {};
// template specialization for bliss::Kmer as kmer type
// The template parameters KMER_SIZE, ALPHABET and word_type are
// set to the appropriate template parameters of bliss::Kmer and do not
// have to be explicitly stated when creating this class.
template <typename BaseIterator, unsigned int KMER_SIZE,
typename ALPHABET, typename word_type>
class PackedKmerGenerationIterator<BaseIterator,
bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> >
: public iterator::one2many_sliding_window_iterator<BaseIterator,
PackedKmerSlidingWindow<BaseIterator,
bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > >
{
protected:
/// The type of the base class
typedef iterator::one2many_sliding_window_iterator<BaseIterator, PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > >
base_class_t;
/// The difference_type of character offsets
typedef typename std::iterator_traits<base_class_t>::difference_type diff_type;
/// The type of the sliding window.
typedef PackedKmerSlidingWindow<BaseIterator, bliss::common::Kmer<KMER_SIZE, ALPHABET, word_type> > functor_t;
public:
/// Default constructor
PackedKmerGenerationIterator() : base_class_t() {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first element of the
* packed and padded sequence to be used for generating
* k-mers.
*/
PackedKmerGenerationIterator(const BaseIterator& baseBegin)
: base_class_t(baseBegin, functor_t()) {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point and advancing
* `char_offset` characters into the underlying sequence.
*
* @param baseBegin An iterator pointing to the first element of the
* packed and padded sequence to be used for generating
* k-mers.
* @param offset A character offset, the constructed iterator is
* advanced by this many positions at construction time.
* This can be used to create the `end` iterator for
* generating sequences.
*/
PackedKmerGenerationIterator(const BaseIterator& baseBegin, diff_type offset)
: base_class_t(baseBegin, functor_t(), offset) {}
protected:
/*****************************
* non public constructors *
*****************************/
// handleing of the `window` object instances is strictly hidden
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point.
*
* @param baseBegin An iterator pointing to the first element of the
* packed and padded sequence to be used for generating
* k-mers.
* @param window The sliding window object used by the iterator.
*/
PackedKmerGenerationIterator(const BaseIterator& baseBegin,
const functor_t& window)
: base_class_t(baseBegin, window) {}
/**
* @brief Constructor for the kmer generation iterator using the underlying
* iterator `baseBegin` as starting point and advancing
* `char_offset` characters into the underlying sequence.
*
* @param baseBegin An iterator pointing to the first element of the
* packed and padded sequence to be used for generating
* k-mers.
* @param offset A character offset, the constructed iterator is
* advanced by this many positions at construction time.
* This can be used to create the `end` iterator for
* generating sequences.
* @param window The sliding window object used by the iterator.
*/
PackedKmerGenerationIterator(const BaseIterator& baseBegin,
const functor_t& window, diff_type offset)
: base_class_t(baseBegin, window, offset) {}
};
} //namespace common
} // namespace bliss
#endif // BLISS_COMMON_KMER_ITERATORS_H
| 39.828 | 162 | 0.638496 | tcpan |
7bdcaaa3422757a0519edafe8464468dacdbe5b7 | 3,162 | cxx | C++ | Hekateros/sw/libhekateros/hekDesc.cxx | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | Hekateros/sw/libhekateros/hekDesc.cxx | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | Hekateros/sw/libhekateros/hekDesc.cxx | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// Package: Hekateros
//
// Library: libhekateros
//
// File: hekDesc.cxx
//
/*! \file
*
* $LastChangedDate: 2014-09-18 16:53:49 -0600 (Thu, 18 Sep 2014) $
* $Rev: 3748 $
*
* \brief Hekateros full description.
*
* \author Robin Knight (robin.knight@roadnarrows.com)
*
* \copyright
* \h_copy 2013-2017. RoadNarrows LLC.\n
* http://www.roadnarrows.com\n
* All Rights Reserved
*/
/*
* @EulaBegin@
*
* Unless otherwise stated explicitly, all materials contained are copyrighted
* and may not be used without RoadNarrows LLC's written consent,
* except as provided in these terms and conditions or in the copyright
* notice (documents and software) or other proprietary notice provided with
* the relevant materials.
*
* IN NO EVENT SHALL THE AUTHOR, ROADNARROWS LLC, OR ANY
* MEMBERS/EMPLOYEES/CONTRACTORS OF ROADNARROWS OR DISTRIBUTORS OF THIS SOFTWARE
* BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE AUTHORS AND ROADNARROWS LLC SPECIFICALLY DISCLAIM ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
* "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* @EulaEnd@
*/
////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string>
#include <vector>
#include "rnr/rnrconfig.h"
#include "rnr/log.h"
#include "Hekateros/hekateros.h"
#include "Hekateros/hekDescArm.h"
#include "Hekateros/hekDescEE.h"
#include "Hekateros/hekDesc.h"
using namespace std;
using namespace hekateros;
void HekDesc::resetDesc()
{
m_descArm.resetDesc();
m_descEE.resetDesc();
m_strFullBrief.clear();
m_bIsDescribed = false;
}
int HekDesc::markAsDescribed()
{
if( !m_descArm.isDescribed() )
{
LOGERROR("Hekateros base description is undefined.");
return -HEK_ECODE_BAD_OP;
}
if( !m_descEE.isDescribed() )
{
LOGERROR("Hekateros end effector description is undefined.");
return -HEK_ECODE_BAD_OP;
}
m_strFullBrief = m_descArm.getProdBrief() +
" with " +
m_descEE.getProdBrief();
m_bIsDescribed = true;
return HEK_OK;
}
bool HekDesc::hasServo(int nServoId)
{
if( m_descArm.hasServo(nServoId) )
{
return true;
}
else if( m_descEE.hasServo(nServoId) )
{
return true;
}
else
{
return false;
}
}
#ifdef RDK_REDO
void hekDesc::setServoOffset(int servoId, int servoOffset) {
m_servoOffsets[servoId] = servoOffset;
}
void hekDesc::setServoLimCW(int servoId, int servoMin) {
m_servosLimCW[servoId] = servoMin;
}
void hekDesc::setServoLimCCW(int servoId, int servoMax) {
m_servosLimCCW[servoId] = servoMax;
}
#endif // RDK_REDO
| 24.703125 | 80 | 0.670778 | roadnarrows-robotics |
7bdf2919746c1ef8a07bf6b606e7bef8996c222e | 4,284 | cpp | C++ | src/texture.cpp | asp437/Garmez | eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26 | [
"MIT"
] | 1 | 2019-10-14T09:16:49.000Z | 2019-10-14T09:16:49.000Z | src/texture.cpp | asp437/Garmez | eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26 | [
"MIT"
] | null | null | null | src/texture.cpp | asp437/Garmez | eeb42cc91eeeea7893af0ce1fd8ccdf1e4af7d26 | [
"MIT"
] | null | null | null | #include <texture.hpp>
#include <glad/glad.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
namespace RGLA {
Texture::~Texture() {
if (_id) {
glDeleteTextures(1, &_id);
}
}
void Texture::BindData() {
RGLA_ENSURE(_data, "Texture data is null");
glGenTextures(1, &_id);
UpdateData();
}
void Texture::UpdateData() {
// TODO: Dynamic source image format detection
glBindTexture(GL_TEXTURE_2D, _id);
if (_channels == 4) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _data);
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, _data);
}
glGenerateMipmap(GL_TEXTURE_2D);
}
void Texture::Use(uint textureUnit) const {
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, _id);
}
void Texture::SetFilteringMode(TextureFilter filter) {
glBindTexture(GL_TEXTURE_2D, _id);
switch (filter) {
case TextureFilter::TF_NEAREST:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case TextureFilter::TF_LINEAR:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
}
Pixel Texture::GetPixel(int x, int y) const {
if (x < 0 || x >= _width || y < 0 || y >= _height) {
throw std::runtime_error("Try to get pixel out of bounds of the texture");
}
uint32* addr = (uint32*)(_data + (x + y * _width) * _channels);
uint32 pixelData = *addr;
switch (_channels) {
case 3:
pixelData = (pixelData & 0xFFFFFF) | 0xFF000000;
return Pixel(pixelData);
case 4:
return Pixel(pixelData);
}
RGLA_ENSURE(false, "Unsupported channels count in GetPixel()");
}
TextureFilter Texture::GetFilteringMode() const {
return TextureFilter::TF_LINEAR; // TODO:
}
FileTexture::FileTexture(const std::string& fileName, bool flipVertical) {
stbi_set_flip_vertically_on_load(flipVertical);
_data = stbi_load(fileName.c_str(), &_width, &_height, &_channels, 0);
if (!_data) {
throw std::runtime_error("Can't load image " + fileName);
}
BindData();
}
FileTexture::~FileTexture() {
if (_data) {
stbi_image_free(_data);
_data = nullptr;
}
}
InMemoryTexture::InMemoryTexture(const int width, const int height, const int channels) {
RGLA_ENSURE(channels == 4, "InMemoryTexture can be only with 4 channels");
_width = width;
_height = height;
_channels = channels;
_data = (unsigned char*) malloc(_width * _height * _channels);
memset(_data, 0x00, _width * _height * _channels);
BindData();
}
InMemoryTexture::InMemoryTexture(const Texture& texture) {
_width = texture.GetWidth();
_height = texture.GetHeight();
_channels = 4;
_data = (unsigned char*) malloc(_width * _height * _channels);
for (int x = 0; x < _width; x++) {
for (int y = 0; y < _height; y++) {
SetPixel(x, y, texture.GetPixel(x, y));
}
}
BindData();
}
InMemoryTexture::~InMemoryTexture() {
free(_data);
}
void InMemoryTexture::SetPixel(int x, int y, Pixel color) {
if (x < 0 || x >= _width || y < 0 || y >= _height) {
throw std::runtime_error("Try to set pixel out of bounds of the texture");
}
uint32* addr = (uint32*)(_data + (x + y * _width) * _channels);
(*addr) = color.data;
}
std::ostream& operator<<(std::ostream& out, const Pixel& pixel) {
out << "(" << (int)pixel.components.r << "," << (int)pixel.components.g << "," << (int)pixel.components.b << "," << (int)pixel.components.a << ")";
return out;
}
}
| 33.46875 | 155 | 0.57493 | asp437 |
7be50ea787e471968b9171387bfb2a4bf10d218b | 8,127 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/nim/project/nimbuildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/nim/project/nimbuildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/nim/project/nimbuildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) Filippo Cucchetto <filippocucchetto@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "nimbuildconfiguration.h"
#include "nimbuildconfigurationwidget.h"
#include "nimcompilerbuildstep.h"
#include "nimproject.h"
#include "nimbuildconfiguration.h"
#include "nimcompilerbuildstep.h"
#include "nimcompilercleanstep.h"
#include "nimproject.h"
#include "../nimconstants.h"
#include <coreplugin/documentmanager.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildinfo.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/buildstep.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectmacroexpander.h>
#include <projectexplorer/target.h>
#include <utils/mimetypes/mimedatabase.h>
#include <utils/qtcassert.h>
using namespace ProjectExplorer;
using namespace Utils;
namespace Nim {
static FileName defaultBuildDirectory(const Kit *k,
const QString &projectFilePath,
const QString &bc,
BuildConfiguration::BuildType buildType)
{
QFileInfo projectFileInfo(projectFilePath);
ProjectMacroExpander expander(projectFilePath, projectFileInfo.baseName(), k, bc, buildType);
QString buildDirectory = expander.expand(Core::DocumentManager::buildDirectory());
if (FileUtils::isAbsolutePath(buildDirectory))
return FileName::fromString(buildDirectory);
auto projectDir = FileName::fromString(projectFileInfo.absoluteDir().absolutePath());
auto result = projectDir.appendPath(buildDirectory);
return result;
}
NimBuildConfiguration::NimBuildConfiguration(Target *target)
: BuildConfiguration(target, Constants::C_NIMBUILDCONFIGURATION_ID)
{
}
void NimBuildConfiguration::initialize(const BuildInfo *info)
{
BuildConfiguration::initialize(info);
auto project = qobject_cast<NimProject *>(target()->project());
QTC_ASSERT(project, return);
// Create the build configuration and initialize it from build info
setBuildDirectory(defaultBuildDirectory(target()->kit(),
project->projectFilePath().toString(),
info->displayName,
info->buildType));
// Add nim compiler build step
{
BuildStepList *buildSteps = stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
auto nimCompilerBuildStep = new NimCompilerBuildStep(buildSteps);
NimCompilerBuildStep::DefaultBuildOptions defaultOption;
switch (info->buildType) {
case BuildConfiguration::Release:
defaultOption = NimCompilerBuildStep::DefaultBuildOptions::Release;
break;
case BuildConfiguration::Debug:
defaultOption = NimCompilerBuildStep::DefaultBuildOptions::Debug;
break;
default:
defaultOption = NimCompilerBuildStep::DefaultBuildOptions::Empty;
break;
}
nimCompilerBuildStep->setDefaultCompilerOptions(defaultOption);
Utils::FileNameList nimFiles = project->nimFiles();
if (!nimFiles.isEmpty())
nimCompilerBuildStep->setTargetNimFile(nimFiles.first());
buildSteps->appendStep(nimCompilerBuildStep);
}
// Add clean step
{
BuildStepList *cleanSteps = stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
cleanSteps->appendStep(new NimCompilerCleanStep(cleanSteps));
}
}
NamedWidget *NimBuildConfiguration::createConfigWidget()
{
return new NimBuildConfigurationWidget(this);
}
BuildConfiguration::BuildType NimBuildConfiguration::buildType() const
{
return BuildConfiguration::Unknown;
}
bool NimBuildConfiguration::fromMap(const QVariantMap &map)
{
if (!BuildConfiguration::fromMap(map))
return false;
const QString displayName = map[Constants::C_NIMBUILDCONFIGURATION_DISPLAY_KEY].toString();
const QString buildDirectory = map[Constants::C_NIMBUILDCONFIGURATION_BUILDDIRECTORY_KEY].toString();
setDisplayName(displayName);
setBuildDirectory(FileName::fromString(buildDirectory));
return true;
}
QVariantMap NimBuildConfiguration::toMap() const
{
QVariantMap result = BuildConfiguration::toMap();
result[Constants::C_NIMBUILDCONFIGURATION_DISPLAY_KEY] = displayName();
result[Constants::C_NIMBUILDCONFIGURATION_BUILDDIRECTORY_KEY] = buildDirectory().toString();
return result;
}
FileName NimBuildConfiguration::cacheDirectory() const
{
return buildDirectory().appendPath(QStringLiteral("nimcache"));
}
FileName NimBuildConfiguration::outFilePath() const
{
const NimCompilerBuildStep *step = nimCompilerBuildStep();
QTC_ASSERT(step, return FileName());
return step->outFilePath();
}
const NimCompilerBuildStep *NimBuildConfiguration::nimCompilerBuildStep() const
{
BuildStepList *steps = stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
QTC_ASSERT(steps, return nullptr);
foreach (BuildStep *step, steps->steps())
if (step->id() == Constants::C_NIMCOMPILERBUILDSTEP_ID)
return qobject_cast<NimCompilerBuildStep *>(step);
return nullptr;
}
NimBuildConfigurationFactory::NimBuildConfigurationFactory()
{
registerBuildConfiguration<NimBuildConfiguration>(Constants::C_NIMBUILDCONFIGURATION_ID);
setSupportedProjectType(Constants::C_NIMPROJECT_ID);
setSupportedProjectMimeTypeName(Constants::C_NIM_PROJECT_MIMETYPE);
}
QList<BuildInfo *> NimBuildConfigurationFactory::availableBuilds(const Target *parent) const
{
// Retrieve the project path
auto project = qobject_cast<NimProject *>(parent->project());
QTC_ASSERT(project, return {});
// Create the build info
BuildInfo *info = createBuildInfo(parent->kit(), project->projectFilePath().toString(),
BuildConfiguration::Debug);
info->displayName.clear(); // ask for a name
info->buildDirectory.clear(); // This depends on the displayName
return {info};
}
QList<BuildInfo *> NimBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
{
BuildInfo *debug = createBuildInfo(k, projectPath, BuildConfiguration::Debug);
BuildInfo *release = createBuildInfo(k, projectPath, BuildConfiguration::Release);
return {debug, release};
}
BuildInfo *NimBuildConfigurationFactory::createBuildInfo(const Kit *k, const QString &projectFilePath,
BuildConfiguration::BuildType buildType) const
{
auto result = new BuildInfo(this);
result->buildType = buildType;
result->displayName = BuildConfiguration::buildTypeName(buildType);
result->buildDirectory = defaultBuildDirectory(k, projectFilePath, result->displayName, buildType);
result->kitId = k->id();
result->typeName = tr("Build");
return result;
}
} // namespace Nim
| 36.773756 | 112 | 0.708503 | kevinlq |
7be983b085d817ba0cca72e3dd0057a12b25612a | 996 | cpp | C++ | legacy/src/pngs2video.cpp | ethank5149/Ising-Model-Visual | 1c83634504467cf4ee4347419f9adbf328773c11 | [
"MIT"
] | null | null | null | legacy/src/pngs2video.cpp | ethank5149/Ising-Model-Visual | 1c83634504467cf4ee4347419f9adbf328773c11 | [
"MIT"
] | null | null | null | legacy/src/pngs2video.cpp | ethank5149/Ising-Model-Visual | 1c83634504467cf4ee4347419f9adbf328773c11 | [
"MIT"
] | 1 | 2021-03-08T13:22:29.000Z | 2021-03-08T13:22:29.000Z | ///\file pngs2video.cpp
///\author Ethan Knox
///\date 7/22/2020.
#include "../include/pngs2video.h"
#include "../include/clean.h"
#include <boost/process.hpp>
#include <fmt/format.h>
#include <iostream>
///\brief Creates a video of the simulation
///
///Uses ffmpeg to convert the png frames into both a gif and mp4, then the now
///obsolete frames are deleted
///\todo Don't delete these images if future option to save them is selected
///
/// \return void
void pngs2video(Ising &p)
{
std::cout << "\nCreating mp4... ";
boost::process::system(fmt::format("ffmpeg -nostats -loglevel 0 -i {0}/frame%d.png {1}", p.outputdir.string(), (p.outputdir/"output.mp4").string()).c_str());
std::cout << "Done!\n" << std::endl;
std::cout << "\nCreating gif... ";
boost::process::system(fmt::format("ffmpeg -nostats -loglevel 0 -i {0}/frame%d.png {1}", p.outputdir.string(), (p.outputdir/"output.gif").string()).c_str());
std::cout << "Done!\n" << std::endl;
clean_pngs(p);
} | 34.344828 | 161 | 0.650602 | ethank5149 |
7beae5cc43cbe3529528fa238c0aa6e1844d096a | 1,373 | cpp | C++ | src/ds/heap/min.cpp | bound1ess/cs | 0824e5ffbc4c1e170486c5e2e481c1a934d3dc63 | [
"MIT"
] | 1 | 2015-03-26T14:49:14.000Z | 2015-03-26T14:49:14.000Z | src/ds/heap/min.cpp | bound1ess/cs | 0824e5ffbc4c1e170486c5e2e481c1a934d3dc63 | [
"MIT"
] | null | null | null | src/ds/heap/min.cpp | bound1ess/cs | 0824e5ffbc4c1e170486c5e2e481c1a934d3dc63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <cassert>
using namespace std;
class MinHeap {
private:
int *heap, size;
bool dirty;
void restore();
public:
MinHeap(int *heap, int size);
~MinHeap();
int extract();
};
int main() {
int n;
scanf("%d", &n);
assert(n > 0);
int *arr = new int[n];
for (int i = 0; i < n; ++i) {
scanf("%d", arr + i);
}
MinHeap heap(arr, n);
for (int i = 0; i < n; ++i) {
printf("%d\n", heap.extract());
}
delete[] arr;
return 0;
}
MinHeap::MinHeap(int *heap, int size) {
this->size = size;
this->dirty = true;
this->heap = new int[size];
for (int i = 0; i < size; ++i) {
this->heap[i] = heap[i];
}
}
MinHeap::~MinHeap() {
delete[] this->heap;
}
int MinHeap::extract() {
assert(this->size > 0);
this->restore();
this->dirty = true;
swap(this->heap[0], this->heap[this->size - 1]);
--this->size;
return this->heap[this->size];
}
void MinHeap::restore() {
if (this->dirty) {
this->dirty = false;
for (int i = this->size / 2; i >= 0; --i) {
int left = i * 2 + 1, right = i * 2 + 2;
if (left < this->size && this->heap[i] > this->heap[left]) {
swap(this->heap[i], this->heap[left]);
}
if (right < this->size && this->heap[i] > this->heap[right]) {
swap(this->heap[i], this->heap[right]);
}
}
}
}
| 19.614286 | 68 | 0.525127 | bound1ess |
7bec1dbe1f989c7bf2d177c3d1f54a8ec8d9e2c9 | 26,694 | cpp | C++ | src/sim/rwr/advancedhts.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/rwr/advancedhts.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/rwr/advancedhts.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | //****************************************************
// RV - I-Hawk
// Starting HARM avionics systems upgrade 07/2008
//****************************************************
#include "stdhdr.h"
#include "F4Vu.h"
#include "missile.h"
#include "Graphics\Include\display.h"
#include "simveh.h"
#include "airunit.h"
#include "simdrive.h"
#include "fcc.h"
#include "sms.h"
#include "object.h"
#include "team.h"
#include "entity.h"
#include "simmover.h"
#include "soundfx.h"
#include "classtbl.h"
#include "rwr.h"
#include "AdvancedHTS.h"
#include "aircrft.h"
const float CURSOR_SIZE = 0.065f;
AdvancedHarmTargetingPod::AdvancedHarmTargetingPod(int idx, SimMoverClass* self) : HarmTargetingPod (idx, self)
{
curMissile = NULL;
curTarget = NULL;
curTargetWP = prevTargetWP = NULL;
curTOF = 0.0f;
timer = 0;
prevTOF = -1.0f;
prevTargteSymbol = prevWPNum = 0;
missileLaunched = false;
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
SMSClass* Sms;
if ( playerAC )
{
Sms = playerAC->Sms;
if ( Sms )
{
curMissile = (MissileClass*)(Sms->GetCurrentWeapon());
}
}
}
AdvancedHarmTargetingPod::~AdvancedHarmTargetingPod (void)
{
}
// RV - I-Hawk - HAD display
void AdvancedHarmTargetingPod::HADDisplay (VirtualDisplay* activeDisplay)
{
float displayX, displayY;
float x2, y2;
float wpX, wpY, wpZ;
float cosAng, sinAng;
WayPointClass *curWaypoint;
GroundListElement* tmpElement;
mlTrig trig;
FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC();
// Let the base class do the basics
HarmTargetingPod::HADDisplay( activeDisplay );
// Set up the trig functions of our current heading
mlSinCos (&trig, platform->Yaw());
cosAng = trig.cos;
sinAng = trig.sin;
// Draw all known emmitters
for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext())
{
if (tmpElement->BaseObject() == NULL) { continue; }
// Check if emitter is on priority list
if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; }
// Compute the world space oriented, display space scaled, ownship relative postion of the emitter
y2 = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
x2 = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
// Rotate it into heading up space and translate it down to deal with our vertical offset
displayX = cosAng * x2 - sinAng * y2;
displayY = sinAng * x2 + cosAng * y2 + HTS_Y_OFFSET;
// Skip this one if its off screen
if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f)) { continue; }
// JB 010726 Clear the designated target if behind the 3/9 line.
if (displayY - HTS_Y_OFFSET < 0)
{
if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
FCC->dropTrackCmd = TRUE;
}
}
DrawEmitter ( tmpElement, displayX, displayY, displayY );
// Mark the locked target
// Mark the locked target
if (displayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
display->SetColor( GetMfdColor(MFD_WHITE) );
display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE);
display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE);
handedoff = true; // Immediate hadnoff in HAD mode
}
display->AdjustOriginInViewport (-displayX, -displayY);
}
// Adjust our viewport origin
display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET);
// Draw the waypoints
display->SetColor( 0xFF00FF00 );
display->AdjustRotationAboutOrigin(-platform->Yaw());
curWaypoint = ((SimVehicleClass*)platform)->waypoint;
if (curWaypoint)
{
curWaypoint->GetLocation (&wpX, &wpY, &wpZ);
y2 = (wpX - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
x2 = (wpY - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
curWaypoint = curWaypoint->GetNextWP();
while (curWaypoint)
{
curWaypoint->GetLocation (&wpX, &wpY, &wpZ);
displayY = (wpX - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
displayX = (wpY - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
display->Line (x2, y2, displayX, displayY);
x2 = displayX;
y2 = displayY;
curWaypoint = curWaypoint->GetNextWP();
}
}
// Reset our display parameters
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
}
// RV - I-Hawk - HAD EXP display
void AdvancedHarmTargetingPod::HADExpDisplay( VirtualDisplay* activeDisplay )
{
float displayX, displayY;
float x, y;
float cosAng, sinAng, origCosAng, origSinAng;
float EXP1OffsetX, EXP1OffsetY, EXP2OffsetX, EXP2OffsetY;
float yawOffsetAng;
float origDisplayX, origDisplayY;
DWORD tempColor;
GroundListElement* tmpElement;
mlTrig trig, trig2;
FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC();
// Let the base class do the basics
HarmTargetingPod::HADExpDisplay( activeDisplay );
// Set up the trig functions of our heading when entered zoom mode
mlSinCos (&trig, yawBackup);
cosAng = trig.cos;
sinAng = trig.sin;
// Set up the trig functions of our heading
mlSinCos ( &trig2, platform->Yaw() );
origCosAng = trig2.cos;
origSinAng = trig2.sin;
// Draw all known emmitters
for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext())
{
if (tmpElement->BaseObject() == NULL) { continue; }
// Check if emitter is on priority list
if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; }
// Hold original positions to keep track if locked target hadn't past 3-9 o'clock line
y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
origDisplayX = origCosAng * x - origSinAng * y;
origDisplayY = origSinAng * x + origCosAng * y + HTS_Y_OFFSET;
// Compute the world space oriented, display space scaled, obacked up ownship relative position of the emitter
y = (tmpElement->BaseObject()->XPos() - XPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
x = (tmpElement->BaseObject()->YPos() - YPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
// Rotate it into heading up space and translate it down to deal with our vertical offset
displayX = cosAng * x - sinAng * y;
displayY = sinAng * x + cosAng * y;
// Deal with the EXP1 offset
EXP1OffsetX = 2.0f * HadOrigCursorX;
EXP1OffsetY = 2.0f * HadOrigCursorY;
displayX -= EXP1OffsetX;
displayY -= EXP1OffsetY;
// Here also add the EXP2 offset if appropriate
if ( HadZoomMode == EXP2 )
{
EXP2OffsetX = 2.0f * HadOrigCursorX + 2.0f * HadOrigCursorX2;
EXP2OffsetY = 2.0f * HadOrigCursorY + 2.0f * HadOrigCursorY2;
EXP2OffsetY += 2.0f * HTS_Y_OFFSET;
if ( displayRange < 10 )
{
EXP2OffsetY -= HTS_Y_OFFSET / 2.0f;
if ( displayRange < 5 )
{
EXP2OffsetY -= HTS_Y_OFFSET / 2.0f;
}
}
displayX -= EXP2OffsetX;
displayY -= EXP2OffsetY;
}
// Skip this one if its off screen
if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f)) { continue; }
// JB 010726 Clear the designated target if behind the 3/9 line.
if ( origDisplayY - HTS_Y_OFFSET < 0 )
{
if ( lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData() )
{
FCC->dropTrackCmd = TRUE;
}
}
DrawEmitter (tmpElement, displayX, displayY, origDisplayY);
// Mark the locked target
if (origDisplayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
tempColor = display->Color();
display->SetColor( GetMfdColor(MFD_WHITE) );
display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE);
display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE);
handedoff = true;
}
display->AdjustOriginInViewport (-displayX, -displayY);
display->SetColor( 0xFF00FF00 );
}
// Now draw the ownship symbol in relation to the zoomed area
y = (platform->XPos() - XPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
x = (platform->YPos() - YPosBackup) * FT_TO_NM / displayRange * HTS_DISPLAY_RADIUS;
// Rotate it into heading up space and translate it down to deal with our vertical offset
displayX = cosAng * x - sinAng * y;
displayY = sinAng * x + cosAng * y;
// Add the EXP1 offset
displayX -= EXP1OffsetX;
displayY -= EXP1OffsetY;
// Here also add the EXP2 offset if appropriate
if ( HadZoomMode == EXP2 )
{
displayX -= EXP2OffsetX;
displayY -= EXP2OffsetY;
}
tempColor = display->Color();
display->AdjustOriginInViewport (displayX, displayY);
// RV - I-Hawk - Ownship "airplane" marker. Here the display is relatively "static" and the
// only thing that moves and turn is the ownship AC marker
display->SetColor( GetMfdColor( MFD_CYAN ) );
static const float NOSE = 0.02f;
static const float TAIL = 0.08f;
static const float WING = 0.06f;
static const float TAIL_WING = 0.02f;
yawOffsetAng = platform->Yaw() - yawBackup;
float yawOffsetAng2 = yawBackup - platform->Yaw();
mlTrig offset, offset2;
mlSinCos( &offset, yawOffsetAng );
mlSinCos( &offset2, yawOffsetAng2 );
sinAng = offset2.sin;
cosAng = offset2.cos;
float r;
float offsetX, offsetY;
r = WING * 0.7f;
x = r * cosAng;
y = r * sinAng;
offsetY = 0.05f * cosAng;
offsetX = 0.05f * sinAng;
display->Line( x, y, -x, -y);
r = TAIL_WING;
x = r * cosAng;
y = r * sinAng;
offsetY = 0.04f * cosAng;
offsetX = 0.04f * sinAng;
sinAng = offset.sin;
cosAng = offset.cos;
r = (NOSE + TAIL) / 1.35f;
y = r * cosAng;
x = r * sinAng;
display->Line( x, y, -x, -y);
display->SetColor ( 0xFF00FF00 );
display->AdjustOriginInViewport (-displayX, -displayY);
// Adjust our viewport origin
display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET);
// Reset our display parameters
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
}
// RV - I-Hawk - HAS mode
void AdvancedHarmTargetingPod::HASDisplay (VirtualDisplay* activeDisplay)
{
unsigned numOfDrawnTargets, curTime;
float displayX, displayY, NormDisplayX, NormDisplayY, NormDisplayYNoOffset;
float x, y, x2, y2;
float cosAng, sinAng;
float range, alpha, ex, ey, phi, elevation;
float rangeX, rangeY, trueRange;
GroundListElement* tmpElement;
mlTrig trig;
FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC();
// Let the base class do the basics
HarmTargetingPod::HASDisplay( activeDisplay );
// Set up the trig functions of our current heading
mlSinCos (&trig, platform->Yaw());
cosAng = trig.cos;
sinAng = trig.sin;
curTime = (unsigned)((SimLibElapsedTime - HASTimer) * MSEC_TO_SEC);
// Draw all known emmitters
ClearDTSB(); // clear DTSB first
numOfDrawnTargets = 0;
for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext())
{
if (tmpElement->BaseObject() == NULL) { continue; }
// Check if emitter is on priority list
if ( !IsInPriorityList ( tmpElement->symbol ) ) { continue; }
// Check if range is less than 60NM (no reason to get anything beyond...)
rangeY = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM;
rangeX = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM;
rangeY *= rangeY;
rangeX *= rangeX;
trueRange = sqrtf( rangeX + rangeY );
if ( trueRange > 60.0f ) { continue; }
// Compute the world space oriented, display space scaled, ownship relative postion of the emitter
y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
float alt = (-platform->ZPos() - (-tmpElement->BaseObject()->ZPos())) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
// Now calculate elevation (and not range)
x2 = x * x;
y2 = y * y;
range = sqrt( x2 + y2 ); // Get range
alpha = atan ( alt / range ); // Get the elevation angle
elevation = (1.0f - (alpha / HALF_PI)) * HAS_DISPLAY_RADIUS;
NormDisplayX = cosAng * x - sinAng * y;
NormDisplayYNoOffset = sinAng * x + cosAng * y;
NormDisplayY = sinAng * x + cosAng * y + HTS_Y_OFFSET;
phi = atan ( NormDisplayX / NormDisplayYNoOffset );
ex = elevation * sin(phi);
ey = elevation * cos(phi);
displayX = ex * zoomFactor;
displayY = ey * zoomFactor + HTS_Y_OFFSET;
// RV - I-Hawk - Diplay only what's inside the ALIC video
if ( !IsInsideALIC(displayX, displayY) ) { continue; }
// What's behind the 3-9 line, display at ALIC bottom line
if ( NormDisplayY < 0.0f + HTS_Y_OFFSET )
{
displayY = 0.0f + HTS_Y_OFFSET;
displayX = -displayX; // Switch sides when it gets inverted...
}
// JB 010726 Clear the designated target if behind the 3/9 line.
if (NormDisplayY - HTS_Y_OFFSET < 0.0f)
{
if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
FCC->dropTrackCmd = TRUE;
}
}
// Draw only emitters which their time had come to be shown according to the HAS timer
if ( numOfDrawnTargets <= curTime )
{
DrawEmitter ( tmpElement, displayX, displayY, displayY );
UpdateDTSB ( tmpElement->symbol, displayX, displayY );
}
numOfDrawnTargets++;
// Adjust bac display viewport as DrawEmitter function is changing the viewport!
display->AdjustOriginInViewport (-displayX, -displayY);
}
HASNumTargets = numOfDrawnTargets;
// RV - I-Hawk - If we have a locked target, go to handoff mode
if ( lockedTarget && lockedTarget->BaseData() )
{
SetSubMode( Handoff );
preHandoffMode = Has;
handoffRefTime = SimLibElapsedTime;
handedoff = false;
}
display->SetColor( 0xFF00FF00 );
// Reset our display parameters
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
}
// RV - I-Hawk - Handoff mode (getting here after target is locked in HAS mode)
void AdvancedHarmTargetingPod::HandoffDisplay (VirtualDisplay* activeDisplay)
{
float displayX, displayY, NormDisplayX, NormDisplayY, NormDisplayYNoOffset;
float x, y, x2, y2;
float cosAng, sinAng;
float range, alpha, ex, ey, phi, elevation;
mlTrig trig;
FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC();
GroundListElement* tmpElement = NULL;
// Let the base class do the basics
HarmTargetingPod::HandoffDisplay( activeDisplay );
display = activeDisplay;
// Set up the trig functions of our current heading
mlSinCos (&trig, platform->Yaw());
cosAng = trig.cos;
sinAng = trig.sin;
// Draw only the locked target
ClearDTSB(); // clear DTSB first
if ( preHandoffMode == Has )
{
for (tmpElement = FCC->GetFirstGroundElement(); tmpElement; tmpElement = tmpElement->GetNext())
{
if ( !lockedTarget || !lockedTarget->BaseData() || preHandoffMode == Pos )
{
break;
}
if (tmpElement->BaseObject() == NULL) { continue; }
// Compute the world space oriented, display space scaled, ownship relative postion of the emitter
y = (tmpElement->BaseObject()->XPos() - platform->XPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
x = (tmpElement->BaseObject()->YPos() - platform->YPos()) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
float alt = (-platform->ZPos() - (-tmpElement->BaseObject()->ZPos())) * FT_TO_NM / displayRange * HAS_DISPLAY_RADIUS;
// Displaying azimuth/elevation like HAS mode
x2 = x * x;
y2 = y * y;
range = sqrt( x2 + y2 );
alpha = atan ( alt / range );
elevation = (1.0f - (alpha / HALF_PI)) * HAS_DISPLAY_RADIUS;
NormDisplayX = cosAng * x - sinAng * y;
NormDisplayYNoOffset = sinAng * x + cosAng * y;
NormDisplayY = sinAng * x + cosAng * y + HTS_Y_OFFSET;
phi = atan ( NormDisplayX / NormDisplayYNoOffset );
ex = elevation * sin(phi);
ey = elevation * cos(phi);
displayX = ex;
displayY = ey + HTS_Y_OFFSET;
// Skip this one if its off screen
//if ((fabs(displayX) > 1.0f) || (fabs(displayY) > 1.0f))
// RV - I-Hawk - Diplay only what's inside the ALIC video
if ( !IsInsideALIC(displayX, displayY) ) { continue; }
// although not drawing none-target emitters on main display, still keep DTSB updated
display->AdjustOriginInViewport (displayX, displayY);
UpdateDTSB ( tmpElement->symbol, displayX, displayY);
display->AdjustOriginInViewport (-displayX, -displayY);
// Only show the locked up target (after we finished updating DTSB list)
if ( tmpElement->BaseObject() != lockedTarget->BaseData() ) { continue; }
// JB 010726 Clear the designated target if behind the 3/9 line.
if (NormDisplayY - HTS_Y_OFFSET < 0.0f)
{
if (lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
FCC->dropTrackCmd = TRUE;
}
}
DrawEmitter ( tmpElement, displayX, displayY, displayY );
BoxTargetDTSB ( tmpElement->symbol, displayX, displayY );
// Mark the locked target
if (displayY - HTS_Y_OFFSET > 0 && lockedTarget && tmpElement->BaseObject() == lockedTarget->BaseData())
{
display->SetColor( GetMfdColor(MFD_WHITE) );
display->Line (-CURSOR_SIZE, -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE);
display->Line ( CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE, CURSOR_SIZE);
display->Line ( -CURSOR_SIZE, -CURSOR_SIZE, CURSOR_SIZE, -CURSOR_SIZE);
}
display->AdjustOriginInViewport (-displayX, -displayY);
}
}
if ( !lockedTarget ) // Back to HAS mode
{
SetSubMode( HAS );
((SimVehicleClass*)platform)->SOIManager(SimVehicleClass::SOI_WEAPON);
handedoff = false;
}
// Check if 3 seconds past since the lock for handoff "delay"
if ( handedoff == false )
{
if ( SimLibElapsedTime - handoffRefTime > 3 * SEC_TO_MSEC )
{
handedoff = true;
}
}
display->SetColor( 0xFF00FF00 );
// Adjust our viewport origin
display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET);
// Reset our display parameters
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
}
// RV - I-Hawk - POS display
void AdvancedHarmTargetingPod::POSDisplay (VirtualDisplay* activeDisplay)
{
int OsbIndex;
int boxed;
int days, hours, minutes, seconds;
DWORD tempColor;
float OsbPosX, OsbPosY;
float LDLVerticalPos = (ALICTOP + ALICBOTTOM) / 2.0f + 0.05f;
float theRange;
float dx, dy, ETA;
float wpX, wpY, wpZ;
float temp;
GroundListElement* tmpElement = NULL;
WayPointClass* tempWP = NULL;
int theWPnum;
char str[24];
FireControlComputer* FCC = ((SimVehicleClass*)platform)->GetFCC();
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
SMSClass* Sms;
if ( playerAC )
{
Sms = playerAC->Sms;
}
if ( Sms && !curMissile )
{
curMissile = (MissileClass*)(Sms->GetCurrentWeapon());
}
display = activeDisplay;
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
// Let the base class do the basics
HarmTargetingPod::POSDisplay( activeDisplay );
ClearDTSB();
ClearPOSTargets();
BuildPOSTargets();
OsbIndex = 0;
for ( int i = 0; i < MAX_POS_TARGETS; i++ )
{
if ( POSTargets[i] )
{
boxed = 0;
tmpElement = POSTargets[i];
tempWP = POSTargetsWPs[i];
GetOsbPos(OsbIndex, OsbPosX, OsbPosY);
tempColor = display->Color();
display->SetColor (GetMfdColor(MFD_WHITY_GRAY)); // "whity" gray
// This one is the current target
if ( i == POSTargetIndex && tmpElement && lockedTarget &&
tmpElement->BaseObject() == lockedTarget->BaseData() )
{
curTarget = POSTargets[i];
curTargetWP = POSTargetsWPs[i];
// If the target had not been handed off already, flash the box.
if ( handedoff == false )
{
boxed = flash ? 2:0;
}
else
{
boxed = 2; // Box it
}
float zero = 0.0f;
UpdateDTSB ( curTarget->symbol, zero, zero ); // Get it into DTSB
display->AdjustOriginInViewport ( -0.55f, LDLVerticalPos - 0.1f + HTS_Y_OFFSET );
DrawEmitterSymbol( curTarget->symbol, boxed );
display->AdjustOriginInViewport ( 0.55f, -(LDLVerticalPos - 0.1f + HTS_Y_OFFSET) );
// Get the waypoint number where this target is at, we need to display it
// under the LSDL line
theWPnum = FindWaypointNum ( curTargetWP );
sprintf (str, "%02d", theWPnum);
display->TextCenter ( -0.54f, LDLVerticalPos - 0.15f + HTS_Y_OFFSET, str );
// Get missile TOF. Should also be with the under-LSDL pre-launch info
if ( curMissile && curTarget && curTarget->BaseObject() )
{
// Get the range to the tmpElement which is the current target "candidate"
dx = fabs(playerAC->XPos() - curTarget->BaseObject()->XPos());
dx *= dx;
dy = fabs(playerAC->YPos() - curTarget->BaseObject()->YPos());
dy *= dy;
theRange = sqrt(dx + dy);
curTOF = curMissile->GetTOF( -playerAC->ZPos(), playerAC->GetVt(), 0.0f, 0.0f, theRange);
}
if ( curTOF > 0.0f )
{
temp = curTOF;
minutes = FloatToInt32 ( temp / 60.0f );
temp -= minutes * 60.0f;
seconds = FloatToInt32 ( temp );
sprintf ( str, "%d:%02d", abs(minutes), abs(seconds) );
display->TextCenter ( -0.55f, LDLVerticalPos - 0.28f + HTS_Y_OFFSET, str );
}
// RV - I-Hawk - Get ETA - BTW I noticed the HUD ETA for waypoints is fucked up
// and not following the DED ETA which is the accurate one... probably the WP
// time arrival function is foobard (which is what the HUD is using)
// Here calculating same way as the DED
curTargetWP->GetLocation ( &wpX, &wpY, &wpZ );
ETA = (float)(SimLibElapsedTime / SEC_TO_MSEC) + FloatToInt32(Distance(
playerAC->XPos(), playerAC->YPos(), wpX, wpY)
/ playerAC->GetVt());
// Calculate ETA
// Get rid of any days first
days = FloatToInt32 ( ETA / 86400.0f ); // 86400 seconds in 24 hours
ETA -= days * 86400.0f;
hours = FloatToInt32 ( ETA / 3600.0f );
ETA -= hours * 3600.0f;
minutes = FloatToInt32 ( ETA / 60.0f );
ETA -= minutes * 60.0f;
seconds = FloatToInt32 ( ETA );
sprintf ( str, "%d:%02d:%02d", abs(hours), abs(minutes), abs(seconds) );
display->TextCenter ( -0.56f, LDLVerticalPos - 0.37f + HTS_Y_OFFSET, str );
}
display->AdjustOriginInViewport (OsbPosX + 0.1f, OsbPosY);
DrawEmitterSymbol( tmpElement->symbol, boxed );
display->AdjustOriginInViewport (-(OsbPosX + 0.1f), -OsbPosY);
display->SetColor (tempColor);
display->CenterOriginInViewport ();
OsbIndex++;
}
else
{
break;
}
}
// In case of a launch, save the target's symbol and WP
if ( curMissile && curMissile->launchState != MissileClass::PreLaunch && lockedTarget )
{
// Stop tracking the missile
curMissile = NULL;
// Backup info on the launched target, and launched waypoint, for TOF
if (curTarget)
{
prevTargteSymbol = curTarget->symbol;
prevWPNum = FindWaypointNum ( curTargetWP );
prevTOF = curTOF;
missileLaunched = true; // update the flag
timer = SimLibElapsedTime;
}
}
if ( missileLaunched ) // Handle the last launched missile data
{
tempColor = display->Color();
display->SetColor(GetMfdColor(MFD_WHITY_GRAY));
// Draw the emitter simbol above the LSDL line at the post-launch info slot is
display->AdjustOriginInViewport ( 0.5f, LDLVerticalPos + 0.1f + HTS_Y_OFFSET );
DrawEmitterSymbol( prevTargteSymbol, 0 );
display->AdjustOriginInViewport ( -0.5f, -(LDLVerticalPos + 0.1f + HTS_Y_OFFSET) );
// Get the previous target waypoint number
sprintf (str, "%02d", prevWPNum);
display->TextCenter ( 0.49f, LDLVerticalPos + 0.25f + HTS_Y_OFFSET, str );
// Get the launched missile TOF, it's just a "dummy" counter...
if ( prevTOF <= 0.0f )
{
prevTOF = 0.0f;
}
else // Tick down the prevTOF
{
if ( SimLibElapsedTime - timer > 1 * SEC_TO_MSEC )
{
prevTOF -= 1.0f;
timer += 1 * SEC_TO_MSEC;
}
}
if ( prevTOF >= 0.0f )
{
temp = prevTOF;
minutes = FloatToInt32 ( temp / 60.0f );
temp -= minutes * 60.0f;
seconds = FloatToInt32 ( temp );
sprintf ( str, "%d:%02d", abs(minutes), abs(seconds) );
display->TextCenter ( 0.48f, LDLVerticalPos + 0.38f + HTS_Y_OFFSET, str );
}
display->SetColor(tempColor);
}
// RV - I-Hawk - If we have a locked target, go to handoff mode
if ( lockedTarget && lockedTarget->BaseData() )
{
preHandoffMode = Pos;
if ( handedoff == false ) // Tick the Handoff timer down
{
if ( SimLibElapsedTime - handoffRefTime > 3 * SEC_TO_MSEC )
{
handedoff = true;
}
}
}
display->SetColor( 0xFF00FF00 );
// Adjust our viewport origin
display->AdjustOriginInViewport (0.0f, HTS_Y_OFFSET);
// Reset our display parameters
display->ZeroRotationAboutOrigin();
display->CenterOriginInViewport ();
}
void AdvancedHarmTargetingPod::DrawEmitter ( GroundListElement* tmpElement, float &displayX, float &displayY, float &origDisplayY )
{
DWORD color;
int boxed;
switch ( submode )
{
case HAS:
color = GetMfdColor(MFD_WHITY_GRAY);
boxed = 0;
break;
case Handoff:
color = GetMfdColor(MFD_WHITY_GRAY);
boxed = 2;
break;
case HAD:
default:
// Set the symbols draw intensity based on its state
if ( origDisplayY - HTS_Y_OFFSET < 0 ) {
color = 0x00008000;
boxed = 0;
} else if ( tmpElement->IsSet(GroundListElement::Launch) ) {
color = GetMfdColor( MFD_RED );
boxed = flash ? 2 : 0;
} else if ( tmpElement->IsSet(GroundListElement::Track) ) {
color = GetMfdColor(MFD_RED);
boxed = 2;
} else if ( tmpElement->IsSet(GroundListElement::Radiate) ) {
color = GetMfdColor(MFD_YELLOW);
boxed = 0;
} else {
color = 0x00008000;
boxed = 0;
}
break;
}
// Adjust our display location and draw the emitter symbol
DWORD tmpColor = display->Color();
display->AdjustOriginInViewport (displayX, displayY);
display->SetColor( color );
DrawEmitterSymbol( tmpElement->symbol, boxed );
display->SetColor( tmpColor );
}
void AdvancedHarmTargetingPod::GetOsbPos ( int &OsbIndex, float &OsbPosX, float &OsbPosY )
{
switch ( OsbIndex )
{
case 0:
GetButtonPos(16, &OsbPosX, &OsbPosY);
break;
case 1:
GetButtonPos(17, &OsbPosX, &OsbPosY);
break;
case 2:
GetButtonPos(18, &OsbPosX, &OsbPosY);
break;
case 3:
default:
GetButtonPos(19, &OsbPosX, &OsbPosY);
break;
}
}
| 30.57732 | 131 | 0.674908 | markbb1957 |
7bed07f3315ed9ee128c09c6a60b76fced607344 | 2,922 | cpp | C++ | Core/Code/Rendering/mitkRenderWindow.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 5 | 2015-05-27T06:57:53.000Z | 2020-03-12T21:08:23.000Z | Core/Code/Rendering/mitkRenderWindow.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 4 | 2020-09-17T16:01:55.000Z | 2022-01-18T21:12:10.000Z | Core/Code/Rendering/mitkRenderWindow.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 2 | 2016-08-17T12:01:04.000Z | 2020-03-12T22:36:36.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkRenderWindow.h"
#include "mitkDisplayPositionEvent.h"
#include "mitkVtkLayerController.h"
#include "mitkRenderingManager.h"
#include "vtkRenderer.h"
#include "vtkRenderWindowInteractor.h"
#include "mitkVtkEventProvider.h"
mitk::RenderWindow::RenderWindow(vtkRenderWindow* renWin, const char* name, mitk::RenderingManager* rm, mitk::BaseRenderer::RenderingMode::Type rmtype )
: m_vtkRenderWindow(renWin)
, m_vtkRenderWindowInteractor(NULL)
, m_vtkMitkEventProvider(NULL)
{
if(m_vtkRenderWindow == NULL)
{
m_vtkRenderWindow = vtkRenderWindow::New();
if(rmtype == mitk::BaseRenderer::RenderingMode::DepthPeeling)
{
m_vtkRenderWindow->SetMultiSamples(0);
m_vtkRenderWindow->SetAlphaBitPlanes(1);
}
else if(rmtype == mitk::BaseRenderer::RenderingMode::MultiSampling)
{
m_vtkRenderWindow->SetMultiSamples(8);
}
else if(rmtype == mitk::BaseRenderer::RenderingMode::Standard)
{
m_vtkRenderWindow->SetMultiSamples(0);
}
}
if ( m_vtkRenderWindow->GetSize()[0] <= 10
|| m_vtkRenderWindow->GetSize()[0] <= 10 )
{
m_vtkRenderWindow->SetSize( 100, 100 );
}
m_vtkRenderWindowInteractor = vtkRenderWindowInteractor::New();
m_vtkRenderWindowInteractor->SetRenderWindow(m_vtkRenderWindow);
m_vtkRenderWindowInteractor->Initialize();
// initialize from RenderWindowBase
Initialize(rm,name,rmtype);
m_vtkMitkEventProvider = vtkEventProvider::New();
m_vtkMitkEventProvider->SetInteractor(this->GetVtkRenderWindowInteractor());
m_vtkMitkEventProvider->SetMitkRenderWindow(this);
m_vtkMitkEventProvider->SetEnabled(1);
}
mitk::RenderWindow::~RenderWindow()
{
Destroy();
m_vtkRenderWindow->Delete();
m_vtkRenderWindowInteractor->Delete();
m_vtkMitkEventProvider->Delete();
}
vtkRenderWindow* mitk::RenderWindow::GetVtkRenderWindow()
{
return m_vtkRenderWindow;
}
vtkRenderWindowInteractor* mitk::RenderWindow::GetVtkRenderWindowInteractor()
{
return m_vtkRenderWindowInteractor;
}
void mitk::RenderWindow::SetSize( int width, int height )
{
this->GetVtkRenderWindow()->SetSize( width, height );
this->resizeMitkEvent( width, height );
}
void mitk::RenderWindow::ReinitEventProvider()
{
m_vtkMitkEventProvider->SetEnabled(0);
m_vtkMitkEventProvider->SetInteractor(this->GetVtkRenderWindowInteractor());
m_vtkMitkEventProvider->SetMitkRenderWindow(this);
m_vtkMitkEventProvider->SetEnabled(1);
} | 29.22 | 152 | 0.729295 | danielknorr |
7bed2175f712018866ba8bfb087e58ac472f3cb8 | 3,906 | hpp | C++ | src/Module/Module.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/Module.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/Module.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | /*!
* \file
* \brief A Module is an abstract concept. Basically, all the objects used in a Simulation are a Module.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef MODULE_HPP_
#define MODULE_HPP_
#include <string>
#include <sstream>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <map>
#include <functional>
#include "Task.hpp"
#include "Socket.hpp"
#ifdef SYSTEMC_MODULE
#include "SC_Module.hpp"
#endif
#include "Tools/Exception/exception.hpp"
namespace aff3ct
{
namespace module
{
/*!
* \class Module
*
* \brief A Module is an abstract concept. Basically, all the objects used in a Simulation are a Module.
*/
class Module
{
protected:
int n_frames; /*!< Number of frames to process in this Module */
std::string name; /*!< Name of the Module. */
std::string short_name; /*!< Short name of the Module. */
std::vector<Task*> tasks_with_nullptr;
public:
std::vector<Task*> tasks;
#ifdef SYSTEMC_MODULE
friend SC_Module_container;
SC_Module_container sc;
#endif
/*!
* \brief Constructor.
*
* \param n_frames: number of frames to process in this Module.
* \param name : Module's name.
*/
explicit Module(const int n_frames = 1)
: n_frames(n_frames), name("Module"), short_name("Module")
#ifdef SYSTEMC_MODULE
, sc(*this)
#endif
{
if (n_frames <= 0)
{
std::stringstream message;
message << "'n_frames' has to be greater than 0 ('n_frames' = " << n_frames << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
}
/*!
* \brief Destructor.
*/
virtual ~Module()
{
for (auto t : tasks) delete t;
}
/*!
* \brief Get the number of frames.
*
* \return the number of frames to process in this Module.
*/
virtual int get_n_frames() const
{
return n_frames;
}
inline void set_name(const std::string &name)
{
this->name = name;
}
inline const std::string& get_name() const
{
return this->name;
}
inline void set_short_name(const std::string &short_name)
{
this->short_name = short_name;
}
inline const std::string& get_short_name() const
{
return this->short_name;
}
inline Task& operator[](const int id)
{
return *tasks_with_nullptr[id];
}
protected:
Task& create_task(const std::string &name, const int id = -1)
{
bool autoalloc = false, autoexec = false, stats = false, fast = false, debug = false;
auto t = new Task(*this, name, autoalloc, autoexec, stats, fast, debug);
if (id < 0)
{
tasks.push_back(t);
tasks_with_nullptr.push_back(t);
}
else
{
if (tasks_with_nullptr.size() > (size_t)id && tasks_with_nullptr[id] == nullptr)
{
tasks.push_back(t);
tasks_with_nullptr[id] = t;
}else
{
delete t;
std::stringstream message;
message << "Impossible to create the task ('task.name' = " << name
<< ", 'task.id' = " << id
<< ", 'tasks.size()' = " << tasks.size()
<< ", 'module.name' = " << this->get_name() << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
}
return *t;
}
template <typename T>
Socket& create_socket_in(Task& task, const std::string &name, const size_t n_elmts)
{
return task.template create_socket_in<T>(name, n_elmts);
}
template <typename T>
Socket& create_socket_in_out(Task& task, const std::string &name, const size_t n_elmts)
{
return task.template create_socket_in_out<T>(name, n_elmts);
}
template <typename T>
Socket& create_socket_out(Task& task, const std::string &name, const size_t n_elmts)
{
return task.template create_socket_out<T>(name, n_elmts);
}
void create_codelet(Task& task, std::function<int(void)> codelet)
{
task.create_codelet(codelet);
}
void register_timer(Task& task, const std::string &key)
{
task.register_timer(key);
}
};
}
}
#endif /* MODULE_HPP_ */
| 21.821229 | 104 | 0.664875 | codechecker123 |
7bf09e9b58f09da5ba62e3de63240aada28fbc9b | 9,377 | cpp | C++ | Solutions/MBED_GR_PEACH/DeviceCode/TouchPanel/MBED_GR_PEACH_touchpanel_driver.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | Solutions/MBED_GR_PEACH/DeviceCode/TouchPanel/MBED_GR_PEACH_touchpanel_driver.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | Solutions/MBED_GR_PEACH/DeviceCode/TouchPanel/MBED_GR_PEACH_touchpanel_driver.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | 1 | 2019-12-05T18:59:01.000Z | 2019-12-05T18:59:01.000Z | ////////////////////////////////////////////////////////////////////////////
// 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) Microsoft Corporation. All rights reserved.
// Portions Copyright (c) Kentaro Sekimoto All rights reserved.
//
////////////////////////////////////////////////////////////////////////////
#include <tinyhal.h>
#include "mbed.h"
#include "MBED_GR_PEACH_TouchPanel_Driver.h"
// XL - A0 - P1_8
// YU - A1 - P1_9
// XR - A2 - P1_10
// YD - A3 - P1_11
// XL - P10_0
// YU - P1_1
// XR - P1_0
// YD - P1_12
#define PIN_XL ((GPIO_PIN)P10_0)
#define PIN_YU ((GPIO_PIN)P1_1)
#define PIN_XR ((GPIO_PIN)P1_0)
#define PIN_YD ((GPIO_PIN)P1_12)
//--//
//#define DEBUG_TOUCHPANEL
struct MBED_GR_PEACH_TouchPanel_Driver g_MBED_GR_PEACH_TouchPanel_Driver;
BOOL MBED_GR_PEACH_TouchPanel_Driver::CalibrationPointGet(TOUCH_PANEL_CALIBRATION_POINT *pTCP)
{
INT32 cDisplayWidth = pTCP->cDisplayWidth;
INT32 cDisplayHeight = pTCP->cDisplayHeight;
int CalibrationRadiusX = cDisplayWidth / 20;
int CalibrationRadiusY = cDisplayHeight / 20;
switch (pTCP -> PointNumber)
{
case 0:
pTCP->CalibrationX = cDisplayWidth / 2;
pTCP->CalibrationY = cDisplayHeight / 2;
break;
case 1:
pTCP->CalibrationX = CalibrationRadiusX * 2;
pTCP->CalibrationY = CalibrationRadiusY * 2;
break;
case 2:
pTCP->CalibrationX = CalibrationRadiusX * 2;
pTCP->CalibrationY = cDisplayHeight - CalibrationRadiusY * 2;
break;
case 3:
pTCP->CalibrationX = cDisplayWidth - CalibrationRadiusX * 2;
pTCP->CalibrationY = cDisplayHeight - CalibrationRadiusY * 2;
break;
case 4:
pTCP->CalibrationX = cDisplayWidth - CalibrationRadiusX * 2;
pTCP->CalibrationY = CalibrationRadiusY * 2;
break;
default:
pTCP->CalibrationX = cDisplayWidth / 2;
pTCP->CalibrationY = cDisplayHeight / 2;
return FALSE;
}
return TRUE;
}
HRESULT MBED_GR_PEACH_TouchPanel_Driver::GetDeviceCaps(unsigned int iIndex, void* lpOutput)
{
if ( lpOutput == NULL )
{
return FALSE;
}
switch ( iIndex )
{
case TOUCH_PANEL_SAMPLE_RATE_ID:
{
TOUCH_PANEL_SAMPLE_RATE *pTSR = (TOUCH_PANEL_SAMPLE_RATE*)lpOutput;
pTSR->SamplesPerSecondLow = g_TouchPanel_Sampling_Settings.SampleRate.SamplesPerSecondLow;
pTSR->SamplesPerSecondHigh = g_TouchPanel_Sampling_Settings.SampleRate.SamplesPerSecondHigh;
pTSR->CurrentSampleRateSetting = g_TouchPanel_Sampling_Settings.SampleRate.CurrentSampleRateSetting;
pTSR->MaxTimeForMoveEvent_ticks = g_TouchPanel_Sampling_Settings.SampleRate.MaxTimeForMoveEvent_ticks;
}
break;
case TOUCH_PANEL_CALIBRATION_POINT_COUNT_ID:
{
TOUCH_PANEL_CALIBRATION_POINT_COUNT *pTCPC = (TOUCH_PANEL_CALIBRATION_POINT_COUNT*)lpOutput;
pTCPC->flags = 0;
pTCPC->cCalibrationPoints = 5;
}
break;
case TOUCH_PANEL_CALIBRATION_POINT_ID:
return(CalibrationPointGet((TOUCH_PANEL_CALIBRATION_POINT*)lpOutput));
default:
return FALSE;
}
return TRUE;
}
void MBED_GR_PEACH_TouchPanel_Driver::GetPoint(TOUCH_PANEL_SAMPLE_FLAGS* pTipState, int* pSource, int* pUnCalX, int* pUnCalY)
{
static BOOL stylusDown = FALSE;
INT32 validReadCount = 0;
*pTipState = 0;
*pUnCalX = 0;
*pUnCalY = 0;
*pSource = 0;
if (g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX >= 3700)
validReadCount = 0;
else
validReadCount = 1;
if (stylusDown)
*pTipState |= TouchSamplePreviousDownFlag;
if ((validReadCount == 1) &&
(g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch == 1)) {
*pTipState |= TouchSampleValidFlag;
*pUnCalX = g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inY; // intentionally changed x <-> y
*pUnCalY = g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX; // intentionally changed x <-> y
*pTipState |= TouchSampleDownFlag;
stylusDown = true;
} else {
*pUnCalX = -1;
*pUnCalY = -1;
stylusDown = false;
}
}
void MBED_GR_PEACH_TouchPanel_Driver::TouchCompletion(void* arg)
{
g_MBED_GR_PEACH_TouchPanel_Driver.Poll();
if (!g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.IsLinked()) {
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.EnqueueDelta(g_MBED_GR_PEACH_TouchPanel_Driver.m_samplingTimespan);
} else
{
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.Abort();
}
}
BOOL MBED_GR_PEACH_TouchPanel_Driver::Initialize(GPIO_INTERRUPT_SERVICE_ROUTINE touchIsrProc)
{
CPU_GPIO_EnableOutputPin(PIN_XL, false);
CPU_GPIO_EnableOutputPin(PIN_YU, false);
CPU_GPIO_EnableOutputPin(PIN_XR, false);
CPU_GPIO_EnableOutputPin(PIN_YD, false);
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX = 0;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inY = 0;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 0;
g_MBED_GR_PEACH_TouchPanel_Driver.m_samplingTimespan = TOUCHPANEL_POLL_TIMESPAN;
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.Initialize();
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.InitializeForISR(MBED_GR_PEACH_TouchPanel_Driver::TouchCompletion, NULL);
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.EnqueueDelta(g_MBED_GR_PEACH_TouchPanel_Driver.m_samplingTimespan);
#if 0
if (!::CPU_GPIO_EnableInputPin2(
0xB4,
FALSE,
touchIsrProc,
NULL,
GPIO_INT_EDGE_BOTH,
RESISTOR_PULLUP))
{
return FALSE;
}
#endif
return TRUE;
}
BOOL MBED_GR_PEACH_TouchPanel_Driver::Uninitialize()
{
if (g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.IsLinked())
{
g_MBED_GR_PEACH_TouchPanel_Driver.m_touchCompletion.Abort();
}
return TRUE;
}
void MBED_GR_PEACH_TouchPanel_Driver::Poll()
{
#if 0
static UINT32 t_state;
UINT32 value;
switch(t_state) {
case 0:
SENSE_ON;
t_state++;
break;
case 1:
if (TOUCH_CHK)
t_state++;
else {
IDLE;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 0;
t_state = 0;
}
break;
case 2: // skip for chattering
case 3:
t_state++;
break;
#if 0
case 4:
if (TOUCH_CHK) {
SENSE_Y_ON;
t_state++;
} else {
IDLE;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 0;
t_state = 0;
}
break;
case 5: // start A-D for getting Y axis
AD_Y_ENABLE;
FM3_ADC1->SCCR |= SCCR_SSTR; // A/D start
t_state++;
break;
case 6: // sense power on
value = FM3_ADC1->SCFD;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX = (UINT16)(value >> 16);
AD_Y_DISABLE;
SENSE_ON;
t_state++;
break;
#else
case 4:
if (TOUCH_CHK) {
GLOBAL_LOCK(irq);
SENSE_Y_ON;
AD_Y_ENABLE;
volatile int i = 10000;
while (i-- > 0);
FM3_ADC1->SCCR |= SCCR_SSTR; // A/D start
do {
value = FM3_ADC1->SCFD;
} while (((value & SCFDL_INVL) != 0) || (16 != (value & 0x1F)));
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inY = (UINT16)(value >> 16);
AD_Y_DISABLE;
SENSE_ON;
t_state += 3;
} else {
IDLE;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 0;
t_state = 0;
}
break;
#endif
case 7:
if (TOUCH_CHK) {
SENSE_X_ON;
t_state++;
} else {
IDLE;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 0;
t_state = 0;
}
break;
case 8: // start A-D for sensing X axis
AD_X_ENABLE;
FM3_ADC2->SCCR |= SCCR_SSTR; // A/D start
t_state++;
break;
case 9: // sense power on
value = FM3_ADC2->SCFD;
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX = (UINT16)(value >> 16);
AD_X_DISABLE;
SENSE_ON;
t_state++;
break;
case 10: // skip for chattering
case 11:
t_state++;
break;
case 12:
if (TOUCH_CHK) {
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_touch = 1;
#ifdef DEBUG_TOUCHPANEL
lcd_printf("x=%d y=%d\r\n",
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inX,
g_MBED_GR_PEACH_TouchPanel_Driver.m_global_inY);
#endif
}
IDLE;
t_state = 0;
break;
default:
t_state = 0;
break;
}
#endif
}
| 30.054487 | 129 | 0.628986 | Sirokujira |
7bf41dbef6119e66d3f13a2a1786b8f77b4dcdf4 | 3,480 | cpp | C++ | source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp | kerry-Cho/maskrcnn_benchmark.cpp | f110f7b6d6ac87b919b8f7aa95527c68f74d234a | [
"MIT"
] | 99 | 2019-05-01T15:23:45.000Z | 2022-01-30T05:11:40.000Z | source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp | conanhung/maskrcnn_benchmark.cpp | eab9787d3140e003662a31a8e01f7ae39469e9a0 | [
"MIT"
] | 18 | 2019-05-21T11:31:44.000Z | 2020-04-03T09:59:27.000Z | source/rcnn/modeling/roi_heads/mask_head/mask_head.cpp | conanhung/maskrcnn_benchmark.cpp | eab9787d3140e003662a31a8e01f7ae39469e9a0 | [
"MIT"
] | 27 | 2019-05-12T05:41:08.000Z | 2021-02-07T01:58:01.000Z | #include "roi_heads/mask_head/mask_head.h"
namespace rcnn{
namespace modeling{
std::pair<std::vector<rcnn::structures::BoxList>, std::vector<torch::Tensor>> KeepOnlyPositiveBoxes(std::vector<rcnn::structures::BoxList> boxes){
std::vector<rcnn::structures::BoxList> positive_boxes;
std::vector<torch::Tensor> positive_inds;
int num_boxes = 0;
for(auto& boxes_per_image : boxes){
torch::Tensor labels = boxes_per_image.GetField("labels");
torch::Tensor inds_mask = labels > 0;
torch::Tensor inds = inds_mask.nonzero().squeeze(1);
positive_boxes.push_back(boxes_per_image[inds]);
positive_inds.push_back(inds_mask);
}
return std::make_pair(positive_boxes, positive_inds);
}
ROIMaskHeadImpl::ROIMaskHeadImpl(int64_t in_channels)
:feature_extractor(MakeROIMaskFeatureExtractor(in_channels)),
predictor(MakeROIMaskPredictor(feature_extractor->out_channels())),
post_processor(MakeRoiMaskPostProcessor()),
loss_evaluator(MakeROIMaskLossEvaluator()){}
std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(std::vector<torch::Tensor> features,
std::vector<rcnn::structures::BoxList> proposals,
std::vector<rcnn::structures::BoxList> targets)
{
if(is_training()){
torch::Tensor mask_logits, x, loss_mask;
std::vector<rcnn::structures::BoxList> positive_boxes, all_proposals;
std::vector<torch::Tensor> positive_inds;
all_proposals = proposals;
std::tie(positive_boxes, positive_inds) = KeepOnlyPositiveBoxes(proposals);
x = feature_extractor->forward(features, proposals);
mask_logits = predictor->forward<torch::Tensor>(x);
loss_mask = loss_evaluator(proposals, mask_logits, targets);
return std::make_tuple(x, all_proposals, std::map<std::string, torch::Tensor>{{"loss_mask", loss_mask}});
}
else{
return forward(features, proposals);
}
}
std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(std::vector<torch::Tensor> features, std::vector<rcnn::structures::BoxList> proposals){
//No target, No training
torch::Tensor x = feature_extractor->forward(features, proposals);
torch::Tensor mask_logits = predictor->forward(x);
std::vector<rcnn::structures::BoxList> result = post_processor(mask_logits, proposals);
return std::make_tuple(x, result, std::map<std::string, torch::Tensor>{});
}
std::tuple<torch::Tensor, std::vector<rcnn::structures::BoxList>, std::map<std::string, torch::Tensor>> ROIMaskHeadImpl::forward(torch::Tensor features, std::vector<rcnn::structures::BoxList> proposals, std::vector<rcnn::structures::BoxList> targets){
//share feature => training
std::vector<rcnn::structures::BoxList> positive_boxes, all_proposals;
std::vector<torch::Tensor> positive_inds;
torch::Tensor mask_logits, x, loss_mask;
all_proposals = proposals;
std::tie(positive_boxes, positive_inds) = KeepOnlyPositiveBoxes(proposals);
x = features[torch::cat(positive_inds, 0)];
mask_logits = predictor->forward(x);
loss_mask = loss_evaluator(proposals, mask_logits, targets);
return std::make_tuple(x, all_proposals, std::map<std::string, torch::Tensor>{{"loss_mask", loss_mask}});
}
ROIMaskHead BuildROIMaskHead(int64_t in_channels){
return ROIMaskHead(in_channels);
}
}
} | 44.615385 | 251 | 0.718103 | kerry-Cho |
7bf4af8d04f359d4f6c7d56c9539443f8bf100af | 115 | cc | C++ | tests/CompileTests/ElsaTestCases/t0003.cc | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | tests/CompileTests/ElsaTestCases/t0003.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | tests/CompileTests/ElsaTestCases/t0003.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z |
typedef int x;
int main()
{
x (y); // this is a declaration according to cppstd sec. 6.8
return y;
}
| 9.583333 | 65 | 0.582609 | maurizioabba |
7bf5d269727403e5b16d4eb0b068d86e75be43f0 | 1,810 | cpp | C++ | cpp_src/problem012.cpp | PhilippSchuette/projecteuler | b74f76e8f27769d5cfc4227ccfb272d0a83ef587 | [
"MIT"
] | 4 | 2018-09-24T14:14:39.000Z | 2021-04-13T01:57:12.000Z | cpp_src/problem012.cpp | PhilippSchuette/projecteuler | b74f76e8f27769d5cfc4227ccfb272d0a83ef587 | [
"MIT"
] | 25 | 2018-09-24T14:18:19.000Z | 2021-05-08T07:03:31.000Z | cpp_src/problem012.cpp | PhilippSchuette/projecteuler | b74f76e8f27769d5cfc4227ccfb272d0a83ef587 | [
"MIT"
] | 3 | 2019-03-01T14:22:21.000Z | 2021-04-13T01:57:53.000Z | // Project Euler Problem 012 Solution
//
// Problem statement: The sequence of triangle numbers is generated by adding the natural numbers. So the 7^{th} triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:<p style="text-align:center;">1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...Let us list the factors of the first seven triangle numbers:<blockquote style="font-family:'courier new';"><b> 1</b>: 1<br /><b> 3</b>: 1,3<br /><b> 6</b>: 1,2,3,6<br /><b>10</b>: 1,2,5,10<br /><b>15</b>: 1,3,5,15<br /><b>21</b>: 1,3,7,21<br /><b>28</b>: 1,2,4,7,14,28</blockquote>We can see that 28 is the first triangle number to have over five divisors.What is the value of the first triangle number to have over five hundred divisors?
//
// Solution description:
//
// Author: Tom Praschan
// 2019/03/08
// License: MIT (see ../LICENSE.md)
#include "problem012.hpp"
#include "prime_utils.hpp"
#include <omp.h>
#include <fmt/format.h>
#include <vector>
#include <numeric> // For std::accumulate
// First find the prime factorization of n,
// then the number of divisors is given by the product
// of the powers of the prime factors + 1
unsigned num_divisors(unsigned n) {
auto &[factors, exponents] = prime_factors(n);
unsigned prod = 1;
for (auto e : exponents)
prod *= (e+1);
return prod;
}
// Return the nth triangle number using Gauß' formula
unsigned triangle_number(unsigned n) {
return (n * (n + 1)) / 2;
}
#ifndef TESTING
int main(int argc, char **argv) {
auto start = omp_get_wtime();
unsigned n = 1;
for (n = 1; num_divisors(triangle_number(n)) <= 500; n++) {}
auto solution = triangle_number(n);
auto end = omp_get_wtime();
fmt::print("Solution: {} \n", solution);
fmt::print("Elapsed time: {}s \n", end - start);
}
#endif
| 39.347826 | 707 | 0.653591 | PhilippSchuette |
7bf645240fb591fe4703883df53f340eae8e37bc | 7,397 | hpp | C++ | include/lexy/dsl/whitespace.hpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | include/lexy/dsl/whitespace.hpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | include/lexy/dsl/whitespace.hpp | IohannRabeson/lexy | 881beb56f030e8f4761514e70cb50d809ac4ad17 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_DSL_WHITESPACE_HPP_INCLUDED
#define LEXY_DSL_WHITESPACE_HPP_INCLUDED
#include <lexy/dsl/base.hpp>
#include <lexy/dsl/choice.hpp>
#include <lexy/dsl/loop.hpp>
#include <lexy/dsl/token.hpp>
#include <lexy/engine/while.hpp>
#include <lexy/token.hpp>
#ifdef LEXY_IGNORE_DEPRECATED_WHITESPACE
# define LEXY_DEPRECATED_WHITESPACE
#else
# define LEXY_DEPRECATED_WHITESPACE \
[[deprecated("operator[] has been deprecated; use dsl::whitespace(ws) instead.")]]
#endif
namespace lexyd
{
template <typename Rule>
struct _wsr : rule_base
{
template <typename NextParser>
struct parser
{
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
auto begin = reader.cur();
if constexpr (lexy::is_token<Rule>)
{
// Parsing a token repeatedly cannot fail, so we can optimize it using an engine.
using engine = lexy::engine_while<typename Rule::token_engine>;
engine::match(reader);
}
else
{
// We need to mark the context with the tag to prevent infinite recursion.
auto ws_context = context.insert(lexy::_tag_whitespace{}, lexy::_tag_whitespace{});
// We can then parse the rule repeatedly using the special context.
using loop_parser
= lexy::rule_parser<decltype(loop(Rule{} | break_)),
lexy::context_discard_parser<decltype(ws_context)>>;
if (!loop_parser::parse(ws_context, reader))
return false;
}
auto end = reader.cur();
// Add a whitespace token node.
if (begin != end)
context.token(lexy::whitespace_token_kind, begin, end);
return NextParser::parse(context, reader, LEXY_FWD(args)...);
}
};
template <typename R>
friend constexpr auto operator|(_wsr<Rule>, R r)
{
return _wsr<decltype(Rule{} | r)>{};
}
template <typename R>
friend constexpr auto operator|(R r, _wsr<Rule>)
{
return _wsr<decltype(r | Rule{})>{};
}
template <typename R>
friend constexpr auto operator/(_wsr<Rule>, R r)
{
return _wsr<decltype(Rule{} / r)>{};
}
template <typename R>
friend constexpr auto operator/(R r, _wsr<Rule>)
{
return _wsr<decltype(r / Rule{})>{};
}
};
struct _ws : rule_base
{
template <typename NextParser>
struct parser
{
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
return lexy::whitespace_parser<Context, NextParser>::parse(context, reader,
LEXY_FWD(args)...);
}
};
/// Overrides implicit whitespace detection.
template <typename Rule>
constexpr auto operator()(Rule) const
{
return _wsr<Rule>{};
}
};
/// Matches whitespace.
constexpr auto whitespace = _ws{};
} // namespace lexyd
namespace lexyd
{
template <typename Rule>
struct _wsn : rule_base
{
static constexpr auto is_branch = Rule::is_branch;
static constexpr auto is_unconditional_branch = Rule::is_unconditional_branch;
template <typename NextParser>
struct parser
{
struct _cont
{
template <typename WsContext, typename Reader, typename Context, typename... Args>
LEXY_DSL_FUNC bool parse(WsContext&, Reader& reader, Context& context, Args&&... args)
{
// Continue with the normal context, after skipping whitespace.
return lexy::whitespace_parser<Context, NextParser>::parse(context, reader,
LEXY_FWD(args)...);
}
};
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args)
-> lexy::rule_try_parse_result
{
// Parse the rule using the context that doesn't allow inner whitespace.
auto ws_context
= context.insert(lexy::_tag_no_whitespace{}, lexy::_tag_no_whitespace{});
return lexy::rule_parser<Rule, _cont>::try_parse(ws_context, reader, context,
LEXY_FWD(args)...);
}
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
// Parse the rule using the context that doesn't allow inner whitespace.
auto ws_context
= context.insert(lexy::_tag_no_whitespace{}, lexy::_tag_no_whitespace{});
return lexy::rule_parser<Rule, _cont>::parse(ws_context, reader, context,
LEXY_FWD(args)...);
}
};
};
/// Disables automatic skipping of whitespace for all tokens of the given rule.
template <typename Rule>
constexpr auto no_whitespace(Rule)
{
if constexpr (lexy::is_token<Rule>)
return Rule{}; // Token already behaves that way.
else
return _wsn<Rule>{};
}
} // namespace lexyd
namespace lexyd
{
template <typename Rule, typename Whitespace>
struct _wsd : rule_base
{
static constexpr auto is_branch = Rule::is_branch;
static constexpr auto is_unconditional_branch = Rule::is_unconditional_branch;
template <typename NextParser>
struct parser
{
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args)
-> lexy::rule_try_parse_result
{
using ws = decltype(token(loop(Whitespace{} | break_)));
lexy::engine_try_match<typename ws::token_engine>(reader);
return lexy::rule_parser<Rule, NextParser>::try_parse(context, reader,
LEXY_FWD(args)...);
}
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
using rule = decltype(loop(token(Whitespace{}) | break_) + Rule{});
return lexy::rule_parser<rule, NextParser>::parse(context, reader, LEXY_FWD(args)...);
}
};
template <typename Tag>
constexpr auto error() const
{
static_assert(lexy::is_token<Rule>);
return Rule{}.template error<Tag>();
}
};
/// Matches whitespace before parsing rule.
template <typename Rule, typename Whitespace>
LEXY_DEPRECATED_WHITESPACE constexpr auto whitespaced(Rule, Whitespace)
{
return _wsd<Rule, Whitespace>{};
}
} // namespace lexyd
#endif // LEXY_DSL_WHITESPACE_HPP_INCLUDED
| 34.565421 | 100 | 0.596728 | IohannRabeson |
7bf87b1b45b9b9d354e72a09ee6337256937ac23 | 5,695 | cpp | C++ | fft.cpp | doug65536/FastSpectrumAnalyzer | 061022f5acb50929c5cd84ec914220e9a087c356 | [
"MIT"
] | 4 | 2016-11-29T06:48:50.000Z | 2021-05-07T00:47:34.000Z | fft.cpp | doug65536/FastSpectrumAnalyzer | 061022f5acb50929c5cd84ec914220e9a087c356 | [
"MIT"
] | null | null | null | fft.cpp | doug65536/FastSpectrumAnalyzer | 061022f5acb50929c5cd84ec914220e9a087c356 | [
"MIT"
] | null | null | null | #include "fft.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <memory>
#include <limits>
#include "stopwatch.h"
#include "asserts.h"
static double worstError0, worstError1, worstError2;
//template<typename T, int logPoints>
//int64_t testffttype(FFT<T, logPoints> &fft, bool fulltest = false)
//{
// typedef T Real;
//// std::array<Real, 65536> input;
// std::vector<Real> result;
//
// int64_t microseconds = 0;
// int64_t bestMicroseconds = std::numeric_limits<int64_t>::max();
// int64_t totalMicroseconds = 0;
// int64_t totalCount = 0;
//
// // Exhaustive brute force test that mixes a pair of waves with
// // different amplitudes at two different nearby frequencies,
// // for halfPoints points - 2. Error and worst case error are measured.
//
// for (auto chk = 1, e = fft.getHalfPoints()-2; chk < e; ++chk)
// {
// auto freq = fft.getFrequency(chk);
// auto freq2 = fft.getFrequency(chk+2);
//
// Stopwatch sw;
// sw.start();
// fft.selfTestIn(freq, 1, false);
// fft.selfTestIn(freq2, 0.001, true);
// fft.process(std::back_inserter(result));
// sw.update();
// microseconds = sw.elapsedMicroseconds();
// totalMicroseconds += microseconds;
// ++totalCount;
// if (bestMicroseconds > microseconds)
// bestMicroseconds = microseconds;
//
// // for (std::size_t i = 0, e = input.size(); i != e; ++i)
//// {
//// input[i] = Real(sin(2 * 3.14159265358979323 * freq * i / fft.maxFreq())
//// + 0.001 * sin(2 * 3.14159265358979323 * freq2 * i / fft.maxFreq()));
//// }
//
//// fft.process(input.begin(), input.end(), std::back_inserter(result));
//
// auto dumpResult = [&]
// {
// for (auto i = result.begin() + std::max(chk - 3, 0),
// e = result.begin() + std::min(chk + 3, fft.getPoints());
// i != e; ++i)
// std::cout << (i - result.begin()) << ": " << std::setprecision(16) << *i << std::endl;
// std::cout << std::endl;
// };
//
// for (auto i = 0, e = fft.getHalfPoints(); i < e; ++i)
// {
// // If not full test, check the first 100 values
// if (i >= 50 && !fulltest)
// {
// // Shortcuts
//
// // Jump to 100 points before the check frequency
// // or do nothing if there aren't over 100 points
// // after i before chk
// if (i < chk - 50)
// {
//// std::cout << "Cheating from " << i << " to " << (chk - 100) << std::endl;
// i = chk - 50;
// }
//
// // Jump to 100 points before the end if after both
// // check points
// if (i > chk + 2 + 50 && i < e - 100)
// {
//// std::cout << "Cheating from " << i << " to " << (e - 100) << std::endl;
// i = e - 50;
// }
// }
//
// double error0 = std::abs(0.0 - result[i]);
// double error1 = std::abs(1.0 - result[i]);
// double error2 = std::abs(0.001 - result[i]);
//
// if (i == chk)
// {
// worstError1 = std::max(worstError1, error1);
// if (!AssertBreakForce(error1 < 0.0015))
// dumpResult();
// }
// else if (i == chk + 2)
// {
// worstError2 = std::max(worstError2, error2);
// if (!AssertBreakForce(error2 < 0.0002))
// // float, logPoints=15, i=12186, 0.0006371234194375575
// dumpResult();
// }
// else
// {
// worstError0 = std::max(worstError0, error0);
// if (!AssertBreakForce(error0 < 0.00075))
// dumpResult();
// }
// }
//
// result.clear();
// }
//
// std::cout << "Worst error 0: " << worstError0 << std::endl;
// std::cout << "Worst error 1: " << worstError1 << std::endl;
// std::cout << "Worst error 2: " << worstError2 << std::endl;
// std::cout << "Best microseconds: " << bestMicroseconds << std::endl;
//
// return totalMicroseconds / totalCount;
//}
//template<typename T, int points>
//class TestFFT
//{
//public:
// static void test()
// {
// // Recursively expand and call templates of smaller point count
// // if the point count is > 4
// std::conditional<(points > 4), TestFFT<T, points-1>, Empty>::type::test();
//
// auto fft = std::make_shared<FFT<T, points>>(44100);
//
// std::cout << "Size is " << (sizeof(*fft)) << std::endl;
//
// auto avg = testffttype(*fft);
// std::cout << (1<<points) << " point: " << avg << " us" << std::endl;
// }
//
//private:
// class Empty
// {
// public:
// static void test()
// {
// }
// };
//};
//
//void testfft()
//{
// // 256 point is about 5 microseconds
// // 1024 point is about 21 microseconds
// // 2048 point is about 49 microseconds
// // 4096 point is about 141 microseconds
// // 8192 point is about 332 microseconds
// // 16384 point is about 837 microseconds
// // 32768 point is about 2214 microseconds
// // 65536 point is about 5233 microseconds
// std::cout << "===================" << std::endl;
// std::cout << "double" << std::endl;
// std::cout << "===================" << std::endl;
// TestFFT<double, 12>::test();
// TestFFT<float, 12>::test();
//}
| 33.89881 | 104 | 0.482704 | doug65536 |
7bfff6ec873202ad7b3c311ab4a11c2ff58abb1c | 233 | cpp | C++ | uva/c/11875.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11875.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11875.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include<cstdio>
main() {
int i, j, n, T, C = 1;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
for (i = 0; i < n; ++i) {
scanf("%d", &j);
if (i == n/2)
printf("Case %d: %d\n", C++, j);
}
}
}
| 16.642857 | 40 | 0.347639 | dk00 |
d0007e4615c7d6b1caca6af03543590e94d246ee | 4,831 | cpp | C++ | lib/EEPROM/EEPROMController.cpp | samuelmoll/TapTimer | 8391d248b09ad8d80df5d640728f9ad57a4b6b1c | [
"MIT"
] | null | null | null | lib/EEPROM/EEPROMController.cpp | samuelmoll/TapTimer | 8391d248b09ad8d80df5d640728f9ad57a4b6b1c | [
"MIT"
] | null | null | null | lib/EEPROM/EEPROMController.cpp | samuelmoll/TapTimer | 8391d248b09ad8d80df5d640728f9ad57a4b6b1c | [
"MIT"
] | null | null | null | #include "EEPROMController.hpp"
EEPROMController::EEPROMController(Valve* v1, Valve* v2, Valve* v3, Valve* v4) {
valve1 = v1;
valve2 = v2;
valve3 = v3;
valve4 = v4;
}
void EEPROMController::initValves(){
uint16_t sig;
sig = eeprom_read_word(&signature);
Serial.print(sig);
if (sig == 0x74EE) {
Serial.print("EEPROM data detected - loading valves.");
uint8_t v1StartHour;
uint8_t v1StartMin;
uint8_t v1Duration;
uint8_t v1Period;
uint8_t v1Enable;
v1StartHour = eeprom_read_byte(&valve1StartHour);
v1StartMin = eeprom_read_byte(&valve1StartMin);
v1Duration = eeprom_read_byte(&valve1Duration);
v1Period = eeprom_read_byte(&valve1Period);
v1Enable = eeprom_read_byte(&valve1Enable);
valve1->setStartTime(v1StartHour, v1StartMin);
valve1->setDuration(v1Duration);
valve1->setPeriod(v1Period);
valve1->enableValve(v1Enable);
uint8_t v2StartHour;
uint8_t v2StartMin;
uint8_t v2Duration;
uint8_t v2Period;
uint8_t v2Enable;
v2StartHour = eeprom_read_byte(&valve2StartHour);
v2StartMin = eeprom_read_byte(&valve2StartMin);
v2Duration = eeprom_read_byte(&valve2Duration);
v2Period = eeprom_read_byte(&valve2Period);
v2Enable = eeprom_read_byte(&valve2Enable);
valve2->setStartTime(v2StartHour, v2StartMin);
valve2->setDuration(v2Duration);
valve2->setPeriod(v2Period);
valve2->enableValve(v2Enable);
uint8_t v3StartHour;
uint8_t v3StartMin;
uint8_t v3Duration;
uint8_t v3Period;
uint8_t v3Enable;
v3StartHour = eeprom_read_byte(&valve3StartHour);
v3StartMin = eeprom_read_byte(&valve3StartMin);
v3Duration = eeprom_read_byte(&valve3Duration);
v3Period = eeprom_read_byte(&valve3Period);
v3Enable = eeprom_read_byte(&valve3Enable);
valve3->setStartTime(v3StartHour, v3StartMin);
valve3->setDuration(v3Duration);
valve3->setPeriod(v3Period);
valve3->enableValve(v3Enable);
uint8_t v4StartHour;
uint8_t v4StartMin;
uint8_t v4Duration;
uint8_t v4Period;
uint8_t v4Enable;
v4StartHour = eeprom_read_byte(&valve4StartHour);
v4StartMin = eeprom_read_byte(&valve4StartMin);
v4Duration = eeprom_read_byte(&valve4Duration);
v4Period = eeprom_read_byte(&valve4Period);
v4Enable = eeprom_read_byte(&valve4Enable);
valve4->setStartTime(v4StartHour, v4StartMin);
valve4->setDuration(v4Duration);
valve4->setPeriod(v4Period);
valve4->enableValve(v4Enable);
}
}
void EEPROMController::updateEEPROM(){
Serial.println("updating EEprom");
uint8_t v1StartHour = valve1->getStartHour();
uint8_t v1StartMin = valve1->getStartMinute();
uint8_t v1Duration = valve1->getDuration();
uint8_t v1Period = valve1->getPeriod();
uint8_t v1Enable = valve1->isEnabled();
eeprom_update_byte((uint8_t*)&valve1StartHour, v1StartHour);
eeprom_update_byte((uint8_t*)&valve1StartMin, v1StartMin);
eeprom_update_byte((uint8_t*)&valve1Duration, v1Duration);
eeprom_update_byte((uint8_t*)&valve1Period, v1Period);
eeprom_update_byte((uint8_t*)&valve1Enable, v1Enable);
uint8_t v2StartHour = valve2->getStartHour();
uint8_t v2StartMin = valve2->getStartMinute();
uint8_t v2Duration = valve2->getDuration();
uint8_t v2Period = valve2->getPeriod();
uint8_t v2Enable = valve2->isEnabled();
eeprom_update_byte((uint8_t*)&valve2StartHour, v2StartHour);
eeprom_update_byte((uint8_t*)&valve2StartMin, v2StartMin);
eeprom_update_byte((uint8_t*)&valve2Duration, v2Duration);
eeprom_update_byte((uint8_t*)&valve2Period, v2Period);
eeprom_update_byte((uint8_t*)&valve2Enable, v2Enable);
uint8_t v3StartHour = valve3->getStartHour();
uint8_t v3StartMin = valve3->getStartMinute();
uint8_t v3Duration = valve3->getDuration();
uint8_t v3Period = valve3->getPeriod();
uint8_t v3Enable = valve3->isEnabled();
eeprom_update_byte((uint8_t*)&valve3StartHour, v3StartHour);
eeprom_update_byte((uint8_t*)&valve3StartMin, v3StartMin);
eeprom_update_byte((uint8_t*)&valve3Duration, v3Duration);
eeprom_update_byte((uint8_t*)&valve3Period, v3Period);
eeprom_update_byte((uint8_t*)&valve3Enable, v3Enable);
uint8_t v4StartHour = valve4->getStartHour();
uint8_t v4StartMin = valve4->getStartMinute();
uint8_t v4Duration = valve4->getDuration();
uint8_t v4Period = valve4->getPeriod();
uint8_t v4Enable = valve4->isEnabled();
eeprom_update_byte((uint8_t*)&valve4StartHour, v4StartHour);
eeprom_update_byte((uint8_t*)&valve4StartMin, v4StartMin);
eeprom_update_byte((uint8_t*)&valve4Duration, v4Duration);
eeprom_update_byte((uint8_t*)&valve4Period, v4Period);
eeprom_update_byte((uint8_t*)&valve4Enable, v4Enable);
eeprom_update_word((uint16_t*)&signature, 0x74EE);
} | 36.598485 | 80 | 0.732354 | samuelmoll |
d00111b7d02c5829f3f6b20ff69e453bed2b1704 | 1,576 | cpp | C++ | Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | 5 | 2019-02-26T18:46:52.000Z | 2022-01-27T23:48:26.000Z | Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | 1 | 2020-06-07T23:44:29.000Z | 2021-04-03T18:49:54.000Z | Sources/Vulkan/erm/rendering/buffers/IBuffer.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | null | null | null | #include "erm/rendering/buffers/IBuffer.h"
#include "erm/rendering/Device.h"
#include "erm/utils/Utils.h"
#include "erm/utils/VkUtils.h"
namespace erm {
IBuffer::IBuffer(
Device& device,
size_t size,
vk::BufferUsageFlags buf,
vk::MemoryPropertyFlags mpf)
: mDevice(device)
, mBufferSize(size)
, mBuf(buf)
, mMpf(mpf)
{
VkUtils::CreateBufferUnique(
device.GetVkPhysicalDevice(),
device.GetVkDevice(),
size,
buf,
mpf,
mBuffer,
mBufferMemory);
mLayout.mBuffer = mBuffer.get();
mLayout.mInfos.emplace_back(BufferInfo {0, mBufferSize});
}
IBuffer::IBuffer(const IBuffer& other)
: mDevice(other.mDevice)
, mBufferSize(other.mBufferSize)
, mBuf(other.mBuf)
, mMpf(other.mMpf)
{
VkUtils::CreateBufferUnique(
mDevice.GetVkPhysicalDevice(),
mDevice.GetVkDevice(),
mBufferSize,
mBuf,
mMpf,
mBuffer,
mBufferMemory);
mLayout.mBuffer = mBuffer.get();
mLayout.mInfos.emplace_back(BufferInfo {0, mBufferSize});
}
IBuffer::IBuffer(IBuffer&& other)
: mDevice(other.mDevice)
, mBufferSize(other.mBufferSize)
, mLayout(std::move(other.mLayout))
, mBuf(std::move(other.mBuf))
, mMpf(std::move(other.mMpf))
, mBuffer(std::move(other.mBuffer))
, mBufferMemory(std::move(other.mBufferMemory))
{}
IBuffer& IBuffer::operator=(IBuffer&& other)
{
if (this == &other)
return *this;
ASSERT(&mDevice == &other.mDevice);
mBufferSize = other.mBufferSize;
mBuf = std::move(other.mBuf);
mMpf = std::move(other.mMpf);
mBuffer = std::move(other.mBuffer);
mBufferMemory = std::move(other.mBufferMemory);
return *this;
}
} // namespace erm
| 20.205128 | 58 | 0.713198 | JALB91 |
d00140b5e36afdf186c95bc8c102d3d5a7b9dded | 3,360 | hpp | C++ | modules/cvv/src/qtutil/signalslot.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 36 | 2017-04-13T03:01:06.000Z | 2022-01-09T10:38:27.000Z | modules/cvv/src/qtutil/signalslot.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7 | 2018-10-16T07:28:12.000Z | 2018-11-15T02:21:16.000Z | modules/cvv/src/qtutil/signalslot.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 22 | 2015-10-23T19:36:18.000Z | 2021-02-02T12:20:32.000Z | #ifndef CVVISUAL_SIGNALEMITTER_HPP
#define CVVISUAL_SIGNALEMITTER_HPP
// std
#include <functional>
#include <stdexcept>
#include <opencv2/core.hpp>
// QT
#include <QObject>
#include <QString>
namespace cvv
{
namespace qtutil
{
/**
* @brief The Signal class can be used for privat or static signals and in case
* of
* conflicts between templates and Q_OBJECT.
*/
class Signal : public QObject
{
Q_OBJECT
public:
/**
* @brief Constructor
* @param parent The parent
*/
Signal(QObject *parent = nullptr) : QObject{ parent }
{
}
/**
* @brief Emits the signal.
* @param args The arguments
*/
void emitSignal() const
{
emit signal();
}
signals:
/**
* @brief The signal emited by emitSignal.
*/
void signal() const;
};
/**
* @brief The Slot class can be used for static slots and in case of conflicts
* between
* templates and Q_OBJECT.
*/
class Slot : public QObject
{
Q_OBJECT
public:
/**
* @brief Constructor
* @param f Function called by the slot slot()
* @throw std::invalid_argument If f is invalide
* @param parent The parent
*/
Slot(const std::function<void()> &f, QObject *parent = nullptr)
: QObject{ parent }, function_{ f }
{
if (!f)
throw std::invalid_argument{ "invalid function" };
}
public
slots:
/**
* @brief The slot calling function()
*/
void slot() const
{
function_();
}
private:
/**
* @brief The function called by the slot slot()
*/
std::function<void()> function_;
};
// ///////////////////////////////////////////////////////////////
// manual "templating" for classes Signal and Slot
// ///////////////////////////////////////////////////////////////
/**
* @brief Similar to Signal (difference: it accepts a QStriang).
*/
class SignalQString : public QObject
{
Q_OBJECT
public:
SignalQString(QObject *parent = nullptr) : QObject{ parent }
{
}
void emitSignal(const QString &t) const
{
emit signal(t);
}
signals:
void signal(QString t) const;
};
/**
* @brief Similar to Slot (difference: it accepts a QString).
*/
class SlotQString : public QObject
{
Q_OBJECT
public:
SlotQString(const std::function<void(QString)> &f,
QObject *parent = nullptr)
: QObject{ parent }, function_{ f }
{
if (!f)
throw std::invalid_argument{ "invalide function" };
}
~SlotQString()
{
}
public
slots:
void slot(QString t) const
{
function_(t);
}
private:
std::function<void(QString)> function_;
};
/**
* @brief Similar to Signal (difference: it accepts a cv::Mat&).
*/
class SignalMatRef : public QObject
{
Q_OBJECT
public:
SignalMatRef(QObject *parent = nullptr) : QObject{ parent }
{
}
void emitSignal(cv::Mat &mat) const
{
emit signal(mat);
}
signals:
/**
* @brief The signal emited by emitSignal.
*/
void signal(cv::Mat &mat) const;
};
/**
* @brief Similar to Slot (difference: it accepts a bool).
*/
class SlotBool : public QObject
{
Q_OBJECT
public:
SlotBool(const std::function<void(bool)> &f, QObject *parent = nullptr)
: QObject{ parent }, function_{ f }
{
if (!f)
throw std::invalid_argument{ "invalide function" };
}
public
slots:
void slot(bool t) const
{
function_(t);
}
private:
std::function<void(bool)> function_;
};
}
} // end namespaces qtutil, cvv
#endif // CVVISUAL_SIGNALEMITTER_HPP
| 17.409326 | 79 | 0.624107 | Nondzu |
d002dacc2b7be2a4fc0cc23114bf1b0d8927518a | 4,849 | cpp | C++ | demos/monotone/main.cpp | Roastmaster/soloud | cf1252478439aca4e2505c3e4d22c1810b13a841 | [
"Zlib"
] | 13 | 2016-10-19T00:33:23.000Z | 2022-02-23T07:55:30.000Z | demos/monotone/main.cpp | Roastmaster/soloud | cf1252478439aca4e2505c3e4d22c1810b13a841 | [
"Zlib"
] | 1 | 2020-10-03T03:47:09.000Z | 2020-10-03T03:47:09.000Z | demos/monotone/main.cpp | Roastmaster/soloud | cf1252478439aca4e2505c3e4d22c1810b13a841 | [
"Zlib"
] | 7 | 2017-07-19T11:24:27.000Z | 2022-02-23T07:55:34.000Z | /*
SoLoud audio engine
Copyright (c) 2013-2015 Jari Komppa
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include "imgui.h"
#include "soloud_demo_framework.h"
#include "soloud.h"
#include "soloud_monotone.h"
#include "soloud_lofifilter.h"
#include "soloud_biquadresonantfilter.h"
#include "soloud_echofilter.h"
#include "soloud_dcremovalfilter.h"
SoLoud::Soloud gSoloud;
SoLoud::Monotone gMusic;
SoLoud::BiquadResonantFilter gBiquad;
SoLoud::LofiFilter gLofi;
SoLoud::EchoFilter gEcho;
SoLoud::DCRemovalFilter gDCRemoval;
int gMusichandle;
float filter_param0[4] = { 0, 0, 0, 0 };
float filter_param1[4] = { 1000, 8000, 0, 0 };
float filter_param2[4] = { 2, 3, 0, 0 };
int hwchannels = 4;
int waveform = 0;
void DemoMainloop()
{
gSoloud.setFilterParameter(gMusichandle, 0, 0, filter_param0[0]);
gSoloud.setFilterParameter(gMusichandle, 1, 0, filter_param0[1]);
gSoloud.setFilterParameter(gMusichandle, 2, 0, filter_param0[2]);
gSoloud.setFilterParameter(gMusichandle, 3, 0, filter_param0[3]);
gSoloud.setFilterParameter(gMusichandle, 0, 2, filter_param1[0]);
gSoloud.setFilterParameter(gMusichandle, 0, 3, filter_param2[0]);
gSoloud.setFilterParameter(gMusichandle, 1, 1, filter_param1[1]);
gSoloud.setFilterParameter(gMusichandle, 1, 2, filter_param2[1]);
DemoUpdateStart();
float *buf = gSoloud.getWave();
float *fft = gSoloud.calcFFT();
ONCE(ImGui::SetNextWindowPos(ImVec2(500, 20)));
ImGui::Begin("Output");
ImGui::PlotLines("##Wave", buf, 256, 0, "Wave", -1, 1, ImVec2(264, 80));
ImGui::PlotHistogram("##FFT", fft, 256/2, 0, "FFT", 0, 10, ImVec2(264,80),8);
ImGui::Text("Music volume : %d%%", (int)floor(gSoloud.getVolume(gMusichandle) * 100));
ImGui::Text("Active voices : %d", gSoloud.getActiveVoiceCount());
ImGui::End();
ONCE(ImGui::SetNextWindowPos(ImVec2(20, 20)));
ImGui::Begin("Control");
if (ImGui::SliderInt("Channels", &hwchannels, 1, 4))
{
gMusic.setParams(hwchannels, waveform);
}
if (ImGui::CollapsingHeader("Waveform", (const char*)0, true, false))
{
if (ImGui::RadioButton("Square", waveform == SoLoud::Monotone::SQUARE))
{
waveform = SoLoud::Monotone::SQUARE;
gMusic.setParams(hwchannels, waveform);
}
if (ImGui::RadioButton("Saw", waveform == SoLoud::Monotone::SAW))
{
waveform = SoLoud::Monotone::SAW;
gMusic.setParams(hwchannels, waveform);
}
if (ImGui::RadioButton("Sin", waveform == SoLoud::Monotone::SIN))
{
waveform = SoLoud::Monotone::SIN;
gMusic.setParams(hwchannels, waveform);
}
if (ImGui::RadioButton("SawSin", waveform == SoLoud::Monotone::SAWSIN))
{
waveform = SoLoud::Monotone::SAWSIN;
gMusic.setParams(hwchannels, waveform);
}
}
ImGui::Separator();
ImGui::Text("Biquad filter (lowpass)");
ImGui::SliderFloat("Wet##4", &filter_param0[0], 0, 1);
ImGui::SliderFloat("Frequency##4", &filter_param1[0], 0, 8000);
ImGui::SliderFloat("Resonance##4", &filter_param2[0], 1, 20);
ImGui::Separator();
ImGui::Text("Lofi filter");
ImGui::SliderFloat("Wet##2", &filter_param0[1], 0, 1);
ImGui::SliderFloat("Rate##2", &filter_param1[1], 1000, 8000);
ImGui::SliderFloat("Bit depth##2", &filter_param2[1], 0, 8);
ImGui::Separator();
ImGui::Text("Echo filter");
ImGui::SliderFloat("Wet##3", &filter_param0[2], 0, 1);
ImGui::Separator();
ImGui::Text("DC removal filter");
ImGui::SliderFloat("Wet##1", &filter_param0[3], 0, 1);
ImGui::End();
DemoUpdateEnd();
}
int DemoEntry(int argc, char *argv[])
{
gMusic.load("audio/Jakim - Aboriginal Derivatives.mon");
gMusic.setParams(10);
gEcho.setParams(0.2f, 0.5f, 0.05f);
gBiquad.setParams(SoLoud::BiquadResonantFilter::LOWPASS, 44100, 4000, 2);
gMusic.setLooping(1);
gMusic.setFilter(0, &gBiquad);
gMusic.setFilter(1, &gLofi);
gMusic.setFilter(2, &gEcho);
gMusic.setFilter(3, &gDCRemoval);
gSoloud.init(SoLoud::Soloud::CLIP_ROUNDOFF | SoLoud::Soloud::ENABLE_VISUALIZATION);
gMusichandle = gSoloud.play(gMusic);
waveform = SoLoud::Monotone::SAW;
gMusic.setParams(hwchannels, waveform);
return 0;
} | 31.901316 | 91 | 0.716849 | Roastmaster |
d003ae19dbe95949e6e4f1e98779e8d6585a6096 | 4,364 | cpp | C++ | pxr/base/tf/testenv/stopwatch.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 3,680 | 2016-07-26T18:28:11.000Z | 2022-03-31T09:55:05.000Z | pxr/base/tf/testenv/stopwatch.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 1,759 | 2016-07-26T19:19:59.000Z | 2022-03-31T21:24:00.000Z | pxr/base/tf/testenv/stopwatch.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 904 | 2016-07-26T18:33:40.000Z | 2022-03-31T09:55:16.000Z | //
// Copyright 2016 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 "pxr/pxr.h"
#include "pxr/base/tf/regTest.h"
#include "pxr/base/tf/stopwatch.h"
#include "pxr/base/tf/stringUtils.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
PXR_NAMESPACE_USING_DIRECTIVE
static bool
IsClose(double a, double b, double epsilon=1e-3)
{
auto diff = fabs(a-b);
return diff <= epsilon * abs(a)
&& diff <= epsilon * abs(b);
}
// XXX: We use a rather large epsilon to account for
// systems with very large sleep times. We still expect
// variance to be within 10% (see IsClose above) for details.
static constexpr double EPSILON = 1e-1;
static bool
Test_TfStopwatch()
{
bool ok = true;
// Test constructor
TfStopwatch watch1;
// Test copy constructor.
TfStopwatch watchCopy(watch1);
if (watchCopy.GetSeconds() != watch1.GetSeconds()) {
cout << "expected watchCopy to contain (0.0) but got (\""
<< watchCopy.GetSeconds()
<< ")" << endl;
ok = false;
}
// Test the timer
// Delay .5 seconds (500 million nanoseconds)
//
watch1.Start();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
watch1.Stop();
// The value of watch1 should be near 0.5 seconds
if (!IsClose(watch1.GetSeconds(), 0.5, EPSILON)) {
cout << "Sleep for .5 seconds but measured time was "
<< watch1.GetSeconds()
<< " seconds."
<< endl;
ok = false;
}
// Delay another .5 seconds and see if watch is near 1
//
watch1.Start();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
watch1.Stop();
// The value of watch1 should be near 1.0 seconds
if (!IsClose(watch1.GetSeconds(), 1.0, EPSILON)) {
cout << "Sleep for 1.0 seconds but measured time was "
<< watch1.GetSeconds()
<< " seconds."
<< endl;
ok = false;
}
// The value of watchCopy should be zero
//
if (watchCopy.GetSeconds() != 0.0) {
cout << "watchCopy has non-zero initial time of "
<< watchCopy.GetSeconds()
<< " seconds."
<< endl;
ok = false;
}
// Test AddFrom
//
watchCopy.AddFrom(watch1);
if (!IsClose(watchCopy.GetSeconds(), watch1.GetSeconds())) {
cout << "AddFrom: watchCopy has time of "
<< watchCopy.GetSeconds()
<< " instead of "
<< watch1.GetSeconds()
<< " seconds."
<< endl;
ok = false;
}
// Test AddFrom
//
watchCopy.AddFrom(watch1);
if (!IsClose(watchCopy.GetSeconds()/watch1.GetSeconds(), 2.0)) {
cout << "AddFrom: watchCopy has time of "
<< watchCopy.GetSeconds()
<< " instead of "
<< 2 * watch1.GetSeconds()
<< " seconds."
<< endl;
ok = false;
}
// Test Reset
watchCopy.Reset();
if (watchCopy.GetSeconds() != 0.0) {
cout << "Reset: watchCopy has time of "
<< watchCopy.GetSeconds()
<< " instead of "
<< 0.0
<< " seconds."
<< endl;
ok = false;
}
return ok;
}
TF_ADD_REGTEST(TfStopwatch);
| 28.710526 | 75 | 0.597388 | DougRogers-DigitalFish |
d007579be52b2bc3053deb5e6505441e1af4de2d | 2,791 | cc | C++ | src/mediaengine/open_cdm_mediaengine_impl.cc | vishalbhoj/open-content-decryption-module | 8a08d6c25a612be0a1a83493cb1229d5748f2a21 | [
"Apache-2.0"
] | 7 | 2018-12-19T15:04:49.000Z | 2020-05-22T07:28:33.000Z | src/mediaengine/open_cdm_mediaengine_impl.cc | vishalbhoj/open-content-decryption-module | 8a08d6c25a612be0a1a83493cb1229d5748f2a21 | [
"Apache-2.0"
] | 4 | 2018-07-11T15:09:08.000Z | 2018-10-19T14:19:56.000Z | src/mediaengine/open_cdm_mediaengine_impl.cc | vishalbhoj/open-content-decryption-module | 8a08d6c25a612be0a1a83493cb1229d5748f2a21 | [
"Apache-2.0"
] | 5 | 2018-06-27T19:19:42.000Z | 2019-05-02T05:09:27.000Z | /*
* Copyright 2014 Fraunhofer FOKUS
*
* 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 "open_cdm_mediaengine_impl.h"
#include <rpc_cdm_mediaengine_handler.h>
#include <cdm_logging.h>
namespace media {
OpenCdmMediaengineImpl::OpenCdmMediaengineImpl(char *session_id_val,
uint32_t session_id_len) {
media_engine_com_ = &(RpcCdmMediaengineHandler::getInstance());
CDM_DLOG() << "Created new media engine impl ";
if( !media_engine_com_->CreateMediaEngineSession(session_id_val,
session_id_len, 0, 0)) {
CDM_DLOG() << "Failed to create media engine session";
}
}
OpenCdmMediaengineImpl::OpenCdmMediaengineImpl(char *session_id_val,
uint32_t session_id_len,
uint8_t *auth_data_val,
uint32_t auth_data_len) {
// create media engine session
media_engine_com_ = &(RpcCdmMediaengineHandler::getInstance());
if(!media_engine_com_->CreateMediaEngineSession(session_id_val,
session_id_len,
auth_data_val,
auth_data_len)) {
CDM_DLOG() << "Failed to create media engine session";
}
}
OpenCdmMediaengineImpl::~OpenCdmMediaengineImpl() {
CDM_DLOG() << "OpenCdmMediaengineImpl destruct!";
}
DecryptResponse OpenCdmMediaengineImpl::Decrypt(const uint8_t *pbIv,
uint32_t cbIv,
const uint8_t *pbData,
uint32_t cbData, uint8_t *out,
uint32_t &out_size) {
printf("_------ Decrypt \n");
CDM_DLOG() << "OpenCdmMediaengineImpl::Decrypt: ";
DecryptResponse response;
response = media_engine_com_->Decrypt(pbIv, cbIv, pbData, cbData, out,
out_size);
return response;
}
int OpenCdmMediaengineImpl::ReleaseMem() {
CDM_DLOG() << "OpenCdmMediaengineImpl::ReleaseMem ";
int response;
response = media_engine_com_->ReleaseMem();
return response;
}
} // namespace media
| 37.716216 | 78 | 0.601218 | vishalbhoj |
d007dd1f0b1cb50a338cc2ad623470753bf57881 | 2,149 | cpp | C++ | euhat/common/JyBuf.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | euhat/common/JyBuf.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | euhat/common/JyBuf.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | #include <EuhatPreDef.h>
#include <common/OpCommon.h>
#include <common/JyDataStream.h>
#include <common/md5.h>
#include <common/JyDataCrypto.h>
#include "JyBuf.h"
#include <EuhatPostDef.h>
JyBuf::JyBuf(int len)
{
reset(len);
}
JyBuf::JyBuf(const string& str)
{
reset(opMemDup(str.c_str(), str.length()), str.length());
}
JyBuf::JyBuf(JyBuf&& in)
{
reset(std::move(in));
}
JyBuf::~JyBuf()
{
}
JyBuf& JyBuf::operator=(JyBuf&& in)
{
reset(std::move(in));
return *this;
}
void JyBuf::reset(JyBuf&& in)
{
data_.reset(in.data_.release());
size_ = in.size_;
in.size_ = 0;
}
void JyBuf::reset(int len)
{
if (len > 0)
data_.reset(new char[len]);
else
data_.reset();
size_ = len;
}
void JyBuf::reset(char *buf, int len)
{
data_.reset(buf);
size_ = len;
}
JyBuf JyBuf::md5(const JyBuf& in)
{
JyBuf out(16);
Md5Ctx md5;
md5Init(&md5);
md5Update(&md5, (unsigned char *)in.data_.get(), in.size_);
md5Final(&md5, (unsigned char *)out.data_.get());
return std::move(out);
}
JyBuf JyBuf::xorData(const JyBuf& other)
{
JyDataWriteStream ds;
::xorData(ds, data_.get(), size_, other);
JyBuf buf = std::move(ds.buf_);
buf.size_ = ds.size();
return std::move(buf);
}
int JyBuf::eq(const JyBuf& other)
{
return size_ == other.size_ && opMemEq(data_.get(), other.data_.get(), size_);
}
JyBufPool::JyBufPool(int unitSize, int maxReserved)
{
unitSize_ = unitSize;
maxReserved_ = maxReserved;
}
JyBufPool::~JyBufPool()
{
}
void JyBufPool::get(JyBufGuard &guard)
{
WhMutexGuard g(&mutex_);
guard.pool_ = this;
if (pool_.size() == 0)
{
guard.reset(new char[unitSize_]);
return;
}
guard.reset(pool_.front().release());
pool_.pop_front();
}
void JyBufPool::ret(char *p)
{
WhMutexGuard guard(&mutex_);
unique_ptr<char[]> ptr(p);
pool_.push_back(move(ptr));
if (pool_.size() > (size_t)maxReserved_)
pool_.pop_front();
}
JyBufGuard::JyBufGuard()
{
pool_ = NULL;
p_ = NULL;
}
JyBufGuard::~JyBufGuard()
{
reset();
}
void JyBufGuard::reset(char *p)
{
if (NULL != p_)
{
pool_->ret(p_);
}
p_ = p;
}
char *JyBufGuard::release()
{
char *p = p_;
p_ = NULL;
return p;
}
char *JyBufGuard::get()
{
return p_;
} | 14.82069 | 79 | 0.651931 | euhat |
d00c070a9b04ac395548f79326e857653e45567d | 392 | cc | C++ | chrome/browser/ui/constrained_window.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/browser/ui/constrained_window.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/browser/ui/constrained_window.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/constrained_window.h"
#include "base/logging.h"
void ConstrainedWindow::FocusConstrainedWindow() {
}
gfx::NativeWindow ConstrainedWindow::GetNativeWindow() {
NOTREACHED();
return NULL;
}
| 24.5 | 73 | 0.755102 | Scopetta197 |
d00da18a0a2cbde1713a1834424e176d8bdde966 | 425 | cpp | C++ | math/kth_root_mod/gen/small.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 290 | 2019-06-06T22:20:36.000Z | 2022-03-27T12:45:04.000Z | math/kth_root_mod/gen/small.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 536 | 2019-06-06T18:25:36.000Z | 2022-03-29T11:46:36.000Z | math/kth_root_mod/gen/small.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 82 | 2019-06-06T18:17:55.000Z | 2022-03-21T07:40:31.000Z | #include <iostream>
bool is_prime(long long a){
for (long long div=2;div*div<=a;++div){
if(a%div==0)return false;
}
return true;
}
int main() {
int t = 2397;
printf("%d\n", t);
int q=0;
for (long long p=2;p<30;++p){
if (!is_prime(p))continue;
for (long long k=0;k<p;++k){
for (long long y=0;y<p;++y){
printf("%lld %lld %lld\n", k, y, p);
++q;
}
}
}
return 0;
}
| 17 | 44 | 0.501176 | tko919 |