hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
38846959d5bf379d9561e83129412060a412a297
32,539
cc
C++
lib/packet.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
1
2020-02-13T07:15:58.000Z
2020-02-13T07:15:58.000Z
lib/packet.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
null
null
null
lib/packet.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
4
2021-11-11T21:47:10.000Z
2021-12-03T00:05:15.000Z
// -*- related-file-name: "../include/click/packet.hh" -*- /* * packet.{cc,hh} -- a packet structure. In the Linux kernel, a synonym for * `struct sk_buff' * Eddie Kohler, Robert Morris, Nickolai Zeldovich * * Copyright (c) 1999-2001 Massachusetts Institute of Technology * Copyright (c) 2008-2011 Regents of the University of California * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #define CLICK_PACKET_DEPRECATED_ENUM #include <click/packet.hh> #include <click/packet_anno.hh> #include <click/glue.hh> #include <click/sync.hh> #if CLICK_USERLEVEL || CLICK_MINIOS # include <unistd.h> #endif CLICK_DECLS /** @file packet.hh * @brief The Packet class models packets in Click. */ /** @class Packet * @brief A network packet. * @nosubgrouping * * Click's Packet class represents network packets within a router. Packet * objects are passed from Element to Element via the Element::push() and * Element::pull() functions. The vast majority of elements handle packets. * * A packet consists of a <em>data buffer</em>, which stores the actual packet * wire data, and a set of <em>annotations</em>, which store extra information * calculated about the packet, such as the destination address to be used for * routing. Every Packet object has different annotations, but a data buffer * may be shared among multiple Packet objects, saving memory and speeding up * packet copies. (See Packet::clone.) As a result a Packet's data buffer is * not writable. To write into a packet, turn it into a nonshared * WritablePacket first, using uniqueify(), push(), or put(). * * <h3>Data Buffer</h3> * * A packet's data buffer is a single flat array of bytes. The buffer may be * larger than the actual packet data, leaving unused spaces called * <em>headroom</em> and <em>tailroom</em> before and after the data proper. * Prepending headers or appending data to a packet can be quite efficient if * there is enough headroom or tailroom. * * The relationships among a Packet object's data buffer variables is shown * here: * * <pre> * data() end_data() * | | * |<- headroom() ->|<----- length() ----->|<- tailroom() ->| * | v v | * +================+======================+================+ * |XXXXXXXXXXXXXXXX| PACKET CONTENTS |XXXXXXXXXXXXXXXX| * +================+======================+================+ * ^ ^ * |<------------------ buffer_length() ------------------->| * | | * buffer() end_buffer() * </pre> * * Most code that manipulates packets is interested only in data() and * length(). * * To create a Packet, call one of the make() functions. To destroy a Packet, * call kill(). To clone a Packet, which creates a new Packet object that * shares this packet's data, call clone(). To uniqueify a Packet, which * unshares the packet data if necessary, call uniqueify(). To allocate extra * space for headers or trailers, call push() and put(). To remove headers or * trailers, call pull() and take(). * * <pre> * data() end_data() * | | * push() | pull() take() | put() * <======= | =======> <======= | =======> * v v * +===========+================================+===========+ * |XXXXXXXXXXX| PACKET CONTENTS |XXXXXXXXXXX| * +===========+================================+===========+ * </pre> * * Packet objects are implemented in different ways in different drivers. The * userlevel driver has its own C++ implementation. In the linuxmodule * driver, however, Packet is an overlay on Linux's native sk_buff * object: the Packet methods access underlying sk_buff data directly, with no * overhead. (For example, Packet::data() returns the sk_buff's data field.) * * <h3>Annotations</h3> * * Annotations are extra information about a packet above and beyond the * packet data. Packet supports several specific annotations, plus a <em>user * annotation area</em> available for arbitrary use by elements. * * <ul> * <li><b>Header pointers:</b> Each packet has three header pointers, designed * to point to the packet's MAC header, network header, and transport header, * respectively. Convenience functions like ip_header() access these pointers * cast to common header types. The header pointers are kept up to date when * operations like push() or uniqueify() change the packet's data buffer. * Header pointers can be null, and they can even point to memory outside the * current packet data bounds. For example, a MAC header pointer will remain * set even after pull() is used to shift the packet data past the MAC header. * As a result, functions like mac_header_offset() can return negative * numbers.</li> * <li><b>Timestamp:</b> A timestamp associated with the packet. Most packet * sources timestamp packets when they enter the router; other elements * examine or modify the timestamp.</li> * <li><b>Device:</b> A pointer to the device on which the packet arrived. * Only meaningful in the linuxmodule driver, but provided in every * driver.</li> * <li><b>Packet type:</b> A small integer indicating whether the packet is * meant for this host, broadcast, multicast, or some other purpose. Several * elements manipulate this annotation; in linuxmodule, setting the annotation * is required for the host network stack to process incoming packets * correctly.</li> * <li><b>Performance counter</b> (linuxmodule only): A 64-bit integer * intended to hold a performance counter value. Used by SetCycleCount and * others.</li> * <li><b>Next and previous packet:</b> Pointers provided to allow elements to * chain packets into a doubly linked list.</li> * <li><b>Annotations:</b> Each packet has @link Packet::anno_size anno_size * @endlink bytes available for annotations. Elements agree to use portions * of the annotation area to communicate per-packet information. Macros in * the <click/packet_anno.hh> header file define the annotations used by * Click's current elements. One common annotation is the network address * annotation -- see Packet::dst_ip_anno(). Routing elements, such as * RadixIPLookup, set the address annotation to indicate the desired next hop; * ARPQuerier uses this annotation to query the next hop's MAC.</li> * </ul> * * New packets start wth all annotations set to zero or null. Cloning a * packet copies its annotations. */ /** @class WritablePacket * @brief A network packet believed not to be shared. * * The WritablePacket type represents Packet objects whose data buffers are * not shared. As a result, WritablePacket's versions of functions that * access the packet data buffer, such as data(), end_buffer(), and * ip_header(), return mutable pointers (<tt>char *</tt> rather than <tt>const * char *</tt>). * * WritablePacket objects are created by Packet::make(), Packet::uniqueify(), * Packet::push(), and Packet::put(), which ensure that the returned packet * does not share its data buffer. * * WritablePacket's interface is the same as Packet's except for these type * differences. For documentation, see Packet. * * @warning The WritablePacket convention reduces the likelihood of error * when modifying packet data, but does not eliminate it. For instance, by * calling WritablePacket::clone(), it is possible to create a WritablePacket * whose data is shared: * @code * Packet *p = ...; * if (WritablePacket *q = p->uniqueify()) { * Packet *p2 = q->clone(); * assert(p2); * q->ip_header()->ip_v = 6; // modifies p2's data as well * } * @endcode * Avoid writing buggy code like this! Use WritablePacket selectively, and * try to avoid calling WritablePacket::clone() when possible. */ Packet::~Packet() { // This is a convenient place to put static assertions. static_assert(addr_anno_offset % 8 == 0 && user_anno_offset % 8 == 0, "Annotations must begin at multiples of 8 bytes."); static_assert(addr_anno_offset + addr_anno_size <= anno_size, "Annotation area too small for address annotations."); static_assert(user_anno_offset + user_anno_size <= anno_size, "Annotation area too small for user annotations."); static_assert(dst_ip_anno_offset == DST_IP_ANNO_OFFSET && dst_ip6_anno_offset == DST_IP6_ANNO_OFFSET && dst_ip_anno_size == DST_IP_ANNO_SIZE && dst_ip6_anno_size == DST_IP6_ANNO_SIZE && dst_ip_anno_size == 4 && dst_ip6_anno_size == 16 && dst_ip_anno_offset + 4 <= anno_size && dst_ip6_anno_offset + 16 <= anno_size, "Address annotations at unexpected locations."); static_assert((default_headroom & 3) == 0, "Default headroom should be a multiple of 4 bytes."); #if CLICK_LINUXMODULE static_assert(sizeof(Anno) <= sizeof(((struct sk_buff *)0)->cb), "Anno structure too big for Linux packet annotation area."); #endif #if CLICK_LINUXMODULE panic("Packet destructor"); #else if (_data_packet) _data_packet->kill(); # if CLICK_USERLEVEL || CLICK_MINIOS else if (_head && _destructor) _destructor(_head, _end - _head, _destructor_argument); else delete[] _head; # elif CLICK_BSDMODULE if (_m) m_freem(_m); # endif _head = _data = 0; #endif } #if !CLICK_LINUXMODULE # if HAVE_CLICK_PACKET_POOL // ** Packet pools ** // Click configurations usually allocate & free tons of packets and it's // important to do so quickly. This specialized packet allocator saves // pre-initialized Packet objects, either with or without data, for fast // reuse. It can support multithreaded deployments: each thread has its own // pool, with a global pool to even out imbalance. # define CLICK_PACKET_POOL_BUFSIZ 2048 # define CLICK_PACKET_POOL_SIZE 1000 // see LIMIT in packetpool-01.testie # define CLICK_GLOBAL_PACKET_POOL_COUNT 16 namespace { struct PacketData { PacketData* next; // link to next free data buffer in pool # if HAVE_MULTITHREAD PacketData* batch_next; // link to next buffer batch unsigned batch_pdcount; // # buffers in this batch # endif }; struct PacketPool { WritablePacket* p; // free packets, linked by p->next() unsigned pcount; // # packets in `p` list PacketData* pd; // free data buffers, linked by pd->next unsigned pdcount; // # buffers in `pd` list # if HAVE_MULTITHREAD PacketPool* thread_pool_next; // link to next per-thread pool # endif }; } # if HAVE_MULTITHREAD static __thread PacketPool *thread_packet_pool; struct GlobalPacketPool { WritablePacket* pbatch; // batches of free packets, linked by p->prev() // p->anno_u32(0) is # packets in batch unsigned pbatchcount; // # batches in `pbatch` list PacketData* pdbatch; // batches of free data buffers unsigned pdbatchcount; // # batches in `pdbatch` list PacketPool* thread_pools; // all thread packet pools volatile uint32_t lock; }; static GlobalPacketPool global_packet_pool; #else static PacketPool global_packet_pool; # endif /** @brief Return the local packet pool for this thread. @pre make_local_packet_pool() has succeeded on this thread. */ static inline PacketPool& local_packet_pool() { # if HAVE_MULTITHREAD return *thread_packet_pool; # else // If not multithreaded, there is only one packet pool. return global_packet_pool; # endif } /** @brief Create and return a local packet pool for this thread. */ static inline PacketPool* make_local_packet_pool() { # if HAVE_MULTITHREAD PacketPool *pp = thread_packet_pool; if (!pp && (pp = new PacketPool)) { memset(pp, 0, sizeof(PacketPool)); while (atomic_uint32_t::swap(global_packet_pool.lock, 1) == 1) /* do nothing */; pp->thread_pool_next = global_packet_pool.thread_pools; global_packet_pool.thread_pools = pp; thread_packet_pool = pp; click_compiler_fence(); global_packet_pool.lock = 0; } return pp; # else return &global_packet_pool; # endif } WritablePacket * WritablePacket::pool_allocate(bool with_data) { PacketPool& packet_pool = *make_local_packet_pool(); (void) with_data; # if HAVE_MULTITHREAD // Steal packets and/or data from the global pool if there's nothing on // the local pool. if ((!packet_pool.p && global_packet_pool.pbatch) || (with_data && !packet_pool.pd && global_packet_pool.pdbatch)) { while (atomic_uint32_t::swap(global_packet_pool.lock, 1) == 1) /* do nothing */; WritablePacket *pp; if (!packet_pool.p && (pp = global_packet_pool.pbatch)) { global_packet_pool.pbatch = static_cast<WritablePacket *>(pp->prev()); --global_packet_pool.pbatchcount; packet_pool.p = pp; packet_pool.pcount = pp->anno_u32(0); } PacketData *pd; if (with_data && !packet_pool.pd && (pd = global_packet_pool.pdbatch)) { global_packet_pool.pdbatch = pd->batch_next; --global_packet_pool.pdbatchcount; packet_pool.pd = pd; packet_pool.pdcount = pd->batch_pdcount; } click_compiler_fence(); global_packet_pool.lock = 0; } # endif /* HAVE_MULTITHREAD */ WritablePacket *p = packet_pool.p; if (p) { packet_pool.p = static_cast<WritablePacket*>(p->next()); --packet_pool.pcount; } else p = new WritablePacket; return p; } WritablePacket * WritablePacket::pool_allocate(uint32_t headroom, uint32_t length, uint32_t tailroom) { uint32_t n = headroom + length + tailroom; if (n < CLICK_PACKET_POOL_BUFSIZ) n = CLICK_PACKET_POOL_BUFSIZ; WritablePacket *p = pool_allocate(n == CLICK_PACKET_POOL_BUFSIZ); if (p) { p->initialize(); PacketData *pd; PacketPool& packet_pool = local_packet_pool(); if (n == CLICK_PACKET_POOL_BUFSIZ && (pd = packet_pool.pd)) { packet_pool.pd = pd->next; --packet_pool.pdcount; p->_head = reinterpret_cast<unsigned char *>(pd); } else if ((p->_head = new unsigned char[n])) /* OK */; else { delete p; return 0; } p->_data = p->_head + headroom; p->_tail = p->_data + length; p->_end = p->_head + n; } return p; } void WritablePacket::recycle(WritablePacket *p) { unsigned char *data = 0; if (!p->_data_packet && p->_head && !p->_destructor && p->_end - p->_head == CLICK_PACKET_POOL_BUFSIZ) { data = p->_head; p->_head = 0; } p->~WritablePacket(); PacketPool& packet_pool = *make_local_packet_pool(); # if HAVE_MULTITHREAD if ((packet_pool.p && packet_pool.pcount == CLICK_PACKET_POOL_SIZE) || (data && packet_pool.pd && packet_pool.pdcount == CLICK_PACKET_POOL_SIZE)) { while (atomic_uint32_t::swap(global_packet_pool.lock, 1) == 1) /* do nothing */; if (packet_pool.p && packet_pool.pcount == CLICK_PACKET_POOL_SIZE) { if (global_packet_pool.pbatchcount == CLICK_GLOBAL_PACKET_POOL_COUNT) { while (WritablePacket *p = packet_pool.p) { packet_pool.p = static_cast<WritablePacket *>(p->next()); ::operator delete((void *) p); } } else { packet_pool.p->set_prev(global_packet_pool.pbatch); packet_pool.p->set_anno_u32(0, packet_pool.pcount); global_packet_pool.pbatch = packet_pool.p; ++global_packet_pool.pbatchcount; packet_pool.p = 0; } packet_pool.pcount = 0; } if (data && packet_pool.pd && packet_pool.pdcount == CLICK_PACKET_POOL_SIZE) { if (global_packet_pool.pdbatchcount == CLICK_GLOBAL_PACKET_POOL_COUNT) { while (PacketData *pd = packet_pool.pd) { packet_pool.pd = pd->next; delete[] reinterpret_cast<unsigned char *>(pd); } } else { packet_pool.pd->batch_next = global_packet_pool.pdbatch; packet_pool.pd->batch_pdcount = packet_pool.pdcount; global_packet_pool.pdbatch = packet_pool.pd; ++global_packet_pool.pdbatchcount; packet_pool.pd = 0; } packet_pool.pdcount = 0; } click_compiler_fence(); global_packet_pool.lock = 0; } # else /* !HAVE_MULTITHREAD */ if (packet_pool.pcount == CLICK_PACKET_POOL_SIZE) { ::operator delete((void *) p); p = 0; } if (data && packet_pool.pdcount == CLICK_PACKET_POOL_SIZE) { delete[] data; data = 0; } # endif /* HAVE_MULTITHREAD */ if (p) { ++packet_pool.pcount; p->set_next(packet_pool.p); packet_pool.p = p; assert(packet_pool.pcount <= CLICK_PACKET_POOL_SIZE); } if (data) { ++packet_pool.pdcount; PacketData *pd = reinterpret_cast<PacketData *>(data); pd->next = packet_pool.pd; packet_pool.pd = pd; assert(packet_pool.pdcount <= CLICK_PACKET_POOL_SIZE); } } # endif /* HAVE_PACKET_POOL */ bool Packet::alloc_data(uint32_t headroom, uint32_t length, uint32_t tailroom) { uint32_t n = length + headroom + tailroom; if (n < min_buffer_length) { tailroom = min_buffer_length - length - headroom; n = min_buffer_length; } # if CLICK_USERLEVEL || CLICK_MINIOS unsigned char *d = new unsigned char[n]; if (!d) return false; _head = d; _data = d + headroom; _tail = _data + length; _end = _head + n; # elif CLICK_BSDMODULE //click_chatter("allocate new mbuf, length=%d", n); if (n > MJUM16BYTES) { click_chatter("trying to allocate %d bytes: too many\n", n); return false; } struct mbuf *m; MGETHDR(m, M_DONTWAIT, MT_DATA); if (!m) return false; if (n > MHLEN) { if (n > MCLBYTES) m_cljget(m, M_DONTWAIT, (n <= MJUMPAGESIZE ? MJUMPAGESIZE : n <= MJUM9BYTES ? MJUM9BYTES : MJUM16BYTES)); else MCLGET(m, M_DONTWAIT); if (!(m->m_flags & M_EXT)) { m_freem(m); return false; } } _m = m; _m->m_data += headroom; _m->m_len = length; _m->m_pkthdr.len = length; assimilate_mbuf(); # endif /* CLICK_USERLEVEL || CLICK_BSDMODULE */ return true; } #endif /* !CLICK_LINUXMODULE */ /** @brief Create and return a new packet. * @param headroom headroom in new packet * @param data data to be copied into the new packet * @param length length of packet * @param tailroom tailroom in new packet * @return new packet, or null if no packet could be created * * The @a data is copied into the new packet. If @a data is null, the * packet's data is left uninitialized. The resulting packet's * buffer_length() will be at least @link Packet::min_buffer_length * min_buffer_length @endlink; if @a headroom + @a length + @a tailroom would * be less, then @a tailroom is increased to make the total @link * Packet::min_buffer_length min_buffer_length @endlink. * * The new packet's annotations are cleared and its header pointers are * null. */ WritablePacket * Packet::make(uint32_t headroom, const void *data, uint32_t length, uint32_t tailroom) { #if CLICK_LINUXMODULE int want = 1; if (struct sk_buff *skb = skbmgr_allocate_skbs(headroom, length + tailroom, &want)) { assert(want == 1); // packet comes back from skbmgr with headroom reserved __skb_put(skb, length); // leave space for data if (data) memcpy(skb->data, data, length); # if PACKET_CLEAN skb->pkt_type = HOST | PACKET_CLEAN; # else skb->pkt_type = HOST; # endif WritablePacket *q = reinterpret_cast<WritablePacket *>(skb); q->clear_annotations(); return q; } else return 0; #else # if HAVE_CLICK_PACKET_POOL WritablePacket *p = WritablePacket::pool_allocate(headroom, length, tailroom); if (!p) return 0; # else WritablePacket *p = new WritablePacket; if (!p) return 0; p->initialize(); if (!p->alloc_data(headroom, length, tailroom)) { p->_head = 0; delete p; return 0; } # endif if (data) memcpy(p->data(), data, length); return p; #endif } #if CLICK_USERLEVEL || CLICK_MINIOS /** @brief Create and return a new packet (userlevel). * @param data data used in the new packet * @param length length of packet * @param destructor destructor function * @param argument argument to destructor function * @param headroom headroom available before the data pointer * @param tailroom tailroom available after data + length * @return new packet, or null if no packet could be created * * The packet's data pointer becomes the @a data: the data is not copied * into the new packet, rather the packet owns the @a data pointer. When the * packet's data is eventually destroyed, either because the packet is * deleted or because of something like a push() or full(), the @a * destructor will be called as @a destructor(@a data, @a length, @a * argument). (If @a destructor is null, the packet data will be freed by * <tt>delete[] @a data</tt>.) The packet has zero headroom and tailroom. * * The returned packet's annotations are cleared and its header pointers are * null. */ WritablePacket * Packet::make(unsigned char *data, uint32_t length, buffer_destructor_type destructor, void* argument, int headroom, int tailroom) { # if HAVE_CLICK_PACKET_POOL WritablePacket *p = WritablePacket::pool_allocate(false); # else WritablePacket *p = new WritablePacket; # endif if (p) { p->initialize(); p->_head = data - headroom; p->_data = data; p->_tail = data + length; p->_end = p->_tail + tailroom; p->_destructor = destructor; p->_destructor_argument = argument; } return p; } /** @brief Copy the content and annotations of another packet (userlevel). * @param source packet * @param headroom for the new packet */ bool Packet::copy(Packet* p, int headroom) { if (headroom + p->length() > buffer_length()) return false; _data = _head + headroom; memcpy(_data,p->data(),p->length()); _tail = _data + p->length(); copy_annotations(p); set_mac_header(p->mac_header() ? data() + p->mac_header_offset() : 0); set_network_header(p->network_header() ? data() + p->network_header_offset() : 0, p->network_header_length()); return true; } #endif // // UNIQUEIFICATION // /** @brief Create a clone of this packet. * @return the cloned packet * * The returned clone has independent annotations, initially copied from this * packet, but shares this packet's data. shared() returns true for both the * packet and its clone. Returns null if there's no memory for the clone. */ Packet * Packet::clone() { #if CLICK_LINUXMODULE struct sk_buff *nskb = skb_clone(skb(), GFP_ATOMIC); return reinterpret_cast<Packet *>(nskb); #elif CLICK_USERLEVEL || CLICK_BSDMODULE || CLICK_MINIOS # if CLICK_BSDMODULE struct mbuf *m; if (this->_m == NULL) return 0; if (this->_m->m_flags & M_EXT && ( this->_m->m_ext.ext_type == EXT_JUMBOP || this->_m->m_ext.ext_type == EXT_JUMBO9 || this->_m->m_ext.ext_type == EXT_JUMBO16)) { if ((m = dup_jumbo_m(this->_m)) == NULL) return 0; } else if ((m = m_dup(this->_m, M_DONTWAIT)) == NULL) return 0; # endif // timing: .31-.39 normal, .43-.55 two allocs, .55-.58 two memcpys # if HAVE_CLICK_PACKET_POOL Packet *p = WritablePacket::pool_allocate(false); # else Packet *p = new WritablePacket; // no initialization # endif if (!p) return 0; Packet* origin = this; if (origin->_data_packet) origin = origin->_data_packet; memcpy(p, this, sizeof(Packet)); p->_use_count = 1; p->_data_packet = origin; # if CLICK_USERLEVEL || CLICK_MINIOS p->_destructor = 0; # else p->_m = m; # endif // increment our reference count because of _data_packet reference origin->_use_count++; return p; #endif /* CLICK_LINUXMODULE */ } WritablePacket * Packet::expensive_uniqueify(int32_t extra_headroom, int32_t extra_tailroom, bool free_on_failure) { assert(extra_headroom >= (int32_t)(-headroom()) && extra_tailroom >= (int32_t)(-tailroom())); #if CLICK_LINUXMODULE struct sk_buff *nskb = skb(); // preserve this, which otherwise loses a ref here if (!free_on_failure) if (!(nskb = skb_clone(nskb, GFP_ATOMIC))) return NULL; // nskb is now not shared, which psk_expand_head asserts if (!(nskb = skb_share_check(nskb, GFP_ATOMIC))) return NULL; if (pskb_expand_head(nskb, extra_headroom, extra_tailroom, GFP_ATOMIC)) { kfree_skb(nskb); return NULL; } // success, so kill the clone from above if (!free_on_failure) kill(); return reinterpret_cast<WritablePacket *>(nskb); #else /* !CLICK_LINUXMODULE */ // If someone else has cloned this packet, then we need to leave its data // pointers around. Make a clone and uniqueify that. if (_use_count > 1) { Packet *p = clone(); WritablePacket *q = (p ? p->expensive_uniqueify(extra_headroom, extra_tailroom, true) : 0); if (q || free_on_failure) kill(); return q; } uint8_t *old_head = _head, *old_end = _end; # if CLICK_BSDMODULE struct mbuf *old_m = _m; # endif if (!alloc_data(headroom() + extra_headroom, length(), tailroom() + extra_tailroom)) { if (free_on_failure) kill(); return 0; } unsigned char *start_copy = old_head + (extra_headroom >= 0 ? 0 : -extra_headroom); unsigned char *end_copy = old_end + (extra_tailroom >= 0 ? 0 : extra_tailroom); memcpy(_head + (extra_headroom >= 0 ? extra_headroom : 0), start_copy, end_copy - start_copy); // free old data if (_data_packet) _data_packet->kill(); # if CLICK_USERLEVEL || CLICK_MINIOS else if (_destructor) _destructor(old_head, old_end - old_head, _destructor_argument); else delete[] old_head; _destructor = 0; # elif CLICK_BSDMODULE m_freem(old_m); // alloc_data() created a new mbuf, so free the old one # endif _use_count = 1; _data_packet = 0; shift_header_annotations(old_head, extra_headroom); return static_cast<WritablePacket *>(this); #endif /* CLICK_LINUXMODULE */ } #ifdef CLICK_BSDMODULE /* BSD kernel module */ struct mbuf * Packet::steal_m() { struct Packet *p; struct mbuf *m2; p = uniqueify(); m2 = p->m(); /* Clear the mbuf from the packet: otherwise kill will MFREE it */ p->_m = 0; p->kill(); return m2; } /* * Duplicate a packet by copying data from an mbuf chain to a new mbuf with a * jumbo cluster (i.e., contiguous storage). */ struct mbuf * Packet::dup_jumbo_m(struct mbuf *m) { int len = m->m_pkthdr.len; struct mbuf *new_m; if (len > MJUM16BYTES) { click_chatter("warning: cannot allocate jumbo cluster for %d bytes", len); return NULL; } new_m = m_getjcl(M_DONTWAIT, m->m_type, m->m_flags & M_COPYFLAGS, (len <= MJUMPAGESIZE ? MJUMPAGESIZE : len <= MJUM9BYTES ? MJUM9BYTES : MJUM16BYTES)); if (!new_m) { click_chatter("warning: jumbo cluster mbuf allocation failed"); return NULL; } m_copydata(m, 0, len, mtod(new_m, caddr_t)); new_m->m_len = len; new_m->m_pkthdr.len = len; /* XXX: Only a subset of what m_dup_pkthdr() would copy: */ new_m->m_pkthdr.rcvif = m->m_pkthdr.rcvif; # if __FreeBSD_version >= 800000 new_m->m_pkthdr.flowid = m->m_pkthdr.flowid; # endif new_m->m_pkthdr.ether_vtag = m->m_pkthdr.ether_vtag; return new_m; } #endif /* CLICK_BSDMODULE */ // // EXPENSIVE_PUSH, EXPENSIVE_PUT // /* * Prepend some empty space before a packet. * May kill this packet and return a new one. */ WritablePacket * Packet::expensive_push(uint32_t nbytes) { static int chatter = 0; if (headroom() < nbytes && chatter < 5) { click_chatter("expensive Packet::push; have %d wanted %d", headroom(), nbytes); chatter++; } if (WritablePacket *q = expensive_uniqueify((nbytes + 128) & ~3, 0, true)) { #ifdef CLICK_LINUXMODULE /* Linux kernel module */ __skb_push(q->skb(), nbytes); #else /* User-space and BSD kernel module */ q->_data -= nbytes; # ifdef CLICK_BSDMODULE q->m()->m_data -= nbytes; q->m()->m_len += nbytes; q->m()->m_pkthdr.len += nbytes; # endif #endif return q; } else return 0; } WritablePacket * Packet::expensive_put(uint32_t nbytes) { static int chatter = 0; if (tailroom() < nbytes && chatter < 5) { click_chatter("expensive Packet::put; have %d wanted %d", tailroom(), nbytes); chatter++; } if (WritablePacket *q = expensive_uniqueify(0, nbytes + 128, true)) { #ifdef CLICK_LINUXMODULE /* Linux kernel module */ __skb_put(q->skb(), nbytes); #else /* User-space and BSD kernel module */ q->_tail += nbytes; # ifdef CLICK_BSDMODULE q->m()->m_len += nbytes; q->m()->m_pkthdr.len += nbytes; # endif #endif return q; } else return 0; } Packet * Packet::shift_data(int offset, bool free_on_failure) { if (offset == 0) return this; // Preserve mac_header, network_header, and transport_header. const unsigned char *dp = data(); if (has_mac_header() && mac_header() >= buffer() && mac_header() <= end_buffer() && mac_header() < dp) dp = mac_header(); if (has_network_header() && network_header() >= buffer() && network_header() <= end_buffer() && network_header() < dp) dp = network_header(); if (has_transport_header() && transport_header() >= buffer() && transport_header() <= end_buffer() && transport_header() < dp) dp = network_header(); if (!shared() && (offset < 0 ? (dp - buffer()) >= (ptrdiff_t)(-offset) : tailroom() >= (uint32_t)offset)) { WritablePacket *q = static_cast<WritablePacket *>(this); memmove((unsigned char *) dp + offset, dp, q->end_data() - dp); #if CLICK_LINUXMODULE struct sk_buff *mskb = q->skb(); mskb->data += offset; mskb->tail += offset; #else /* User-space and BSD kernel module */ q->_data += offset; q->_tail += offset; # if CLICK_BSDMODULE q->m()->m_data += offset; # endif #endif shift_header_annotations(q->buffer(), offset); return this; } else { int tailroom_offset = (offset < 0 ? -offset : 0); if (offset < 0 && headroom() < (uint32_t)(-offset)) offset = -headroom() + ((uintptr_t)(data() + offset) & 7); else offset += ((uintptr_t)buffer() & 7); return expensive_uniqueify(offset, tailroom_offset, free_on_failure); } } #if HAVE_CLICK_PACKET_POOL static void cleanup_pool(PacketPool *pp, int global) { unsigned pcount = 0, pdcount = 0; while (WritablePacket *p = pp->p) { ++pcount; pp->p = static_cast<WritablePacket *>(p->next()); ::operator delete((void *) p); } while (PacketData *pd = pp->pd) { ++pdcount; pp->pd = pd->next; delete[] reinterpret_cast<unsigned char *>(pd); } assert(pcount <= CLICK_PACKET_POOL_SIZE); assert(pdcount <= CLICK_PACKET_POOL_SIZE); assert(global || (pcount == pp->pcount && pdcount == pp->pdcount)); } #endif void Packet::static_cleanup() { #if HAVE_CLICK_PACKET_POOL # if HAVE_MULTITHREAD while (PacketPool* pp = global_packet_pool.thread_pools) { global_packet_pool.thread_pools = pp->thread_pool_next; cleanup_pool(pp, 0); delete pp; } unsigned rounds = global_packet_pool.pbatchcount; if (rounds < global_packet_pool.pdbatchcount) rounds = global_packet_pool.pdbatchcount; assert(rounds <= CLICK_GLOBAL_PACKET_POOL_COUNT); PacketPool fake_pool; while (global_packet_pool.pbatch || global_packet_pool.pdbatch) { if ((fake_pool.p = global_packet_pool.pbatch)) global_packet_pool.pbatch = static_cast<WritablePacket*>(fake_pool.p->prev()); if ((fake_pool.pd = global_packet_pool.pdbatch)) global_packet_pool.pdbatch = fake_pool.pd->batch_next; cleanup_pool(&fake_pool, 1); --rounds; } assert(rounds == 0); # else cleanup_pool(&global_packet_pool, 0); # endif #endif } CLICK_ENDDECLS
32.967579
114
0.664987
[ "object" ]
38876477a64112755d3e96881e0e341dcb316b03
997
cpp
C++
LuckBalance.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
LuckBalance.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
LuckBalance.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <chrono> #include<bits/stdc++.h> using namespace std; using namespace std::chrono; void print(vector<vector<int>> vect) { for(int i = 0; i< vect.size(); i++) { for(int j = 0; j<vect[0].size(); j++) cout<<vect[i][j]<<" "; cout<<"\n"; } } bool sortcol( const vector<int>& v1, const vector<int>& v2 ) { return v1[0] > v2[0]; } int main() { auto start = high_resolution_clock::now(); vector<vector<int>> arr{{5,1}, {2,1}, {1,1}, {8,1}, {10,0}, {5,0}}; cout<<"\n"; print(arr); sort(arr.begin(), arr.end(), sortcol); cout<<"\n"; print(arr); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout <<"\nExecution time: "<<duration.count() <<" microseconds"<<endl; return 0; }
22.659091
74
0.503511
[ "vector" ]
388ab4699ab20439452134f3703a6322e930685a
6,321
cpp
C++
pthread/Implementation.cpp
dpocheng/CPP-Sobel-Filter-for-edge-detection
609fb98f010af60ee66a1cbb3f1963602f153634
[ "Apache-2.0" ]
null
null
null
pthread/Implementation.cpp
dpocheng/CPP-Sobel-Filter-for-edge-detection
609fb98f010af60ee66a1cbb3f1963602f153634
[ "Apache-2.0" ]
null
null
null
pthread/Implementation.cpp
dpocheng/CPP-Sobel-Filter-for-edge-detection
609fb98f010af60ee66a1cbb3f1963602f153634
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Pok On Cheng // // 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. /*************************** * Pok On Cheng (pocheng) * * 74157306 * * CompSci 131 Lab 1 B * ***************************/ #include <algorithm> #include <cstdlib> #include <cctype> #include <cmath> #include <sstream> #include <fstream> #include <iostream> #include <vector> #include <mutex> #include <thread> /* Global variables, Look at their usage in main() */ int image_height; int image_width; int image_maxShades; int inputImage[1000][1000]; int outputImage[1000][1000]; int num_threads; int chunkSize; int maxChunk; int nextAvailableChunk; std::mutex mutexes; /* ****************Change and add functions below ***************** */ int get_dynamic_chunk() { mutexes.lock(); int N = chunkSize * nextAvailableChunk; nextAvailableChunk += 1; mutexes.unlock(); return N; } void sobel_algorithm(int dynamic_chunk) { int sumx, sumy, sum; int maskX[3][3]; int maskY[3][3]; /* 3x3 Sobel mask for X Dimension. */ maskX[0][0] = -1; maskX[0][1] = 0; maskX[0][2] = 1; maskX[1][0] = -2; maskX[1][1] = 0; maskX[1][2] = 2; maskX[2][0] = -1; maskX[2][1] = 0; maskX[2][2] = 1; /* 3x3 Sobel mask for Y Dimension. */ maskY[0][0] = 1; maskY[0][1] = 2; maskY[0][2] = 1; maskY[1][0] = 0; maskY[1][1] = 0; maskY[1][2] = 0; maskY[2][0] = -1; maskY[2][1] = -2; maskY[2][2] = -1; for (int x = dynamic_chunk; x < (dynamic_chunk+chunkSize); ++x) { for (int y = 0; y < image_width; ++y){ sumx = 0; sumy = 0; /* For handling image boundaries */ if (x == 0 || x == ((dynamic_chunk+chunkSize)-1) || y == 0 || y == (image_width-1)) { sum = 0; } else { /* Gradient calculation in X Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++){ sumx += (inputImage[x+i][y+j] * maskX[i+1][j+1]); } } /* Gradient calculation in Y Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++){ sumy += (inputImage[x+i][y+j] * maskY[i+1][j+1]); } } /* Gradient magnitude */ sum = (abs(sumx) + abs(sumy)); } /* outputImage[x][y] = (0 <= sum <= 255); */ if (sum >= 0 && sum <= 255) { outputImage[x][y] = sum; } else if (sum > 255) { outputImage[x][y] = 0; } else if (sum < 0) { outputImage[x][y] = 255; } } } } void compute_chunk() { int X = get_dynamic_chunk(); sobel_algorithm(X); } void dispatch_threads() { std::vector<std::thread> threads; nextAvailableChunk = 0; for (int i = 0; i < num_threads; i++) { threads.push_back(std::thread(compute_chunk)); } for (int i = 0; i < num_threads; i++) { threads[i].join(); } } /* ****************Need not to change the function below ***************** */ int main(int argc, char* argv[]) { if(argc != 5) { std::cout << "ERROR: Incorrect number of arguments. Format is: <Input image filename> <Output image filename> <Threads#> <Chunk size>" << std::endl; return 0; } std::ifstream file(argv[1]); if(!file.is_open()) { std::cout << "ERROR: Could not open file " << argv[1] << std::endl; return 0; } num_threads = std::atoi(argv[3]); chunkSize = std::atoi(argv[4]); std::cout << "Detect edges in " << argv[1] << " using " << num_threads << " threads\n" << std::endl; /* ******Reading image into 2-D array below******** */ std::string workString; /* Remove comments '#' and check image format */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ if( workString.at(1) != '2' ){ std::cout << "Input image is not a valid PGM image" << std::endl; return 0; } else { break; } } else { continue; } } /* Check image size */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); int n; stream >> n; image_width = n; stream >> n; image_height = n; break; } else { continue; } } /* maxChunk is total number of chunks to process */ maxChunk = ceil((float)image_height/chunkSize); /* Check image max shades */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); stream >> image_maxShades; break; } else { continue; } } /* Fill input image matrix */ int pixel_val; for( int i = 0; i < image_height; i++ ) { if( std::getline(file,workString) && workString.at(0) != '#' ){ std::stringstream stream(workString); for( int j = 0; j < image_width; j++ ){ if( !stream ) break; stream >> pixel_val; inputImage[i][j] = pixel_val; } } else { continue; } } /************ Function that creates threads and manage dynamic allocation of chunks *********/ dispatch_threads(); /* ********Start writing output to your file************ */ std::ofstream ofile(argv[2]); if( ofile.is_open() ) { ofile << "P2" << "\n" << image_width << " " << image_height << "\n" << image_maxShades << "\n"; for( int i = 0; i < image_height; i++ ) { for( int j = 0; j < image_width; j++ ){ ofile << outputImage[i][j] << " "; } ofile << "\n"; } } else { std::cout << "ERROR: Could not open output file " << argv[2] << std::endl; return 0; } return 0; }
27.012821
156
0.523019
[ "vector" ]
389c2b3fc8e5d98b6db3bb17dc981f1666c973ae
1,603
cpp
C++
C++/BucketSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
215
2021-10-01T08:18:16.000Z
2022-03-29T04:12:03.000Z
C++/BucketSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
175
2021-10-03T10:47:31.000Z
2021-10-20T11:55:32.000Z
C++/BucketSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
807
2021-10-01T08:11:45.000Z
2021-11-21T18:57:09.000Z
/*bucketSort(arr[], n) 1) Create n empty buckets (Or lists). 2) Do following for every array element arr[i]. .......a) Insert arr[i] into bucket[n*array[i]] 3) Sort individual buckets using insertion sort. 4) Concatenate all sorted buckets. */ /*Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code, C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets. The main step to analyze is step 3. */ // C++ program to sort an // array using bucket sort #include <algorithm> #include <iostream> #include <vector> using namespace std; // Function to sort arr[] of // size n using bucket sort void bucketSort(float arr[], int n) { // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements // in different buckets for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } /* Driver program to test above function */ int main() { float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); cout << "Sorted array is \n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; }
26.716667
344
0.635059
[ "vector" ]
389f79a4ef757737bf79955fa7eb78956fc80e6a
102,284
cpp
C++
ptgl/Core/PrimitiveShapeVertex.cpp
tsumehashi/ptgl
00434830fa6fbc7987513d6bdd9c967ca66a70c5
[ "Apache-2.0" ]
1
2019-04-06T11:46:02.000Z
2019-04-06T11:46:02.000Z
ptgl/Core/PrimitiveShapeVertex.cpp
tsumehashi/ptgl
00434830fa6fbc7987513d6bdd9c967ca66a70c5
[ "Apache-2.0" ]
null
null
null
ptgl/Core/PrimitiveShapeVertex.cpp
tsumehashi/ptgl
00434830fa6fbc7987513d6bdd9c967ca66a70c5
[ "Apache-2.0" ]
null
null
null
#include "PrimitiveShapeVertex.h" #include <cmath> namespace ptgl { PrimitiveShapeVertex::PrimitiveShapeVertex() { } PrimitiveShapeVertex::~PrimitiveShapeVertex() { } // Point const VertexList PrimitiveShapeVertex::PointVertices = { {0, 0, 0, 0, 0, 1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::PointIndices = { 0 }; // Box (sides) # if 1 // flat box const VertexList PrimitiveShapeVertex::BoxVertices = { // top {0.5, 0.5, 0.5, 0, 0, 1, 0, 0}, {-0.5, 0.5, 0.5, 0, 0, 1, 0, 0}, {-0.5, -0.5, 0.5, 0, 0, 1, 0, 0}, {0.5, -0.5, 0.5, 0, 0, 1, 0, 0}, // bottom {0.5, -0.5, -0.5, 0, 0, -1, 0, 0}, {-0.5, -0.5, -0.5, 0, 0, -1, 0, 0}, {-0.5, 0.5, -0.5, 0, 0, -1, 0, 0}, {0.5, 0.5, -0.5, 0, 0, -1, 0, 0}, // front {0.5, 0.5, 0.5, 1, 0, 0, 0}, {0.5, -0.5, 0.5, 1, 0, 0, 0}, {0.5, -0.5, -0.5, 1, 0, 0, 0}, {0.5, 0.5, -0.5, 1, 0, 0, 0}, // back {-0.5, 0.5, -0.5, -1, 0, 0, 0}, {-0.5, -0.5, -0.5, -1, 0, 0, 0}, {-0.5, -0.5, 0.5, -1, 0, 0, 0}, {-0.5, 0.5, 0.5, -1, 0, 0, 0}, // right {0.5, -0.5, 0.5, 0, -1, 0, 0}, {-0.5, -0.5, 0.5, 0, -1, 0, 0}, {-0.5, -0.5, -0.5, 0, -1, 0, 0}, {0.5, -0.5, -0.5, 0, -1, 0, 0}, // left {0.5, 0.5, -0.5, 0, 1, 0, 0}, {-0.5, 0.5, -0.5, 0, 1, 0, 0}, {-0.5, 0.5, 0.5, 0, 1, 0, 0}, {0.5, 0.5, 0.5, 0, 1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::BoxIndices = { // top 0, 1, 2, 2, 3, 0, // bottom 4, 5, 6, 6, 7, 4, // front 8, 9, 10, 10, 11, 8, // back 12, 13, 14, 14, 15, 12, // right 16, 17, 18, 18, 19, 16, // left 20, 21, 22, 22, 23, 20, }; #else // smooth box const VertexList PrimitiveShapeVertex::BoxVertices = { {0.5, -0.5, -0.5, 1.5708, -1.5708, -1.5708, 0, 0}, {0.5, -0.5, 0.5, 1.5708, -1.5708, 1.5708, 0, 0}, {-0.5, -0.5, 0.5, -1.5708, -1.5708, 1.5708, 0, 0}, {-0.5, -0.5, -0.5, -1.5708, -1.5708, -1.5708, 0, 0}, {0.5, 0.5, -0.5, 1.5708, 1.5708, -1.5708, 0, 0}, {0.5, 0.5, 0.5, 1.5708, 1.5708, 1.5708, 0, 0}, {-0.5, 0.5, 0.5, -1.5708, 1.5708, 1.5708, 0, 0}, {-0.5, 0.5, -0.5, -1.5708, 1.5708, -1.5708, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::BoxIndices = { 1, 2, 3, 7, 6, 5, 4, 5, 1, 5, 6, 2, 2, 6, 7, 0, 3, 7, 0, 1, 3, 4, 7, 5, 0, 4, 1, 1, 5, 2, 3, 2, 7, 4, 0, 7, }; #endif //const VertexList PrimitiveShapeVertex::BoxVertices = { // {-0.5, -0.5, 0.5, 0, -1, 0, 0, 0}, // {-0.5, 0.5, 0.5, 0, 1, 0, 0, 0}, // {-0.5, -0.5, -0.5, 0, -1, 0, 0, 0}, // {-0.5, 0.5, -0.5, 0, 0, -1, 0, 0}, // {0.5, -0.5, 0.5, 0, -1, 0, 0, 0}, // {0.5, 0.5, 0.5, 0, 1, 0, 0, 0}, // {0.5, -0.5, -0.5, 1, 0, 0, 0, 0}, // {0.5, 0.5, -0.5, 0, 1, 0, 0, 0}, //}; // //const std::vector<GLuint> PrimitiveShapeVertex::BoxIndices = { // 3, 2, 0, // 7, 6, 2, // 5, 4, 6, // 1, 0, 4, // 2, 6, 4, // 7, 3, 1, // 1, 3, 0, // 3, 7, 2, // 7, 5, 6, // 5, 1, 4, // 0, 2, 4, // 5, 7, 1, //}; // Sphere (radius) const VertexList PrimitiveShapeVertex::SphereVertices = { {0, -1, 0, 0.1558, -0.9878, 0, 0, 0}, {0.723607, -0.44722, 0.525725, 0.6153, -0.5545, 0.5603, 0, 0}, {-0.276388, -0.44722, 0.850649, -0.1685, -0.5545, 0.8149, 0, 0}, {-0.894426, -0.447216, 0, -0.8271, -0.5545, 0.0916, 0, 0}, {-0.276388, -0.44722, -0.850649, -0.3427, -0.5545, -0.7583, 0, 0}, {0.723607, -0.44722, -0.525725, 0.723, -0.5545, -0.4121, 0, 0}, {0.276388, 0.44722, 0.850649, 0.2945, 0.3024, 0.9065, 0, 0}, {-0.723607, 0.44722, 0.525725, -0.7711, 0.3024, 0.5603, 0, 0}, {-0.723607, 0.44722, -0.525725, -0.7711, 0.3024, -0.5603, 0, 0}, {0.276388, 0.44722, -0.850649, 0.2945, 0.3024, -0.9065, 0, 0}, {0.894426, 0.447216, 0, 0.9532, 0.3024, 0, 0, 0}, {0, 1, 0, 0.1261, 0.9878, 0.0916, 0, 0}, {-0.232822, -0.657519, 0.716563, -0.0711, -0.6369, 0.7676, 0, 0}, {-0.162456, -0.850654, 0.499995, 0.0144, -0.8363, 0.5481, 0, 0}, {-0.077607, -0.96795, 0.238853, 0.0891, -0.9575, 0.2744, 0, 0}, {0.203181, -0.96795, 0.147618, 0.2627, -0.9158, 0.3039, 0, 0}, {0.425323, -0.850654, 0.309011, 0.4674, -0.7594, 0.4526, 0, 0}, {0.609547, -0.657519, 0.442856, 0.6153, -0.5545, 0.5603, 0, 0}, {0.531941, -0.502302, 0.681712, 0.6153, -0.5545, 0.5603, 0, 0}, {0.262869, -0.525738, 0.809012, 0.3854, -0.5955, 0.7049, 0, 0}, {-0.029639, -0.502302, 0.864184, 0.1026, -0.5955, 0.7968, 0, 0}, {0.812729, -0.502301, -0.295238, 0.7081, -0.6369, -0.3049, 0, 0}, {0.850648, -0.525736, 0, 0.74, -0.6726, -0, 0, 0}, {0.812729, -0.502301, 0.295238, 0.7081, -0.6369, 0.3049, 0, 0}, {0.203181, -0.96795, -0.147618, 0.1558, -0.9878, 0, 0, 0}, {0.425323, -0.850654, -0.309011, 0.3702, -0.9158, -0.1559, 0, 0}, {0.609547, -0.657519, -0.442856, 0.5749, -0.7594, -0.3046, 0, 0}, {-0.753442, -0.657515, 0, -0.752, -0.6369, 0.1696, 0, 0}, {-0.52573, -0.850652, 0, -0.5168, -0.8363, 0.183, 0, 0}, {-0.251147, -0.967949, 0, -0.2334, -0.9575, 0.1696, 0, 0}, {-0.483971, -0.502302, 0.716565, -0.3427, -0.5545, 0.7583, 0, 0}, {-0.688189, -0.525736, 0.499997, -0.5513, -0.5955, 0.5843, 0, 0}, {-0.831051, -0.502299, 0.238853, -0.7261, -0.5955, 0.3438, 0, 0}, {-0.232822, -0.657519, -0.716563, -0.3936, -0.6369, -0.6628, 0, 0}, {-0.162456, -0.850654, -0.499995, -0.3338, -0.8363, -0.435, 0, 0}, {-0.077607, -0.96795, -0.238853, -0.2334, -0.9575, -0.1696, 0, 0}, {-0.831051, -0.502299, -0.238853, -0.8271, -0.5545, -0.0916, 0, 0}, {-0.688189, -0.525736, -0.499997, -0.7261, -0.5955, -0.3438, 0, 0}, {-0.483971, -0.502302, -0.716565, -0.5513, -0.5955, -0.5843, 0, 0}, {-0.029639, -0.502302, -0.864184, -0.1685, -0.5545, -0.8149, 0, 0}, {0.262869, -0.525738, -0.809012, 0.1026, -0.5955, -0.7968, 0, 0}, {0.531941, -0.502302, -0.681712, 0.3854, -0.5955, -0.7049, 0, 0}, {0.956626, 0.251149, 0.147618, 0.9854, 0.1702, 0, 0, 0}, {0.951058, -0, 0.309013, 0.9831, -0.0962, 0.1557, 0, 0}, {0.860698, -0.251151, 0.442858, 0.8864, -0.3485, 0.3049, 0, 0}, {0.860698, -0.251151, -0.442858, 0.8193, -0.3987, -0.4121, 0, 0}, {0.951058, 0, -0.309013, 0.9363, -0.1745, -0.3046, 0, 0}, {0.956626, 0.251149, -0.147618, 0.9846, 0.0784, -0.156, 0, 0}, {0.155215, 0.251152, 0.955422, 0.3045, 0.1702, 0.9372, 0, 0}, {0, -0, 1, 0.1557, -0.0962, 0.9831, 0, 0}, {-0.155215, -0.251152, 0.955422, -0.016, -0.3485, 0.9372, 0, 0}, {0.687159, -0.251152, 0.681715, 0.6451, -0.3987, 0.6519, 0, 0}, {0.587786, 0, 0.809017, 0.5791, -0.1745, 0.7964, 0, 0}, {0.436007, 0.251152, 0.864188, 0.4526, 0.0784, 0.8883, 0, 0}, {-0.860698, 0.251151, 0.442858, -0.7972, 0.1702, 0.5792, 0, 0}, {-0.951058, -0, 0.309013, -0.8869, -0.0962, 0.4519, 0, 0}, {-0.956626, -0.251149, 0.147618, -0.8963, -0.3485, 0.2744, 0, 0}, {-0.436007, -0.251152, 0.864188, -0.4206, -0.3987, 0.8149, 0, 0}, {-0.587786, 0, 0.809017, -0.5785, -0.1745, 0.7968, 0, 0}, {-0.687159, 0.251152, 0.681715, -0.7049, 0.0784, 0.7049, 0, 0}, {-0.687159, 0.251152, -0.681715, -0.7972, 0.1702, -0.5792, 0, 0}, {-0.587786, -0, -0.809017, -0.7038, -0.0962, -0.7038, 0, 0}, {-0.436007, -0.251152, -0.864188, -0.5379, -0.3485, -0.7676, 0, 0}, {-0.956626, -0.251149, -0.147618, -0.905, -0.3987, -0.1482, 0, 0}, {-0.951058, 0, -0.309013, -0.9366, -0.1745, -0.3039, 0, 0}, {-0.860698, 0.251151, -0.442858, -0.8883, 0.0784, -0.4526, 0, 0}, {0.436007, 0.251152, -0.864188, 0.3045, 0.1702, -0.9372, 0, 0}, {0.587786, -0, -0.809017, 0.4519, -0.0962, -0.8869, 0, 0}, {0.687159, -0.251152, -0.681715, 0.5638, -0.3485, -0.7488, 0, 0}, {-0.155215, -0.251152, -0.955422, -0.1387, -0.3987, -0.9065, 0, 0}, {0, 0, -1, -0.0004, -0.1745, -0.9846, 0, 0}, {0.155215, 0.251152, -0.955422, 0.156, 0.0784, -0.9846, 0, 0}, {0.831051, 0.502299, 0.238853, 0.905, 0.3987, 0.1482, 0, 0}, {0.688189, 0.525736, 0.499997, 0.8039, 0.4399, 0.4003, 0, 0}, {0.483971, 0.502302, 0.716565, 0.6291, 0.4399, 0.6409, 0, 0}, {0.029639, 0.502302, 0.864184, 0.1387, 0.3987, 0.9065, 0, 0}, {-0.262869, 0.525738, 0.809012, -0.1323, 0.4399, 0.8883, 0, 0}, {-0.531941, 0.502302, 0.681712, -0.4151, 0.4399, 0.7964, 0, 0}, {-0.812729, 0.502301, 0.295238, -0.8193, 0.3987, 0.4121, 0, 0}, {-0.850648, 0.525736, 0, -0.8857, 0.4399, 0.1487, 0, 0}, {-0.812729, 0.502301, -0.295238, -0.8857, 0.4399, -0.1487, 0, 0}, {-0.531941, 0.502302, -0.681712, -0.6451, 0.3987, -0.6519, 0, 0}, {-0.262869, 0.525738, -0.809012, -0.4151, 0.4399, -0.7964, 0, 0}, {0.029639, 0.502302, -0.864184, -0.1323, 0.4399, -0.8883, 0, 0}, {0.483971, 0.502302, -0.716565, 0.4206, 0.3987, -0.8149, 0, 0}, {0.688189, 0.525736, -0.499997, 0.6291, 0.4399, -0.6409, 0, 0}, {0.831051, 0.502299, -0.238853, 0.8039, 0.4399, -0.4003, 0, 0}, {0.077607, 0.96795, 0.238853, 0.2334, 0.9575, 0.1696, 0, 0}, {0.162456, 0.850654, 0.499995, 0.3338, 0.8363, 0.435, 0, 0}, {0.232822, 0.657519, 0.716563, 0.3936, 0.6369, 0.6628, 0, 0}, {0.753442, 0.657515, 0, 0.8271, 0.5545, 0.0916, 0, 0}, {0.52573, 0.850652, 0, 0.6441, 0.7594, 0.0915, 0, 0}, {0.251147, 0.967949, 0, 0.3912, 0.9158, 0.0915, 0, 0}, {-0.203181, 0.96795, 0.147618, -0.0891, 0.9575, 0.2743, 0, 0}, {-0.425323, 0.850654, 0.309011, -0.3105, 0.8363, 0.4519, 0, 0}, {-0.609547, 0.657519, 0.442856, -0.5087, 0.6369, 0.5792, 0, 0}, {-0.203181, 0.96795, -0.147618, -0.2885, 0.9575, 0, 0, 0}, {-0.425323, 0.850654, -0.309011, -0.5257, 0.8363, -0.1557, 0, 0}, {-0.609547, 0.657519, -0.442856, -0.7081, 0.6369, -0.3049, 0, 0}, {0.077607, 0.96795, -0.238853, -0.0891, 0.9575, -0.2743, 0, 0}, {0.162456, 0.850654, -0.499995, -0.0144, 0.8363, -0.5481, 0, 0}, {0.232822, 0.657519, -0.716563, 0.0711, 0.6369, -0.7676, 0, 0}, {0.3618, 0.894429, -0.262863, 0.3338, 0.8363, -0.435, 0, 0}, {0.638194, 0.72361, -0.262864, 0.5987, 0.6726, -0.435, 0, 0}, {0.447209, 0.723612, -0.525728, 0.3936, 0.6369, -0.6628, 0, 0}, {-0.138197, 0.89443, -0.425319, -0.3105, 0.8363, -0.4519, 0, 0}, {-0.05279, 0.723612, -0.688185, -0.2287, 0.6726, -0.7038, 0, 0}, {-0.361804, 0.723612, -0.587778, -0.5087, 0.6369, -0.5792, 0, 0}, {-0.44721, 0.894429, 0, -0.5257, 0.8363, 0.1557, 0, 0}, {-0.670817, 0.723611, -0.162457, -0.74, 0.6726, 0, 0, 0}, {-0.670817, 0.723611, 0.162457, -0.7081, 0.6369, 0.3049, 0, 0}, {-0.138197, 0.89443, 0.425319, -0.0144, 0.8363, 0.5481, 0, 0}, {-0.361804, 0.723612, 0.587778, -0.2287, 0.6726, 0.7038, 0, 0}, {-0.05279, 0.723612, 0.688185, 0.0711, 0.6369, 0.7676, 0, 0}, {0.3618, 0.894429, 0.262863, 0.5168, 0.8363, 0.183, 0, 0}, {0.447209, 0.723612, 0.525728, 0.5987, 0.6726, 0.435, 0, 0}, {0.638194, 0.72361, 0.262864, 0.752, 0.6369, 0.1696, 0, 0}, {0.861804, 0.276396, -0.425322, 0.7544, 0.3611, -0.5481, 0, 0}, {0.809019, 0, -0.587782, 0.7038, 0.0962, -0.7038, 0, 0}, {0.670821, 0.276397, -0.688189, 0.5379, 0.3485, -0.7676, 0, 0}, {-0.138199, 0.276397, -0.951055, -0.2882, 0.3611, -0.8869, 0, 0}, {-0.309016, -0, -0.951057, -0.4519, 0.0962, -0.8869, 0, 0}, {-0.447215, 0.276397, -0.850649, -0.5638, 0.3485, -0.7488, 0, 0}, {-0.947213, 0.276396, -0.162458, -0.9325, 0.3611, 0, 0, 0}, {-1, 1e-06, 0, -0.9831, 0.0962, 0.1557, 0, 0}, {-0.947213, 0.276397, 0.162458, -0.8864, 0.3485, 0.3049, 0, 0}, {-0.447216, 0.276397, 0.850648, -0.2882, 0.3611, 0.8869, 0, 0}, {-0.309017, -1e-06, 0.951056, -0.1557, 0.0962, 0.9831, 0, 0}, {-0.138199, 0.276397, 0.951055, 0.016, 0.3485, 0.9372, 0, 0}, {0.67082, 0.276396, 0.68819, 0.7544, 0.3611, 0.5481, 0, 0}, {0.809019, -2e-06, 0.587783, 0.8869, 0.0962, 0.4519, 0, 0}, {0.861804, 0.276394, 0.425323, 0.8963, 0.3485, 0.2744, 0, 0}, {0.309017, -0, -0.951056, 0.1557, -0.0962, -0.9831, 0, 0}, {0.447216, -0.276398, -0.850648, 0.2882, -0.3611, -0.8869, 0, 0}, {0.138199, -0.276398, -0.951055, -0.016, -0.3485, -0.9372, 0, 0}, {-0.809018, -0, -0.587783, -0.8869, -0.0962, -0.4519, 0, 0}, {-0.670819, -0.276397, -0.688191, -0.7544, -0.3611, -0.5481, 0, 0}, {-0.861803, -0.276396, -0.425324, -0.8963, -0.3485, -0.2744, 0, 0}, {-0.809018, 0, 0.587783, -0.7038, -0.0962, 0.7038, 0, 0}, {-0.861803, -0.276396, 0.425324, -0.7544, -0.3611, 0.5481, 0, 0}, {-0.670819, -0.276397, 0.688191, -0.5379, -0.3485, 0.7676, 0, 0}, {0.309017, 0, 0.951056, 0.4519, -0.0962, 0.8869, 0, 0}, {0.138199, -0.276398, 0.951055, 0.2882, -0.3611, 0.8869, 0, 0}, {0.447216, -0.276398, 0.850648, 0.5638, -0.3485, 0.7488, 0, 0}, {1, 0, 0, 0.9831, -0.0962, -0.1557, 0, 0}, {0.947213, -0.276396, 0.162458, 0.9325, -0.3611, 0, 0, 0}, {0.947213, -0.276396, -0.162458, 0.8864, -0.3485, -0.3049, 0, 0}, {0.361803, -0.723612, -0.587779, 0.2287, -0.6726, -0.7038, 0, 0}, {0.138197, -0.894429, -0.425321, 0.0144, -0.8363, -0.5481, 0, 0}, {0.052789, -0.723611, -0.688186, -0.0711, -0.6369, -0.7676, 0, 0}, {-0.447211, -0.723612, -0.525727, -0.5987, -0.6726, -0.435, 0, 0}, {-0.361801, -0.894429, -0.262863, -0.5168, -0.8363, -0.183, 0, 0}, {-0.638195, -0.723609, -0.262863, -0.752, -0.6369, -0.1696, 0, 0}, {-0.638195, -0.723609, 0.262864, -0.5987, -0.6726, 0.435, 0, 0}, {-0.361801, -0.894428, 0.262864, -0.3338, -0.8363, 0.435, 0, 0}, {-0.447211, -0.72361, 0.525729, -0.3936, -0.6369, 0.6628, 0, 0}, {0.670817, -0.723611, -0.162457, 0.5257, -0.8363, -0.1557, 0, 0}, {0.670818, -0.72361, 0.162458, 0.5257, -0.8363, 0.1557, 0, 0}, {0.447211, -0.894428, 1e-06, 0.2885, -0.9575, 0, 0, 0}, {0.05279, -0.723612, 0.688185, 0.2287, -0.6726, 0.7038, 0, 0}, {0.138199, -0.894429, 0.425321, 0.3105, -0.8363, 0.4519, 0, 0}, {0.361805, -0.723611, 0.587779, 0.5087, -0.6369, 0.5792, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::SphereIndices = { 0, 15, 14, 1, 17, 23, 0, 14, 29, 0, 29, 35, 0, 35, 24, 1, 23, 44, 2, 20, 50, 3, 32, 56, 4, 38, 62, 5, 41, 68, 1, 44, 51, 2, 50, 57, 3, 56, 63, 4, 62, 69, 5, 68, 45, 6, 74, 89, 7, 77, 95, 8, 80, 98, 9, 83, 101, 10, 86, 90, 92, 99, 11, 91, 102, 92, 90, 103, 91, 92, 102, 99, 102, 100, 99, 91, 103, 102, 103, 104, 102, 102, 104, 100, 104, 101, 100, 90, 86, 103, 86, 85, 103, 103, 85, 104, 85, 84, 104, 104, 84, 101, 84, 9, 101, 99, 96, 11, 100, 105, 99, 101, 106, 100, 99, 105, 96, 105, 97, 96, 100, 106, 105, 106, 107, 105, 105, 107, 97, 107, 98, 97, 101, 83, 106, 83, 82, 106, 106, 82, 107, 82, 81, 107, 107, 81, 98, 81, 8, 98, 96, 93, 11, 97, 108, 96, 98, 109, 97, 96, 108, 93, 108, 94, 93, 97, 109, 108, 109, 110, 108, 108, 110, 94, 110, 95, 94, 98, 80, 109, 80, 79, 109, 109, 79, 110, 79, 78, 110, 110, 78, 95, 78, 7, 95, 93, 87, 11, 94, 111, 93, 95, 112, 94, 93, 111, 87, 111, 88, 87, 94, 112, 111, 112, 113, 111, 111, 113, 88, 113, 89, 88, 95, 77, 112, 77, 76, 112, 112, 76, 113, 76, 75, 113, 113, 75, 89, 75, 6, 89, 87, 92, 11, 88, 114, 87, 89, 115, 88, 87, 114, 92, 114, 91, 92, 88, 115, 114, 115, 116, 114, 114, 116, 91, 116, 90, 91, 89, 74, 115, 74, 73, 115, 115, 73, 116, 73, 72, 116, 116, 72, 90, 72, 10, 90, 47, 86, 10, 46, 117, 47, 45, 118, 46, 47, 117, 86, 117, 85, 86, 46, 118, 117, 118, 119, 117, 117, 119, 85, 119, 84, 85, 45, 68, 118, 68, 67, 118, 118, 67, 119, 67, 66, 119, 119, 66, 84, 66, 9, 84, 71, 83, 9, 70, 120, 71, 69, 121, 70, 71, 120, 83, 120, 82, 83, 70, 121, 120, 121, 122, 120, 120, 122, 82, 122, 81, 82, 69, 62, 121, 62, 61, 121, 121, 61, 122, 61, 60, 122, 122, 60, 81, 60, 8, 81, 65, 80, 8, 64, 123, 65, 63, 124, 64, 65, 123, 80, 123, 79, 80, 64, 124, 123, 124, 125, 123, 123, 125, 79, 125, 78, 79, 63, 56, 124, 56, 55, 124, 124, 55, 125, 55, 54, 125, 125, 54, 78, 54, 7, 78, 59, 77, 7, 58, 126, 59, 57, 127, 58, 59, 126, 77, 126, 76, 77, 58, 127, 126, 127, 128, 126, 126, 128, 76, 128, 75, 76, 57, 50, 127, 50, 49, 127, 127, 49, 128, 49, 48, 128, 128, 48, 75, 48, 6, 75, 53, 74, 6, 52, 129, 53, 51, 130, 52, 53, 129, 74, 129, 73, 74, 52, 130, 129, 130, 131, 129, 129, 131, 73, 131, 72, 73, 51, 44, 130, 44, 43, 130, 130, 43, 131, 43, 42, 131, 131, 42, 72, 42, 10, 72, 66, 71, 9, 67, 132, 66, 68, 133, 67, 66, 132, 71, 132, 70, 71, 67, 133, 132, 133, 134, 132, 132, 134, 70, 134, 69, 70, 68, 41, 133, 41, 40, 133, 133, 40, 134, 40, 39, 134, 134, 39, 69, 39, 4, 69, 60, 65, 8, 61, 135, 60, 62, 136, 61, 60, 135, 65, 135, 64, 65, 61, 136, 135, 136, 137, 135, 135, 137, 64, 137, 63, 64, 62, 38, 136, 38, 37, 136, 136, 37, 137, 37, 36, 137, 137, 36, 63, 36, 3, 63, 54, 59, 7, 55, 138, 54, 56, 139, 55, 54, 138, 59, 138, 58, 59, 55, 139, 138, 139, 140, 138, 138, 140, 58, 140, 57, 58, 56, 32, 139, 32, 31, 139, 139, 31, 140, 31, 30, 140, 140, 30, 57, 30, 2, 57, 48, 53, 6, 49, 141, 48, 50, 142, 49, 48, 141, 53, 141, 52, 53, 49, 142, 141, 142, 143, 141, 141, 143, 52, 143, 51, 52, 50, 20, 142, 20, 19, 142, 142, 19, 143, 19, 18, 143, 143, 18, 51, 18, 1, 51, 42, 47, 10, 43, 144, 42, 44, 145, 43, 42, 144, 47, 144, 46, 47, 43, 145, 144, 145, 146, 144, 144, 146, 46, 146, 45, 46, 44, 23, 145, 23, 22, 145, 145, 22, 146, 22, 21, 146, 146, 21, 45, 21, 5, 45, 26, 41, 5, 25, 147, 26, 24, 148, 25, 26, 147, 41, 147, 40, 41, 25, 148, 147, 148, 149, 147, 147, 149, 40, 149, 39, 40, 24, 35, 148, 35, 34, 148, 148, 34, 149, 34, 33, 149, 149, 33, 39, 33, 4, 39, 33, 38, 4, 34, 150, 33, 35, 151, 34, 33, 150, 38, 150, 37, 38, 34, 151, 150, 151, 152, 150, 150, 152, 37, 152, 36, 37, 35, 29, 151, 29, 28, 151, 151, 28, 152, 28, 27, 152, 152, 27, 36, 27, 3, 36, 27, 32, 3, 28, 153, 27, 29, 154, 28, 27, 153, 32, 153, 31, 32, 28, 154, 153, 154, 155, 153, 153, 155, 31, 155, 30, 31, 29, 14, 154, 14, 13, 154, 154, 13, 155, 13, 12, 155, 155, 12, 30, 12, 2, 30, 21, 26, 5, 22, 156, 21, 23, 157, 22, 21, 156, 26, 156, 25, 26, 22, 157, 156, 157, 158, 156, 156, 158, 25, 158, 24, 25, 23, 17, 157, 17, 16, 157, 157, 16, 158, 16, 15, 158, 158, 15, 24, 15, 0, 24, 12, 20, 2, 13, 159, 12, 14, 160, 13, 12, 159, 20, 159, 19, 20, 13, 160, 159, 160, 161, 159, 159, 161, 19, 161, 18, 19, 14, 15, 160, 15, 16, 160, 160, 16, 161, 16, 17, 161, 161, 17, 18, 17, 1, 18, }; // Cylinder (length, radius) #if 0 // smooth const VertexList PrimitiveShapeVertex::CylinderVertices = { {-1, 0, -0.5, 0, 0, -1, 0, 0}, {-1, 0, 0.5, 0, 0, 1, 0, 0}, {-0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {-0.980785, 0.19509, 0.5, 0, 0, 1, 0, 0}, {-0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {-0.92388, 0.382683, 0.5, 0, 0, 1, 0, 0}, {-0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {-0.83147, 0.55557, 0.5, 0, 0, 1, 0, 0}, {-0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {-0.707107, 0.707107, 0.5, 0, 0, 1, 0, 0}, {-0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {-0.55557, 0.83147, 0.5, 0, 0, 1, 0, 0}, {-0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {-0.382683, 0.92388, 0.5, 0, 0, 1, 0, 0}, {-0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {-0.19509, 0.980785, 0.5, 0, 0, 1, 0, 0}, {-0, 1, -0.5, 0, 0, -1, 0, 0}, {-0, 1, 0.5, 0, 0, 1, 0, 0}, {0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {0.19509, 0.980785, 0.5, 0, 0, 1, 0, 0}, {0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {0.382683, 0.92388, 0.5, 0, 0, 1, 0, 0}, {0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {0.55557, 0.83147, 0.5, 0, 0, 1, 0, 0}, {0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {0.707107, 0.707107, 0.5, 0, 0, 1, 0, 0}, {0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {0.83147, 0.55557, 0.5, 0, 0, 1, 0, 0}, {0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {0.92388, 0.382683, 0.5, 0, 0, 1, 0, 0}, {0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {0.980785, 0.19509, 0.5, 0, 0, 1, 0, 0}, {1, -0, -0.5, 0, 0, -1, 0, 0}, {1, -0, 0.5, 0, 0, 1, 0, 0}, {0.980785, -0.195091, -0.5, 0, 0, -1, 0, 0}, {0.980785, -0.195091, 0.5, 0, 0, 1, 0, 0}, {0.923879, -0.382684, -0.5, 0, 0, -1, 0, 0}, {0.923879, -0.382684, 0.5, 0, 0, 1, 0, 0}, {0.831469, -0.555571, -0.5, 0, 0, -1, 0, 0}, {0.831469, -0.555571, 0.5, 0, 0, 1, 0, 0}, {0.707106, -0.707107, -0.5, 0, 0, -1, 0, 0}, {0.707106, -0.707107, 0.5, 0, 0, 1, 0, 0}, {0.55557, -0.83147, -0.5, 0, 0, -1, 0, 0}, {0.55557, -0.83147, 0.5, 0, 0, 1, 0, 0}, {0.382683, -0.92388, -0.5, 0, 0, -1, 0, 0}, {0.382683, -0.92388, 0.5, 0, 0, 1, 0, 0}, {0.195089, -0.980785, -0.5, 0, 0, -1, 0, 0}, {0.195089, -0.980785, 0.5, 0, 0, 1, 0, 0}, {-1e-06, -1, -0.5, 0, 0, -1, 0, 0}, {-1e-06, -1, 0.5, 0, 0, 1, 0, 0}, {-0.195091, -0.980785, -0.5, 0, 0, -1, 0, 0}, {-0.195091, -0.980785, 0.5, 0, 0, 1, 0, 0}, {-0.382684, -0.923879, -0.5, 0, 0, -1, 0, 0}, {-0.382684, -0.923879, 0.5, 0, 0, 1, 0, 0}, {-0.555571, -0.831469, -0.5, 0, 0, -1, 0, 0}, {-0.555571, -0.831469, 0.5, 0, 0, 1, 0, 0}, {-0.707108, -0.707106, -0.5, 0, 0, -1, 0, 0}, {-0.707108, -0.707106, 0.5, 0, 0, 1, 0, 0}, {-0.83147, -0.555569, -0.5, 0, 0, -1, 0, 0}, {-0.83147, -0.555569, 0.5, 0, 0, 1, 0, 0}, {-0.92388, -0.382682, -0.5, 0, 0, -1, 0, 0}, {-0.92388, -0.382682, 0.5, -0.9569, -0.2903, 0, 0, 0}, {-0.980786, -0.195089, -0.5, 0, 0, -1, 0, 0}, {-0.980786, -0.195089, 0.5, -0.9952, -0.098, 0, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::CylinderIndices = { 1, 3, 2, 3, 5, 4, 5, 7, 6, 7, 9, 8, 9, 11, 10, 11, 13, 12, 13, 15, 14, 15, 17, 16, 17, 19, 18, 19, 21, 20, 21, 23, 22, 23, 25, 24, 25, 27, 26, 27, 29, 28, 29, 31, 30, 31, 33, 32, 33, 35, 34, 35, 37, 36, 37, 39, 38, 39, 41, 40, 41, 43, 42, 43, 45, 44, 45, 47, 46, 47, 49, 48, 49, 51, 50, 51, 53, 52, 53, 55, 54, 55, 57, 56, 57, 59, 58, 59, 61, 60, 37, 21, 53, 63, 1, 0, 61, 63, 62, 30, 46, 14, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 38, 38, 39, 40, 40, 41, 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 60, 5, 3, 1, 1, 63, 5, 61, 59, 57, 57, 55, 53, 53, 51, 49, 49, 47, 53, 45, 43, 37, 41, 39, 37, 37, 35, 33, 33, 31, 29, 29, 27, 25, 25, 23, 21, 21, 19, 17, 17, 15, 21, 13, 11, 9, 9, 7, 5, 5, 63, 61, 61, 57, 5, 53, 47, 45, 43, 41, 37, 37, 33, 21, 29, 25, 21, 21, 15, 13, 13, 9, 21, 5, 57, 53, 53, 45, 37, 33, 29, 21, 21, 9, 5, 5, 53, 21, 62, 63, 0, 60, 61, 62, 62, 0, 2, 2, 4, 6, 6, 8, 10, 10, 12, 6, 14, 16, 18, 18, 20, 14, 22, 24, 30, 26, 28, 30, 30, 32, 34, 34, 36, 38, 38, 40, 42, 42, 44, 46, 46, 48, 50, 50, 52, 54, 54, 56, 62, 58, 60, 62, 62, 2, 14, 6, 12, 14, 14, 20, 22, 24, 26, 30, 30, 34, 46, 38, 42, 46, 46, 50, 62, 56, 58, 62, 2, 6, 14, 14, 22, 30, 34, 38, 46, 50, 54, 62, 62, 14, 46, }; #else const VertexList PrimitiveShapeVertex::CylinderVertices = { {-1, 0, -0.5, -0.9952, -0.098, 0, 0, 0}, {-1, 0, 0.5, -0.9952, 0.098, 0, 0, 0}, {-0.980785, 0.19509, -0.5, -0.9569, 0.2903, 0, 0, 0}, {-0.980785, 0.19509, 0.5, -0.9569, 0.2903, 0, 0, 0}, {-0.92388, 0.382683, -0.5, -0.8819, 0.4714, 0, 0, 0}, {-0.92388, 0.382683, 0.5, -0.8819, 0.4714, 0, 0, 0}, {-0.83147, 0.55557, -0.5, -0.773, 0.6344, 0, 0, 0}, {-0.83147, 0.55557, 0.5, -0.773, 0.6344, 0, 0, 0}, {-0.707107, 0.707107, -0.5, -0.6344, 0.773, 0, 0, 0}, {-0.707107, 0.707107, 0.5, -0.6344, 0.773, 0, 0, 0}, {-0.55557, 0.83147, -0.5, -0.4714, 0.8819, 0, 0, 0}, {-0.55557, 0.83147, 0.5, -0.4714, 0.8819, 0, 0, 0}, {-0.382683, 0.92388, -0.5, -0.2903, 0.9569, 0, 0, 0}, {-0.382683, 0.92388, 0.5, -0.2903, 0.9569, 0, 0, 0}, {-0.19509, 0.980785, -0.5, -0.098, 0.9952, 0, 0, 0}, {-0.19509, 0.980785, 0.5, -0.098, 0.9952, 0, 0, 0}, {0, 1, -0.5, 0.098, 0.9952, 0, 0, 0}, {0, 1, 0.5, 0.098, 0.9952, 0, 0, 0}, {0.19509, 0.980785, -0.5, 0.2903, 0.9569, 0, 0, 0}, {0.19509, 0.980785, 0.5, 0.2903, 0.9569, 0, 0, 0}, {0.382683, 0.92388, -0.5, 0.4714, 0.8819, 0, 0, 0}, {0.382683, 0.92388, 0.5, 0.4714, 0.8819, 0, 0, 0}, {0.55557, 0.83147, -0.5, 0.6344, 0.773, 0, 0, 0}, {0.55557, 0.83147, 0.5, 0.6344, 0.773, 0, 0, 0}, {0.707107, 0.707107, -0.5, 0.773, 0.6344, 0, 0, 0}, {0.707107, 0.707107, 0.5, 0.773, 0.6344, 0, 0, 0}, {0.83147, 0.55557, -0.5, 0.8819, 0.4714, 0, 0, 0}, {0.83147, 0.55557, 0.5, 0.8819, 0.4714, 0, 0, 0}, {0.92388, 0.382683, -0.5, 0.9569, 0.2903, 0, 0, 0}, {0.92388, 0.382683, 0.5, 0.9569, 0.2903, 0, 0, 0}, {0.980785, 0.19509, -0.5, 0.9952, 0.098, 0, 0, 0}, {0.980785, 0.19509, 0.5, 0.9952, 0.098, 0, 0, 0}, {1, 0, -0.5, 0.9952, -0.098, 0, 0, 0}, {1, 0, 0.5, 0.9952, -0.098, 0, 0, 0}, {0.980785, -0.195091, -0.5, 0.9569, -0.2903, 0, 0, 0}, {0.980785, -0.195091, 0.5, 0.9569, -0.2903, 0, 0, 0}, {0.923879, -0.382684, -0.5, 0.8819, -0.4714, 0, 0, 0}, {0.923879, -0.382684, 0.5, 0.8819, -0.4714, 0, 0, 0}, {0.831469, -0.555571, -0.5, 0.773, -0.6344, 0, 0, 0}, {0.831469, -0.555571, 0.5, 0.773, -0.6344, 0, 0, 0}, {0.707106, -0.707107, -0.5, 0.6344, -0.773, 0, 0, 0}, {0.707106, -0.707107, 0.5, 0.6344, -0.773, 0, 0, 0}, {0.55557, -0.83147, -0.5, 0.4714, -0.8819, 0, 0, 0}, {0.55557, -0.83147, 0.5, 0.4714, -0.8819, 0, 0, 0}, {0.382683, -0.92388, -0.5, 0.2903, -0.9569, 0, 0, 0}, {0.382683, -0.92388, 0.5, 0.2903, -0.9569, 0, 0, 0}, {0.195089, -0.980785, -0.5, 0.098, -0.9952, 0, 0, 0}, {0.195089, -0.980785, 0.5, 0.098, -0.9952, 0, 0, 0}, {-1e-06, -1, -0.5, -0.098, -0.9952, 0, 0, 0}, {-1e-06, -1, 0.5, -0.098, -0.9952, 0, 0, 0}, {-0.195091, -0.980785, -0.5, -0.2903, -0.9569, 0, 0, 0}, {-0.195091, -0.980785, 0.5, -0.2903, -0.9569, 0, 0, 0}, {-0.382684, -0.923879, -0.5, -0.4714, -0.8819, 0, 0, 0}, {-0.382684, -0.923879, 0.5, -0.4714, -0.8819, 0, 0, 0}, {-0.555571, -0.831469, -0.5, -0.6344, -0.773, 0, 0, 0}, {-0.555571, -0.831469, 0.5, -0.6344, -0.773, 0, 0, 0}, {-0.707108, -0.707106, -0.5, -0.773, -0.6344, 0, 0, 0}, {-0.707108, -0.707106, 0.5, -0.773, -0.6344, 0, 0, 0}, {-0.83147, -0.555569, -0.5, -0.8819, -0.4714, 0, 0, 0}, {-0.83147, -0.555569, 0.5, -0.8819, -0.4714, 0, 0, 0}, {-0.92388, -0.382682, -0.5, -0.9569, -0.2903, 0, 0, 0}, {-0.92388, -0.382682, 0.5, -0.9569, -0.2903, 0, 0, 0}, {-0.980786, -0.195089, -0.5, -0.9952, -0.098, 0, 0, 0}, {-0.980786, -0.195089, 0.5, -0.9952, -0.098, 0, 0, 0}, {0, 0, -0.5, 0, 0, -1, 0, 0}, {0, 0, 0.5, 0, 0, 1, 0, 0}, {-1, 0, -0.5, 0, 0, -1, 0, 0}, {-1, 0, 0.5, 0, 0, 1, 0, 0}, {-0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {-0.980785, 0.19509, 0.5, 0, 0, 1, 0, 0}, {-0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {-0.92388, 0.382683, 0.5, 0, 0, 1, 0, 0}, {-0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {-0.83147, 0.55557, 0.5, 0, 0, 1, 0, 0}, {-0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {-0.707107, 0.707107, 0.5, 0, 0, 1, 0, 0}, {-0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {-0.55557, 0.83147, 0.5, 0, 0, 1, 0, 0}, {-0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {-0.382683, 0.92388, 0.5, 0, 0, 1, 0, 0}, {-0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {-0.19509, 0.980785, 0.5, 0, 0, 1, 0, 0}, {0, 1, -0.5, 0, 0, -1, 0, 0}, {0, 1, 0.5, 0, 0, 1, 0, 0}, {0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {0.19509, 0.980785, 0.5, 0, 0, 1, 0, 0}, {0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {0.382683, 0.92388, 0.5, 0, 0, 1, 0, 0}, {0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {0.55557, 0.83147, 0.5, 0, 0, 1, 0, 0}, {0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {0.707107, 0.707107, 0.5, 0, 0, 1, 0, 0}, {0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {0.83147, 0.55557, 0.5, 0, 0, 1, 0, 0}, {0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {0.92388, 0.382683, 0.5, 0, 0, 1, 0, 0}, {0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {0.980785, 0.19509, 0.5, 0, 0, 1, 0, 0}, {1, 0, -0.5, 0, 0, -1, 0, 0}, {1, 0, 0.5, 0, 0, 1, 0, 0}, {0.980785, -0.195091, -0.5, 0, 0, -1, 0, 0}, {0.980785, -0.195091, 0.5, 0, 0, 1, 0, 0}, {0.923879, -0.382684, -0.5, 0, 0, -1, 0, 0}, {0.923879, -0.382684, 0.5, 0, 0, 1, 0, 0}, {0.831469, -0.555571, -0.5, 0, 0, -1, 0, 0}, {0.831469, -0.555571, 0.5, 0, 0, 1, 0, 0}, {0.707106, -0.707107, -0.5, 0, 0, -1, 0, 0}, {0.707106, -0.707107, 0.5, 0, 0, 1, 0, 0}, {0.55557, -0.83147, -0.5, 0, 0, -1, 0, 0}, {0.55557, -0.83147, 0.5, 0, 0, 1, 0, 0}, {0.382683, -0.92388, -0.5, 0, 0, -1, 0, 0}, {0.382683, -0.92388, 0.5, 0, 0, 1, 0, 0}, {0.195089, -0.980785, -0.5, 0, 0, -1, 0, 0}, {0.195089, -0.980785, 0.5, 0, 0, 1, 0, 0}, {-1e-06, -1, -0.5, 0, 0, -1, 0, 0}, {-1e-06, -1, 0.5, 0, 0, 1, 0, 0}, {-0.195091, -0.980785, -0.5, 0, 0, -1, 0, 0}, {-0.195091, -0.980785, 0.5, 0, 0, 1, 0, 0}, {-0.382684, -0.923879, -0.5, 0, 0, -1, 0, 0}, {-0.382684, -0.923879, 0.5, 0, 0, 1, 0, 0}, {-0.555571, -0.831469, -0.5, 0, 0, -1, 0, 0}, {-0.555571, -0.831469, 0.5, 0, 0, 1, 0, 0}, {-0.707108, -0.707106, -0.5, 0, 0, -1, 0, 0}, {-0.707108, -0.707106, 0.5, 0, 0, 1, 0, 0}, {-0.83147, -0.555569, -0.5, 0, 0, -1, 0, 0}, {-0.83147, -0.555569, 0.5, 0, 0, 1, 0, 0}, {-0.92388, -0.382682, -0.5, 0, 0, -1, 0, 0}, {-0.92388, -0.382682, 0.5, 0, 0, 1, 0, 0}, {-0.980786, -0.195089, -0.5, 0, 0, -1, 0, 0}, {-0.980786, -0.195089, 0.5, 0, 0, 1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::CylinderIndices = { 1, 3, 2, 3, 5, 4, 5, 7, 6, 7, 9, 8, 9, 11, 10, 11, 13, 12, 13, 15, 14, 15, 17, 16, 17, 19, 18, 19, 21, 20, 21, 23, 22, 23, 25, 24, 25, 27, 26, 27, 29, 28, 29, 31, 30, 31, 33, 32, 33, 35, 34, 35, 37, 36, 37, 39, 38, 39, 41, 40, 41, 43, 42, 43, 45, 44, 45, 47, 46, 47, 49, 48, 49, 51, 50, 51, 53, 52, 53, 55, 54, 55, 57, 56, 57, 59, 58, 59, 61, 60, 61, 63, 62, 63, 1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 38, 38, 39, 40, 40, 41, 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 60, 60, 61, 62, 62, 63, 0, 64, 66, 68, 65, 69, 67, 64, 68, 70, 65, 71, 69, 64, 70, 72, 65, 73, 71, 64, 72, 74, 65, 75, 73, 64, 74, 76, 65, 77, 75, 64, 76, 78, 65, 79, 77, 64, 78, 80, 65, 81, 79, 64, 80, 82, 65, 83, 81, 64, 82, 84, 65, 85, 83, 64, 84, 86, 65, 87, 85, 64, 86, 88, 65, 89, 87, 64, 88, 90, 65, 91, 89, 64, 90, 92, 65, 93, 91, 64, 92, 94, 65, 95, 93, 64, 94, 96, 65, 97, 95, 64, 96, 98, 65, 99, 97, 64, 98, 100, 65, 101, 99, 64, 100, 102, 65, 103, 101, 64, 102, 104, 65, 105, 103, 64, 104, 106, 65, 107, 105, 64, 106, 108, 65, 109, 107, 64, 108, 110, 65, 111, 109, 64, 110, 112, 65, 113, 111, 64, 112, 114, 65, 115, 113, 64, 114, 116, 65, 117, 115, 64, 116, 118, 65, 119, 117, 64, 118, 120, 65, 121, 119, 64, 120, 122, 65, 123, 121, 64, 122, 124, 65, 125, 123, 64, 124, 126, 65, 127, 125, 64, 126, 128, 65, 129, 127, 64, 128, 66, 65, 67, 129, }; #endif // Cylinder-Side const VertexList PrimitiveShapeVertex::CylinderSideVertices = { {-1, 0, -0.5, -0.9952, -0.098, 0, 0, 0}, {-1, 0, 0.5, -0.9952, 0.098, 0, 0, 0}, {-0.980785, 0.19509, -0.5, -0.9569, 0.2903, 0, 0, 0}, {-0.980785, 0.19509, 0.5, -0.9569, 0.2903, 0, 0, 0}, {-0.92388, 0.382683, -0.5, -0.8819, 0.4714, 0, 0, 0}, {-0.92388, 0.382683, 0.5, -0.8819, 0.4714, 0, 0, 0}, {-0.83147, 0.55557, -0.5, -0.773, 0.6344, 0, 0, 0}, {-0.83147, 0.55557, 0.5, -0.773, 0.6344, 0, 0, 0}, {-0.707107, 0.707107, -0.5, -0.6344, 0.773, 0, 0, 0}, {-0.707107, 0.707107, 0.5, -0.6344, 0.773, 0, 0, 0}, {-0.55557, 0.83147, -0.5, -0.4714, 0.8819, 0, 0, 0}, {-0.55557, 0.83147, 0.5, -0.4714, 0.8819, 0, 0, 0}, {-0.382683, 0.92388, -0.5, -0.2903, 0.9569, 0, 0, 0}, {-0.382683, 0.92388, 0.5, -0.2903, 0.9569, 0, 0, 0}, {-0.19509, 0.980785, -0.5, -0.098, 0.9952, 0, 0, 0}, {-0.19509, 0.980785, 0.5, -0.098, 0.9952, 0, 0, 0}, {-0, 1, -0.5, 0.098, 0.9952, 0, 0, 0}, {-0, 1, 0.5, 0.098, 0.9952, 0, 0, 0}, {0.19509, 0.980785, -0.5, 0.2903, 0.9569, 0, 0, 0}, {0.19509, 0.980785, 0.5, 0.2903, 0.9569, 0, 0, 0}, {0.382683, 0.92388, -0.5, 0.4714, 0.8819, 0, 0, 0}, {0.382683, 0.92388, 0.5, 0.4714, 0.8819, 0, 0, 0}, {0.55557, 0.83147, -0.5, 0.6344, 0.773, 0, 0, 0}, {0.55557, 0.83147, 0.5, 0.6344, 0.773, 0, 0, 0}, {0.707107, 0.707107, -0.5, 0.773, 0.6344, 0, 0, 0}, {0.707107, 0.707107, 0.5, 0.773, 0.6344, 0, 0, 0}, {0.83147, 0.55557, -0.5, 0.8819, 0.4714, 0, 0, 0}, {0.83147, 0.55557, 0.5, 0.8819, 0.4714, 0, 0, 0}, {0.92388, 0.382683, -0.5, 0.9569, 0.2903, 0, 0, 0}, {0.92388, 0.382683, 0.5, 0.9569, 0.2903, 0, 0, 0}, {0.980785, 0.19509, -0.5, 0.9952, 0.098, 0, 0, 0}, {0.980785, 0.19509, 0.5, 0.9952, 0.098, 0, 0, 0}, {1, -0, -0.5, 0.9952, -0.098, 0, 0, 0}, {1, -0, 0.5, 0.9952, -0.098, 0, 0, 0}, {0.980785, -0.195091, -0.5, 0.9569, -0.2903, 0, 0, 0}, {0.980785, -0.195091, 0.5, 0.9569, -0.2903, 0, 0, 0}, {0.923879, -0.382684, -0.5, 0.8819, -0.4714, 0, 0, 0}, {0.923879, -0.382684, 0.5, 0.8819, -0.4714, 0, 0, 0}, {0.831469, -0.555571, -0.5, 0.773, -0.6344, 0, 0, 0}, {0.831469, -0.555571, 0.5, 0.773, -0.6344, 0, 0, 0}, {0.707106, -0.707107, -0.5, 0.6344, -0.773, 0, 0, 0}, {0.707106, -0.707107, 0.5, 0.6344, -0.773, 0, 0, 0}, {0.55557, -0.83147, -0.5, 0.4714, -0.8819, 0, 0, 0}, {0.55557, -0.83147, 0.5, 0.4714, -0.8819, 0, 0, 0}, {0.382683, -0.92388, -0.5, 0.2903, -0.9569, 0, 0, 0}, {0.382683, -0.92388, 0.5, 0.2903, -0.9569, 0, 0, 0}, {0.195089, -0.980785, -0.5, 0.098, -0.9952, 0, 0, 0}, {0.195089, -0.980785, 0.5, 0.098, -0.9952, 0, 0, 0}, {-1e-06, -1, -0.5, -0.098, -0.9952, 0, 0, 0}, {-1e-06, -1, 0.5, -0.098, -0.9952, 0, 0, 0}, {-0.195091, -0.980785, -0.5, -0.2903, -0.9569, 0, 0, 0}, {-0.195091, -0.980785, 0.5, -0.2903, -0.9569, 0, 0, 0}, {-0.382684, -0.923879, -0.5, -0.4714, -0.8819, 0, 0, 0}, {-0.382684, -0.923879, 0.5, -0.4714, -0.8819, 0, 0, 0}, {-0.555571, -0.831469, -0.5, -0.6344, -0.773, 0, 0, 0}, {-0.555571, -0.831469, 0.5, -0.6344, -0.773, 0, 0, 0}, {-0.707108, -0.707106, -0.5, -0.773, -0.6344, 0, 0, 0}, {-0.707108, -0.707106, 0.5, -0.773, -0.6344, 0, 0, 0}, {-0.83147, -0.555569, -0.5, -0.8819, -0.4714, 0, 0, 0}, {-0.83147, -0.555569, 0.5, -0.8819, -0.4714, 0, 0, 0}, {-0.92388, -0.382682, -0.5, -0.9569, -0.2903, 0, 0, 0}, {-0.92388, -0.382682, 0.5, -0.9569, -0.2903, 0, 0, 0}, {-0.980786, -0.195089, -0.5, -0.9952, -0.098, 0, 0, 0}, {-0.980786, -0.195089, 0.5, -0.9952, -0.098, 0, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::CylinderSideIndices = { 1, 3, 2, 3, 5, 4, 5, 7, 6, 7, 9, 8, 9, 11, 10, 11, 13, 12, 13, 15, 14, 15, 17, 16, 17, 19, 18, 19, 21, 20, 21, 23, 22, 23, 25, 24, 25, 27, 26, 27, 29, 28, 29, 31, 30, 31, 33, 32, 33, 35, 34, 35, 37, 36, 37, 39, 38, 39, 41, 40, 41, 43, 42, 43, 45, 44, 45, 47, 46, 47, 49, 48, 49, 51, 50, 51, 53, 52, 53, 55, 54, 55, 57, 56, 57, 59, 58, 59, 61, 60, 61, 63, 62, 63, 1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 38, 38, 39, 40, 40, 41, 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 60, 60, 61, 62, 62, 63, 0, }; // UpperSphere const VertexList PrimitiveShapeVertex::UpperSphereVertices = { {0, -0.19509, 0.980785, 0.0286, -0.2902, 0.9565, 0, 0}, {0, -0.382683, 0.92388, 0.0464, -0.4709, 0.881, 0, 0}, {0, -0.55557, 0.83147, 0.0624, -0.6332, 0.7715, 0, 0}, {0, -0.707107, 0.707107, 0.0624, -0.6332, 0.7715, 0, 0}, {0, -0.83147, 0.55557, 0.0865, -0.8786, 0.4696, 0, 0}, {0, -0.92388, 0.382683, 0.0938, -0.9527, 0.289, 0, 0}, {0, -0.980785, 0.19509, 0.0976, -0.9904, 0.0975, 0, 0}, {0, -1, 0, 0.0976, -0.9904, 0.0975, 0, 0}, {-0.03806, -0.191342, 0.980785, -0.0846, -0.279, 0.9565, 0, 0}, {-0.074658, -0.37533, 0.92388, -0.0846, -0.279, 0.9565, 0, 0}, {-0.108386, -0.544895, 0.83147, -0.1847, -0.6088, 0.7715, 0, 0}, {-0.13795, -0.69352, 0.707107, -0.2248, -0.7412, 0.6326, 0, 0}, {-0.162212, -0.815493, 0.55557, -0.2563, -0.8448, 0.4696, 0, 0}, {-0.18024, -0.906127, 0.382683, -0.2779, -0.9161, 0.289, 0, 0}, {-0.191342, -0.96194, 0.19509, -0.2889, -0.9524, 0.0975, 0, 0}, {-0.19509, -0.980785, 0, -0.2889, -0.9524, 0.0975, 0, 0}, {-0.074658, -0.18024, 0.980785, -0.1374, -0.2571, 0.9565, 0, 0}, {-0.146447, -0.353553, 0.92388, -0.2231, -0.4173, 0.881, 0, 0}, {-0.212608, -0.51328, 0.83147, -0.2999, -0.5611, 0.7715, 0, 0}, {-0.270598, -0.653281, 0.707107, -0.3651, -0.6831, 0.6326, 0, 0}, {-0.31819, -0.768178, 0.55557, -0.4162, -0.7786, 0.4696, 0, 0}, {-0.353553, -0.853553, 0.382683, -0.4162, -0.7786, 0.4696, 0, 0}, {-0.37533, -0.906127, 0.19509, -0.4691, -0.8777, 0.0975, 0, 0}, {-0.382684, -0.923879, 0, -0.4691, -0.8777, 0.0975, 0, 0}, {-0.108387, -0.162212, 0.980785, -0.185, -0.2254, 0.9565, 0, 0}, {-0.212608, -0.31819, 0.92388, -0.3002, -0.3658, 0.881, 0, 0}, {-0.308658, -0.46194, 0.83147, -0.3002, -0.3658, 0.881, 0, 0}, {-0.392848, -0.587938, 0.707107, -0.4913, -0.5987, 0.6326, 0, 0}, {-0.46194, -0.691342, 0.55557, -0.5601, -0.6825, 0.4696, 0, 0}, {-0.51328, -0.768178, 0.382683, -0.6073, -0.74, 0.289, 0, 0}, {-0.544895, -0.815493, 0.19509, -0.6073, -0.74, 0.289, 0, 0}, {-0.55557, -0.831469, 0, -0.6314, -0.7693, 0.0976, 0, 0}, {-0.13795, -0.13795, 0.980785, -0.2254, -0.185, 0.9565, 0, 0}, {-0.270598, -0.270598, 0.92388, -0.3658, -0.3002, 0.881, 0, 0}, {-0.392848, -0.392847, 0.83147, -0.4918, -0.4036, 0.7715, 0, 0}, {-0.5, -0.5, 0.707107, -0.4918, -0.4036, 0.7715, 0, 0}, {-0.587938, -0.587938, 0.55557, -0.6825, -0.5601, 0.4696, 0, 0}, {-0.653282, -0.653281, 0.382683, -0.74, -0.6073, 0.289, 0, 0}, {-0.69352, -0.69352, 0.19509, -0.74, -0.6073, 0.289, 0, 0}, {-0.707107, -0.707107, 0, -0.7693, -0.6314, 0.0976, 0, 0}, {-0.162212, -0.108386, 0.980785, -0.2571, -0.1374, 0.9565, 0, 0}, {-0.31819, -0.212607, 0.92388, -0.4173, -0.223, 0.881, 0, 0}, {-0.46194, -0.308658, 0.83147, -0.5611, -0.2999, 0.7715, 0, 0}, {-0.587938, -0.392847, 0.707107, -0.5611, -0.2999, 0.7715, 0, 0}, {-0.691342, -0.46194, 0.55557, -0.7786, -0.4162, 0.4696, 0, 0}, {-0.768178, -0.51328, 0.382683, -0.7786, -0.4162, 0.4696, 0, 0}, {-0.815493, -0.544895, 0.19509, -0.8777, -0.4691, 0.0976, 0, 0}, {-0.83147, -0.55557, 0, -0.8777, -0.4691, 0.0976, 0, 0}, {-0.18024, -0.074658, 0.980785, -0.279, -0.0846, 0.9565, 0, 0}, {-0.353554, -0.146446, 0.92388, -0.4528, -0.1374, 0.881, 0, 0}, {-0.51328, -0.212607, 0.83147, -0.4528, -0.1374, 0.881, 0, 0}, {-0.653282, -0.270598, 0.707107, -0.7412, -0.2248, 0.6326, 0, 0}, {-0.768178, -0.318189, 0.55557, -0.8448, -0.2563, 0.4696, 0, 0}, {-0.853554, -0.353553, 0.382683, -0.8448, -0.2563, 0.4696, 0, 0}, {-0.906128, -0.37533, 0.19509, -0.9524, -0.2889, 0.0976, 0, 0}, {-0.92388, -0.382683, 0, -0.9524, -0.2889, 0.0976, 0, 0}, {-0.191342, -0.03806, 0.980785, -0.2902, -0.0286, 0.9565, 0, 0}, {-0.375331, -0.074658, 0.92388, -0.4709, -0.0464, 0.881, 0, 0}, {-0.544895, -0.108386, 0.83147, -0.6332, -0.0624, 0.7715, 0, 0}, {-0.69352, -0.137949, 0.707107, -0.6332, -0.0624, 0.7715, 0, 0}, {-0.815493, -0.162211, 0.55557, -0.8786, -0.0865, 0.4696, 0, 0}, {-0.906128, -0.18024, 0.382683, -0.8786, -0.0865, 0.4696, 0, 0}, {-0.96194, -0.191341, 0.19509, -0.9904, -0.0975, 0.0976, 0, 0}, {-0.980785, -0.19509, 0, -0.9904, -0.0975, 0.0976, 0, 0}, {-0.195091, 0, 0.980785, -0.098, 0.0097, 0.9951, 0, 0}, {-0.382684, 0, 0.92388, -0.4709, 0.0464, 0.881, 0, 0}, {-0.55557, 0, 0.83147, -0.6332, 0.0624, 0.7715, 0, 0}, {-0.707107, 0, 0.707107, -0.6332, 0.0624, 0.7715, 0, 0}, {-0.83147, 0, 0.55557, -0.8786, 0.0865, 0.4696, 0, 0}, {-0.92388, 0, 0.382683, -0.8786, 0.0865, 0.4696, 0, 0}, {-0.980785, 0, 0.19509, -0.9904, 0.0975, 0.0976, 0, 0}, {-1, 0, 0, -0.9904, 0.0975, 0.0976, 0, 0}, {-0.191342, 0.038061, 0.980785, -0.279, 0.0846, 0.9565, 0, 0}, {-0.375331, 0.074658, 0.92388, -0.279, 0.0846, 0.9565, 0, 0}, {-0.544895, 0.108387, 0.83147, -0.6088, 0.1847, 0.7715, 0, 0}, {-0.69352, 0.13795, 0.707107, -0.7412, 0.2248, 0.6326, 0, 0}, {-0.815493, 0.162212, 0.55557, -0.7412, 0.2248, 0.6326, 0, 0}, {-0.906128, 0.18024, 0.382683, -0.8448, 0.2563, 0.4696, 0, 0}, {-0.96194, 0.191342, 0.19509, -0.9524, 0.2889, 0.0976, 0, 0}, {-0.980785, 0.195091, 0, -0.9524, 0.2889, 0.0976, 0, 0}, {-0.18024, 0.074658, 0.980785, -0.2571, 0.1374, 0.9565, 0, 0}, {-0.353554, 0.146447, 0.92388, -0.4173, 0.223, 0.881, 0, 0}, {-0.51328, 0.212608, 0.83147, -0.5611, 0.2999, 0.7715, 0, 0}, {-0.653282, 0.270598, 0.707107, -0.5611, 0.2999, 0.7715, 0, 0}, {-0.768178, 0.31819, 0.55557, -0.7786, 0.4162, 0.4696, 0, 0}, {-0.853554, 0.353554, 0.382683, -0.7786, 0.4162, 0.4696, 0, 0}, {-0.906127, 0.375331, 0.19509, -0.8777, 0.4691, 0.0976, 0, 0}, {-0.92388, 0.382684, 0, -0.8777, 0.4691, 0.0976, 0, 0}, {-0.162212, 0.108387, 0.980785, -0.2254, 0.185, 0.9565, 0, 0}, {-0.31819, 0.212608, 0.92388, -0.3658, 0.3002, 0.881, 0, 0}, {-0.46194, 0.308659, 0.83147, -0.4918, 0.4036, 0.7715, 0, 0}, {-0.587938, 0.392848, 0.707107, -0.5987, 0.4913, 0.6326, 0, 0}, {-0.691342, 0.46194, 0.55557, -0.5987, 0.4913, 0.6326, 0, 0}, {-0.768178, 0.51328, 0.382683, -0.6825, 0.5601, 0.4696, 0, 0}, {-0.815493, 0.544895, 0.19509, -0.7693, 0.6314, 0.0976, 0, 0}, {-0.83147, 0.555571, 0, -0.7693, 0.6314, 0.0976, 0, 0}, {-0.13795, 0.13795, 0.980785, -0.185, 0.2254, 0.9565, 0, 0}, {-0.270598, 0.270599, 0.92388, -0.185, 0.2254, 0.9565, 0, 0}, {-0.392848, 0.392848, 0.83147, -0.3002, 0.3658, 0.881, 0, 0}, {-0.5, 0.5, 0.707107, -0.4036, 0.4918, 0.7715, 0, 0}, {-0.587938, 0.587938, 0.55557, -0.5601, 0.6825, 0.4696, 0, 0}, {-0.653282, 0.653282, 0.382683, -0.5601, 0.6825, 0.4696, 0, 0}, {-0.69352, 0.69352, 0.19509, -0.6314, 0.7693, 0.0976, 0, 0}, {-0.707107, 0.707107, 0, -0.6314, 0.7693, 0.0976, 0, 0}, {-0.108386, 0.162212, 0.980785, -0.1374, 0.2571, 0.9565, 0, 0}, {-0.212608, 0.31819, 0.92388, -0.1374, 0.2571, 0.9565, 0, 0}, {-0.308658, 0.46194, 0.83147, -0.2999, 0.5611, 0.7715, 0, 0}, {-0.392848, 0.587938, 0.707107, -0.3651, 0.6831, 0.6326, 0, 0}, {-0.46194, 0.691342, 0.55557, -0.4162, 0.7786, 0.4696, 0, 0}, {-0.51328, 0.768178, 0.382683, -0.4162, 0.7786, 0.4696, 0, 0}, {-0.544895, 0.815493, 0.19509, -0.4691, 0.8777, 0.0976, 0, 0}, {-0.55557, 0.83147, 0, -0.4691, 0.8777, 0.0976, 0, 0}, {-0.074658, 0.18024, 0.980785, -0.0846, 0.279, 0.9565, 0, 0}, {-0.146447, 0.353554, 0.92388, -0.1374, 0.4528, 0.881, 0, 0}, {-0.212608, 0.51328, 0.83147, -0.1374, 0.4528, 0.881, 0, 0}, {-0.270598, 0.653282, 0.707107, -0.2248, 0.7412, 0.6326, 0, 0}, {-0.31819, 0.768178, 0.55557, -0.2563, 0.8448, 0.4696, 0, 0}, {-0.353553, 0.853554, 0.382683, -0.2563, 0.8448, 0.4696, 0, 0}, {-0.37533, 0.906128, 0.19509, -0.2889, 0.9524, 0.0976, 0, 0}, {-0.382683, 0.92388, 0, -0.2889, 0.9524, 0.0976, 0, 0}, {-0.03806, 0.191342, 0.980785, -0.0286, 0.2902, 0.9565, 0, 0}, {-0.074658, 0.375331, 0.92388, -0.0286, 0.2902, 0.9565, 0, 0}, {-0.108386, 0.544896, 0.83147, -0.0464, 0.4709, 0.881, 0, 0}, {-0.13795, 0.69352, 0.707107, -0.0759, 0.7708, 0.6326, 0, 0}, {-0.162212, 0.815493, 0.55557, -0.0865, 0.8786, 0.4696, 0, 0}, {-0.18024, 0.906128, 0.382683, -0.0865, 0.8786, 0.4696, 0, 0}, {-0.191342, 0.96194, 0.19509, -0.0938, 0.9527, 0.289, 0, 0}, {-0.19509, 0.980786, 0, -0.0975, 0.9904, 0.0976, 0, 0}, {0, 0.195091, 0.980785, 0.0286, 0.2902, 0.9565, 0, 0}, {-0, 0.382684, 0.92388, 0.0464, 0.4709, 0.881, 0, 0}, {-0, 0.555571, 0.83147, 0.0464, 0.4709, 0.881, 0, 0}, {0, 0.707107, 0.707107, 0.0624, 0.6332, 0.7715, 0, 0}, {0, 0.83147, 0.55557, 0.0865, 0.8786, 0.4696, 0, 0}, {-0, 0.92388, 0.382683, 0.0865, 0.8786, 0.4696, 0, 0}, {0, 0.980785, 0.19509, 0.0975, 0.9904, 0.0976, 0, 0}, {0, 1, 0, 0.0975, 0.9904, 0.0976, 0, 0}, {0.03806, 0.191342, 0.980785, 0.0846, 0.279, 0.9565, 0, 0}, {0.074658, 0.375331, 0.92388, 0.1374, 0.4528, 0.881, 0, 0}, {0.108386, 0.544896, 0.83147, 0.1374, 0.4528, 0.881, 0, 0}, {0.13795, 0.69352, 0.707107, 0.1847, 0.6088, 0.7715, 0, 0}, {0.162212, 0.815493, 0.55557, 0.2563, 0.8448, 0.4696, 0, 0}, {0.18024, 0.906128, 0.382683, 0.2563, 0.8448, 0.4696, 0, 0}, {0.191342, 0.96194, 0.19509, 0.2779, 0.9161, 0.289, 0, 0}, {0.19509, 0.980786, 0, 0.2889, 0.9524, 0.0976, 0, 0}, {0.074658, 0.18024, 0.980785, 0.1374, 0.2571, 0.9565, 0, 0}, {0.146447, 0.353554, 0.92388, 0.2231, 0.4173, 0.881, 0, 0}, {0.212608, 0.51328, 0.83147, 0.2999, 0.5611, 0.7715, 0, 0}, {0.270598, 0.653282, 0.707107, 0.2999, 0.5611, 0.7715, 0, 0}, {0.31819, 0.768178, 0.55557, 0.4162, 0.7786, 0.4696, 0, 0}, {0.353553, 0.853554, 0.382683, 0.4162, 0.7786, 0.4696, 0, 0}, {0.37533, 0.906127, 0.19509, 0.4691, 0.8777, 0.0976, 0, 0}, {0.382684, 0.92388, 0, 0.4691, 0.8777, 0.0976, 0, 0}, {0.108386, 0.162212, 0.980785, 0.185, 0.2254, 0.9565, 0, 0}, {0.212608, 0.31819, 0.92388, 0.3002, 0.3658, 0.881, 0, 0}, {0.308658, 0.46194, 0.83147, 0.3002, 0.3658, 0.881, 0, 0}, {0.392847, 0.587938, 0.707107, 0.4036, 0.4918, 0.7715, 0, 0}, {0.46194, 0.691342, 0.55557, 0.5601, 0.6825, 0.4696, 0, 0}, {0.51328, 0.768178, 0.382683, 0.5601, 0.6825, 0.4696, 0, 0}, {0.544895, 0.815493, 0.19509, 0.6073, 0.74, 0.289, 0, 0}, {0.55557, 0.83147, 0, 0.6314, 0.7693, 0.0976, 0, 0}, {0.13795, 0.13795, 0.980785, 0.2254, 0.185, 0.9565, 0, 0}, {0.270598, 0.270598, 0.92388, 0.3658, 0.3002, 0.881, 0, 0}, {0.392848, 0.392848, 0.83147, 0.3658, 0.3002, 0.881, 0, 0}, {0.5, 0.5, 0.707107, 0.4918, 0.4036, 0.7715, 0, 0}, {0.587938, 0.587938, 0.55557, 0.6825, 0.5601, 0.4696, 0, 0}, {0.653281, 0.653282, 0.382683, 0.6825, 0.5601, 0.4696, 0, 0}, {0.69352, 0.69352, 0.19509, 0.7693, 0.6314, 0.0976, 0, 0}, {0.707107, 0.707107, 0, 0.7693, 0.6314, 0.0976, 0, 0}, {0.162212, 0.108387, 0.980785, 0.2571, 0.1374, 0.9565, 0, 0}, {0.31819, 0.212608, 0.92388, 0.4173, 0.223, 0.881, 0, 0}, {0.46194, 0.308659, 0.83147, 0.4173, 0.223, 0.881, 0, 0}, {0.587938, 0.392848, 0.707107, 0.5611, 0.2999, 0.7715, 0, 0}, {0.691342, 0.46194, 0.55557, 0.7786, 0.4162, 0.4696, 0, 0}, {0.768178, 0.51328, 0.382683, 0.7786, 0.4162, 0.4696, 0, 0}, {0.815493, 0.544895, 0.19509, 0.8777, 0.4691, 0.0976, 0, 0}, {0.83147, 0.55557, 0, 0.8777, 0.4691, 0.0976, 0, 0}, {0.18024, 0.074658, 0.980785, 0.0942, 0.0286, 0.9951, 0, 0}, {0.353553, 0.146447, 0.92388, 0.4528, 0.1374, 0.881, 0, 0}, {0.51328, 0.212608, 0.83147, 0.4528, 0.1374, 0.881, 0, 0}, {0.653281, 0.270598, 0.707107, 0.6088, 0.1847, 0.7715, 0, 0}, {0.768177, 0.31819, 0.55557, 0.7412, 0.2248, 0.6326, 0, 0}, {0.853553, 0.353554, 0.382683, 0.8448, 0.2563, 0.4696, 0, 0}, {0.906127, 0.37533, 0.19509, 0.9524, 0.2889, 0.0976, 0, 0}, {0.92388, 0.382684, 0, 0.9524, 0.2889, 0.0976, 0, 0}, {0.191342, 0.038061, 0.980785, 0.279, 0.0846, 0.9565, 0, 0}, {0.37533, 0.074658, 0.92388, 0.2902, 0.0286, 0.9565, 0, 0}, {0.544895, 0.108387, 0.83147, 0.4709, 0.0464, 0.881, 0, 0}, {0.69352, 0.13795, 0.707107, 0.7708, 0.0759, 0.6326, 0, 0}, {0.815493, 0.162212, 0.55557, 0.8786, 0.0865, 0.4696, 0, 0}, {0.906127, 0.18024, 0.382683, 0.8786, 0.0865, 0.4696, 0, 0}, {0.961939, 0.191342, 0.19509, 0.9904, 0.0975, 0.0976, 0, 0}, {0.980785, 0.19509, 0, 0.9904, 0.0975, 0.0976, 0, 0}, {0.19509, 0, 0.980785, 0.2902, 0.0286, 0.9565, 0, 0}, {0.382683, 0, 0.92388, 0.4709, -0.0464, 0.881, 0, 0}, {0.55557, 0, 0.83147, 0.4709, -0.0464, 0.881, 0, 0}, {0.707107, 0, 0.707107, 0.6332, -0.0624, 0.7715, 0, 0}, {0.831469, 0, 0.55557, 0.8786, -0.0865, 0.4696, 0, 0}, {0.923879, 0, 0.382683, 0.8786, -0.0865, 0.4696, 0, 0}, {0.980785, 0, 0.19509, 0.9904, -0.0976, 0.0976, 0, 0}, {1, 0, 0, 0.9904, -0.0976, 0.0976, 0, 0}, {0.191342, -0.03806, 0.980785, 0.279, -0.0846, 0.9565, 0, 0}, {0.37533, -0.074658, 0.92388, 0.279, -0.0846, 0.9565, 0, 0}, {0.544895, -0.108386, 0.83147, 0.4528, -0.1374, 0.881, 0, 0}, {0.69352, -0.137949, 0.707107, 0.7412, -0.2248, 0.6326, 0, 0}, {0.815493, -0.162211, 0.55557, 0.8448, -0.2563, 0.4696, 0, 0}, {0.906127, -0.18024, 0.382683, 0.8448, -0.2563, 0.4696, 0, 0}, {0.961939, -0.191342, 0.19509, 0.9524, -0.2889, 0.0976, 0, 0}, {0.980785, -0.19509, 0, 0.9524, -0.2889, 0.0976, 0, 0}, {0, 0, 1, 0.0097, -0.098, 0.9951, 0, 0}, {0.18024, -0.074658, 0.980785, 0.2571, -0.1374, 0.9565, 0, 0}, {0.353553, -0.146446, 0.92388, 0.2571, -0.1374, 0.9565, 0, 0}, {0.51328, -0.212607, 0.83147, 0.4173, -0.223, 0.881, 0, 0}, {0.653281, -0.270598, 0.707107, 0.5611, -0.2999, 0.7715, 0, 0}, {0.768177, -0.318189, 0.55557, 0.7786, -0.4162, 0.4696, 0, 0}, {0.853553, -0.353553, 0.382683, 0.7786, -0.4162, 0.4696, 0, 0}, {0.906127, -0.37533, 0.19509, 0.8777, -0.4691, 0.0976, 0, 0}, {0.923879, -0.382683, 0, 0.8777, -0.4691, 0.0976, 0, 0}, {0.162212, -0.108386, 0.980785, 0.2254, -0.185, 0.9565, 0, 0}, {0.31819, -0.212607, 0.92388, 0.3658, -0.3002, 0.881, 0, 0}, {0.46194, -0.308658, 0.83147, 0.3658, -0.3002, 0.881, 0, 0}, {0.587938, -0.392847, 0.707107, 0.4918, -0.4036, 0.7715, 0, 0}, {0.691341, -0.461939, 0.55557, 0.6825, -0.5601, 0.4696, 0, 0}, {0.768178, -0.51328, 0.382683, 0.6825, -0.5601, 0.4696, 0, 0}, {0.815493, -0.544895, 0.19509, 0.7693, -0.6314, 0.0976, 0, 0}, {0.831469, -0.55557, 0, 0.7693, -0.6314, 0.0976, 0, 0}, {0.13795, -0.137949, 0.980785, 0.185, -0.2254, 0.9565, 0, 0}, {0.270598, -0.270598, 0.92388, 0.3002, -0.3658, 0.881, 0, 0}, {0.392847, -0.392847, 0.83147, 0.4036, -0.4918, 0.7715, 0, 0}, {0.5, -0.5, 0.707107, 0.4036, -0.4918, 0.7715, 0, 0}, {0.587937, -0.587937, 0.55557, 0.5601, -0.6825, 0.4696, 0, 0}, {0.653281, -0.653281, 0.382683, 0.5601, -0.6825, 0.4696, 0, 0}, {0.693519, -0.693519, 0.19509, 0.6073, -0.74, 0.289, 0, 0}, {0.707106, -0.707106, 0, 0.6314, -0.7693, 0.0976, 0, 0}, {0.108386, -0.162211, 0.980785, 0.0464, -0.0869, 0.9951, 0, 0}, {0.212607, -0.318189, 0.92388, 0.1374, -0.2571, 0.9565, 0, 0}, {0.308658, -0.461939, 0.83147, 0.2231, -0.4173, 0.881, 0, 0}, {0.392847, -0.587937, 0.707107, 0.2999, -0.5611, 0.7715, 0, 0}, {0.461939, -0.691341, 0.55557, 0.4162, -0.7786, 0.4696, 0, 0}, {0.51328, -0.768177, 0.382683, 0.4162, -0.7786, 0.4696, 0, 0}, {0.544895, -0.815492, 0.19509, 0.4691, -0.8777, 0.0976, 0, 0}, {0.55557, -0.831469, 0, 0.4691, -0.8777, 0.0976, 0, 0}, {0.074658, -0.18024, 0.980785, 0.0846, -0.279, 0.9565, 0, 0}, {0.146447, -0.353553, 0.92388, 0.1374, -0.4528, 0.881, 0, 0}, {0.212607, -0.51328, 0.83147, 0.1847, -0.6088, 0.7715, 0, 0}, {0.270598, -0.653281, 0.707107, 0.1847, -0.6088, 0.7715, 0, 0}, {0.318189, -0.768177, 0.55557, 0.2563, -0.8448, 0.4696, 0, 0}, {0.353553, -0.853553, 0.382683, 0.2563, -0.8448, 0.4696, 0, 0}, {0.37533, -0.906127, 0.19509, 0.2779, -0.9161, 0.289, 0, 0}, {0.382683, -0.923879, 0, 0.2889, -0.9524, 0.0976, 0, 0}, {0.03806, -0.191342, 0.980785, 0.0286, -0.2902, 0.9565, 0, 0}, {0.074658, -0.37533, 0.92388, 0.0286, -0.2902, 0.9565, 0, 0}, {0.108386, -0.544895, 0.83147, 0.0464, -0.4709, 0.881, 0, 0}, {0.13795, -0.69352, 0.707107, 0.0624, -0.6332, 0.7715, 0, 0}, {0.162211, -0.815492, 0.55557, 0.0759, -0.7708, 0.6326, 0, 0}, {0.18024, -0.906127, 0.382683, 0.0865, -0.8786, 0.4696, 0, 0}, {0.191341, -0.961939, 0.19509, 0.0938, -0.9527, 0.289, 0, 0}, {0.19509, -0.980785, 0, 0.0976, -0.9904, 0.0975, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::UpperSphereIndices = { 3, 11, 12, 4, 12, 13, 5, 13, 14, 6, 14, 15, 0, 8, 9, 2, 1, 9, 2, 10, 11, 9, 17, 18, 10, 18, 19, 11, 19, 20, 12, 20, 21, 13, 21, 22, 14, 22, 23, 8, 16, 17, 22, 21, 29, 22, 30, 31, 16, 24, 25, 17, 25, 26, 18, 26, 27, 19, 27, 28, 20, 28, 29, 26, 34, 35, 27, 35, 36, 28, 36, 37, 29, 37, 38, 31, 30, 38, 24, 32, 33, 25, 33, 34, 39, 38, 46, 32, 40, 41, 33, 41, 42, 34, 42, 43, 36, 35, 43, 36, 44, 45, 37, 45, 46, 44, 43, 51, 44, 52, 53, 46, 45, 53, 46, 54, 55, 40, 48, 49, 41, 49, 50, 42, 50, 51, 48, 56, 57, 49, 57, 58, 51, 50, 58, 51, 59, 60, 52, 60, 61, 54, 53, 61, 54, 62, 63, 59, 67, 68, 60, 68, 69, 62, 61, 69, 62, 70, 71, 56, 64, 65, 57, 65, 66, 58, 66, 67, 65, 64, 72, 65, 73, 74, 66, 74, 75, 68, 67, 75, 68, 76, 77, 70, 69, 77, 70, 78, 79, 76, 84, 85, 78, 77, 85, 78, 86, 87, 72, 80, 81, 74, 73, 81, 74, 82, 83, 75, 83, 84, 80, 88, 89, 81, 89, 90, 82, 90, 91, 84, 83, 91, 84, 92, 93, 86, 85, 93, 86, 94, 95, 92, 100, 101, 94, 93, 101, 94, 102, 103, 88, 96, 97, 89, 97, 98, 90, 98, 99, 91, 99, 100, 97, 105, 106, 99, 98, 106, 100, 99, 107, 100, 108, 109, 102, 101, 109, 102, 110, 111, 96, 104, 105, 110, 109, 117, 110, 118, 119, 104, 112, 113, 106, 105, 113, 106, 114, 115, 107, 115, 116, 108, 116, 117, 114, 122, 123, 115, 123, 124, 116, 124, 125, 118, 117, 125, 118, 126, 127, 112, 120, 121, 113, 121, 122, 126, 134, 135, 120, 128, 129, 122, 121, 129, 123, 122, 130, 123, 131, 132, 124, 132, 133, 126, 125, 133, 131, 130, 138, 132, 131, 139, 132, 140, 141, 134, 133, 141, 134, 142, 143, 128, 136, 137, 129, 137, 138, 142, 150, 151, 136, 144, 145, 137, 145, 146, 139, 138, 146, 140, 139, 147, 140, 148, 149, 142, 141, 149, 148, 147, 155, 148, 156, 157, 150, 149, 157, 150, 158, 159, 144, 152, 153, 145, 153, 154, 146, 154, 155, 152, 160, 161, 153, 161, 162, 155, 154, 162, 156, 155, 163, 156, 164, 165, 158, 157, 165, 159, 158, 166, 164, 163, 171, 164, 172, 173, 166, 165, 173, 166, 174, 175, 160, 168, 169, 161, 169, 170, 163, 162, 170, 168, 176, 177, 169, 177, 178, 171, 170, 178, 172, 171, 179, 172, 180, 181, 174, 173, 181, 174, 182, 183, 180, 188, 189, 182, 181, 189, 182, 190, 191, 177, 176, 184, 177, 185, 186, 179, 178, 186, 180, 179, 187, 185, 193, 194, 187, 186, 194, 187, 195, 196, 188, 196, 197, 190, 189, 197, 190, 198, 199, 185, 184, 192, 198, 197, 205, 198, 206, 207, 193, 192, 200, 193, 201, 202, 195, 194, 202, 196, 195, 203, 196, 204, 205, 201, 210, 211, 203, 202, 211, 203, 212, 213, 204, 213, 214, 206, 205, 214, 206, 215, 216, 200, 209, 210, 215, 214, 222, 215, 223, 224, 209, 217, 218, 211, 210, 218, 212, 211, 219, 213, 212, 220, 213, 221, 222, 219, 227, 228, 221, 220, 228, 221, 229, 230, 223, 222, 230, 223, 231, 232, 217, 225, 226, 218, 226, 227, 232, 231, 239, 225, 233, 234, 226, 234, 235, 227, 235, 236, 229, 228, 236, 229, 237, 238, 231, 230, 238, 236, 235, 243, 237, 236, 244, 237, 245, 246, 239, 238, 246, 239, 247, 248, 234, 233, 241, 235, 234, 242, 247, 255, 256, 241, 249, 250, 242, 250, 251, 243, 251, 252, 245, 244, 252, 245, 253, 254, 247, 246, 254, 0, 208, 8, 8, 208, 16, 16, 208, 24, 24, 208, 32, 32, 208, 40, 40, 208, 48, 48, 208, 56, 56, 208, 64, 64, 208, 72, 72, 208, 80, 80, 208, 88, 88, 208, 96, 96, 208, 104, 104, 208, 112, 112, 208, 120, 120, 208, 128, 128, 208, 136, 136, 208, 144, 144, 208, 152, 152, 208, 160, 160, 208, 168, 168, 208, 176, 176, 208, 184, 184, 208, 192, 192, 208, 200, 200, 208, 209, 209, 208, 217, 217, 208, 225, 225, 208, 233, 233, 208, 241, 241, 208, 249, 253, 252, 3, 254, 253, 4, 255, 254, 5, 256, 255, 6, 249, 208, 0, 250, 249, 0, 251, 250, 1, 252, 251, 2, 4, 3, 12, 5, 4, 13, 6, 5, 14, 7, 6, 15, 1, 0, 9, 10, 2, 9, 3, 2, 11, 10, 9, 18, 11, 10, 19, 12, 11, 20, 13, 12, 21, 14, 13, 22, 15, 14, 23, 9, 8, 17, 30, 22, 29, 23, 22, 31, 17, 16, 25, 18, 17, 26, 19, 18, 27, 20, 19, 28, 21, 20, 29, 27, 26, 35, 28, 27, 36, 29, 28, 37, 30, 29, 38, 39, 31, 38, 25, 24, 33, 26, 25, 34, 47, 39, 46, 33, 32, 41, 34, 33, 42, 35, 34, 43, 44, 36, 43, 37, 36, 45, 38, 37, 46, 52, 44, 51, 45, 44, 53, 54, 46, 53, 47, 46, 55, 41, 40, 49, 42, 41, 50, 43, 42, 51, 49, 48, 57, 50, 49, 58, 59, 51, 58, 52, 51, 60, 53, 52, 61, 62, 54, 61, 55, 54, 63, 60, 59, 68, 61, 60, 69, 70, 62, 69, 63, 62, 71, 57, 56, 65, 58, 57, 66, 59, 58, 67, 73, 65, 72, 66, 65, 74, 67, 66, 75, 76, 68, 75, 69, 68, 77, 78, 70, 77, 71, 70, 79, 77, 76, 85, 86, 78, 85, 79, 78, 87, 73, 72, 81, 82, 74, 81, 75, 74, 83, 76, 75, 84, 81, 80, 89, 82, 81, 90, 83, 82, 91, 92, 84, 91, 85, 84, 93, 94, 86, 93, 87, 86, 95, 93, 92, 101, 102, 94, 101, 95, 94, 103, 89, 88, 97, 90, 89, 98, 91, 90, 99, 92, 91, 100, 98, 97, 106, 107, 99, 106, 108, 100, 107, 101, 100, 109, 110, 102, 109, 103, 102, 111, 97, 96, 105, 118, 110, 117, 111, 110, 119, 105, 104, 113, 114, 106, 113, 107, 106, 115, 108, 107, 116, 109, 108, 117, 115, 114, 123, 116, 115, 124, 117, 116, 125, 126, 118, 125, 119, 118, 127, 113, 112, 121, 114, 113, 122, 127, 126, 135, 121, 120, 129, 130, 122, 129, 131, 123, 130, 124, 123, 132, 125, 124, 133, 134, 126, 133, 139, 131, 138, 140, 132, 139, 133, 132, 141, 142, 134, 141, 135, 134, 143, 129, 128, 137, 130, 129, 138, 143, 142, 151, 137, 136, 145, 138, 137, 146, 147, 139, 146, 148, 140, 147, 141, 140, 149, 150, 142, 149, 156, 148, 155, 149, 148, 157, 158, 150, 157, 151, 150, 159, 145, 144, 153, 146, 145, 154, 147, 146, 155, 153, 152, 161, 154, 153, 162, 163, 155, 162, 164, 156, 163, 157, 156, 165, 166, 158, 165, 167, 159, 166, 172, 164, 171, 165, 164, 173, 174, 166, 173, 167, 166, 175, 161, 160, 169, 162, 161, 170, 171, 163, 170, 169, 168, 177, 170, 169, 178, 179, 171, 178, 180, 172, 179, 173, 172, 181, 182, 174, 181, 175, 174, 183, 181, 180, 189, 190, 182, 189, 183, 182, 191, 185, 177, 184, 178, 177, 186, 187, 179, 186, 188, 180, 187, 186, 185, 194, 195, 187, 194, 188, 187, 196, 189, 188, 197, 198, 190, 197, 191, 190, 199, 193, 185, 192, 206, 198, 205, 199, 198, 207, 201, 193, 200, 194, 193, 202, 203, 195, 202, 204, 196, 203, 197, 196, 205, 202, 201, 211, 212, 203, 211, 204, 203, 213, 205, 204, 214, 215, 206, 214, 207, 206, 216, 201, 200, 210, 223, 215, 222, 216, 215, 224, 210, 209, 218, 219, 211, 218, 220, 212, 219, 221, 213, 220, 214, 213, 222, 220, 219, 228, 229, 221, 228, 222, 221, 230, 231, 223, 230, 224, 223, 232, 218, 217, 226, 219, 218, 227, 240, 232, 239, 226, 225, 234, 227, 226, 235, 228, 227, 236, 237, 229, 236, 230, 229, 238, 239, 231, 238, 244, 236, 243, 245, 237, 244, 238, 237, 246, 247, 239, 246, 240, 239, 248, 242, 234, 241, 243, 235, 242, 248, 247, 256, 242, 241, 250, 243, 242, 251, 244, 243, 252, 253, 245, 252, 246, 245, 254, 255, 247, 254, 4, 253, 3, 5, 254, 4, 6, 255, 5, 7, 256, 6, 1, 250, 0, 2, 251, 1, 3, 252, 2, }; // LowerSphere const VertexList PrimitiveShapeVertex::LowerSphereVertices = { {0, -1, 0, -0.0975, -0.9904, -0.0976, 0, 0}, {0, -0.980786, -0.19509, 0.0976, -0.9904, -0.0975, 0, 0}, {0, -0.92388, -0.382683, 0.0938, -0.9527, -0.289, 0, 0}, {0, -0.83147, -0.55557, 0.0865, -0.8786, -0.4696, 0, 0}, {0, -0.707107, -0.707107, 0.0759, -0.7708, -0.6326, 0, 0}, {0, -0.55557, -0.83147, 0.0624, -0.6332, -0.7715, 0, 0}, {0, -0.382683, -0.92388, 0.0464, -0.4709, -0.881, 0, 0}, {0, -0.19509, -0.980785, 0.0286, -0.2902, -0.9565, 0, 0}, {0, 0, -1, 0.0097, -0.098, -0.9951, 0, 0}, {-0.19509, -0.980785, 0, -0.2889, -0.9524, -0.0975, 0, 0}, {-0.191342, -0.96194, -0.19509, -0.2889, -0.9524, -0.0976, 0, 0}, {-0.18024, -0.906128, -0.382683, -0.2563, -0.8448, -0.4696, 0, 0}, {-0.162212, -0.815493, -0.55557, -0.2563, -0.8448, -0.4696, 0, 0}, {-0.13795, -0.69352, -0.707107, -0.2248, -0.7412, -0.6326, 0, 0}, {-0.108386, -0.544895, -0.83147, -0.1374, -0.4528, -0.881, 0, 0}, {-0.074658, -0.37533, -0.92388, -0.0846, -0.279, -0.9565, 0, 0}, {-0.03806, -0.191342, -0.980785, -0.0846, -0.279, -0.9565, 0, 0}, {-0.382683, -0.92388, 0, -0.4691, -0.8777, -0.0976, 0, 0}, {-0.37533, -0.906128, -0.19509, -0.4513, -0.8443, -0.289, 0, 0}, {-0.353553, -0.853554, -0.382683, -0.4513, -0.8443, -0.289, 0, 0}, {-0.31819, -0.768178, -0.55557, -0.3651, -0.6831, -0.6326, 0, 0}, {-0.270598, -0.653282, -0.707107, -0.3651, -0.6831, -0.6326, 0, 0}, {-0.212608, -0.51328, -0.83147, -0.2999, -0.5611, -0.7715, 0, 0}, {-0.146447, -0.353553, -0.92388, -0.1374, -0.2571, -0.9565, 0, 0}, {-0.074658, -0.18024, -0.980785, -0.1374, -0.2571, -0.9565, 0, 0}, {-0.55557, -0.83147, 0, -0.6314, -0.7693, -0.0975, 0, 0}, {-0.544895, -0.815493, -0.19509, -0.6314, -0.7693, -0.0975, 0, 0}, {-0.51328, -0.768178, -0.382683, -0.6073, -0.74, -0.289, 0, 0}, {-0.46194, -0.691342, -0.55557, -0.5601, -0.6825, -0.4696, 0, 0}, {-0.392848, -0.587938, -0.707107, -0.4913, -0.5987, -0.6326, 0, 0}, {-0.308658, -0.46194, -0.83147, -0.3002, -0.3658, -0.881, 0, 0}, {-0.212608, -0.31819, -0.92388, -0.185, -0.2254, -0.9565, 0, 0}, {-0.108386, -0.162212, -0.980785, -0.185, -0.2254, -0.9565, 0, 0}, {-0.707107, -0.707107, 0, -0.7693, -0.6314, -0.0976, 0, 0}, {-0.69352, -0.69352, -0.19509, -0.74, -0.6073, -0.289, 0, 0}, {-0.653282, -0.653282, -0.382683, -0.74, -0.6073, -0.289, 0, 0}, {-0.587938, -0.587938, -0.55557, -0.5987, -0.4913, -0.6326, 0, 0}, {-0.5, -0.5, -0.707107, -0.4918, -0.4036, -0.7715, 0, 0}, {-0.392848, -0.392848, -0.83147, -0.4918, -0.4036, -0.7715, 0, 0}, {-0.270598, -0.270598, -0.92388, -0.2254, -0.185, -0.9565, 0, 0}, {-0.13795, -0.13795, -0.980785, -0.2254, -0.185, -0.9565, 0, 0}, {-0.83147, -0.55557, 0, -0.8777, -0.4691, -0.0976, 0, 0}, {-0.815493, -0.544895, -0.19509, -0.8443, -0.4513, -0.289, 0, 0}, {-0.768178, -0.51328, -0.382683, -0.8443, -0.4513, -0.289, 0, 0}, {-0.691342, -0.46194, -0.55557, -0.7786, -0.4162, -0.4696, 0, 0}, {-0.587938, -0.392848, -0.707107, -0.6831, -0.3651, -0.6326, 0, 0}, {-0.46194, -0.308658, -0.83147, -0.5611, -0.2999, -0.7715, 0, 0}, {-0.31819, -0.212608, -0.92388, -0.4173, -0.223, -0.881, 0, 0}, {-0.162212, -0.108386, -0.980785, -0.2571, -0.1374, -0.9565, 0, 0}, {-0.92388, -0.382683, 0, -0.9524, -0.2889, -0.0976, 0, 0}, {-0.906127, -0.37533, -0.19509, -0.9161, -0.2779, -0.289, 0, 0}, {-0.853553, -0.353553, -0.382683, -0.9161, -0.2779, -0.289, 0, 0}, {-0.768178, -0.31819, -0.55557, -0.7412, -0.2248, -0.6326, 0, 0}, {-0.653282, -0.270598, -0.707107, -0.7412, -0.2248, -0.6326, 0, 0}, {-0.51328, -0.212607, -0.83147, -0.4528, -0.1374, -0.881, 0, 0}, {-0.353553, -0.146447, -0.92388, -0.4528, -0.1374, -0.881, 0, 0}, {-0.18024, -0.074658, -0.980785, -0.279, -0.0846, -0.9565, 0, 0}, {-0.980785, -0.19509, 0, -0.9904, -0.0975, -0.0976, 0, 0}, {-0.96194, -0.191342, -0.19509, -0.9527, -0.0938, -0.289, 0, 0}, {-0.906127, -0.18024, -0.382683, -0.9527, -0.0938, -0.289, 0, 0}, {-0.815493, -0.162212, -0.55557, -0.8786, -0.0865, -0.4696, 0, 0}, {-0.69352, -0.13795, -0.707107, -0.7708, -0.0759, -0.6326, 0, 0}, {-0.544895, -0.108386, -0.83147, -0.4709, -0.0464, -0.881, 0, 0}, {-0.37533, -0.074658, -0.92388, -0.2902, -0.0286, -0.9565, 0, 0}, {-0.191342, -0.03806, -0.980785, -0.2902, -0.0286, -0.9565, 0, 0}, {-1, 0, 0, -0.9904, 0.0976, -0.0976, 0, 0}, {-0.980785, 0, -0.19509, -0.9527, 0.0938, -0.289, 0, 0}, {-0.92388, 0, -0.382683, -0.9527, 0.0938, -0.289, 0, 0}, {-0.83147, 0, -0.55557, -0.8786, 0.0865, -0.4696, 0, 0}, {-0.707107, 0, -0.707107, -0.7708, 0.0759, -0.6326, 0, 0}, {-0.55557, 0, -0.83147, -0.4709, 0.0464, -0.881, 0, 0}, {-0.382683, 0, -0.92388, -0.2902, 0.0286, -0.9565, 0, 0}, {-0.19509, 0, -0.980785, -0.2902, 0.0286, -0.9565, 0, 0}, {-0.980785, 0.195091, 0, -0.9524, 0.2889, -0.0976, 0, 0}, {-0.96194, 0.191342, -0.19509, -0.9161, 0.2779, -0.289, 0, 0}, {-0.906127, 0.18024, -0.382683, -0.9161, 0.2779, -0.289, 0, 0}, {-0.815493, 0.162212, -0.55557, -0.8448, 0.2563, -0.4696, 0, 0}, {-0.69352, 0.13795, -0.707107, -0.7412, 0.2248, -0.6326, 0, 0}, {-0.544895, 0.108387, -0.83147, -0.4528, 0.1374, -0.881, 0, 0}, {-0.37533, 0.074658, -0.92388, -0.4528, 0.1374, -0.881, 0, 0}, {-0.191342, 0.03806, -0.980785, -0.279, 0.0846, -0.9565, 0, 0}, {-0.92388, 0.382684, 0, -0.9524, 0.2889, -0.0976, 0, 0}, {-0.906127, 0.37533, -0.19509, -0.8443, 0.4513, -0.289, 0, 0}, {-0.853553, 0.353553, -0.382683, -0.8443, 0.4513, -0.289, 0, 0}, {-0.768178, 0.31819, -0.55557, -0.6831, 0.3651, -0.6326, 0, 0}, {-0.653282, 0.270598, -0.707107, -0.6831, 0.3651, -0.6326, 0, 0}, {-0.51328, 0.212608, -0.83147, -0.4173, 0.2231, -0.881, 0, 0}, {-0.353553, 0.146447, -0.92388, -0.2571, 0.1374, -0.9565, 0, 0}, {-0.18024, 0.074658, -0.980785, -0.2571, 0.1374, -0.9565, 0, 0}, {-0.83147, 0.55557, 0, -0.7693, 0.6314, -0.0976, 0, 0}, {-0.815493, 0.544895, -0.19509, -0.74, 0.6073, -0.289, 0, 0}, {-0.768178, 0.51328, -0.382683, -0.74, 0.6073, -0.289, 0, 0}, {-0.691342, 0.46194, -0.55557, -0.5987, 0.4913, -0.6326, 0, 0}, {-0.587938, 0.392848, -0.707107, -0.5987, 0.4913, -0.6326, 0, 0}, {-0.46194, 0.308658, -0.83147, -0.3658, 0.3002, -0.881, 0, 0}, {-0.31819, 0.212608, -0.92388, -0.3658, 0.3002, -0.881, 0, 0}, {-0.162212, 0.108387, -0.980785, -0.2254, 0.185, -0.9565, 0, 0}, {-0.707107, 0.707107, 0, -0.6314, 0.7693, -0.0976, 0, 0}, {-0.69352, 0.69352, -0.19509, -0.6073, 0.74, -0.289, 0, 0}, {-0.653282, 0.653282, -0.382683, -0.6073, 0.74, -0.289, 0, 0}, {-0.587938, 0.587938, -0.55557, -0.4913, 0.5987, -0.6326, 0, 0}, {-0.5, 0.5, -0.707107, -0.4913, 0.5987, -0.6326, 0, 0}, {-0.392847, 0.392848, -0.83147, -0.4036, 0.4918, -0.7715, 0, 0}, {-0.270598, 0.270598, -0.92388, -0.3002, 0.3658, -0.881, 0, 0}, {-0.13795, 0.13795, -0.980785, -0.185, 0.2254, -0.9565, 0, 0}, {-0.55557, 0.83147, 0, -0.4691, 0.8777, -0.0976, 0, 0}, {-0.544895, 0.815493, -0.19509, -0.4513, 0.8443, -0.289, 0, 0}, {-0.51328, 0.768178, -0.382683, -0.4513, 0.8443, -0.289, 0, 0}, {-0.46194, 0.691342, -0.55557, -0.4162, 0.7786, -0.4696, 0, 0}, {-0.392847, 0.587938, -0.707107, -0.3651, 0.6831, -0.6326, 0, 0}, {-0.308658, 0.46194, -0.83147, -0.2999, 0.5611, -0.7715, 0, 0}, {-0.212607, 0.31819, -0.92388, -0.1374, 0.2571, -0.9565, 0, 0}, {-0.108386, 0.162212, -0.980785, -0.1374, 0.2571, -0.9565, 0, 0}, {-0.382683, 0.92388, 0, -0.2889, 0.9524, -0.0976, 0, 0}, {-0.37533, 0.906127, -0.19509, -0.2889, 0.9524, -0.0976, 0, 0}, {-0.353553, 0.853553, -0.382683, -0.2779, 0.9161, -0.289, 0, 0}, {-0.318189, 0.768178, -0.55557, -0.2248, 0.7412, -0.6326, 0, 0}, {-0.270598, 0.653282, -0.707107, -0.2248, 0.7412, -0.6326, 0, 0}, {-0.212607, 0.51328, -0.83147, -0.1374, 0.4528, -0.881, 0, 0}, {-0.146447, 0.353554, -0.92388, -0.1374, 0.4528, -0.881, 0, 0}, {-0.074658, 0.18024, -0.980785, -0.0846, 0.279, -0.9565, 0, 0}, {-0.19509, 0.980785, 0, -0.0975, 0.9904, -0.0976, 0, 0}, {-0.191342, 0.96194, -0.19509, -0.0938, 0.9527, -0.289, 0, 0}, {-0.18024, 0.906128, -0.382683, -0.0938, 0.9527, -0.289, 0, 0}, {-0.162211, 0.815493, -0.55557, -0.0759, 0.7708, -0.6326, 0, 0}, {-0.13795, 0.69352, -0.707107, -0.0759, 0.7708, -0.6326, 0, 0}, {-0.108386, 0.544895, -0.83147, -0.0624, 0.6332, -0.7715, 0, 0}, {-0.074658, 0.37533, -0.92388, -0.0464, 0.4709, -0.881, 0, 0}, {-0.03806, 0.191342, -0.980785, -0.0286, 0.2902, -0.9565, 0, 0}, {0, 1, 0, 0.0975, 0.9904, -0.0976, 0, 0}, {0, 0.980785, -0.19509, 0.0938, 0.9527, -0.289, 0, 0}, {0, 0.92388, -0.382683, 0.0938, 0.9527, -0.289, 0, 0}, {0, 0.831469, -0.55557, 0.0759, 0.7708, -0.6326, 0, 0}, {0, 0.707107, -0.707107, 0.0624, 0.6332, -0.7715, 0, 0}, {0, 0.55557, -0.83147, 0.0624, 0.6332, -0.7715, 0, 0}, {0, 0.382684, -0.92388, 0.0464, 0.4709, -0.881, 0, 0}, {0, 0.19509, -0.980785, 0.0286, 0.2902, -0.9565, 0, 0}, {0.195091, 0.980785, 0, 0.2889, 0.9524, -0.0976, 0, 0}, {0.191342, 0.96194, -0.19509, 0.2779, 0.9161, -0.289, 0, 0}, {0.18024, 0.906128, -0.382683, 0.2779, 0.9161, -0.289, 0, 0}, {0.162212, 0.815493, -0.55557, 0.2248, 0.7412, -0.6326, 0, 0}, {0.13795, 0.69352, -0.707107, 0.1847, 0.6088, -0.7715, 0, 0}, {0.108386, 0.544895, -0.83147, 0.1847, 0.6088, -0.7715, 0, 0}, {0.074658, 0.37533, -0.92388, 0.1374, 0.4528, -0.881, 0, 0}, {0.03806, 0.191342, -0.980785, 0.0846, 0.279, -0.9565, 0, 0}, {0.382684, 0.92388, 0, 0.4691, 0.8777, -0.0976, 0, 0}, {0.37533, 0.906127, -0.19509, 0.4513, 0.8443, -0.289, 0, 0}, {0.353553, 0.853553, -0.382683, 0.4513, 0.8443, -0.289, 0, 0}, {0.31819, 0.768178, -0.55557, 0.3651, 0.6831, -0.6326, 0, 0}, {0.270598, 0.653282, -0.707107, 0.2999, 0.5611, -0.7715, 0, 0}, {0.212608, 0.51328, -0.83147, 0.2999, 0.5611, -0.7715, 0, 0}, {0.146447, 0.353553, -0.92388, 0.1374, 0.2571, -0.9565, 0, 0}, {0.074658, 0.18024, -0.980785, 0.1374, 0.2571, -0.9565, 0, 0}, {0.55557, 0.83147, 0, 0.6314, 0.7693, -0.0976, 0, 0}, {0.544895, 0.815493, -0.19509, 0.6073, 0.74, -0.289, 0, 0}, {0.51328, 0.768178, -0.382683, 0.6073, 0.74, -0.289, 0, 0}, {0.46194, 0.691341, -0.55557, 0.4913, 0.5987, -0.6326, 0, 0}, {0.392848, 0.587938, -0.707107, 0.4036, 0.4918, -0.7715, 0, 0}, {0.308658, 0.46194, -0.83147, 0.3002, 0.3658, -0.881, 0, 0}, {0.212608, 0.31819, -0.92388, 0.3002, 0.3658, -0.881, 0, 0}, {0.108386, 0.162212, -0.980785, 0.185, 0.2254, -0.9565, 0, 0}, {0.707107, 0.707107, 0, 0.7693, 0.6314, -0.0976, 0, 0}, {0.69352, 0.69352, -0.19509, 0.74, 0.6073, -0.289, 0, 0}, {0.653282, 0.653282, -0.382683, 0.74, 0.6073, -0.289, 0, 0}, {0.587938, 0.587938, -0.55557, 0.6825, 0.5601, -0.4696, 0, 0}, {0.5, 0.5, -0.707107, 0.4918, 0.4036, -0.7715, 0, 0}, {0.392848, 0.392847, -0.83147, 0.3658, 0.3002, -0.881, 0, 0}, {0.270598, 0.270598, -0.92388, 0.2254, 0.185, -0.9565, 0, 0}, {0.13795, 0.13795, -0.980785, 0.2254, 0.185, -0.9565, 0, 0}, {0.83147, 0.55557, 0, 0.8777, 0.4691, -0.0976, 0, 0}, {0.815493, 0.544895, -0.19509, 0.8443, 0.4513, -0.289, 0, 0}, {0.768178, 0.51328, -0.382683, 0.8443, 0.4513, -0.289, 0, 0}, {0.691342, 0.46194, -0.55557, 0.6831, 0.3651, -0.6326, 0, 0}, {0.587938, 0.392848, -0.707107, 0.5611, 0.2999, -0.7715, 0, 0}, {0.46194, 0.308658, -0.83147, 0.4173, 0.223, -0.881, 0, 0}, {0.31819, 0.212607, -0.92388, 0.2571, 0.1374, -0.9565, 0, 0}, {0.162212, 0.108386, -0.980785, 0.2571, 0.1374, -0.9565, 0, 0}, {0.92388, 0.382683, 0, 0.9524, 0.2889, -0.0976, 0, 0}, {0.906127, 0.37533, -0.19509, 0.9161, 0.2779, -0.289, 0, 0}, {0.853553, 0.353554, -0.382683, 0.9161, 0.2779, -0.289, 0, 0}, {0.768178, 0.318189, -0.55557, 0.8448, 0.2563, -0.4696, 0, 0}, {0.653282, 0.270598, -0.707107, 0.6088, 0.1847, -0.7715, 0, 0}, {0.51328, 0.212608, -0.83147, 0.6088, 0.1847, -0.7715, 0, 0}, {0.353553, 0.146447, -0.92388, 0.279, 0.0846, -0.9565, 0, 0}, {0.18024, 0.074658, -0.980785, 0.279, 0.0846, -0.9565, 0, 0}, {0.980785, 0.19509, 0, 0.9904, 0.0975, -0.0976, 0, 0}, {0.96194, 0.191342, -0.19509, 0.9527, 0.0938, -0.289, 0, 0}, {0.906128, 0.18024, -0.382683, 0.9527, 0.0938, -0.289, 0, 0}, {0.815493, 0.162212, -0.55557, 0.7708, 0.0759, -0.6326, 0, 0}, {0.69352, 0.13795, -0.707107, 0.6332, 0.0624, -0.7715, 0, 0}, {0.544895, 0.108386, -0.83147, 0.6332, 0.0624, -0.7715, 0, 0}, {0.37533, 0.074658, -0.92388, 0.2902, 0.0286, -0.9565, 0, 0}, {0.191342, 0.03806, -0.980785, 0.2902, 0.0286, -0.9565, 0, 0}, {1, -0, 0, 0.9904, 0.0975, -0.0976, 0, 0}, {0.980785, -0, -0.19509, 0.9527, -0.0938, -0.289, 0, 0}, {0.92388, 0, -0.382683, 0.9527, -0.0938, -0.289, 0, 0}, {0.831469, -0, -0.55557, 0.8786, -0.0865, -0.4696, 0, 0}, {0.707107, -0, -0.707107, 0.7708, -0.0759, -0.6326, 0, 0}, {0.55557, 0, -0.83147, 0.4709, -0.0464, -0.881, 0, 0}, {0.382683, 0, -0.92388, 0.2902, -0.0286, -0.9565, 0, 0}, {0.19509, 0, -0.980785, 0.2902, -0.0286, -0.9565, 0, 0}, {0.980785, -0.19509, 0, 0.9904, -0.0976, -0.0976, 0, 0}, {0.961939, -0.191342, -0.19509, 0.9524, -0.2889, -0.0976, 0, 0}, {0.906127, -0.18024, -0.382683, 0.9161, -0.2779, -0.289, 0, 0}, {0.815493, -0.162212, -0.55557, 0.7412, -0.2248, -0.6326, 0, 0}, {0.69352, -0.13795, -0.707107, 0.6088, -0.1847, -0.7715, 0, 0}, {0.544895, -0.108386, -0.83147, 0.4528, -0.1374, -0.881, 0, 0}, {0.37533, -0.074658, -0.92388, 0.279, -0.0846, -0.9565, 0, 0}, {0.191342, -0.03806, -0.980785, 0.279, -0.0846, -0.9565, 0, 0}, {0.923879, -0.382683, 0, 0.9524, -0.2889, -0.0976, 0, 0}, {0.906127, -0.37533, -0.19509, 0.8443, -0.4513, -0.289, 0, 0}, {0.853553, -0.353553, -0.382683, 0.8443, -0.4513, -0.289, 0, 0}, {0.768177, -0.31819, -0.55557, 0.6831, -0.3651, -0.6326, 0, 0}, {0.653281, -0.270598, -0.707107, 0.6831, -0.3651, -0.6326, 0, 0}, {0.51328, -0.212607, -0.83147, 0.5611, -0.2999, -0.7715, 0, 0}, {0.353553, -0.146447, -0.92388, 0.2571, -0.1374, -0.9565, 0, 0}, {0.18024, -0.074658, -0.980785, 0.2571, -0.1374, -0.9565, 0, 0}, {0.831469, -0.55557, 0, 0.8777, -0.4691, -0.0976, 0, 0}, {0.815493, -0.544895, -0.19509, 0.7693, -0.6314, -0.0976, 0, 0}, {0.768178, -0.51328, -0.382683, 0.74, -0.6073, -0.289, 0, 0}, {0.691341, -0.46194, -0.55557, 0.5987, -0.4913, -0.6326, 0, 0}, {0.587938, -0.392847, -0.707107, 0.5987, -0.4913, -0.6326, 0, 0}, {0.46194, -0.308658, -0.83147, 0.3658, -0.3002, -0.881, 0, 0}, {0.31819, -0.212607, -0.92388, 0.2254, -0.185, -0.9565, 0, 0}, {0.162212, -0.108386, -0.980785, 0.2254, -0.185, -0.9565, 0, 0}, {0.707106, -0.707107, 0, 0.6314, -0.7693, -0.0976, 0, 0}, {0.693519, -0.69352, -0.19509, 0.6073, -0.74, -0.289, 0, 0}, {0.653282, -0.653281, -0.382683, 0.6073, -0.74, -0.289, 0, 0}, {0.587937, -0.587938, -0.55557, 0.4913, -0.5987, -0.6326, 0, 0}, {0.5, -0.5, -0.707107, 0.4036, -0.4918, -0.7715, 0, 0}, {0.392847, -0.392847, -0.83147, 0.4036, -0.4918, -0.7715, 0, 0}, {0.270598, -0.270598, -0.92388, 0.185, -0.2254, -0.9565, 0, 0}, {0.13795, -0.13795, -0.980785, 0.185, -0.2254, -0.9565, 0, 0}, {0.55557, -0.831469, 0, 0.4691, -0.8777, -0.0976, 0, 0}, {0.544895, -0.815493, -0.19509, 0.4513, -0.8443, -0.289, 0, 0}, {0.51328, -0.768178, -0.382683, 0.4513, -0.8443, -0.289, 0, 0}, {0.461939, -0.691341, -0.55557, 0.3651, -0.6831, -0.6326, 0, 0}, {0.392847, -0.587938, -0.707107, 0.2999, -0.5611, -0.7715, 0, 0}, {0.308658, -0.46194, -0.83147, 0.223, -0.4173, -0.881, 0, 0}, {0.212607, -0.318189, -0.92388, 0.1374, -0.2571, -0.9565, 0, 0}, {0.108386, -0.162212, -0.980785, 0.1374, -0.2571, -0.9565, 0, 0}, {0.382683, -0.923879, 0, 0.4691, -0.8777, -0.0976, 0, 0}, {0.37533, -0.906127, -0.19509, 0.2779, -0.9161, -0.289, 0, 0}, {0.353553, -0.853553, -0.382683, 0.2779, -0.9161, -0.289, 0, 0}, {0.318189, -0.768177, -0.55557, 0.2248, -0.7412, -0.6326, 0, 0}, {0.270598, -0.653281, -0.707107, 0.1847, -0.6088, -0.7715, 0, 0}, {0.212607, -0.51328, -0.83147, 0.1847, -0.6088, -0.7715, 0, 0}, {0.146447, -0.353553, -0.92388, 0.1374, -0.4528, -0.881, 0, 0}, {0.074658, -0.18024, -0.980785, 0.0846, -0.279, -0.9565, 0, 0}, {0.19509, -0.980785, 0, 0.0976, -0.9904, -0.0975, 0, 0}, {0.191341, -0.961939, -0.19509, 0.0938, -0.9527, -0.289, 0, 0}, {0.18024, -0.906127, -0.382683, 0.0938, -0.9527, -0.289, 0, 0}, {0.162211, -0.815493, -0.55557, 0.0759, -0.7708, -0.6326, 0, 0}, {0.13795, -0.69352, -0.707107, 0.0624, -0.6332, -0.7715, 0, 0}, {0.108386, -0.544895, -0.83147, 0.0464, -0.4709, -0.881, 0, 0}, {0.074658, -0.37533, -0.92388, 0.0286, -0.2902, -0.9565, 0, 0}, {0.03806, -0.191342, -0.980785, 0.0286, -0.2902, -0.9565, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::LowerSphereIndices = { 2, 11, 12, 3, 12, 13, 4, 13, 14, 6, 5, 14, 6, 15, 16, 0, 9, 10, 1, 10, 11, 10, 18, 19, 11, 19, 20, 13, 12, 20, 14, 13, 21, 14, 22, 23, 15, 23, 24, 10, 9, 17, 23, 22, 30, 23, 31, 32, 17, 25, 26, 18, 26, 27, 20, 19, 27, 20, 28, 29, 22, 21, 29, 26, 34, 35, 28, 27, 35, 29, 28, 36, 30, 29, 37, 30, 38, 39, 31, 39, 40, 25, 33, 34, 38, 46, 47, 39, 47, 48, 33, 41, 42, 34, 42, 43, 36, 35, 43, 36, 44, 45, 37, 45, 46, 44, 43, 51, 45, 44, 52, 46, 45, 53, 47, 46, 54, 48, 47, 55, 41, 49, 50, 42, 50, 51, 55, 63, 64, 50, 49, 57, 50, 58, 59, 52, 51, 59, 52, 60, 61, 54, 53, 61, 54, 62, 63, 60, 68, 69, 62, 61, 69, 62, 70, 71, 63, 71, 72, 57, 65, 66, 58, 66, 67, 60, 59, 67, 65, 73, 74, 66, 74, 75, 68, 67, 75, 69, 68, 76, 70, 69, 77, 70, 78, 79, 71, 79, 80, 76, 84, 85, 78, 77, 85, 78, 86, 87, 80, 79, 87, 74, 73, 81, 74, 82, 83, 76, 75, 83, 82, 81, 89, 82, 90, 91, 84, 83, 91, 84, 92, 93, 86, 85, 93, 86, 94, 95, 87, 95, 96, 94, 93, 101, 94, 102, 103, 96, 95, 103, 89, 97, 98, 90, 98, 99, 92, 91, 99, 92, 100, 101, 97, 105, 106, 98, 106, 107, 100, 99, 107, 100, 108, 109, 102, 101, 109, 103, 102, 110, 104, 103, 111, 110, 109, 117, 111, 110, 118, 111, 119, 120, 105, 113, 114, 106, 114, 115, 108, 107, 115, 109, 108, 116, 114, 122, 123, 116, 115, 123, 116, 124, 125, 118, 117, 125, 118, 126, 127, 120, 119, 127, 113, 121, 122, 127, 126, 134, 128, 127, 135, 121, 129, 130, 122, 130, 131, 124, 123, 131, 124, 132, 133, 126, 125, 133, 132, 131, 139, 132, 140, 141, 133, 141, 142, 135, 134, 142, 136, 135, 143, 129, 137, 138, 130, 138, 139, 143, 151, 152, 137, 145, 146, 138, 146, 147, 140, 139, 147, 140, 148, 149, 141, 149, 150, 143, 142, 150, 148, 147, 155, 148, 156, 157, 149, 157, 158, 151, 150, 158, 151, 159, 160, 145, 153, 154, 146, 154, 155, 159, 167, 168, 153, 161, 162, 154, 162, 163, 156, 155, 163, 156, 164, 165, 157, 165, 166, 158, 166, 167, 164, 172, 173, 165, 173, 174, 166, 174, 175, 167, 175, 176, 161, 169, 170, 162, 170, 171, 164, 163, 171, 169, 177, 178, 170, 178, 179, 172, 171, 179, 172, 180, 181, 173, 181, 182, 174, 182, 183, 175, 183, 184, 180, 188, 189, 181, 189, 190, 183, 182, 190, 183, 191, 192, 177, 185, 186, 178, 186, 187, 180, 179, 187, 186, 185, 193, 186, 194, 195, 188, 187, 195, 188, 196, 197, 189, 197, 198, 191, 190, 198, 191, 199, 200, 197, 205, 206, 198, 206, 207, 199, 207, 208, 194, 193, 201, 194, 202, 203, 196, 195, 203, 197, 196, 204, 202, 210, 211, 204, 203, 211, 204, 212, 213, 205, 213, 214, 206, 214, 215, 207, 215, 216, 202, 201, 209, 215, 214, 222, 215, 223, 224, 210, 209, 217, 210, 218, 219, 212, 211, 219, 212, 220, 221, 214, 213, 221, 218, 226, 227, 220, 219, 227, 220, 228, 229, 222, 221, 229, 222, 230, 231, 223, 231, 232, 218, 217, 225, 230, 238, 239, 231, 239, 240, 225, 233, 234, 226, 234, 235, 228, 227, 235, 228, 236, 237, 229, 237, 238, 236, 235, 243, 236, 244, 245, 237, 245, 246, 238, 246, 247, 239, 247, 248, 234, 233, 241, 234, 242, 243, 247, 255, 256, 242, 241, 249, 242, 250, 251, 244, 243, 251, 244, 252, 253, 245, 253, 254, 247, 246, 254, 8, 7, 16, 8, 16, 24, 8, 24, 32, 8, 32, 40, 8, 40, 48, 8, 48, 56, 8, 56, 64, 8, 64, 72, 8, 72, 80, 8, 80, 88, 8, 88, 96, 8, 96, 104, 8, 104, 112, 8, 112, 120, 8, 120, 128, 8, 128, 136, 8, 136, 144, 8, 144, 152, 8, 152, 160, 8, 160, 168, 8, 168, 176, 8, 176, 184, 8, 184, 192, 8, 192, 200, 8, 200, 208, 8, 208, 216, 8, 216, 224, 8, 224, 232, 8, 232, 240, 8, 240, 248, 8, 248, 256, 251, 2, 3, 252, 3, 4, 253, 4, 5, 254, 5, 6, 255, 6, 7, 8, 256, 7, 249, 0, 1, 250, 1, 2, 3, 2, 12, 4, 3, 13, 5, 4, 14, 15, 6, 14, 7, 6, 16, 1, 0, 10, 2, 1, 11, 11, 10, 19, 12, 11, 20, 21, 13, 20, 22, 14, 21, 15, 14, 23, 16, 15, 24, 18, 10, 17, 31, 23, 30, 24, 23, 32, 18, 17, 26, 19, 18, 27, 28, 20, 27, 21, 20, 29, 30, 22, 29, 27, 26, 35, 36, 28, 35, 37, 29, 36, 38, 30, 37, 31, 30, 39, 32, 31, 40, 26, 25, 34, 39, 38, 47, 40, 39, 48, 34, 33, 42, 35, 34, 43, 44, 36, 43, 37, 36, 45, 38, 37, 46, 52, 44, 51, 53, 45, 52, 54, 46, 53, 55, 47, 54, 56, 48, 55, 42, 41, 50, 43, 42, 51, 56, 55, 64, 58, 50, 57, 51, 50, 59, 60, 52, 59, 53, 52, 61, 62, 54, 61, 55, 54, 63, 61, 60, 69, 70, 62, 69, 63, 62, 71, 64, 63, 72, 58, 57, 66, 59, 58, 67, 68, 60, 67, 66, 65, 74, 67, 66, 75, 76, 68, 75, 77, 69, 76, 78, 70, 77, 71, 70, 79, 72, 71, 80, 77, 76, 85, 86, 78, 85, 79, 78, 87, 88, 80, 87, 82, 74, 81, 75, 74, 83, 84, 76, 83, 90, 82, 89, 83, 82, 91, 92, 84, 91, 85, 84, 93, 94, 86, 93, 87, 86, 95, 88, 87, 96, 102, 94, 101, 95, 94, 103, 104, 96, 103, 90, 89, 98, 91, 90, 99, 100, 92, 99, 93, 92, 101, 98, 97, 106, 99, 98, 107, 108, 100, 107, 101, 100, 109, 110, 102, 109, 111, 103, 110, 112, 104, 111, 118, 110, 117, 119, 111, 118, 112, 111, 120, 106, 105, 114, 107, 106, 115, 116, 108, 115, 117, 109, 116, 115, 114, 123, 124, 116, 123, 117, 116, 125, 126, 118, 125, 119, 118, 127, 128, 120, 127, 114, 113, 122, 135, 127, 134, 136, 128, 135, 122, 121, 130, 123, 122, 131, 132, 124, 131, 125, 124, 133, 134, 126, 133, 140, 132, 139, 133, 132, 141, 134, 133, 142, 143, 135, 142, 144, 136, 143, 130, 129, 138, 131, 130, 139, 144, 143, 152, 138, 137, 146, 139, 138, 147, 148, 140, 147, 141, 140, 149, 142, 141, 150, 151, 143, 150, 156, 148, 155, 149, 148, 157, 150, 149, 158, 159, 151, 158, 152, 151, 160, 146, 145, 154, 147, 146, 155, 160, 159, 168, 154, 153, 162, 155, 154, 163, 164, 156, 163, 157, 156, 165, 158, 157, 166, 159, 158, 167, 165, 164, 173, 166, 165, 174, 167, 166, 175, 168, 167, 176, 162, 161, 170, 163, 162, 171, 172, 164, 171, 170, 169, 178, 171, 170, 179, 180, 172, 179, 173, 172, 181, 174, 173, 182, 175, 174, 183, 176, 175, 184, 181, 180, 189, 182, 181, 190, 191, 183, 190, 184, 183, 192, 178, 177, 186, 179, 178, 187, 188, 180, 187, 194, 186, 193, 187, 186, 195, 196, 188, 195, 189, 188, 197, 190, 189, 198, 199, 191, 198, 192, 191, 200, 198, 197, 206, 199, 198, 207, 200, 199, 208, 202, 194, 201, 195, 194, 203, 204, 196, 203, 205, 197, 204, 203, 202, 211, 212, 204, 211, 205, 204, 213, 206, 205, 214, 207, 206, 215, 208, 207, 216, 210, 202, 209, 223, 215, 222, 216, 215, 224, 218, 210, 217, 211, 210, 219, 220, 212, 219, 213, 212, 221, 222, 214, 221, 219, 218, 227, 228, 220, 227, 221, 220, 229, 230, 222, 229, 223, 222, 231, 224, 223, 232, 226, 218, 225, 231, 230, 239, 232, 231, 240, 226, 225, 234, 227, 226, 235, 236, 228, 235, 229, 228, 237, 230, 229, 238, 244, 236, 243, 237, 236, 245, 238, 237, 246, 239, 238, 247, 240, 239, 248, 242, 234, 241, 235, 234, 243, 248, 247, 256, 250, 242, 249, 243, 242, 251, 252, 244, 251, 245, 244, 253, 246, 245, 254, 255, 247, 254, 252, 251, 3, 253, 252, 4, 254, 253, 5, 255, 254, 6, 256, 255, 7, 250, 249, 1, 251, 250, 2, }; // Cone (length, radius) const VertexList PrimitiveShapeVertex::ConeVertices = { {0, 0, 0.5, -0.7054, -0.0695, 0.7054, 0, 0}, {-1, 0, -0.5, -0.7054, -0.0695, 0.7054, 0, 0}, {-0.980785, 0.19509, -0.5, -0.6783, 0.2058, 0.7054, 0, 0}, {-0.92388, 0.382683, -0.5, -0.6251, 0.3341, 0.7054, 0, 0}, {-0.83147, 0.55557, -0.5, -0.5479, 0.4497, 0.7054, 0, 0}, {-0.707107, 0.707107, -0.5, -0.4497, 0.5479, 0.7054, 0, 0}, {-0.55557, 0.83147, -0.5, -0.3341, 0.6251, 0.7054, 0, 0}, {-0.382683, 0.92388, -0.5, -0.2058, 0.6783, 0.7054, 0, 0}, {-0.19509, 0.980785, -0.5, -0.0695, 0.7054, 0.7054, 0, 0}, {0, 1, -0.5, 0.0695, 0.7054, 0.7054, 0, 0}, {0.19509, 0.980785, -0.5, 0.2058, 0.6783, 0.7054, 0, 0}, {0.382683, 0.92388, -0.5, 0.3341, 0.6251, 0.7054, 0, 0}, {0.55557, 0.83147, -0.5, 0.4497, 0.5479, 0.7054, 0, 0}, {0.707107, 0.707107, -0.5, 0.5479, 0.4497, 0.7054, 0, 0}, {0.83147, 0.55557, -0.5, 0.6251, 0.3341, 0.7054, 0, 0}, {0.92388, 0.382683, -0.5, 0.6783, 0.2058, 0.7054, 0, 0}, {0.980785, 0.19509, -0.5, 0.7054, 0.0695, 0.7054, 0, 0}, {1, 0, -0.5, 0.7054, -0.0695, 0.7054, 0, 0}, {0.980785, -0.195091, -0.5, 0.6783, -0.2058, 0.7054, 0, 0}, {0.923879, -0.382684, -0.5, 0.6251, -0.3341, 0.7054, 0, 0}, {0.831469, -0.555571, -0.5, 0.5479, -0.4497, 0.7054, 0, 0}, {0.707106, -0.707107, -0.5, 0.4497, -0.5479, 0.7054, 0, 0}, {0.55557, -0.83147, -0.5, 0.3341, -0.6251, 0.7054, 0, 0}, {0.382683, -0.92388, -0.5, 0.2058, -0.6783, 0.7054, 0, 0}, {0.195089, -0.980785, -0.5, 0.0695, -0.7054, 0.7054, 0, 0}, {-1e-06, -1, -0.5, -0.0695, -0.7054, 0.7054, 0, 0}, {-0.195091, -0.980785, -0.5, -0.2058, -0.6783, 0.7054, 0, 0}, {-0.382684, -0.923879, -0.5, -0.3341, -0.6251, 0.7054, 0, 0}, {-0.555571, -0.831469, -0.5, -0.4497, -0.5479, 0.7054, 0, 0}, {-0.707108, -0.707106, -0.5, -0.5479, -0.4497, 0.7054, 0, 0}, {-0.83147, -0.555569, -0.5, -0.6251, -0.3341, 0.7054, 0, 0}, {-0.92388, -0.382682, -0.5, -0.6783, -0.2058, 0.7054, 0, 0}, {-0.980786, -0.195089, -0.5, -0.7054, -0.0695, 0.7054, 0, 0}, {0, 0, -0.5, 0, 0, -1, 0, 0}, {-1, 0, -0.5, 0, 0, -1, 0, 0}, {-0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {-0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {-0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {-0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {-0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {-0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {-0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {0, 1, -0.5, 0, 0, -1, 0, 0}, {0.19509, 0.980785, -0.5, 0, 0, -1, 0, 0}, {0.382683, 0.92388, -0.5, 0, 0, -1, 0, 0}, {0.55557, 0.83147, -0.5, 0, 0, -1, 0, 0}, {0.707107, 0.707107, -0.5, 0, 0, -1, 0, 0}, {0.83147, 0.55557, -0.5, 0, 0, -1, 0, 0}, {0.92388, 0.382683, -0.5, 0, 0, -1, 0, 0}, {0.980785, 0.19509, -0.5, 0, 0, -1, 0, 0}, {1, 0, -0.5, 0, 0, -1, 0, 0}, {0.980785, -0.195091, -0.5, 0, 0, -1, 0, 0}, {0.923879, -0.382684, -0.5, 0, 0, -1, 0, 0}, {0.831469, -0.555571, -0.5, 0, 0, -1, 0, 0}, {0.707106, -0.707107, -0.5, 0, 0, -1, 0, 0}, {0.55557, -0.83147, -0.5, 0, 0, -1, 0, 0}, {0.382683, -0.92388, -0.5, 0, 0, -1, 0, 0}, {0.195089, -0.980785, -0.5, 0, 0, -1, 0, 0}, {-1e-06, -1, -0.5, 0, 0, -1, 0, 0}, {-0.195091, -0.980785, -0.5, 0, 0, -1, 0, 0}, {-0.382684, -0.923879, -0.5, 0, 0, -1, 0, 0}, {-0.555571, -0.831469, -0.5, 0, 0, -1, 0, 0}, {-0.707108, -0.707106, -0.5, 0, 0, -1, 0, 0}, {-0.83147, -0.555569, -0.5, 0, 0, -1, 0, 0}, {-0.92388, -0.382682, -0.5, 0, 0, -1, 0, 0}, {-0.980786, -0.195089, -0.5, 0, 0, -1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::ConeIndices = { 1, 0, 2, 2, 0, 3, 3, 0, 4, 4, 0, 5, 5, 0, 6, 6, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0, 10, 10, 0, 11, 11, 0, 12, 12, 0, 13, 13, 0, 14, 14, 0, 15, 15, 0, 16, 16, 0, 17, 17, 0, 18, 18, 0, 19, 19, 0, 20, 20, 0, 21, 21, 0, 22, 22, 0, 23, 23, 0, 24, 24, 0, 25, 25, 0, 26, 26, 0, 27, 27, 0, 28, 28, 0, 29, 29, 0, 30, 30, 0, 31, 31, 0, 32, 32, 0, 1, 33, 34, 35, 33, 35, 36, 33, 36, 37, 33, 37, 38, 33, 38, 39, 33, 39, 40, 33, 40, 41, 33, 41, 42, 33, 42, 43, 33, 43, 44, 33, 44, 45, 33, 45, 46, 33, 46, 47, 33, 47, 48, 33, 48, 49, 33, 49, 50, 33, 50, 51, 33, 51, 52, 33, 52, 53, 33, 53, 54, 33, 54, 55, 33, 55, 56, 33, 56, 57, 33, 57, 58, 33, 58, 59, 33, 59, 60, 33, 60, 61, 33, 61, 62, 33, 62, 63, 33, 63, 64, 33, 64, 65, 33, 65, 34, }; // Ring (length, outer_radius, inner_radius) // Circle (radius) const VertexList PrimitiveShapeVertex::CircleVertices = { {0, 0, 0, 0, 0, -1, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0}, {-1, 0, 0, 0, 0, -1, 0, 0}, {-1, 0, 0, 0, 0, 1, 0, 0}, {-0.980785, 0.19509, 0, 0, 0, -1, 0, 0}, {-0.980785, 0.19509, 0, 0, 0, 1, 0, 0}, {-0.92388, 0.382683, 0, 0, 0, -1, 0, 0}, {-0.92388, 0.382683, 0, 0, 0, 1, 0, 0}, {-0.83147, 0.55557, 0, 0, 0, -1, 0, 0}, {-0.83147, 0.55557, 0, 0, 0, 1, 0, 0}, {-0.707107, 0.707107, 0, 0, 0, -1, 0, 0}, {-0.707107, 0.707107, 0, 0, 0, 1, 0, 0}, {-0.55557, 0.83147, 0, 0, 0, -1, 0, 0}, {-0.55557, 0.83147, 0, 0, 0, 1, 0, 0}, {-0.382683, 0.92388, 0, 0, 0, -1, 0, 0}, {-0.382683, 0.92388, 0, 0, 0, 1, 0, 0}, {-0.19509, 0.980785, 0, 0, 0, -1, 0, 0}, {-0.19509, 0.980785, 0, 0, 0, 1, 0, 0}, {-0, 1, 0, 0, 0, -1, 0, 0}, {-0, 1, 0, 0, 0, 1, 0, 0}, {0.19509, 0.980785, 0, 0, 0, -1, 0, 0}, {0.19509, 0.980785, 0, 0, 0, 1, 0, 0}, {0.382683, 0.92388, 0, 0, 0, -1, 0, 0}, {0.382683, 0.92388, 0, 0, 0, 1, 0, 0}, {0.55557, 0.83147, 0, 0, 0, -1, 0, 0}, {0.55557, 0.83147, 0, 0, 0, 1, 0, 0}, {0.707107, 0.707107, 0, 0, 0, -1, 0, 0}, {0.707107, 0.707107, 0, 0, 0, 1, 0, 0}, {0.83147, 0.55557, 0, 0, 0, -1, 0, 0}, {0.83147, 0.55557, 0, 0, 0, 1, 0, 0}, {0.92388, 0.382683, 0, 0, 0, -1, 0, 0}, {0.92388, 0.382683, 0, 0, 0, 1, 0, 0}, {0.980785, 0.19509, 0, 0, 0, -1, 0, 0}, {0.980785, 0.19509, 0, 0, 0, 1, 0, 0}, {1, -0, 0, 0, 0, -1, 0, 0}, {1, -0, 0, 0, 0, 1, 0, 0}, {0.980785, -0.195091, 0, 0, 0, -1, 0, 0}, {0.980785, -0.195091, 0, 0, 0, 1, 0, 0}, {0.923879, -0.382684, 0, 0, 0, -1, 0, 0}, {0.923879, -0.382684, 0, 0, 0, 1, 0, 0}, {0.831469, -0.555571, 0, 0, 0, -1, 0, 0}, {0.831469, -0.555571, 0, 0, 0, 1, 0, 0}, {0.707106, -0.707107, 0, 0, 0, -1, 0, 0}, {0.707106, -0.707107, 0, 0, 0, 1, 0, 0}, {0.55557, -0.83147, 0, 0, 0, -1, 0, 0}, {0.55557, -0.83147, 0, 0, 0, 1, 0, 0}, {0.382683, -0.92388, 0, 0, 0, -1, 0, 0}, {0.382683, -0.92388, 0, 0, 0, 1, 0, 0}, {0.195089, -0.980785, 0, 0, 0, -1, 0, 0}, {0.195089, -0.980785, 0, 0, 0, 1, 0, 0}, {-1e-06, -1, 0, 0, 0, -1, 0, 0}, {-1e-06, -1, 0, 0, 0, 1, 0, 0}, {-0.195091, -0.980785, 0, 0, 0, -1, 0, 0}, {-0.195091, -0.980785, 0, 0, 0, 1, 0, 0}, {-0.382684, -0.923879, 0, 0, 0, -1, 0, 0}, {-0.382684, -0.923879, 0, 0, 0, 1, 0, 0}, {-0.555571, -0.831469, 0, 0, 0, -1, 0, 0}, {-0.555571, -0.831469, 0, 0, 0, 1, 0, 0}, {-0.707108, -0.707106, 0, 0, 0, -1, 0, 0}, {-0.707108, -0.707106, 0, 0, 0, 1, 0, 0}, {-0.83147, -0.555569, 0, 0, 0, -1, 0, 0}, {-0.83147, -0.555569, 0, 0, 0, 1, 0, 0}, {-0.92388, -0.382682, 0, 0, 0, -1, 0, 0}, {-0.92388, -0.382682, 0, 0, 0, 1, 0, 0}, {-0.980786, -0.195089, 0, 0, 0, -1, 0, 0}, {-0.980786, -0.195089, 0, 0, 0, 1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::CircleIndices = { 0, 2, 4, 1, 5, 3, 0, 4, 6, 1, 7, 5, 0, 6, 8, 1, 9, 7, 0, 8, 10, 1, 11, 9, 0, 10, 12, 1, 13, 11, 0, 12, 14, 1, 15, 13, 0, 14, 16, 1, 17, 15, 0, 16, 18, 1, 19, 17, 0, 18, 20, 1, 21, 19, 0, 20, 22, 1, 23, 21, 0, 22, 24, 1, 25, 23, 0, 24, 26, 1, 27, 25, 0, 26, 28, 1, 29, 27, 0, 28, 30, 1, 31, 29, 0, 30, 32, 1, 33, 31, 0, 32, 34, 1, 35, 33, 0, 34, 36, 1, 37, 35, 0, 36, 38, 1, 39, 37, 0, 38, 40, 1, 41, 39, 0, 40, 42, 1, 43, 41, 0, 42, 44, 1, 45, 43, 0, 44, 46, 1, 47, 45, 0, 46, 48, 1, 49, 47, 0, 48, 50, 1, 51, 49, 0, 50, 52, 1, 53, 51, 0, 52, 54, 1, 55, 53, 0, 54, 56, 1, 57, 55, 0, 56, 58, 1, 59, 57, 0, 58, 60, 1, 61, 59, 0, 60, 62, 1, 63, 61, 0, 62, 64, 1, 65, 63, 0, 64, 2, 1, 3, 65, }; // RingCircle (outer_radius, inner_radius) // Rect (width, height) // flat box const VertexList PrimitiveShapeVertex::RectVertices = { // top {0.5, 0.5, 0, 0, 0, 1, 0, 0}, {-0.5, 0.5, 0, 0, 0, 1, 0, 0}, {-0.5, -0.5, 0, 0, 0, 1, 0, 0}, {0.5, -0.5, 0, 0, 0, 1, 0, 0}, // bottom {0.5, -0.5, 0, 0, 0, -1, 0, 0}, {-0.5, -0.5, 0, 0, 0, -1, 0, 0}, {-0.5, 0.5, 0, 0, 0, -1, 0, 0}, {0.5, 0.5, 0, 0, 0, -1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::RectIndices = { // top 0, 1, 2, 2, 3, 0, // bottom 4, 5, 6, 6, 7, 4, }; // CircleLine // Circle (radius) const VertexList PrimitiveShapeVertex::CircleLineVertices = { {-1, 0, 0, 0, 0, 1, 0, 0}, {-0.980785, 0.19509, 0, 0, 0, 1, 0, 0}, {-0.92388, 0.382683, 0, 0, 0, 1, 0, 0}, {-0.83147, 0.55557, 0, 0, 0, 1, 0, 0}, {-0.707107, 0.707107, 0, 0, 0, 1, 0, 0}, {-0.55557, 0.83147, 0, 0, 0, 1, 0, 0}, {-0.382683, 0.92388, 0, 0, 0, 1, 0, 0}, {-0.19509, 0.980785, 0, 0, 0, 1, 0, 0}, {-0, 1, 0, 0, 0, 1, 0, 0}, {0.19509, 0.980785, 0, 0, 0, 1, 0, 0}, {0.382683, 0.92388, 0, 0, 0, 1, 0, 0}, {0.55557, 0.83147, 0, 0, 0, 1, 0, 0}, {0.707107, 0.707107, 0, 0, 0, 1, 0, 0}, {0.83147, 0.55557, 0, 0, 0, 1, 0, 0}, {0.92388, 0.382683, 0, 0, 0, 1, 0, 0}, {0.980785, 0.19509, 0, 0, 0, 1, 0, 0}, {1, -0, 0, 0, 0, 1, 0, 0}, {0.980785, -0.195091, 0, 0, 0, 1, 0, 0}, {0.923879, -0.382684, 0, 0, 0, 1, 0, 0}, {0.831469, -0.555571, 0, 0, 0, 1, 0, 0}, {0.707106, -0.707107, 0, 0, 0, 1, 0, 0}, {0.55557, -0.83147, 0, 0, 0, 1, 0, 0}, {0.382683, -0.92388, 0, 0, 0, 1, 0, 0}, {0.195089, -0.980785, 0, 0, 0, 1, 0, 0}, {-1e-06, -1, 0, 0, 0, 1, 0, 0}, {-0.195091, -0.980785, 0, 0, 0, 1, 0, 0}, {-0.382684, -0.923879, 0, 0, 0, 1, 0, 0}, {-0.555571, -0.831469, 0, 0, 0, 1, 0, 0}, {-0.707108, -0.707106, 0, 0, 0, 1, 0, 0}, {-0.83147, -0.555569, 0, 0, 0, 1, 0, 0}, {-0.92388, -0.382682, 0, 0, 0, 1, 0, 0}, {-0.980786, -0.195089, 0, 0, 0, 1, 0, 0}, {-1, 0, 0, 0, 0, 1, 0, 0}, }; const std::vector<GLuint> PrimitiveShapeVertex::CircleLineIndices = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, }; VertexSet PrimitiveShapeVertex::generateRingCircle(double outer_radius, double inner_radius, bool bothSide) { const int quality = 64; VertexSet vertexSet; vertexSet.vertices.emplace_back(outer_radius, 0, 0, 0, 0, 1); vertexSet.vertices.emplace_back(inner_radius, 0, 0, 0, 0, 1); for (int i = 1; i < quality+1; ++i) { double t = -2.0*M_PI*i/(double)quality; // cw double ox = outer_radius * cos(t); double oy = outer_radius * sin(t); double ix = inner_radius * cos(t); double iy = inner_radius * sin(t); // set vertex vertexSet.vertices.emplace_back(ox, oy, 0, 0, 0, 1); vertexSet.vertices.emplace_back(ix, iy, 0, 0, 0, 1); // set index int id0 = vertexSet.vertices.size()-4; int id1 = vertexSet.vertices.size()-3; int id2 = vertexSet.vertices.size()-2; int id3 = vertexSet.vertices.size()-1; // tri0 0, 1, 2 vertexSet.indices.push_back(id0); vertexSet.indices.push_back(id1); vertexSet.indices.push_back(id2); // tri1 3, 2, 1 vertexSet.indices.push_back(id3); vertexSet.indices.push_back(id2); vertexSet.indices.push_back(id1); } if (bothSide) { // set back side VertexList vertices = vertexSet.vertices; // reverse normal for (auto& vt : vertexSet.vertices) { vertices.emplace_back(vt.x, vt.y, vt.z, 0, 0, -1); } size_t offset = vertexSet.vertices.size(); IndexList indices = vertexSet.indices; for (auto itr = vertexSet.indices.rbegin(); itr != vertexSet.indices.rend(); ++itr) { indices.push_back(*itr + offset); } vertexSet.vertices.swap(vertices); vertexSet.indices.swap(indices); } return vertexSet; } void PrimitiveShapeVertex::setVertexBothSide(VertexSet& vertexSet) { VertexList vertices = vertexSet.vertices; // reverse normal for (auto& vt : vertexSet.vertices) { vertices.emplace_back(vt.x, vt.y, vt.z, 0, 0, -1); } size_t offset = vertexSet.vertices.size(); IndexList indices = vertexSet.indices; for (auto itr = vertexSet.indices.rbegin(); itr != vertexSet.indices.rend(); ++itr) { indices.push_back(*itr + offset); } vertexSet.vertices.swap(vertices); vertexSet.indices.swap(indices); } } /* namespace ptgl */
32.337654
107
0.480192
[ "vector" ]
38b0722f6cc4a6c9d2462e614bf6b733b00b3fed
8,907
cpp
C++
dev/Code/Sandbox/Plugins/CryDesigner/Util/EdgesSharpnessManager.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Sandbox/Plugins/CryDesigner/Util/EdgesSharpnessManager.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Sandbox/Plugins/CryDesigner/Util/EdgesSharpnessManager.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "EdgesSharpnessManager.h" #include "Core/Model.h" #include "Core/Polygon.h" #include "ElementManager.h" #include <AzCore/Math/Uuid.h> void EdgeSharpnessManager::Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bUndo, CD::Model* pModel) { if (bLoading) { int nEdgeSharpnessCount = xmlNode->getChildCount(); for (int i = 0; i < nEdgeSharpnessCount; ++i) { XmlNodeRef pSemiSharpCreaseNode = xmlNode->getChild(i); CD::SEdgeSharpness semiSharpCrease; const char* name = NULL; pSemiSharpCreaseNode->getAttr("name", &name); semiSharpCrease.name = name; pSemiSharpCreaseNode->getAttr("sharpness", semiSharpCrease.sharpness); pSemiSharpCreaseNode->getAttr("guid", semiSharpCrease.guid); int nEdgeCount = pSemiSharpCreaseNode->getChildCount(); for (int k = 0; k < nEdgeCount; ++k) { XmlNodeRef pEdgeNode = pSemiSharpCreaseNode->getChild(k); BrushEdge3D e; pEdgeNode->getAttr("v0", e.m_v[0]); pEdgeNode->getAttr("v1", e.m_v[1]); semiSharpCrease.edges.push_back(e); } m_EdgeSharpnessList.push_back(semiSharpCrease); } } else { std::vector<CD::SEdgeSharpness>::iterator ii = m_EdgeSharpnessList.begin(); for (; ii != m_EdgeSharpnessList.end(); ++ii) { const CD::SEdgeSharpness& semiSharpCrease = *ii; if (semiSharpCrease.edges.empty()) { continue; } XmlNodeRef pSemiSharpCreaseNode(xmlNode->newChild("SemiSharpCrease")); pSemiSharpCreaseNode->setAttr("name", semiSharpCrease.name); pSemiSharpCreaseNode->setAttr("sharpness", semiSharpCrease.sharpness); pSemiSharpCreaseNode->setAttr("guid", semiSharpCrease.guid); for (int i = 0, iEdgeCount(semiSharpCrease.edges.size()); i < iEdgeCount; ++i) { XmlNodeRef pEdgeNode = pSemiSharpCreaseNode->newChild("edge"); pEdgeNode->setAttr("v0", semiSharpCrease.edges[i].m_v[0]); pEdgeNode->setAttr("v1", semiSharpCrease.edges[i].m_v[1]); } } } } void EdgeSharpnessManager::CopyFromModel(CD::Model* pModel, const CD::Model* pSrcModel) { EdgeSharpnessManager* pDestEdgeSharpnessMgr = pModel->GetEdgeSharpnessMgr(); const EdgeSharpnessManager* pSrcEdgeSharpnessMgr = pSrcModel->GetEdgeSharpnessMgr(); pDestEdgeSharpnessMgr->Clear(); pDestEdgeSharpnessMgr->m_EdgeSharpnessList = pSrcEdgeSharpnessMgr->m_EdgeSharpnessList; } bool EdgeSharpnessManager::AddEdges(const char* name, ElementManager* pElements, float sharpness) { std::vector<BrushEdge3D> edges; for (int i = 0, iCount(pElements->GetCount()); i < iCount; ++i) { const SElement& element = pElements->Get(i); if (element.IsEdge()) { edges.push_back(element.GetEdge()); } if (element.IsFace() && element.m_pPolygon) { for (int k = 0, iEdgeCount(element.m_pPolygon->GetEdgeCount()); k < iEdgeCount; ++k) { edges.push_back(element.m_pPolygon->GetEdge(k)); } } } return AddEdges(name, edges, sharpness); } bool EdgeSharpnessManager::AddEdges(const char* name, const std::vector<BrushEdge3D>& edges, float sharpness) { if (edges.empty() || HasName(name)) { return false; } int iEdgeCount(edges.size()); for (int i = 0, iEdgeCount(edges.size()); i < iEdgeCount; ++i) { DeleteEdge(GetEdgeInfo(edges[i])); } CD::SEdgeSharpness edgeSharpness; edgeSharpness.name = name; edgeSharpness.edges = edges; edgeSharpness.sharpness = sharpness; edgeSharpness.guid = AZ::Uuid::CreateRandom(); m_EdgeSharpnessList.push_back(edgeSharpness); return true; } void EdgeSharpnessManager::RemoveEdgeSharpness(const char* name) { std::vector<CD::SEdgeSharpness>::iterator ii = m_EdgeSharpnessList.begin(); for (; ii != m_EdgeSharpnessList.end(); ++ii) { if (!azstricmp(name, ii->name.c_str())) { m_EdgeSharpnessList.erase(ii); break; } } } void EdgeSharpnessManager::RemoveEdgeSharpness(const BrushEdge3D& edge) { BrushEdge3D invEdge = edge.GetInverted(); std::vector<CD::SEdgeSharpness>::iterator ii = m_EdgeSharpnessList.begin(); for (; ii != m_EdgeSharpnessList.end(); ) { for (int i = 0, iEdgeCount(ii->edges.size()); i < iEdgeCount; ++i) { if (ii->edges[i].IsEquivalent(edge) || ii->edges[i].IsEquivalent(invEdge)) { ii->edges.erase(ii->edges.begin() + i); break; } } if (ii->edges.empty()) { ii = m_EdgeSharpnessList.erase(ii); } else { ++ii; } } } void EdgeSharpnessManager::SetSharpness(const char* name, float sharpness) { CD::SEdgeSharpness* pEdgeSharpness = FindEdgeSharpness(name); if (pEdgeSharpness == NULL) { return; } pEdgeSharpness->sharpness = sharpness; } void EdgeSharpnessManager::Rename(const char* oldName, const char* newName) { CD::SEdgeSharpness* pEdgeSharpness = FindEdgeSharpness(oldName); if (pEdgeSharpness == NULL) { return; } pEdgeSharpness->name = newName; } CD::SEdgeSharpness* EdgeSharpnessManager::FindEdgeSharpness(const char* name) { if (name) { for (int i = 0, iCount(m_EdgeSharpnessList.size()); i < iCount; ++i) { if (m_EdgeSharpnessList[i].name == name) { return &m_EdgeSharpnessList[i]; } } } return NULL; } float EdgeSharpnessManager::FindSharpness(const BrushEdge3D& edge) const { BrushEdge3D invEdge = edge.GetInverted(); for (int i = 0, iCount(m_EdgeSharpnessList.size()); i < iCount; ++i) { const std::vector<BrushEdge3D>& edges = m_EdgeSharpnessList[i].edges; for (int k = 0, iEdgeCount(edges.size()); k < iEdgeCount; ++k) { if (edges[k].IsEquivalent(edge) || edges[k].IsEquivalent(invEdge)) { return m_EdgeSharpnessList[i].sharpness; } } } return 0; } bool EdgeSharpnessManager::HasName(const char* name) const { for (int i = 0, iCount(m_EdgeSharpnessList.size()); i < iCount; ++i) { if (!azstricmp(m_EdgeSharpnessList[i].name.c_str(), name)) { return true; } } return false; } EdgeSharpnessManager::SSharpEdgeInfo EdgeSharpnessManager::GetEdgeInfo(const BrushEdge3D& edge) { SSharpEdgeInfo sei; BrushEdge3D invertedEdge = edge.GetInverted(); for (int i = 0, iCount(m_EdgeSharpnessList.size()); i < iCount; ++i) { CD::SEdgeSharpness& edgeSharpness = m_EdgeSharpnessList[i]; for (int k = 0, iEdgeCount(edgeSharpness.edges.size()); k < iEdgeCount; ++k) { if (edgeSharpness.edges[k].IsEquivalent(edge) || edgeSharpness.edges[k].IsEquivalent(invertedEdge)) { sei.sharpnessindex = i; sei.edgeindex = k; break; } } if (sei.edgeindex != -1) { break; } } return sei; } void EdgeSharpnessManager::DeleteEdge(const SSharpEdgeInfo& edgeInfo) { if (edgeInfo.sharpnessindex == -1 || edgeInfo.sharpnessindex >= m_EdgeSharpnessList.size()) { return; } CD::SEdgeSharpness& sharpness = m_EdgeSharpnessList[edgeInfo.sharpnessindex]; if (edgeInfo.edgeindex >= sharpness.edges.size()) { return; } sharpness.edges.erase(sharpness.edges.begin() + edgeInfo.edgeindex); } string EdgeSharpnessManager::GenerateValidName(const char* baseName) const { string validName(baseName); char numStr[10] = {0, }; int i = 0; while (i < 1000000) { if (!HasName(validName)) { break; } validName = baseName; sprintf(numStr, "%d", ++i); validName += numStr; } return validName; }
30.608247
111
0.609521
[ "vector", "model" ]
38b5310a2c3f6f9c359469fe52b1be89cb49c4d1
1,753
hpp
C++
VS_GETServer/AsynchronusGetServer/server.hpp
jjgrayg/Boost-ASIO-Asynchronous-GET-Server
91922224ee225592e512f86f7fcb5a709c99d2fa
[ "BSL-1.0" ]
1
2022-03-18T22:23:08.000Z
2022-03-18T22:23:08.000Z
VS_GETServer/AsynchronusGetServer/server.hpp
jjgrayg/Boost-ASIO-Asynchronous-GET-Server
91922224ee225592e512f86f7fcb5a709c99d2fa
[ "BSL-1.0" ]
null
null
null
VS_GETServer/AsynchronusGetServer/server.hpp
jjgrayg/Boost-ASIO-Asynchronous-GET-Server
91922224ee225592e512f86f7fcb5a709c99d2fa
[ "BSL-1.0" ]
null
null
null
/* A basic asynchronous server that responds to browser get requests. Capable of sending a limited number of binary files and all text files with a properly formatted HTTP response. Author: Jarod Graygo Special thanks to GitHub user beached for his barebones ASIO server His base code may be found here: https://gist.github.com/beached/d2383f9b14dafcc0f585 */ #ifndef SERVER_HPP #define SERVER_HPP #include <cstdint> #include <iostream> #include <list> #include <memory> #include <vector> #include <fstream> #include <algorithm> #include "connection.hpp" using std::vector; class Server { private: std::ofstream log_writer; boost::asio::io_service m_ioservice; boost::asio::ip::tcp::acceptor m_acceptor; std::list<Connection> m_connections; using con_handle_t = std::list<Connection>::iterator; public: Server() : m_ioservice(), m_acceptor(m_ioservice), m_connections(), log_writer() { } void write_to_log(string); void close_log_writer(); void close_connection(con_handle_t); void handle_read(con_handle_t, boost::system::error_code const&, size_t); void do_async_read(con_handle_t); void handle_response(con_handle_t, std::shared_ptr<string>, bool, boost::system::error_code const&); void write_response(con_handle_t); void handle_acknowledge(con_handle_t, std::shared_ptr<string>, boost::system::error_code const&); void handle_accept(con_handle_t&, boost::system::error_code const&); void start_accept(); void listen(uint16_t); void run(); void stop(); string parse_get(const char[]); std::tuple<string, bool, vector<unsigned char>> formulate_response(string); }; vector<string> split_string(string, char); #endif // SERVER_HPP
29.711864
104
0.731318
[ "vector" ]
38b5666e1a6ab3ad6b90c87cb90833183d43917e
6,177
cpp
C++
source/Player_DeepQ.cpp
codabeans/StarCraft-Micro-AI
1988f134ea59beff1c37386759ce54fbbc1357f6
[ "MIT" ]
1
2019-12-25T11:34:25.000Z
2019-12-25T11:34:25.000Z
source/Player_DeepQ.cpp
codabeans/StarCraft-Micro-AI
1988f134ea59beff1c37386759ce54fbbc1357f6
[ "MIT" ]
null
null
null
source/Player_DeepQ.cpp
codabeans/StarCraft-Micro-AI
1988f134ea59beff1c37386759ce54fbbc1357f6
[ "MIT" ]
null
null
null
#include "../include/Player_DeepQ.h" using namespace SparCraft; using namespace caffe; using namespace std; //constructor, sets important private member variables //as well as constructs our caffe network, if it can Player_DeepQ::Player_DeepQ(const IDType & playerID, const DeepQParameters & params) { _playerID = playerID; _params = params; _frameNumber = 0; _logData = true; _notBeginning = false; _modelFile = "../models/model.prototxt"; _weightFile = "../models/weights.prototxt"; initializeNet(); //Per the parameter, set the hardware usage in caffe if(_params.getGPU()) { Caffe::set_mode(Caffe::GPU); } else { Caffe::set_mode(Caffe::CPU); } } //check if the inputted string exists as a file bool fileExists(string file) { std::ifstream ifile(file.c_str()); return (bool)ifile; } //To be ran at the initialization of the Player //Loads the CNN as well as the weights (if there are any to load) void Player_DeepQ::initializeNet() { //Load the architecture from _modelFile, and init for TRAIN //If the file isn't found, give a fatalerror as the player would //be unable to play :'( feelsbadman.jpg //caffe will give its own error(s) if something is wrong with the files if(fileExists(_modelFile)) _net.reset(new Net<float>(_modelFile, TRAIN)); else System::FatalError("Problem Opening Model file"); //Copy weights from a previously trained net of the same architecture //Don't have said file yet, soon! if(fileExists(_weightFile)) _net->CopyTrainedLayersFrom(_weightFile); } //convert the ENUM ActionTypes to int values so a NN can hopefully make sense of them int moveInt(const IDType moveType) { if (moveType == ActionTypes::ATTACK) { return 10; } else if (moveType == ActionTypes::MOVE) { return 20; } else if (moveType == ActionTypes::RELOAD) { return 30; } else if (moveType == ActionTypes::PASS) { return 40; } else if (moveType == ActionTypes::HEAL) { return 50; } else return 0; } //Populate _img with the game's frame, as well as load actions in _moves void Player_DeepQ::prepareModelInput(const vector<Action> & moveVec) { //clear _moves from the previous turn _moves.clear(); //Then load the contents in moveVec into _moves (a vector<vector<int> >) // ID, Action, Move X, Move Y, Move index (attackee, healee, etc.) for(int i = 0; i < moveVec.size(); i++) { Action move = moveVec[i]; vector<float> unitMove{float(move.unit()), float(moveInt(move.type())), float(move.pos().x()), float(move.pos().y()), float(move.index())}; _moves.push_back(unitMove); } vector<float> emptyMove{0,0,0,0,0}; for(int i = 0; i < 10-moveVec.size(); i++) { _moves.push_back(emptyMove); } } //Load a set of actions into the network void Player_DeepQ::loadActions() { // caffe stores the data as a long array of floats stored in a pointer Blob<float>* action_layer = _net->input_blobs()[1]; float* data = action_layer->mutable_cpu_data(); for(int i = 0; i < 10; i++) { for(int j = 0; j < 5; j++) { data[i*5+j] = _moves[i][j]; } } } void Player_DeepQ::forward() { loadActions(); _net->Forward(); } void Player_DeepQ::getNetOutput() { boost::shared_ptr<Blob<float> > output_layer = _net->blob_by_name("reward"); float output; for(int i = 0; i < 1; i++) { output = output_layer->cpu_data()[i]; } _predictedReward = output; } void Player_DeepQ::getMoves(GameState & state, const MoveArray & moves, vector<Action> & moveVec) { if(_frameNumber == 0) { backward(state); if(rand() % 10 + 1 < 7) selectRandomMoves(moves, moveVec); else selectBestMoves(moves, moveVec); prepareModelInput(moveVec); forward(); } else { _frameNumber ++; if(_frameNumber > 4){ _frameNumber == 0; } } } //Select random moves to be used as a learning experience for the network void Player_DeepQ::selectRandomMoves(const MoveArray & moves, std::vector<Action> & moveVec) { moveVec.clear(); for (IDType u(0); u<moves.numUnits(); ++u) { moveVec.push_back(moves.getMove(u, rand() % (moves.numMoves(u)))); } } //Feed all (or at least a lot) of move sets into the network, and keep the one //that the network thinks is best void Player_DeepQ::selectBestMoves(const MoveArray & moves, std::vector<Action> & moveVec) { //TODO: THIS //dummy code for now moveVec.clear(); for (IDType u(0); u<moves.numUnits(); ++u) { moveVec.push_back(moves.getMove(u, rand() % (moves.numMoves(u)))); } } void Player_DeepQ::getReward(const GameState state) { _actualReward = state.evalLTD2(_playerID); } void Player_DeepQ::setReward() { //caffe stores the data as a long array of floats stored in a pointer Blob<float>* action_layer = _net->input_blobs()[2]; float* data = action_layer->mutable_cpu_data(); for(int i = 0; i < 10; i++) { for(int j = 0; j < 5; j++) { data[0] = _actualReward; } } } void Player_DeepQ::backward(const GameState state) { getReward(state); if(_actualReward != 0) { _notBeginning = true; } if(_notBeginning) { getNetOutput(); //No need to do back prop if we're just gathering data if(!_logData) { setReward(); //do the actual learning _net->Backward(); _net->Update(); //Monitoring purposes, REMOVE FOR FINAL VERSION cout << "Predicted: " << _predictedReward << " Actual: " << _actualReward << endl; } } //logDataPoint(); } string GenerateRandomString(const int length) { string randomString; for(int i = 0; i < length; i++) { char randomChar = 'A' + (random() % 26); randomString.push_back(randomChar); } return randomString; }
25.953782
147
0.613728
[ "vector", "model" ]
38b9446d088e03e0354d2bb57198e060dd5f34ea
14,223
cpp
C++
src/main.cpp
cs498/mazegenerator
9fb9b816088e7f312d8411689c9f182175a2a45c
[ "MIT" ]
null
null
null
src/main.cpp
cs498/mazegenerator
9fb9b816088e7f312d8411689c9f182175a2a45c
[ "MIT" ]
null
null
null
src/main.cpp
cs498/mazegenerator
9fb9b816088e7f312d8411689c9f182175a2a45c
[ "MIT" ]
null
null
null
#include "breadthfirstsearch.h" #include "circularhexagonmaze.h" #include "circularmaze.h" #include "depthfirstsearch.h" #include "hexagonalmaze.h" #include "honeycombmaze.h" #include "kruskal.h" #include "looperasedrandomwalk.h" #include "prim.h" #include "rectangularmaze.h" #include "usermaze.h" #include <cstring> #include <iostream> #include <map> #include <string> #include <fstream> #include <sstream> #include <unordered_map> #include <unordered_set> #include <utility> const std::unordered_set<std::string> COLORS({"white", "black", "dark-grey", "red", "web-green", "web-blue", "dark-magenta", "dark-cyan", "dark-orange", "dark-yellow", "royalblue", "goldenrod", "dark-spring-green", "purple", "steelblue", "dark-red", "dark-chartreuse", "orchid", "aquamarine", "brown", "yellow", "turquoise", "grey0", "grey10", "grey20", "grey30", "grey40", "grey50", "grey60", "grey70", "grey", "grey80", "grey90", "grey100", "light-red", "light-green", "light-blue", "light-magenta", "light-cyan", "light-goldenrod", "light-pink", "light-turquoise", "gold", "green", "dark-green", "spring-green", "forest-green", "sea-green", "blue", "dark-blue", "midnight-blue", "navy", "medium-blue", "skyblue", "cyan", "magenta", "dark-turquoise", "dark-pink", "coral", "light-coral", "orange-red", "salmon", "dark-salmon", "khaki", "dark-khaki", "dark-goldenrod", "beige", "olive", "orange", "violet", "dark-violet", "plum", "dark-plum", "dark-olivegreen", "orangered4", "brown4", "sienna4", "orchid4", "mediumpurple3", "slateblue1", "yellow4", "sienna1", "tan1", "sandybrown", "light-salmon", "pink", "khaki1", "lemonchiffon", "bisque", "honeydew", "slategrey", "seagreen", "antiquewhite", "chartreuse", "greenyellow", "gray", "light-gray", "light-grey", "dark-gray", "slategray", "gray0", "gray10", "gray20", "gray30", "gray40", "gray50", "gray60", "gray70", "gray80", "gray90", "gray100"}); const std::unordered_map<std::string, std::pair<std::string, std::string>> HOLIDAY_THEMES({{"valentines", std::make_pair("brown", "pink")}, {"easter", std::make_pair("pink", "skyblue")}, {"halloween", std::make_pair("orange", "black")}, {"thanksgiving", std::make_pair("goldenrod", "brown")}, {"christmas", std::make_pair("red", "green")}}); void usage(std::ostream &out) { out << "Usage: mazegen [--help] [-m <maze type>] [-a <algorithm type>]" << std::endl; out << " [-s <size> | -w <width> -h <height>]" << std::endl; out << " [-t <output type>] [-o <output prefix>]" << std::endl; out << " [-f <graph description file (for m=5)>]" << std::endl; out << std::endl; out << "Optional arguments" << std::endl; out << " --help " << "Show this message and exit" << std::endl; out << " -m " << "Maze type" << std::endl; out << " " << "0: Rectangular (default)" << std::endl; out << " " << "1: Hexagonal (triangular lattice)" << std::endl; out << " " << "2: Honeycomb" << std::endl; out << " " << "3: Circular" << std::endl; out << " " << "4: Circular (triangular lattice)" << std::endl; out << " " << "5: User defined graph" << std::endl; out << " -a " << "Algorithm type" << std::endl; out << " " << "0: Kruskal's algorithm (default)" << std::endl; out << " " << "1: Depth-first search" << std::endl; out << " " << "2: Breadth-first search" << std::endl; out << " " << "3: Loop-erased random walk" << std::endl; out << " " << "4: Prim's algorithm" << std::endl; out << " -s " << "Size (non-rectangular mazes, default: 20)" << std::endl; out << " -w,-h " << "Width and height (rectangular maze, default: 20)" << std::endl; out << " -t " << "Output type" << std::endl; out << " " << "0: svg output (default)" << std::endl; out << " " << "1: png output using gnuplot (.plt) intermediate " << std::endl; out << " -o " << "Prefix for .svg, .plt and .png outputs (default: maze)" << std::endl; out << " -c " << "Color of the lines of the maze (defaut: black)" << std::endl; out << " -b " << "Color of the background of the maze (defaut: white)" << std::endl; out << " -l " << "Width of the lines of the maze (default: 3)" << std::endl; out << " -i " << "Text file to style the maze: color of the lines (-c), background color (-b), the width of the lines (-l)" << std::endl; out << " -d " << "Holiday theme stylization: valentines, easter, halloween, thanskgiving, christmas" << std::endl; } int main(int argc, char *argv[]) { std::string outputprefix = "maze", infile = ""; std::string color = "black", backColor = "white"; bool theme = false; int strokeWidth = 3; std::map<std::string, int> optionmap{{"-m", 0}, {"-a", 0}, {"-s", 20}, {"-w", 20}, {"-h", 20}, {"-o", 0}, {"-f", 0}, {"--help", 0}, {"-t", 0}, {"-c", 0}, {"-l", 3}, {"-b", 0}, {"-i", 0}, {"-d", 0}}; for (int i = 1; i < argc; i++) { if (optionmap.find(argv[i]) == optionmap.end()) { std::cerr << "Unknown argument " << argv[i] << "\n"; usage(std::cerr); return 1; } if (strcmp("-o", argv[i]) == 0) { if (i + 1 == argc) { std::cerr << "Missing output prefix" << std::endl; usage(std::cerr); return 1; } outputprefix = argv[++i]; continue; } else if (strcmp("-f", argv[i]) == 0) { if (i + 1 == argc) { std::cerr << "Missing maze input file" << std::endl; usage(std::cerr); return 1; } infile = argv[++i]; continue; } else if (strcmp("--help", argv[i]) == 0) { usage(std::cout); return 0; } if (i + 1 == argc) { std::cerr << "Missing option for argument " << argv[i] << std::endl; usage(std::cerr); return 1; } if (strcmp("-d", argv[i]) == 0) { if (HOLIDAY_THEMES.find(argv[i + 1]) == HOLIDAY_THEMES.end()) { std::cerr << "Unknown holiday theme " << argv[i + 1] << std::endl; usage(std::cerr); return 1; } theme = true; color = HOLIDAY_THEMES.at(argv[++i]).first; backColor = HOLIDAY_THEMES.at(argv[i]).second; } else if (strcmp("-i", argv[i]) == 0) { std::string fileName = argv[++i]; std::ifstream inputFile; inputFile.open(fileName,std::ios::in); if (inputFile.is_open()) { std::string line; std::vector<std::string> tokens; while (getline(inputFile,line)) { if (line.length() < 1) { continue; } std::stringstream ss(line); std::string token; tokens.clear(); while (getline(ss, token, ' ')) { std::cout << token << std::endl; tokens.push_back(token); } if (tokens.size() == 3) { color = tokens[0]; backColor = tokens[1]; strokeWidth= stoi(tokens[2]); break; } } inputFile.close(); } } else if (strcmp("-c", argv[i]) == 0) { if (COLORS.find(argv[i + 1]) == COLORS.end()) { std::cerr << "Unknown color " << argv[i + 1] << std::endl; usage(std::cerr); return 1; } ++i; if (!theme) color = argv[i]; } else if (strcmp("-b", argv[i]) == 0) { if (COLORS.find(argv[i + 1]) == COLORS.end()) { std::cerr << "Unknown background color " << argv[i + 1] << std::endl; usage(std::cerr); return 1; } ++i; if (!theme) backColor = argv[i]; } else { int x; try { x = std::stoi(argv[i + 1]); } catch (...) { std::cerr << "Invalid argument " << argv[i + 1] << " for option " << argv[i] << "\n"; usage(std::cerr); return 0; } optionmap[argv[i++]] = x; } } Maze *maze; SpanningtreeAlgorithm *algorithm; switch (optionmap["-m"]) { case 0: if (optionmap["-w"] < 1 or optionmap["-h"] < 1) { std::cerr << "Invalide size " << optionmap["-w"] << "x" << optionmap["-h"] << " for rectangular maze\n"; usage(std::cerr); return 1; } std::cout << "Rectangular maze of size " << optionmap["-w"] << "x" << optionmap["-h"] << "\n"; maze = new RectangularMaze(optionmap["-w"], optionmap["-h"]); break; case 1: if (optionmap["-s"] < 1) { std::cerr << "Invalide size " << optionmap["-s"] << " for hexagonal maze with triangular lattice\n"; usage(std::cerr); return 1; } std::cout << "Hexagonal maze with triangular lattice of size " << optionmap["-s"] << "\n"; maze = new HexagonalMaze(optionmap["-s"]); break; case 2: if (optionmap["-s"] < 1) { std::cerr << "Invalide size " << optionmap["-s"] << " for honeycomb maze\n"; usage(std::cerr); return 1; } std::cout << "Honeycomb maze of size " << optionmap["-s"] << "\n"; maze = new HoneyCombMaze(optionmap["-s"]); break; case 3: if (optionmap["-s"] < 1) { std::cerr << "Invalide size " << optionmap["-s"] << " for circular maze\n"; usage(std::cerr); return 1; } std::cout << "Circular maze of size " << optionmap["-s"] << "\n"; maze = new CircularMaze(optionmap["-s"]); break; case 4: if (optionmap["-s"] < 1) { std::cerr << "Invalide size " << optionmap["-s"] << " for circular maze with triangular lattice\n"; usage(std::cerr); return 1; } std::cout << "Circular maze with triangular lattice of size " << optionmap["-s"] << "\n"; maze = new CircularHexagonMaze(optionmap["-s"]); break; case 5: if (infile == "") { std::cerr << "Graph description file not provided for user-defined graph\n"; usage(std::cerr); return 1; } std::cout << "User-defined graph\n"; maze = new UserMaze(infile); break; default: std::cerr << "Unknown maze type " << optionmap["-m"]; usage(std::cerr); return 1; } switch (optionmap["-a"]) { case 0: std::cout << "Maze generation using Kruskal's algorithm\n"; algorithm = new Kruskal; break; case 1: std::cout << "Maze generation using Depth-first search\n"; algorithm = new DepthFirstSearch; break; case 2: std::cout << "Maze generation using Breadth-first search\n"; algorithm = new BreadthFirstSearch; break; case 3: std::cout << "Maze generation using Loop-erased random walk\n"; algorithm = new LoopErasedRandomWalk; break; case 4: std::cout << "Maze generation using Prim's algorithm\n"; algorithm = new Prim; break; default: std::cerr << "Unknown algorithm type " << optionmap["-a"]; usage(std::cerr); return 1; } if (optionmap["-t"] < 0 or optionmap["-t"] > 1) { std::cerr << "Unknown output type " << optionmap["-a"]; usage(std::cerr); return 1; } Style::init({ color, backColor, strokeWidth }); std::cout << "Initialising graph..." << std::endl; maze->InitialiseGraph(); std::cout << "Generating maze..." << std::endl; maze->GenerateMaze(algorithm); if (optionmap["-t"] == 0) { std::cout << "Rendering maze to '" << outputprefix << ".svg'..." << std::endl; maze->PrintMazeSVG(outputprefix); } else { std::cout << "Exporting maze plotting parameters to '" << outputprefix << ".plt' ..." << std::endl; maze->PrintMazeGnuplot(outputprefix); std::cout << "Rendering maze to '" << outputprefix << ".png' using gnuplot..." << std::endl; system(("gnuplot '" + outputprefix + ".plt'").c_str()); } return 0; }
37.827128
145
0.440976
[ "vector" ]
38c235fa9bb33d72abfadeb919e0c01f570bea2a
1,872
cpp
C++
modules/aos/scene/PrismaticJoint.cpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/aos/scene/PrismaticJoint.cpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/aos/scene/PrismaticJoint.cpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
#include "PrismaticJoint.h" namespace aos { PrismaticJoint::PrismaticJoint() : KinematicJoint(0.0, 10.0, 0.0, true) { } PrismaticJoint::~PrismaticJoint() { } void PrismaticJoint::set_joint_value(real_t value) { if (value > _joint_max_limit || value < _joint_min_limit) { // Todo - Add notification that joint is out limit (visual notification) } _joint_value = value; _joint_transform = _compute_joint_transform(); _update_global_transform(); } real_t PrismaticJoint::get_joint_value() const { return _joint_value; } void PrismaticJoint::set_min_limit(real_t min) { _joint_min_limit = min; } void PrismaticJoint::set_max_limit(real_t max) { _joint_max_limit = max; } void PrismaticJoint::_notification(int p_what) { } Transform PrismaticJoint::_compute_joint_transform() const { Transform t; t.translate(0.0, 0.0, _joint_value); return t; } void PrismaticJoint::_bind_methods() { ClassDB::bind_method(D_METHOD("set_joint_value", "joint_value"), &PrismaticJoint::set_joint_value); ClassDB::bind_method(D_METHOD("get_joint_value"), &PrismaticJoint::get_joint_value); ClassDB::bind_method(D_METHOD("set_joint_min_limit", "min_limit"), &PrismaticJoint::set_min_limit); ClassDB::bind_method(D_METHOD("get_joint_min_limit"), &PrismaticJoint::get_min_limit); ClassDB::bind_method(D_METHOD("set_joint_max_limit", "max"), &PrismaticJoint::set_max_limit); ClassDB::bind_method(D_METHOD("get_joint_max_limit"), &PrismaticJoint::get_max_limit); ADD_PROPERTY(PropertyInfo(Variant::REAL, "joint value"), "set_joint_value", "get_joint_value"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "joint max limit"), "set_joint_max_limit", "get_joint_max_limit"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "joint min limit"), "set_joint_min_limit", "get_joint_min_limit"); } }
26.742857
111
0.737179
[ "transform" ]
38c36a4a8a811fac373885bddf5a655a6b25ad04
3,507
cpp
C++
laplace-2d/laplace/main.cpp
dglowienka/numerical_models
bfc7ba15737d4066a92c72d9789835e6799086fa
[ "MIT" ]
null
null
null
laplace-2d/laplace/main.cpp
dglowienka/numerical_models
bfc7ba15737d4066a92c72d9789835e6799086fa
[ "MIT" ]
null
null
null
laplace-2d/laplace/main.cpp
dglowienka/numerical_models
bfc7ba15737d4066a92c72d9789835e6799086fa
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include "gaussian_elimination.h" int main(void) { using namespace std; int m, n; double l, r, t, b; vector<double> b_it; vector<vector<double>> A_it; vector<vector<double>> a; ofstream laplace; laplace.open("Laplace.txt"); printf("\tEnter boundary conditions\n"); printf("\tValue on left side: "); l = 75; printf("\tValue on right side: "); r = 50; printf("\tValue on top side: "); t = 100; printf("\tValue on bottom side: "); b = 0; printf("\tEnter number of steps in x and y direction: "); m = 8; printf("\tEnter number of steps in y direction: "); n = 10; // Init all vectors b_it.resize(n*m); A_it.resize(n*n, vector<double>(m*m)); a.resize(n+2, vector<double>(m+2)); //assigning boundary values begins for (int i = 0; i <= m+1; i++) { a[i][0] = b; a[i][n+1] = t; } //assigning boundary values ends for (int i = 0; i <= n+1; i++) { a[0][i] = l; a[m+1][i] = r; } // Find A matrix and b vector for Ax=b linear algebric int k_it = 0; for (int j = 1; j <= n; j++) { for (int i = 1; i <= m; i++) { A_it[k_it][k_it] = -4; // Middle (no boundary around) if (i > 1 && i < m && j>1 && j < n) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it - 1][k_it] = 1; //i-1,j A_it[k_it + 1][k_it] = 1; //i+1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = 0; } // Bottom if (j == 1) { // Bottom-left if (i == 1) { A_it[k_it + 1][k_it] = 1; //i+1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = -(b + l); } // Bottom-right if (i == m) { A_it[k_it - 1][k_it] = 1; //i-1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = -(b + r); } // Bottom-middle if ((i > 1) && (i < m)) { A_it[k_it - 1][k_it] = 1; //i-1,j A_it[k_it + 1][k_it] = 1; //i+1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = -b; } } // Top if (j == n) { // Top-left if (i == 1) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it + 1][k_it] = 1; //i+1,j b_it[k_it] = -(t + l); } // Top-right if (i == m) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it - 1][k_it] = 1; //i-1,j b_it[k_it] = -(t + r); } // Top-middle if ((i > 1) && (i < m)) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it - 1][k_it] = 1; //i-1,j A_it[k_it + 1][k_it] = 1; //i+1,j b_it[k_it] = -t; } } // Left if (i == 1) { // Left-bottom // Left-top // Left-middle if (j > 1 && j < m) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it + 1][k_it] = 1; //i+1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = -l; } } //Right if (i == m) { // Right-top // Right-bottom // Right-middle if (j > 1 && j < m) { A_it[k_it - n][k_it] = 1; //i,j-1 A_it[k_it - 1][k_it] = 1; //i-1,j A_it[k_it + n][k_it] = 1; //i,j+1 b_it[k_it] = -r; } } k_it++; } } vector<double> tmp_result; tmp_result = gaussian_elimination(A_it, b_it); // Copy results of x to array with all the data int count=0; for (int j = 1; j <= n; j++) { for (int i = 1; i <= m; i++) { a[i][j] = tmp_result[count]; count++; } } // Print the results for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a[i].size(); j++) { laplace << a[i][j] << "\n"; count++; } } laplace.close(); }
19.269231
58
0.461648
[ "vector" ]
38c85c22e32d2daa274126a76fa3d1890fdd87c5
8,659
cpp
C++
src/server/libaccess/aclpath.cpp
jvirkki/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
13
2015-10-09T05:59:20.000Z
2021-11-12T10:38:51.000Z
src/server/libaccess/aclpath.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
null
null
null
src/server/libaccess/aclpath.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
6
2016-05-23T10:53:29.000Z
2019-12-13T17:57:32.000Z
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <netsite.h> #include <base/nsassert.h> #include <base/ereport.h> #include <libaccess/acl.h> // generic ACL definitions #include <libaccess/aclproto.h> // internal prototypes #include <libaccess/aclglobal.h> // global data #include "aclpriv.h" // internal data structure definitions #include <libaccess/dbtlibaccess.h> // strings #include "plhash.h" /* ACL_AddAclName * Adds the ACLs for just the terminal object specified in a pathname. * INPUT * path The filesystem pathname of the terminal object. * acllistp The address of the list of ACLs found thus far. * Could be NULL. If so, a new acllist will be allocated (if any * acls are found). Otherwise the existing list will be added to. * masterlist Usually the ACL list of the virtual server. */ void ACL_AddAclName(char *path, ACLListHandle_t **acllistp, ACLListHandle_t *masterlist) { ACLHandle_t *acl; NSErr_t *errp = 0; #ifdef XP_WIN32 acl = ACL_ListFind(errp, masterlist, path, ACL_CASE_INSENSITIVE); #else acl = ACL_ListFind(errp, masterlist, path, ACL_CASE_SENSITIVE); #endif if (!acl) return; NS_ASSERT(ACL_AssertAcl(acl)); ereport(LOG_VERBOSE, "acl: matched an acl for [%s]", path); if (!*acllistp) *acllistp = ACL_ListNew(errp); ACL_ListAppend(NULL, *acllistp, acl, 0); NS_ASSERT(ACL_AssertAcllist(*acllistp)); return; } /* ACL_GetAcls */ static PRBool ACL_GetAcls(char *path, ACLListHandle_t **acllistp, char *prefix, ACLListHandle_t *masterlist, PRBool flagExtensions, PRBool flagParents) { PRBool res = PR_TRUE; char *slashp=path; int slashidx; // ppath needs to be ACL_PATH_MAX+maxppath+3 // maxppath is assumed to be 24 char ppath[ACL_PATH_MAX+24+3]; int prefixlen; int ppathlen; NS_ASSERT(path); NS_ASSERT(prefix); if ((!path) || (!ppath)) { ereport(LOG_SECURITY, XP_GetAdminStr(DBT_aclcacheNullPath)); res = PR_FALSE; return res; } strncpy(ppath, prefix, ACL_PATH_MAX); int lenPath = strlen(path); prefixlen = strlen(ppath); /* Find the extension */ char *suffix = NULL; int suffixlen = 0; if (flagExtensions) { /* The extension begins with the last '.' in the last path segment */ suffix = strrchr(path, '.'); if (suffix && !strchr(suffix, '/')) suffixlen = strlen(suffix); else suffix = NULL; } /* Do we have enough room in ppath? */ if (lenPath+prefixlen+3+suffixlen >= sizeof(ppath)) { ereport(LOG_SECURITY, XP_GetAdminStr(DBT_aclcachePath2Long)); res = PR_FALSE; return res; } ACL_CritEnter(); /* Handle the extension */ if (suffix) { /* Handle "*.jsp" */ ppath[prefixlen] = '*'; memcpy(&ppath[prefixlen + 1], suffix, suffixlen + 1); ACL_AddAclName(ppath, acllistp, masterlist); } /* Handle the first "/". i.e. the root directory */ if (*path == '/') { /* Handle "/" */ ppath[prefixlen]='/'; ppath[prefixlen+1]='\0'; if (flagParents) ACL_AddAclName(ppath, acllistp, masterlist); /* Handle "/*" */ ppath[prefixlen + 1] = '*'; ppath[prefixlen + 2] = 0; ACL_AddAclName(ppath, acllistp, masterlist); if (suffix) { /* Handle "/*.jsp" */ memcpy(&ppath[prefixlen + 2], suffix, suffixlen + 1); ACL_AddAclName(ppath, acllistp, masterlist); } slashp = path; } do { slashp = strchr(++slashp, '/'); if (slashp) { slashidx = slashp - path; ppathlen = prefixlen + slashidx; /* Handle "/a/b" */ memcpy(&ppath[prefixlen], path, slashidx); ppath[ppathlen] = '\0'; if (flagParents || !slashp[1]) ACL_AddAclName(ppath, acllistp, masterlist); /* Handle "/a/b/" */ ppath[ppathlen] = '/'; ppath[ppathlen + 1] = 0; if (flagParents) ACL_AddAclName(ppath, acllistp, masterlist); /* Handle "/a/b/*" */ ppath[ppathlen + 1] = '*'; ppath[ppathlen + 2] = 0; ACL_AddAclName(ppath, acllistp, masterlist); if (suffix) { /* Handle "/a/b/*.jsp" */ memcpy(&ppath[ppathlen + 2], suffix, suffixlen + 1); ACL_AddAclName(ppath, acllistp, masterlist); } continue; } /* Handle "/a/b/c.jsp" */ memcpy(&ppath[prefixlen], path, lenPath + 1); ACL_AddAclName(ppath, acllistp, masterlist); /* Handle "/a/b/c.jsp/" */ ppathlen = prefixlen + lenPath; ppath[ppathlen] = '/'; ppath[ppathlen + 1] = 0; ACL_AddAclName(ppath, acllistp, masterlist); /* Handle "/a/b/c.jsp/*" */ ppath[ppathlen + 1] = '*'; ppath[ppathlen + 2] = 0; ACL_AddAclName(ppath, acllistp, masterlist); break; } while (slashp); ACL_CritExit(); return res; } /* ACL_GetPathAcls * Adds the ACLs for all directories plus the terminal object along a given * filesystem pathname. For each pathname component, look for the name, the * name + "/", and the name + "/*". The last one is because the resource * picker likes to postpend "/*" for directories. * INPUT * path The filesystem pathname of the terminal object. * acllistp The address of the list of ACLs found thus far. * Could be NULL. If so, a new acllist will be allocated (if any * acls are found). Otherwise the existing list will be added to. * prefix A string to be prepended to the path component when looking * for a matching ACL tag. * masterlist Usually the ACL list of the virtual server. * * XXX this stuff needs to be made MUCH more efficient. I think it's one of the main reasons why * uncached ACLs are horribly slow. It will call ACL_AddAclName->ACL_ListFind a mindboggling * number of times, like 2 + (n * 3) + 3, where n is the number of "/"'s in "path". * A possible way to optimize this would be to build a sparse tree that mirrors the file system * directory structure, with ACLs that apply to a path associated to the corresponding node. * ACL_GetPathAcls could walk the tree according to "path" and pick up any ACLs that are on the way. * The necessary data structures could maybe be piggybacked onto the ACLList. * The tree would need to be constructed for every VS acllist, though. * There are various optimizations: * - If no path or uri ACLs are present, do not construct the tree. * * With the introduction of extension mapping for Servlet spec compliance, * the situation has gotten even worse. * * ACL_GetPathAcls is currently used with the "uri=" and "path=" prefixes. */ PRBool ACL_GetPathAcls(char *path, ACLListHandle_t **acllistp, char *prefix, ACLListHandle_t *masterlist) { return ACL_GetAcls(path, acllistp, prefix, masterlist, PR_FALSE, PR_TRUE); }
34.7751
137
0.649382
[ "object" ]
38d5cc23f82b782e2bcb3c5a3bef8425a956a1c2
5,211
cpp
C++
src/rws_subscription.cpp
herrvonregen/abb_librws
a34f824b76b7a63b41f53054f1d0588535aa6b39
[ "BSD-3-Clause" ]
null
null
null
src/rws_subscription.cpp
herrvonregen/abb_librws
a34f824b76b7a63b41f53054f1d0588535aa6b39
[ "BSD-3-Clause" ]
5
2021-11-25T09:24:05.000Z
2022-02-21T13:41:14.000Z
src/rws_subscription.cpp
NoMagicAi/abb_librws
bbd22f45ae43d087f64411d3114658445dd73407
[ "BSD-3-Clause" ]
2
2021-03-20T09:30:53.000Z
2022-01-02T13:13:30.000Z
#include <abb_librws/rws_subscription.h> #include <abb_librws/rws_error.h> #include <abb_librws/parsing.h> #include <Poco/Net/HTTPRequest.h> #include <boost/exception/diagnostic_information.hpp> #include <iostream> namespace abb :: rws { using namespace Poco::Net; SubscriptionGroup::SubscriptionGroup(SubscriptionManager& subscription_manager, SubscriptionResources const& resources) : subscription_manager_ {subscription_manager} , subscription_group_id_ {subscription_manager.openSubscription(getURI(subscription_manager, resources))} { } SubscriptionGroup::SubscriptionGroup(SubscriptionGroup&& rhs) : subscription_manager_ {rhs.subscription_manager_} , subscription_group_id_ {rhs.subscription_group_id_} { // Clear subscription_group_id_ of the SubscriptionGroup that has been moved from, // s.t. its destructor does not close the subscription. rhs.subscription_group_id_.clear(); } SubscriptionGroup::~SubscriptionGroup() { close(); } void SubscriptionGroup::close() { if (!subscription_group_id_.empty()) { subscription_manager_.closeSubscription(subscription_group_id_); subscription_group_id_.clear(); } } void SubscriptionGroup::detach() noexcept { subscription_group_id_.clear(); } SubscriptionReceiver SubscriptionGroup::receive() const { return SubscriptionReceiver {subscription_manager_, subscription_group_id_}; } std::vector<std::pair<std::string, SubscriptionPriority>> SubscriptionGroup::getURI( SubscriptionManager& subscription_manager, SubscriptionResources const& resources) { std::vector<std::pair<std::string, SubscriptionPriority>> uri; uri.reserve(resources.size()); for (auto&& r : resources) uri.emplace_back(r.getURI(subscription_manager), r.getPriority()); return uri; } const std::chrono::microseconds SubscriptionReceiver::DEFAULT_SUBSCRIPTION_TIMEOUT {40000000000}; SubscriptionReceiver::SubscriptionReceiver(SubscriptionManager& subscription_manager, std::string const& subscription_group_id) : subscription_manager_ {subscription_manager} , webSocket_ {subscription_manager_.receiveSubscription(subscription_group_id)} { } SubscriptionReceiver::~SubscriptionReceiver() { } bool SubscriptionReceiver::waitForEvent(SubscriptionCallback& callback, std::chrono::microseconds timeout) { WebSocketFrame frame; if (webSocketReceiveFrame(frame, timeout)) { Poco::AutoPtr<Poco::XML::Document> doc = parser_.parseString(frame.frame_content); subscription_manager_.processEvent(doc, callback); return true; } return false; } bool SubscriptionReceiver::webSocketReceiveFrame(WebSocketFrame& frame, std::chrono::microseconds timeout) { auto now = std::chrono::steady_clock::now(); auto deadline = std::chrono::steady_clock::now() + timeout; // If the connection is still active... int flags = 0; std::string content; int number_of_bytes_received = 0; // Wait for (non-ping) WebSocket frames. do { now = std::chrono::steady_clock::now(); if (now >= deadline) BOOST_THROW_EXCEPTION(TimeoutError {"WebSocket frame receive timeout"}); webSocket_.setReceiveTimeout(std::chrono::duration_cast<std::chrono::microseconds>(deadline - now).count()); flags = 0; try { number_of_bytes_received = webSocket_.receiveFrame(websocket_buffer_, sizeof(websocket_buffer_), flags); } catch (Poco::TimeoutException const&) { BOOST_THROW_EXCEPTION( TimeoutError {"WebSocket frame receive timeout"} << boost::errinfo_nested_exception(boost::current_exception()) ); } content = std::string(websocket_buffer_, number_of_bytes_received); // Check for ping frame. if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PING) { // Reply with a pong frame. webSocket_.sendFrame(websocket_buffer_, number_of_bytes_received, WebSocket::FRAME_FLAG_FIN | WebSocket::FRAME_OP_PONG); } } while ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PING); // Check for closing frame. if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_CLOSE) { // Do not pass content of a closing frame to end user, // according to "The WebSocket Protocol" RFC6455. frame.frame_content.clear(); frame.flags = flags; return false; } frame.flags = flags; frame.frame_content = content; return number_of_bytes_received != 0; } void SubscriptionReceiver::shutdown() { // Shut down the socket. This should make webSocketReceiveFrame() return as soon as possible. webSocket_.shutdown(); } void SubscriptionCallback::processEvent(IOSignalStateEvent const& event) { } void SubscriptionCallback::processEvent(RAPIDExecutionStateEvent const& event) { } void SubscriptionCallback::processEvent(ControllerStateEvent const& event) { } void SubscriptionCallback::processEvent(OperationModeEvent const& event) { } }
27.282723
129
0.709269
[ "vector" ]
38e0ab150ecf07b71754c109becf1e46273a4719
920
cpp
C++
week2/leetcode1074.cpp
AndyRao/GeekTime_Algorithm
6a8273d577bf8306dc3b44c2693cc2b0a69e8ad6
[ "Apache-2.0" ]
null
null
null
week2/leetcode1074.cpp
AndyRao/GeekTime_Algorithm
6a8273d577bf8306dc3b44c2693cc2b0a69e8ad6
[ "Apache-2.0" ]
null
null
null
week2/leetcode1074.cpp
AndyRao/GeekTime_Algorithm
6a8273d577bf8306dc3b44c2693cc2b0a69e8ad6
[ "Apache-2.0" ]
null
null
null
class Solution { public: int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { int count = 0; int m = matrix.size(); int n = matrix[0].size(); for(int i = 0; i < m; i++) { vector<int> sum(n); for(int j = i; j < m; j++) { for(int k = 0; k < n; k++) { sum[k] += matrix[j][k]; } count += subarraySum(sum, target); } } return count; } private: int subarraySum(vector<int>& nums, int k) { int len = nums.size(); unordered_map<int, int> counts; int pre = 0; int ans = 0; //不要忘了下面这一行 counts[0] = 1; for(int i = 0; i < len; i++) { pre += nums[i]; int temp = pre - k; ans += counts[temp]; counts[pre]++; } return ans; } };
24.864865
72
0.408696
[ "vector" ]
38e3fe131b480c2553184b7fe8ea98698306cdc3
466
cpp
C++
move/general_move.cpp
Alaya-in-Matrix/Chinese-chess
f8e9963251186e696289a8060a7ead70eb0efe47
[ "WTFPL" ]
2
2019-11-08T10:01:59.000Z
2020-05-21T12:41:10.000Z
move/general_move.cpp
Alaya-in-Matrix/Chinese-chess
f8e9963251186e696289a8060a7ead70eb0efe47
[ "WTFPL" ]
null
null
null
move/general_move.cpp
Alaya-in-Matrix/Chinese-chess
f8e9963251186e696289a8060a7ead70eb0efe47
[ "WTFPL" ]
null
null
null
#include<iostream> #include<vector> #include"../global.h" using namespace std; /****************************声明*********************************/ void General_move(short pos,short Side_tag,vector<mov>& Move_array) { void Save_move(short&,short&,vector<mov>&); short i=0; for(i=0;i<4;i++) { short next=pos+General_direction[i]; if(General_legal[next])//如果该位置是合法的 { if(!(board[next] & Side_tag)) { Save_move(pos,next,Move_array); } } } }
17.923077
67
0.572961
[ "vector" ]
38f1802dbdc720acede6fb611e42339b70a2ea29
567
cpp
C++
Dojo/C++ Programming Practices and Principles - Stroustrup/ch4/ex13sieveoferatosthenes.cpp
miguelraz/PathToPerformance
4f098e55023007e62c338d31a7ed2a46a3c99752
[ "MIT" ]
5
2017-05-04T22:25:06.000Z
2022-02-15T13:44:50.000Z
Dojo/C++ Programming Practices and Principles - Stroustrup/ch4/ex13sieveoferatosthenes.cpp
miguelraz/PathToPerformance
4f098e55023007e62c338d31a7ed2a46a3c99752
[ "MIT" ]
null
null
null
Dojo/C++ Programming Practices and Principles - Stroustrup/ch4/ex13sieveoferatosthenes.cpp
miguelraz/PathToPerformance
4f098e55023007e62c338d31a7ed2a46a3c99752
[ "MIT" ]
null
null
null
//Exercise13: Sieve of Eratosthenes int main() { cout << "Gimme the x in 1:x " << endl; int max; cin >> max; vector<int> numbers(max,0); vector<int> primes; for (int i = 0; i < max; ++i) numbers[i] = i; for (int i = 2; i < max; ++i) { if (numbers[i] != 0 && i != 0) { primes.push_back(i); cout << i << " was just added as a prime " << endl; for (int j = 2; j*i < max; ++i) { primes[i*j] = 0; cout << "The multiples of " << i << " have been set to 0. " << endl; } } if (numbers[i] == 0) continue; }
21
74
0.486772
[ "vector" ]
38f3c1be91cb964be56db7bb77412de087413a2f
8,967
cpp
C++
src/v2i-hub/PreemptionPlugin/src/include/PreemptionPluginWorker.cpp
networkmodeling/V2X-Hub
d363f49a4c9af76823a23033b9f7983f2f6ae095
[ "Apache-2.0" ]
null
null
null
src/v2i-hub/PreemptionPlugin/src/include/PreemptionPluginWorker.cpp
networkmodeling/V2X-Hub
d363f49a4c9af76823a23033b9f7983f2f6ae095
[ "Apache-2.0" ]
null
null
null
src/v2i-hub/PreemptionPlugin/src/include/PreemptionPluginWorker.cpp
networkmodeling/V2X-Hub
d363f49a4c9af76823a23033b9f7983f2f6ae095
[ "Apache-2.0" ]
null
null
null
//========================================================================== // Name : PreemptionPlugin.cpp // Author : FHWA Saxton Transportation Operations Laboratory // Version : // Copyright : Copyright (c) 2019 FHWA Saxton Transportation Operations Laboratory. All rights reserved. // Description : Preemption Plugin //========================================================================== #include "PreemptionPluginWorker.hpp" using namespace std; namespace PreemptionPlugin { void PreemptionPluginWorker::ProcessMapMessageFile(std::string path){ if(path != ""){ try { boost::property_tree::read_json(path, geofence_data); BOOST_FOREACH( boost::property_tree::ptree::value_type const& v, geofence_data.get_child( "data" ) ) { assert(v.first.empty()); // array elements have no names boost::property_tree::ptree subtree = v.second; list <double> geox; list <double> geoy; BOOST_FOREACH( boost::property_tree::ptree::value_type const& u, subtree.get_child( "geox" ) ) { assert(u.first.empty()); // array elements have no names // std::cout << u.second.get<double>("") << std::endl; double d = u.second.get<double>(""); geox.push_back(d); } BOOST_FOREACH( boost::property_tree::ptree::value_type const& u, subtree.get_child( "geoy" ) ) { assert(u.first.empty()); // array elements have no names double d = u.second.get<double>(""); geoy.push_back(d); } GeofenceObject* geofenceObject = new GeofenceObject(geox,geoy,subtree.get<double>("PreemptCall"),subtree.get<double>("HeadingMin"),subtree.get<double>("HeadingMax")); GeofenceSet.push_back(geofenceObject); } } catch(...) { std::cout << "Caught exception from reading a file"; } } } bool PreemptionPluginWorker::CarInGeofence(double x, double y, double geox[], double geoy[], int GeoCorners) { int i, j=GeoCorners-1 ; bool oddNodes ; for (i=0; i<GeoCorners; i++) { if ((geoy[i]< y && geoy[j]>=y || geoy[j]< y && geoy[i]>=y) && (geox[i]<=x || geox[j]<=x)) { oddNodes^=(geox[i]+(y-geoy[i])/(geoy[j]-geoy[i])*(geox[j]-geox[i])<x); } j=i; } return oddNodes; } void PreemptionPluginWorker::VehicleLocatorWorker(BsmMessage* msg){ double micro = 10000000.0; PreemptionObject* po = new PreemptionObject; VehicleCoordinate* vehicle_coordinate = new VehicleCoordinate; auto bsm = msg->get_j2735_data(); int buff_size = bsm->coreData.id.size; po->vehicle_id = (int)*(bsm->coreData.id.buf); vehicle_coordinate->lat = bsm->coreData.lat / micro; vehicle_coordinate->lon = bsm->coreData.Long / micro; vehicle_coordinate->elevation = bsm->coreData.elev; vehicle_coordinate->heading = bsm->coreData.heading * 0.0125; for (auto const& it: GeofenceSet) { double geox[it->geox.size()]; int k = 0; for (double const &i: it->geox) { geox[k++] = i; } double geoy[it->geoy.size()]; k = 0; for (double const &i: it->geoy) { geoy[k++] = i; } bool in_geo = CarInGeofence(vehicle_coordinate->lon, vehicle_coordinate->lat, geoy, geox, it->geox.size()); if(in_geo){ if(vehicle_coordinate->heading > it->minHeading && vehicle_coordinate->heading < it->maxHeading) { po->approach = "1"; po->preemption_plan = std::to_string(it->PreemptCall); PreemptionPlaner(po); return; } else { po->approach = "0"; } } else { po ->approach = "0"; } } PreemptionPlaner(po); return; }; void PreemptionPluginWorker::PreemptionPlaner(PreemptionObject* po){ if(po->approach == "1") { if ( preemption_map.find(po->vehicle_id) == preemption_map.end() ) { TurnOnPreemption(po); } else { std::cout << "Already sent the preemption plan."; } } else if(po->approach == "0"){ if (preemption_map.find(po->vehicle_id) == preemption_map.end() ) { std::cout << " vehicle id does not exitst" << po->vehicle_id << std::endl; } else { TurnOffPreemption(po); } } else{ std::cout << "approach is not 0 or 1" << po->approach << std::endl; } std::cout << " Finished PreemptionPlaner" << std::endl; }; void PreemptionPluginWorker::TurnOnPreemption(PreemptionObject* po){ std::string preemption_plan_flag = "1"; std::asctime(std::localtime(&(po->time))); preemption_map[po->vehicle_id] = *po; std::string PreemptionOid = base_preemption_oid + po->preemption_plan; int response = SendOid(PreemptionOid.c_str(), preemption_plan_flag.c_str()); if(response != 0){ std::cout << "Sending oid intrupted with an error."; } else{ std::cout << "Finished sending preemption plan."; } } void PreemptionPluginWorker::TurnOffPreemption(PreemptionObject* po){ std::string preemption_plan, preemption_plan_flag = ""; preemption_plan = preemption_map[po ->vehicle_id].preemption_plan; preemption_plan_flag = "0"; std::string PreemptionOid = base_preemption_oid + preemption_plan; int response = SendOid(PreemptionOid.c_str(), preemption_plan_flag.c_str()); if(response != 0){ std::cout << "Sending oid intrupted with an error."; } else{ std::cout << "Finished sending preemption plan."; } preemption_map.erase(po->vehicle_id); } int PreemptionPluginWorker::SendOid(const char *PreemptionOid, const char *value) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response = NULL; netsnmp_variable_list *vars; oid name[MAX_OID_LEN]; size_t name_length; int status; int failures = 0; int exitval = 0; init_snmp("snmpset"); snmp_sess_init(&session); session.peername = strdup(ip_with_port.c_str()); session.version = snmp_version; session.community = (u_char *)snmp_community.c_str(); session.community_len = strlen((const char*) session.community); session.timeout = 1000000; SOCK_STARTUP; ss = snmp_open(&session); if (ss == NULL) { snmp_sess_perror("snmpset", &session); SOCK_CLEANUP; exit(1); } // create PDU for SET request and add object names and values to request pdu = snmp_pdu_create(SNMP_MSG_SET); name_length = MAX_OID_LEN; if (snmp_parse_oid(PreemptionOid, name, &name_length) == NULL) { snmp_perror(PreemptionOid); failures++; } else { if (snmp_add_var (pdu, name, name_length, 'i', value)) { snmp_perror(PreemptionOid); failures++; } } if (failures) { snmp_close(ss); SOCK_CLEANUP; exit(1); } //send the request status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (1) { print_variable(response->variables->name, response->variables->name_length, response->variables); } } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); exitval = 2; } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpset", ss); exitval = 1; } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; }; };
34.621622
186
0.51578
[ "object" ]
38f93571245b52080e614ac526cd7c18e6d8d79b
9,239
cpp
C++
engine/conversion/source/CharacterDumper.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/conversion/source/CharacterDumper.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/conversion/source/CharacterDumper.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include <iomanip> #include <sstream> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #include "global_prototypes.hpp" #include "ArtifactDumper.hpp" #include "AttackDumper.hpp" #include "CharacterDumper.hpp" #include "ClassManager.hpp" #include "ColourTextKeys.hpp" #include "ConductsDumper.hpp" #include "Conversion.hpp" #include "CreatureProperties.hpp" #include "CreatureTranslator.hpp" #include "DeathDumper.hpp" #include "Environment.hpp" #include "EquipmentDumper.hpp" #include "Game.hpp" #include "InventoryDumper.hpp" #include "MembershipsDumper.hpp" #include "Metadata.hpp" #include "MessageBufferDumper.hpp" #include "MessageManagerFactory.hpp" #include "ModifiersDumper.hpp" #include "MortuaryDumper.hpp" #include "PartyTextKeys.hpp" #include "QuestDumper.hpp" #include "RaceManager.hpp" #include "ReligionManager.hpp" #include "ResistancesDumper.hpp" #include "SizeTextKeys.hpp" #include "SkillsDumper.hpp" #include "SpellsDumper.hpp" #include "StatsDumper.hpp" #include "TextKeys.hpp" #include "TextMessages.hpp" #include "VictoryDumper.hpp" using namespace std; using namespace boost::algorithm; CharacterDumper::CharacterDumper(CreaturePtr new_creature, const uint new_num_cols) : creature(new_creature), num_cols(new_num_cols) { } CharacterDumper::~CharacterDumper() { } string CharacterDumper::str() const { ostringstream ss; Game& game = Game::instance(); Metadata meta; string version = meta.get_game_version_synopsis(); ss << String::centre(version, num_cols) << endl << endl; string name_title_user = TextMessages::get_name_and_title(creature); string user = Environment::get_user_name(); if (!user.empty()) { name_title_user += " (" + user + ")"; } ss << String::centre(name_title_user, num_cols) << endl; ss << get_synopsis() << endl << endl; ss << get_vital_statistics(); StatsDumper stats_dumper(creature, num_cols); ss << stats_dumper.str() << endl << endl; ResistancesDumper res_dumper(creature, num_cols); ss << res_dumper.str() << endl << endl; ModifiersDumper mod_dumper(creature, num_cols); ss << mod_dumper.str() << endl << endl; DeathDumper death_dumper(creature, num_cols); string death = death_dumper.str(); if (!death.empty()) { ss << death << endl << endl; } VictoryDumper victory_dumper(creature, num_cols); string victory = victory_dumper.str(); // Most characters won't be winners - don't add extra newlines to those // that aren't. if (!victory.empty()) { ss << victory << endl << endl; } ConductsDumper conducts_dumper(creature, num_cols); ss << conducts_dumper.str() << endl << endl; MembershipsDumper memberships_dumper(creature, num_cols); ss << memberships_dumper.str() << endl << endl; SkillsDumper skills_dumper(creature, num_cols); ss << skills_dumper.str() << endl << endl; SpellsDumper spells_dumper(creature, num_cols); ss << spells_dumper.str() << endl << endl; QuestDumper quest_dumper(creature, num_cols); ss << quest_dumper.str() << endl << endl; EquipmentDumper equipment_dumper(creature, num_cols); ss << equipment_dumper.str() << endl << endl; InventoryDumper inventory_dumper(creature, num_cols); ss << inventory_dumper.str() << endl << endl; ss << get_carrying_capacity() << endl << endl; ArtifactDumper artifact_dumper(game.get_items_ref(), game.get_item_generation_values_ref(), num_cols); ss << artifact_dumper.str() << endl << endl; AttackDumper attack_dumper(creature, num_cols); ss << attack_dumper.str() << endl << endl; MessageBufferDumper mbd(MM::instance(), num_cols); ss << mbd.str() << endl << endl; MortuaryDumper mortuary_dumper(creature, num_cols); ss << mortuary_dumper.str() << endl << endl; ss << get_party() << endl << endl; ss << StringTable::get(TextKeys::MAXIMUM_DEPTH_REACHED) << ": " << creature->get_max_depth_reached().str(true) << endl << endl; ss << StringTable::get(TextKeys::TURNS) << ": " << creature->get_turns() << endl << endl; double seconds = game.get_total_elapsed_game_time(std::chrono::system_clock::now()); ulonglong secs = static_cast<ulonglong>(seconds) % 60; ulonglong minutes = (static_cast<ulonglong>(seconds) / 60) % 60; ulonglong hours = static_cast<ulonglong>(seconds) / 3600; ss << StringTable::get(TextKeys::TOTAL_ELAPSED_TIME) << ": " << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) << std::setfill('0') << secs << endl << endl; return ss.str(); } // Helper functions string CharacterDumper::get_party() const { ostringstream ss; ss << TextMessages::get_hirelings_hired_message(creature->get_hirelings_hired()) << endl; ss << TextMessages::get_adventurers_joined_message(creature->get_adventurers_joined()) << endl << endl; // Party info Game& game = Game::instance(); MapPtr current_map = game.get_current_map(); if (current_map != nullptr) { ss << StringTable::get(PartyTextKeys::CURRENT_PARTY) << ": "; if (current_map->get_map_type() == MapType::MAP_TYPE_WORLD) { ss << StringTable::get(PartyTextKeys::PARTY_IN_TRANSIT); } else { const CreatureMap& creatures = current_map->get_creatures_ref(); vector<string> follower_descs; for (const auto& c_pair : creatures) { ostringstream ss2; CreaturePtr f = c_pair.second; CharacterDumper cd(f); if (f && f->get_additional_property(CreatureProperties::CREATURE_PROPERTIES_LEADER_ID) == creature->get_id()) { string name = f->get_name(); ss2 << " - "; if (name.empty()) { ss2 << StringTable::get(f->get_short_description_sid()); } else { ss2 << name; } ss2 << " " << "(" << cd.get_synopsis(false) << ")"; follower_descs.push_back(ss2.str()); } } if (follower_descs.empty()) { ss << "-"; } else { ss << endl; for (const string& fdesc : follower_descs) { ss << fdesc << endl; } } } } return ss.str(); } string CharacterDumper::get_synopsis(const bool centre) const { ostringstream ss; string race_id = creature->get_race_id(); string class_id = creature->get_class_id(); ClassManager cm; RaceManager rm; Race* race = rm.get_race(race_id); Class* char_class = cm.get_class(class_id); if (race && char_class) { string race_name = StringTable::get(race->get_race_name_sid()); string class_name = StringTable::get(char_class->get_class_name_sid()); string character_synopsis = "L" + std::to_string(creature->get_level().get_current()) + " " + race_name + " " + class_name; trim_right(character_synopsis); if (centre) { ss << String::centre(character_synopsis, num_cols); } else { ss << character_synopsis; } } return ss.str(); } // Get the creature's vital statistics: age, sex, size, hair, eyes. string CharacterDumper::get_vital_statistics() const { ostringstream ss; vector<string> vl(10); // First, pad the lines: for (string& s : vl) { s = String::add_trailing_spaces(s, num_cols); } // First line string age = StringTable::get(TextKeys::AGE) + ": " + std::to_string(creature->get_age().get_current()); Alignment a; string alignment = StringTable::get(TextKeys::ALIGNMENT) + ": " + StringTable::get(a.get_alignment_sid(creature->get_alignment().get_alignment_range())); string size = StringTable::get(SizeTextKeys::SIZE) + ": " + StringTable::get(SizeTextKeys::get_size_sid_from_creature_size(creature->get_size())); vl.at(0).replace(0, age.size(), age); vl.at(0).replace(30, alignment.size(), alignment); vl.at(0).replace(60, size.size(), size); // Second line ReligionManager rm; string deity_id = creature->get_religion().get_active_deity_id(); string deity = StringTable::get(TextKeys::DEITY) + ": " + StringTable::get(rm.get_deity_name_sid(deity_id)); string hair_colour = StringTable::get(TextKeys::HAIR_COLOUR) + ": " + StringTable::get(ColourTextKeys::get_colour_sid_from_hair_colour(creature->get_hair_colour())); string eye_colour = StringTable::get(TextKeys::EYE_COLOUR) + ": " + StringTable::get(ColourTextKeys::get_colour_sid_from_eye_colour(creature->get_eye_colour())); vl.at(1).replace(0, deity.size(), deity); vl.at(1).replace(30, hair_colour.size(), hair_colour); vl.at(1).replace(60, eye_colour.size(), eye_colour); // Third Line CreatureSex cs = creature->get_sex(); if (cs != CreatureSex::CREATURE_SEX_NOT_SPECIFIED) { string sex = StringTable::get(TextKeys::SEX) + ": " + TextMessages::get_sex(cs); vl.at(2).replace(0, sex.size(), sex); } for (string& s : vl) { trim_right(s); if (!s.empty()) { ss << s << endl; } } ss << endl; return ss.str(); } string CharacterDumper::get_carrying_capacity() const { ostringstream ss; if (creature != nullptr) { ss << StringTable::get(TextKeys::CARRYING_CAPACITY) << ": " << TextMessages::get_carrying_capacity_message(creature); } return ss.str(); }
29.14511
232
0.668146
[ "vector" ]
38f97191106b26b71a8a45955573d8cbe54a9404
900
cc
C++
components/ntp_snippets/mock_content_suggestions_provider_observer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/ntp_snippets/mock_content_suggestions_provider_observer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/ntp_snippets/mock_content_suggestions_provider_observer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 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 "components/ntp_snippets/mock_content_suggestions_provider_observer.h" namespace ntp_snippets { MockContentSuggestionsProviderObserver:: MockContentSuggestionsProviderObserver() = default; MockContentSuggestionsProviderObserver:: ~MockContentSuggestionsProviderObserver() = default; void MockContentSuggestionsProviderObserver::OnNewSuggestions( ContentSuggestionsProvider* provider, Category category, std::vector<ContentSuggestion> suggestions) { std::list<ContentSuggestion> suggestions_list; for (ContentSuggestion& suggestion : suggestions) { suggestions_list.push_back(std::move(suggestion)); } OnNewSuggestions(provider, category, suggestions_list); } } // namespace ntp_snippets
33.333333
79
0.801111
[ "vector" ]
38fc46a91ff5c3561a6d225ccc1458c0ffbe4ba1
2,369
cpp
C++
src/swift2d/materials/HeatSpriteShader.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/materials/HeatSpriteShader.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/materials/HeatSpriteShader.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer // // // // This software may be modified and distributed under the terms // // of the MIT license. See the LICENSE file for details. // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/materials/HeatSpriteShader.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// HeatSpriteShader::HeatSpriteShader() : Shader( R"( // vertex shader --------------------------------------------------------- @include "shifted_instanced_texcoords_quad_vertex_shader" )", R"( // fragment shader ------------------------------------------------------- @include "version" // varyings in vec2 texcoords; flat in int instance_id; // uniforms uniform sampler2D diffuse; uniform float opacity[100]; uniform mat3 heat_transform[100]; layout (location = 0) out vec4 fragColor; void main(void) { vec3 dir = texture(diffuse, texcoords).rga; dir.xy = (heat_transform[instance_id] * vec3(dir.xy-0.5, 0.0)).xy + 0.5; fragColor = vec4(dir.xy, 0, dir.z*opacity[instance_id]); } )" ) , projection(get_uniform<math::mat3>("projection")) , transform(get_uniform<math::mat3>("transform")) , heat_transform(get_uniform<math::mat3>("heat_transform")) , depth(get_uniform<float>("depth")) , parallax(get_uniform<float>("parallax")) , diffuse(get_uniform<int>("diffuse")) , texcoord_offset_scale(get_uniform<math::vec4>("texcoord_offset_scale")) , opacity(get_uniform<float>("opacity")) {} //////////////////////////////////////////////////////////////////////////////// }
40.152542
80
0.398902
[ "transform" ]
ac024c87823ed6f9f2a43295fac3131d279b9a31
5,545
cpp
C++
qbGradient.cpp
QuantitativeBytes/qbGradient
ca0f9d519f164daf1992deeae3008c76212937ee
[ "MIT" ]
3
2021-11-02T18:39:15.000Z
2021-12-22T10:15:06.000Z
qbGradient.cpp
QuantitativeBytes/qbGradient
ca0f9d519f164daf1992deeae3008c76212937ee
[ "MIT" ]
null
null
null
qbGradient.cpp
QuantitativeBytes/qbGradient
ca0f9d519f164daf1992deeae3008c76212937ee
[ "MIT" ]
1
2021-11-02T18:39:17.000Z
2021-11-02T18:39:17.000Z
/* ************************************************************************ qbGradient class implementation. qbGradient is a simple implementation of the gradient descent method for numerical optimization, intended to demonstrate the principles of the method for educational purposes. The code utilizes function pointers so that the user can specify an external object function to be minimized that can take any form over any number of variables. The code is intended to be studied along side the corresponding videos on the QuantitativeBytes YouTube channel. The specific videos relating to this code may be found here: Episode 1 - The theory of the gradient descent technique: https://youtu.be/BjkmFVv4ccw Episode 2 - Basic implementation in C++: https://youtu.be/eyCq3cNFpMU The QuantitativeBytes YouTube channel may be found here: www.youtube.com/c/QuantitativeBytes As this code is paired with the corresponding videos, pull requests will not be accepted. MIT LICENSE Copyright (c) 2021 Michael Bennett 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 "qbGradient.hpp" #include <iostream> #include <fstream> #include <math.h> // Constructor. qbGradient::qbGradient() { // Set defaults. m_nDims = 0; m_stepSize = 0.0; m_maxIter = 1; m_h = 0.001; m_gradientThresh = 1e-09; } // Destructor. qbGradient::~qbGradient() { // Tidy up anything that needs tidying up... } // Function to set the object function. void qbGradient::SetObjectFcn(std::function<double(std::vector<double>*)> objectFcn) { m_objectFcn = objectFcn; } // Function to set the start point. // Note that this also sets the number of degrees of freedom. void qbGradient::SetStartPoint(const std::vector<double> startPoint) { // Copy the start point. m_startPoint = startPoint; // Determine the number of degrees of freedom. m_nDims = m_startPoint.size(); } // Function to set the step size. void qbGradient::SetStepSize(double stepSize) { m_stepSize = stepSize; } // Function to set the maximum number of iterations. void qbGradient::SetMaxIterations(int maxIterations) { m_maxIter = maxIterations; } // Function to set the gradient magnitude threshold (stopping condition). // The optimization stops when the gradient magnitude falls below this value. void qbGradient::SetGradientThresh(double gradientThresh) { m_gradientThresh = gradientThresh; } // Function to perform the actual optimization. bool qbGradient::Optimize(std::vector<double> *funcLoc, double *funcVal) { // Set the currentPoint to the startPoint. m_currentPoint = m_startPoint; // Loop up to max iterations or until threshold reached. int iterCount = 0; double gradientMagnitude = 1.0; while ((iterCount < m_maxIter) && (gradientMagnitude > m_gradientThresh)) { // Compute the gradient vector. std::vector<double> gradientVector = ComputeGradientVector(); gradientMagnitude = ComputeGradientMagnitude(gradientVector); // Compute the new point. std::vector<double> newPoint = m_currentPoint; for (int i=0; i<m_nDims; ++i) { newPoint[i] += -(gradientVector[i] * m_stepSize); } // Update the current point. m_currentPoint = newPoint; // Increment the iteration counter. iterCount++; } // Return the results. *funcLoc = m_currentPoint; *funcVal = m_objectFcn(&m_currentPoint); return 0; } /* Function to compute the gradient of the object function in the specified dimension. */ double qbGradient::ComputeGradient(int dim) { // Make a copy of the current location. std::vector<double> newPoint = m_currentPoint; // Modify the copy, according to h and dim. newPoint[dim] += m_h; // Compute the two function values for these points. double funcVal1 = m_objectFcn(&m_currentPoint); double funcVal2 = m_objectFcn(&newPoint); // Compute the approximate numerical gradient. return (funcVal2 - funcVal1) / m_h; } // Function to compute the gradient vector. std::vector<double> qbGradient::ComputeGradientVector() { std::vector<double> gradientVector = m_currentPoint; for (int i=0; i<m_nDims; ++i) gradientVector[i] = ComputeGradient(i); return gradientVector; } // Function to compute the gradient magnitude. double qbGradient::ComputeGradientMagnitude(std::vector<double> gradientVector) { double vectorMagnitude = 0.0; for (int i=0; i<m_nDims; ++i) vectorMagnitude += gradientVector[i] * gradientVector[i]; return sqrt(vectorMagnitude); }
30.13587
84
0.728224
[ "object", "vector" ]
f199f139d2d33a2c8bf7317d9f8019f5c66a2203
12,440
cpp
C++
MapReaderV2/UE3/FStaticMesh.cpp
balannarcis96/skylake-tools
e1ff6308d250f81397a85ab6012cc4dc10e06228
[ "MIT" ]
3
2020-05-18T14:37:07.000Z
2020-12-24T08:49:34.000Z
MapReaderV2/UE3/FStaticMesh.cpp
balannarcis96/skylake-tools
e1ff6308d250f81397a85ab6012cc4dc10e06228
[ "MIT" ]
null
null
null
MapReaderV2/UE3/FStaticMesh.cpp
balannarcis96/skylake-tools
e1ff6308d250f81397a85ab6012cc4dc10e06228
[ "MIT" ]
null
null
null
#include "FStaticMesh.h" #include "UObject.h" #include "FLightMap.h" #include "D3D.h" #include <fstream> FVert::FVert() { } FVert::FVert(FIStream * stream) :FReadable(stream) { pVertex = stream->ReadInt32(); iSide = stream->ReadInt32(); shadowTexCoord = FVector2(stream); backfaceShadowTexCoord = FVector2(stream); } FPositionVertexData::FPositionVertexData() { vertices = nullptr; } FPositionVertexData::FPositionVertexData(FIStream * stream) :FReadable(stream) { stride = stream->ReadInt32(); count = stream->ReadInt32(); int32 temp = stream->ReadInt32(); if (temp != stride) { throw "FPositionVertexData::Incorrect stride "; } temp = stream->ReadInt32(); if (temp != count) { throw "FPositionVertexData::Incorrect count "; } if (stride != sizeof(D3DXVECTOR3)) { throw "FPositionVertexData::Unknown stride"; } if (stride && count) { vertices = new D3DXVECTOR3[count]; stream->Read((uint8*)vertices, sizeof(D3DXVECTOR3)* count); } } FPositionVertexData::~FPositionVertexData() { if (vertices) { delete[] vertices; vertices = nullptr; } } FUVVertexData::FUVVertexData() { } FUVVertexData::FUVVertexData(FIStream * stream) :FReadable(stream) { numUVStets = stream->ReadInt32(); stride = stream->ReadInt32(); numUVs = stream->ReadInt32(); bUseFullUVs = stream->ReadInt32(); size = 0; int32 temp = stream->ReadInt32(); if (temp != stride) { throw "Error, incorrect textstride"; } temp = stream->ReadInt32(); if (temp != numUVs) { throw "Error, incorrect textcount"; } if (bUseFullUVs) { switch (numUVStets) { case 1: { size = sizeof(FUVFloat1); }break; case 2: { size = sizeof(FUVFloat2); }break; case 3: { size = sizeof(FUVFloat3); }break; case 4: { size = sizeof(FUVFloat4); }break; default: break; } } else { switch (numUVStets) { case 1: { size = sizeof(FUVHalf1); }break; case 2: { size = sizeof(FUVHalf2); }break; case 3: { size = sizeof(FUVHalf3); }break; case 4: { size = sizeof(FUVHalf4); }break; default: break; } } if (!size) { throw "Invalid UVs count"; } if (numUVs) { data = new uint8[size * numUVs]; stream->Read(data, size* numUVs); } } FUVVertexData::~FUVVertexData() { if (data) { delete[] data; data = nullptr; } } FStaticMeshSection::FStaticMeshSection() { indexBuffer = nullptr; indices = nullptr; } FStaticMeshSection::FStaticMeshSection(FIStream * stream) :FReadable(stream) { material = stream->ReadInt32(); enableCollision = stream->ReadInt32(); oldEnableCollision = stream->ReadInt32(); bEnableShadowCasting = stream->ReadInt32(); firstIndex = stream->ReadInt32(); faceCount = stream->ReadInt32(); minVertexIndex = stream->ReadInt32(); maxVertexIndex = stream->ReadInt32(); materialIndex = stream->ReadInt32(); fragmentCount = stream->ReadInt32(); if (fragmentCount) { fragments.push_back(FFragmentRange(stream)); } indexBuffer = nullptr; indices = nullptr; } FStaticMeshSection::~FStaticMeshSection() { if (indexBuffer) { indexBuffer->Release(); indexBuffer = nullptr; } if (indices) { delete[]indices; indices = nullptr; } } void FStaticMeshSection::Init(FMultiSizeIndexContainer * indexContainer) { if (faceCount == 0) { return; } indexCount = faceCount * 3; if (indexContainer->elementSize == sizeof(uint16)) { indices = (uint8*)malloc(sizeof(uint16) * indexCount); indexSize = sizeof(uint16); uint16 * lodIndices = (uint16 *)indexContainer->rawData; uint16 * _indices = (uint16*)indices; for (uint32 faceIndex = 0; faceIndex < faceCount; faceIndex++) { _indices[faceIndex * 3 + 0] = lodIndices[firstIndex + ((faceIndex * 3) + 0)]; _indices[faceIndex * 3 + 1] = lodIndices[firstIndex + ((faceIndex * 3) + 1)]; _indices[faceIndex * 3 + 2] = lodIndices[firstIndex + ((faceIndex * 3) + 2)]; } dxgiFormat = DXGI_FORMAT_R16_UINT; } else if (indexContainer->elementSize == sizeof(uint32)) { indexSize = sizeof(uint32); indices = (uint8*)malloc(sizeof(uint32) * indexCount); uint32 * lodIndices = (uint32*)indexContainer->rawData; uint32 * _indices = (uint32*)indices; for (uint32 faceIndex = 0; faceIndex < faceCount; faceIndex++) { _indices[faceIndex * 3 + 0] = lodIndices[firstIndex + ((faceIndex * 3) + 0)]; _indices[faceIndex * 3 + 1] = lodIndices[firstIndex + ((faceIndex * 3) + 1)]; _indices[faceIndex * 3 + 2] = lodIndices[firstIndex + ((faceIndex * 3) + 2)]; } dxgiFormat = DXGI_FORMAT_R32_UINT; } else { throw std::exception("Unknown index size"); } auto* d3dDevice = GetD3DDevice(); D3D11_BUFFER_DESC bDesc; ZeroMemory(&bDesc, sizeof(bDesc)); bDesc.Usage = D3D11_USAGE_DEFAULT; bDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bDesc.ByteWidth = indexSize* indexCount; D3D11_SUBRESOURCE_DATA bData; ZeroMemory(&bData, sizeof(bData)); bData.pSysMem = indices; HRESULT result = d3dDevice->CreateBuffer(&bDesc, &bData, &indexBuffer); if (FAILED(result)) { throw std::exception("Failed to create index buffer"); } } void FStaticMeshSection::Render(ID3D11DeviceContext* context) { if (!indexCount) { return; } if (!fragmentCount || !fragments[0].numPrimitives) { return; } context->IASetIndexBuffer(indexBuffer, dxgiFormat, 0); context->DrawIndexed(indexCount, 0, 0); } FStaticColorData::FStaticColorData() { } FStaticColorData::FStaticColorData(FIStream * stream) :FReadable(stream) { stride = stream->ReadInt32(); count = stream->ReadInt32(); if (stride != 4) { throw "FStaticColorData::Incorrect colorstride"; } int32 temp = stream->ReadInt32(); if (temp != stride) { throw "FStaticColorData::Colorstride missamtch"; } temp = stream->ReadInt32(); if (temp != count) { throw "FStaticColorData::Color count missamtch"; } if (stride && count) { data = new uint8[stride * count]; stream->Read(data, stride* count); } } FStaticColorData::~FStaticColorData() { if (data) { delete[] data; data = nullptr; } } FStaticMeshComponentLODInfo::FStaticMeshComponentLODInfo() { } FStaticMeshComponentLODInfo::FStaticMeshComponentLODInfo(FIStream * stream) :FReadable(stream) { shadowMaps = FArray<UObject*>(stream); shadowVertexBuffers = FArray<UObject*>(stream); lightMap = FLightMap::FromStream(stream); unkShadowMap = UObject::ReadFromStream(stream); } FStaticMeshComponentLODInfo::~FStaticMeshComponentLODInfo() { if (lightMap) { delete lightMap; lightMap = nullptr; } } FStaticLodInfo::FStaticLodInfo() :FReadable() { vertices = nullptr; possitionBuffer = nullptr; vertexBuffer = nullptr; legacyEdges = nullptr; indexContainer = nullptr; textureBuffer = nullptr; } void ReadFStaticLodInfo(FIStream * stream, FStaticLodInfo* lod) { int32 bulkDataCount, bulkDataSize; stream->ReadInt32(); bulkDataCount = stream->ReadInt32(); bulkDataSize = stream->ReadInt32(); stream->ReadInt32(); if (bulkDataCount && bulkDataSize) { throw std::exception("Unk data found!!"); return; } lod->sectionsCount = stream->ReadInt32(); if (lod->sectionsCount) { lod->sections = new FStaticMeshSection[lod->sectionsCount]; for (int32 i = 0; i < lod->sectionsCount; i++) { lod->sections[i] = FStaticMeshSection(stream); } } lod->possitionBuffer = new FPositionVertexData(stream); lod->textureBuffer = new FUVVertexData(stream); lod->colorBuffer = FStaticColorData(stream); lod->numVertices = stream->ReadInt32(); lod->indexContainer = new FMultiSizeIndexContainer(stream); lod->wireframeIndexBuffer = FMultiSizeIndexContainer(stream); int32 test = stream->ReadInt32(); if (test != sizeof(FEdge)) { throw std::exception("Incorrect FEdge size"); return; } lod->legacyEdgeCount = stream->ReadInt32(); if (lod->legacyEdgeCount) { lod->legacyEdges = new FEdge[lod->legacyEdgeCount]; stream->Read((uint8*)lod->legacyEdges, lod->legacyEdgeCount * sizeof(FEdge)); } test = stream->ReadInt32(); if (test) { throw std::exception("unk ending"); } } FStaticLodInfo::FStaticLodInfo(FIStream * stream) :FReadable(stream) { vertices = nullptr; possitionBuffer = nullptr; vertexBuffer = nullptr; textureBuffer = nullptr; indexContainer = nullptr; legacyEdges = nullptr; } FStaticLodInfo::~FStaticLodInfo() { if (vertexBuffer) { vertexBuffer->Release(); vertexBuffer = nullptr; } if (legacyEdges) { delete[] legacyEdges; legacyEdges = nullptr; } if (vertices) { delete[] vertices; vertices = nullptr; } if (possitionBuffer) { delete possitionBuffer; possitionBuffer = nullptr; } if (textureBuffer) { delete textureBuffer; textureBuffer = nullptr; } if (indexContainer) { delete indexContainer; indexContainer = nullptr; } } void FStaticLodInfo::Render(bool defaultVBuffer) { auto* d3dDeviceContext = GetD3DDeviceContext(); if (defaultVBuffer) { UINT offset = 0; UINT stride = sizeof(D3DVertex); d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); d3dDeviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset); } for (int32 i = 0; i < sectionsCount; i++) { sections[i].Render(d3dDeviceContext); } } void FStaticLodInfo::Init() { if (!numVertices) { return; } float scale = 0.1f; HRESULT result; vertices = new D3DVertex[numVertices]; ZeroMemory(vertices, sizeof(D3DVertex)* numVertices); D3DVertex* v = vertices; D3DXVECTOR3 * pos = possitionBuffer->vertices; for (uint32 i = 0; i < numVertices; i++, pos++, v++) { //v->position.x = pos->y; //-pos->y; pos->x //v->position.y = pos->z; // pos->z; pos->y //v->position.z = pos->x; // pos->x; pos->z v->position.x = pos->x; v->position.y = pos->y; v->position.z = pos->z; if (textureBuffer->bUseFullUVs) { if (textureBuffer->numUVStets == 2) { FUVFloat2 * cuvs = (FUVFloat2 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else if (textureBuffer->numUVStets == 3) { FUVFloat3 * cuvs = (FUVFloat3 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else if (textureBuffer->numUVStets == 4) { FUVFloat4 * cuvs = (FUVFloat4 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else { if (textureBuffer->numUVStets != 1) { throw std::exception("unexptected uv count"); } FUVFloat1 * cuvs = (FUVFloat1 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs.uv[0]; v->uv.y = cuvs[i].UVs.uv[1]; } } else { if (textureBuffer->numUVStets == 2) { FUVHalf2* cuvs = (FUVHalf2 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else if (textureBuffer->numUVStets == 3) { FUVHalf3* cuvs = (FUVHalf3 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else if (textureBuffer->numUVStets == 4) { FUVHalf3* cuvs = (FUVHalf3 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs[0].uv[0]; v->uv.y = cuvs[i].UVs[0].uv[1]; } else { if (textureBuffer->numUVStets != 1) { throw std::exception("unexptected uv count"); } FUVHalf1 * cuvs = (FUVHalf1 *)textureBuffer->data; _UnpackNormal(cuvs[i].normal[1].normal, &v->normal); v->uv.x = cuvs[i].UVs.uv[0]; v->uv.y = cuvs[i].UVs.uv[1]; } } } delete possitionBuffer; possitionBuffer = nullptr; for (int32 i = 0; i < sectionsCount; i++) { sections[i].Init(indexContainer); } D3D11_BUFFER_DESC bDesc; ZeroMemory(&bDesc, sizeof(bDesc)); bDesc.Usage = D3D11_USAGE_DEFAULT; bDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bDesc.ByteWidth = sizeof(D3DVertex) * numVertices; bDesc.StructureByteStride = 0; bDesc.CPUAccessFlags = 0; bDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA bData; bData.pSysMem = vertices; bData.SysMemPitch = 0; bData.SysMemSlicePitch = 0; auto* d3dDevice = GetD3DDevice(); result = d3dDevice->CreateBuffer(&bDesc, &bData, &vertexBuffer); if (FAILED(result)) { throw std::exception("Failed to create vertex buffer"); } }
22.017699
82
0.674035
[ "render" ]
f19a62364ab1c27590ccf38dbddf14f1268b4cb8
7,596
cpp
C++
src/main.cpp
Gnarwhal/LudumDare44
a09e60a57cd7da22d401651ae4b9fbe3f7389ab0
[ "MIT" ]
null
null
null
src/main.cpp
Gnarwhal/LudumDare44
a09e60a57cd7da22d401651ae4b9fbe3f7389ab0
[ "MIT" ]
null
null
null
src/main.cpp
Gnarwhal/LudumDare44
a09e60a57cd7da22d401651ae4b9fbe3f7389ab0
[ "MIT" ]
null
null
null
/******************************************************************************* * * Copyright (c) 2019 Gnarly Narwhal * * ----------------------------------------------------------------------------- * * 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 <iostream> #include <chrono> #include "geno/GenoInts.h" #include "geno/GenoMacros.h" #include "geno/math/linear/GenoMatrix4.h" #include "geno/thread/GenoTime.h" #include "geno/engine/GenoEngine.h" #include "geno/engine/GenoLoop.h" #include "geno/engine/GenoInput.h" #include "geno/engine/GenoWindow.h" #include "geno/engine/GenoCamera2D.h" #include "geno/gl/GenoGL.h" #include "geno/gl/GenoFramebuffer.h" #include "geno/gl/GenoVao.h" #include "geno/shaders/GenoShader2c.h" #include "geno/audio/GenoAudioDevice.h" #include "geno/audio/GenoAudioSource.h" #include "geno/audio/GenoAudioBuffer.h" #include "pinball/shaders/GlowShader.h" #include "pinball/Scene.h" #include "pinball/Image.h" #include "pinball/Intro.h" #include "pinball/Level.h" #include "pinball/levels/StartSplash.h" #include "pinball/levels/Info1.h" #include "pinball/levels/IntroLevel.h" #include "pinball/levels/Info2.h" #include "pinball/levels/Level1.h" #include "pinball/levels/Level2.h" #include "pinball/levels/Win.h" bool init(); void begin(); void loop(); void load(uint32 level); void update(); void render(); void cleanup(); bool toggle = true; GenoWindow * window; GenoCamera2D * camera; GenoFramebuffer * framebuffer1; GenoFramebuffer * framebuffer2; GlowShader * glow; GenoVao * vao; GenoAudioSource * source; GenoAudioBuffer * audio; Image * image; Scene * scene; int32 main(int32 argc, char ** argv) { init(); begin(); cleanup(); /////// TIME TRIALS - LEAVE FOR FUTURE USE /////// /* const uint32 NUM_ITERATIONS = 1000000; auto begin1 = std::chrono::high_resolution_clock::now(); auto end1 = std::chrono::high_resolution_clock::now(); auto begin2 = std::chrono::high_resolution_clock::now(); auto end2 = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end1 - begin1).count() << std::endl; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end2 - begin2).count() << std::endl; */ return 0; } bool init() { GenoEngine::init(); GenoMonitor * monitor = GenoMonitors::getPrimaryMonitor(); GenoVideoMode * videoMode = monitor->getDefaultVideoMode(); GenoLoopCreateInfo loopInfo = {}; loopInfo.targetFps = videoMode->getRefreshRate(); loopInfo.deltaScale = 1; loopInfo.callback = loop; loopInfo.numSubLoops = 0; loopInfo.subLoops = 0; GenoEngine::setLoop(loopInfo); int32 winHints[] = { GLFW_CONTEXT_VERSION_MAJOR, 3, GLFW_CONTEXT_VERSION_MINOR, 3, GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE, GLFW_SAMPLES, 4 }; GenoWindowCreateInfo winInfo = {}; winInfo.defaultPosition = true; winInfo.fullscreen = true; winInfo.title = "Genome"; winInfo.numHints = GENO_ARRAY_SIZE(winHints) / 2; winInfo.hints = winHints; winInfo.depth = false; winInfo.clearRed = 0; winInfo.clearGreen = 0; winInfo.clearBlue = 0; window = GenoWindow::create(winInfo); if (window == 0) { std::cerr << "Window creation failed!" << std::endl; GenoEngine::stopLoop(); return false; } window->activate(); GenoEngine::setSwapInterval(1); GenoEngine::initGlew(); glEnable(GL_MULTISAMPLE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); camera = new GenoCamera2D(0, 1920, 1080, 0, 0, 1); uint32 textureParams[] = { GL_TEXTURE_MIN_FILTER, GL_NEAREST, GL_TEXTURE_MAG_FILTER, GL_NEAREST, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE }; GenoFramebufferCreateInfo bufferInfo = {}; bufferInfo.width = videoMode->getWidth(); bufferInfo.height = videoMode->getHeight(); bufferInfo.numColorAttachments = 1; bufferInfo.depthAttachmentType = GENO_FRAMEBUFFER_DEPTH_BUFFER; bufferInfo.numTextureParams = GENO_ARRAY_SIZE(textureParams) / 2; bufferInfo.textureParams = textureParams; framebuffer1 = new GenoFramebuffer(bufferInfo); framebuffer2 = new GenoFramebuffer(bufferInfo); glow = new GlowShader(); float vertices[] = { 1, -1, 0, // Top left 1, 1, 0, // Bottom left -1, 1, 0, // Bottom right -1, -1, 0 // Top right }; uint32 indices[] = { 0, 1, 3, 1, 2, 3 }; float texCoords[] = { 1, 0, 1, 1, 0, 1, 0, 0 }; vao = new GenoVao(4, vertices, 6, indices); vao->addAttrib(4, 2, texCoords); GenoAudioDevices::getDefaultOutputDevice()->setActive(); audio = new GenoAudioBuffer("res/audio/harp.wav"); source = new GenoAudioSource(audio); source->loop(true); source->play(); Scene::init(); Intro::init(camera); Level::init(camera); Info::init(camera); load(0); image = new Image(camera, { 1, 1 }, { 5, 5 }, "res/img/Background.png"); return true; } void begin() { GenoEngine::startLoop(); } void loop() { update(); render(); } void load(uint32 level) { using SceneLoader = Scene * (*)(GenoCamera2D *, GlowShader *); const static SceneLoader loaders[] = { loadSplash, loadInfo1, loadIntroLevel, loadInfo2, loadLevel1, loadLevel2, loadWin }; if (level == GENO_ARRAY_SIZE(loaders)) GenoEngine::stopLoop(); else { delete scene; scene = loaders[level](camera, glow); } } void update() { if (window->shouldClose()) GenoEngine::stopLoop(); scene->update(); if (scene->isComplete()) load(scene->nextScene()); camera->update(); } void render() { framebuffer1->bind(); GenoFramebuffer::clear(); scene->renderGlow(); framebuffer2->bind(); GenoFramebuffer::clear(); framebuffer1->getColorTexture()->bind(); image->getTexture()->bind(1); glow->enable(); glow->setMvp(GenoMatrix4f::makeIdentity()); glow->setResolution(window->getWidth(), window->getHeight()); glow->setHorizontal(true); vao->render(); GenoFramebuffer::bindDefault(); GenoFramebuffer::clear(); framebuffer2->getColorTexture()->bind(); scene->bindBackground(1); glow->enable(); glow->setMvp(GenoMatrix4f::makeIdentity()); glow->setResolution(window->getWidth(), window->getHeight()); glow->setHorizontal(false); vao->render(); scene->render(); window->swap(); } void cleanup() { delete image; delete scene; delete vao; delete glow; delete framebuffer1; delete framebuffer2; delete camera; delete window; GenoEngine::destroy(); }
25.575758
104
0.685361
[ "render" ]
f19da41b8de48d83d740741d2528d3183626422c
11,914
cpp
C++
moveit_planners/pilz_industrial_motion_planner/src/velocity_profile_atrap.cpp
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
1,116
2016-07-29T06:39:49.000Z
2022-03-31T08:42:14.000Z
moveit_planners/pilz_industrial_motion_planner/src/velocity_profile_atrap.cpp
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
2,784
2016-07-29T15:19:38.000Z
2022-03-31T01:35:59.000Z
moveit_planners/pilz_industrial_motion_planner/src/velocity_profile_atrap.cpp
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
956
2016-07-30T17:03:44.000Z
2022-03-31T15:48:31.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2018 Pilz GmbH & Co. KG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Pilz GmbH & Co. KG nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include "pilz_industrial_motion_planner/velocity_profile_atrap.h" namespace pilz_industrial_motion_planner { VelocityProfileATrap::VelocityProfileATrap(double max_vel, double max_acc, double max_dec) : max_vel_(fabs(max_vel)) , max_acc_(fabs(max_acc)) , max_dec_(fabs(max_dec)) , start_pos_(0) , end_pos_(0) , start_vel_(0) , a1_(0) , a2_(0) , a3_(0) , b1_(0) , b2_(0) , b3_(0) , c1_(0) , c2_(0) , c3_(0) , t_a_(0) , t_b_(0) , t_c_(0) { } void VelocityProfileATrap::SetProfile(double pos1, double pos2) { start_pos_ = pos1; end_pos_ = pos2; start_vel_ = 0.0; if (start_pos_ == end_pos_) { // goal already reached, set everything to zero setEmptyProfile(); return; } else { // get the sign double s = ((end_pos_ - start_pos_) > 0.0) - ((end_pos_ - start_pos_) < 0.0); double dis = fabs(end_pos_ - start_pos_); double min_dis_max_vel = 0.5 * max_vel_ * max_vel_ / max_acc_ + 0.5 * max_vel_ * max_vel_ / max_dec_; // max_vel can be reached if (dis > min_dis_max_vel) { // acceleration phase a1_ = start_pos_; a2_ = 0.0; a3_ = s * max_acc_ / 2.0; t_a_ = max_vel_ / max_acc_; // constant phase b1_ = a1_ + a3_ * t_a_ * t_a_; b2_ = s * max_vel_; b3_ = 0; t_b_ = (dis - min_dis_max_vel) / max_vel_; // deceleration phase c1_ = b1_ + b2_ * (t_b_); c2_ = s * max_vel_; c3_ = -s * max_dec_ / 2.0; t_c_ = max_vel_ / max_dec_; } // max_vel cannot be reached, no constant velocity phase else { // compute the new velocity of constant phase double new_vel = s * sqrt(2.0 * dis * max_acc_ * max_dec_ / (max_acc_ + max_dec_)); // acceleration phase a1_ = start_pos_; a2_ = 0.0; a3_ = s * max_acc_ / 2.0; t_a_ = fabs(new_vel) / max_acc_; // constant phase b1_ = a1_ + a3_ * t_a_ * t_a_; b2_ = new_vel; b3_ = 0; t_b_ = 0.0; // deceleration phase c1_ = b1_; c2_ = new_vel; c3_ = -s * max_dec_ / 2.0; t_c_ = fabs(new_vel) / max_dec_; } } } void VelocityProfileATrap::SetProfileDuration(double pos1, double pos2, double duration) { // compute the fastest case SetProfile(pos1, pos2); // cannot be faster if (Duration() > duration) { return; } double ratio = Duration() / duration; a2_ *= ratio; a3_ *= ratio * ratio; b2_ *= ratio; b3_ *= ratio * ratio; c2_ *= ratio; c3_ *= ratio * ratio; t_a_ /= ratio; t_b_ /= ratio; t_c_ /= ratio; } bool VelocityProfileATrap::setProfileAllDurations(double pos1, double pos2, double duration1, double duration2, double duration3) { // compute the fastest case SetProfile(pos1, pos2); assert(duration1 > 0); assert(duration3 > 0); // cannot be faster if (Duration() - (duration1 + duration2 + duration3) > KDL::epsilon) { return false; } // get the sign double s = ((end_pos_ - start_pos_) > 0.0) - ((end_pos_ - start_pos_) < 0.0); // compute the new velocity/acceleration/decel4eration double dis = fabs(end_pos_ - start_pos_); double new_vel = s * dis / (duration2 + duration1 / 2.0 + duration3 / 2.0); double new_acc = new_vel / duration1; double new_dec = -new_vel / duration3; if ((fabs(new_vel) - max_vel_ > KDL::epsilon) || (fabs(new_acc) - max_acc_ > KDL::epsilon) || (fabs(new_dec) - max_dec_ > KDL::epsilon)) { return false; } else { // set profile start_pos_ = pos1; end_pos_ = pos2; // acceleration phase a1_ = start_pos_; a2_ = 0.0; a3_ = new_acc / 2.0; t_a_ = duration1; // constant phase b1_ = a1_ + a3_ * t_a_ * t_a_; b2_ = new_vel; b3_ = 0; t_b_ = duration2; // deceleration phase c1_ = b1_ + b2_ * (t_b_); c2_ = new_vel; c3_ = new_dec / 2.0; t_c_ = duration3; return true; } } bool VelocityProfileATrap::setProfileStartVelocity(double pos1, double pos2, double vel1) { if (vel1 == 0) { SetProfile(pos1, pos2); return true; } // get the sign double s = ((pos2 - pos1) > 0.0) - ((pos2 - pos1) < 0.0); if (s * vel1 <= 0) { // TODO initial velocity is in opposite derection of start-end vector return false; } start_pos_ = pos1; end_pos_ = pos2; start_vel_ = vel1; // minimum brake distance double min_brake_dis = 0.5 * vel1 * vel1 / max_dec_; // minimum distance to reach the maximum velocity double min_dis_max_vel = 0.5 * (max_vel_ - start_vel_) * (max_vel_ + start_vel_) / max_acc_ + 0.5 * max_vel_ * max_vel_ / max_dec_; double dis = fabs(end_pos_ - start_pos_); // brake, acceleration in opposite direction, deceleration if (dis <= min_brake_dis) { // brake to zero velocity t_a_ = fabs(start_vel_ / max_dec_); a1_ = start_pos_; a2_ = start_vel_; a3_ = -0.5 * s * max_dec_; // compute the velocity in opposite direction double new_vel = -s * sqrt(2.0 * fabs(min_brake_dis - dis) * max_acc_ * max_dec_ / (max_acc_ + max_dec_)); // acceleration in opposite direction t_b_ = fabs(new_vel / max_acc_); b1_ = a1_ + a2_ * t_a_ + a3_ * t_a_ * t_a_; b2_ = 0; b3_ = -s * 0.5 * max_acc_; // deceleration to zero t_c_ = fabs(new_vel / max_dec_); c1_ = b1_ + b2_ * t_b_ + b3_ * t_b_ * t_b_; c2_ = new_vel; c3_ = 0.5 * s * max_dec_; } else if (dis <= min_dis_max_vel) { // compute the reached velocity double new_vel = s * sqrt((dis + 0.5 * start_vel_ * start_vel_ / max_acc_) * 2.0 * max_acc_ * max_dec_ / (max_acc_ + max_dec_)); // acceleration to new velocity t_a_ = fabs(new_vel - start_vel_) / max_acc_; a1_ = start_pos_; a2_ = start_vel_; a3_ = 0.5 * s * max_acc_; // no constant velocity phase t_b_ = 0; b1_ = a1_ + a2_ * t_a_ + a3_ * t_a_ * t_a_; b2_ = 0; b3_ = 0; // deceleration to zero velocity t_c_ = fabs(new_vel / max_dec_); c1_ = b1_; c2_ = new_vel; c3_ = -0.5 * s * max_dec_; } else { // acceleration to max velocity t_a_ = fabs(max_vel_ - start_vel_) / max_acc_; a1_ = start_pos_; a2_ = start_vel_; a3_ = 0.5 * s * max_acc_; // constant velocity t_b_ = (dis - min_dis_max_vel) / max_vel_; b1_ = a1_ + a2_ * t_a_ + a3_ * t_a_ * t_a_; b2_ = max_vel_; b3_ = 0; // deceleration to zero velocity t_c_ = max_vel_ / max_dec_; c1_ = b1_ + b2_ * t_b_ + b3_ * t_b_ * t_b_; c2_ = max_vel_; c3_ = -0.5 * s * max_dec_; } return true; } double VelocityProfileATrap::Duration() const { return t_a_ + t_b_ + t_c_; } double VelocityProfileATrap::Pos(double time) const { if (time < 0) { return start_pos_; } else if (time < t_a_) { return a1_ + time * (a2_ + a3_ * time); } else if (time < (t_a_ + t_b_)) { return b1_ + (time - t_a_) * (b2_ + b3_ * (time - t_a_)); } else if (time <= (t_a_ + t_b_ + t_c_)) { return c1_ + (time - t_a_ - t_b_) * (c2_ + c3_ * (time - t_a_ - t_b_)); } else { return end_pos_; } } double VelocityProfileATrap::Vel(double time) const { if (time < 0) { return start_vel_; } else if (time < t_a_) { return a2_ + 2 * a3_ * time; } else if (time < (t_a_ + t_b_)) { return b2_ + 2 * b3_ * (time - t_a_); } else if (time <= (t_a_ + t_b_ + t_c_)) { return c2_ + 2 * c3_ * (time - t_a_ - t_b_); } else { return 0; } } double VelocityProfileATrap::Acc(double time) const { if (time <= 0) { return 0; } else if (time <= t_a_) { return 2 * a3_; } else if (time <= (t_a_ + t_b_)) { return 2 * b3_; } else if (time <= (t_a_ + t_b_ + t_c_)) { return 2 * c3_; } else { return 0; } } KDL::VelocityProfile* VelocityProfileATrap::Clone() const { VelocityProfileATrap* trap = new VelocityProfileATrap(max_vel_, max_acc_, max_dec_); trap->setProfileAllDurations(this->start_pos_, this->end_pos_, this->t_a_, this->t_b_, this->t_c_); return trap; } // LCOV_EXCL_START // No tests for the print function void VelocityProfileATrap::Write(std::ostream& os) const { os << *this; } std::ostream& operator<<(std::ostream& os, const VelocityProfileATrap& p) { os << "Asymmetric Trapezoid " << std::endl << "maximal velocity: " << p.max_vel_ << std::endl << "maximal acceleration: " << p.max_acc_ << std::endl << "maximal deceleration: " << p.max_dec_ << std::endl << "start position: " << p.start_pos_ << std::endl << "end position: " << p.end_pos_ << std::endl << "start velocity: " << p.start_vel_ << std::endl << "a1: " << p.a1_ << std::endl << "a2: " << p.a2_ << std::endl << "a3: " << p.a3_ << std::endl << "b1: " << p.b1_ << std::endl << "b2: " << p.b2_ << std::endl << "b3: " << p.b3_ << std::endl << "c1: " << p.c1_ << std::endl << "c2: " << p.c2_ << std::endl << "c3: " << p.c3_ << std::endl << "firstPhaseDuration " << p.firstPhaseDuration() << std::endl << "secondPhaseDuration " << p.secondPhaseDuration() << std::endl << "thirdPhaseDuration " << p.thirdPhaseDuration() << std::endl; return os; } // LCOV_EXCL_STOP bool VelocityProfileATrap::operator==(const VelocityProfileATrap& other) const { return (max_vel_ == other.max_vel_ && max_acc_ == other.max_acc_ && max_dec_ == other.max_dec_ && start_pos_ == other.start_pos_ && end_pos_ == other.end_pos_ && start_vel_ == other.start_vel_ && a1_ == other.a1_ && a2_ == other.a2_ && a3_ == other.a3_ && b1_ == other.b1_ && b2_ == other.b2_ && b3_ == other.b3_ && c1_ == other.c1_ && c2_ == other.c2_ && c3_ == other.c3_ && t_a_ == other.t_a_ && t_b_ == other.t_b_ && t_c_ == other.t_c_); } VelocityProfileATrap::~VelocityProfileATrap() { } void VelocityProfileATrap::setEmptyProfile() { a1_ = end_pos_; a2_ = 0; a3_ = 0; b1_ = end_pos_; b2_ = 0; c1_ = end_pos_; c2_ = 0; c3_ = 0; t_a_ = 0; t_b_ = 0; t_c_ = 0; } } // namespace pilz_industrial_motion_planner
26.358407
119
0.602988
[ "vector" ]
f1a1d245438a722adb409ef6be0a7b75448e59df
9,454
cxx
C++
Filters/ExtractDataType/vtkExtractPolyData.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
4
2016-01-21T21:45:43.000Z
2021-07-31T19:24:09.000Z
Filters/ExtractDataType/vtkExtractPolyData.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
null
null
null
Filters/ExtractDataType/vtkExtractPolyData.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
6
2015-08-31T06:21:03.000Z
2021-07-31T19:24:10.000Z
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkExtractPolyData.cxx,v $ By: Matthew Livingstone =========================================================================*/ // Modified By: Matthew Livingstone #include "vtkExtractPolyData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkCompositeDataIterator.h" #include "vtkInformationIntegerKey.h" #include "vtkMultiPieceDataSet.h" #include "vtkPolyData.h" #include "vtkAppendPolyData.h" #include "vtkExecutive.h" #include "vtkSmartPointer.h" #include "vtkCompositeDataSet.h" #include <vtkstd/set> class vtkExtractPolyData::vtkSet : public vtkstd::set<unsigned int> { }; vtkStandardNewMacro(vtkExtractPolyData); vtkCxxRevisionMacro(vtkExtractPolyData, "$Revision: 1.4 $"); vtkInformationKeyMacro(vtkExtractPolyData, DONT_PRUNE, Integer); //---------------------------------------------------------------------------- vtkExtractPolyData::vtkExtractPolyData() { this->Indices = new vtkExtractPolyData::vtkSet(); this->PruneOutput = 1; } //---------------------------------------------------------------------------- vtkExtractPolyData::~vtkExtractPolyData() { delete this->Indices; } //---------------------------------------------------------------------------- void vtkExtractPolyData::AddIndex(unsigned int index) { this->Indices->insert(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractPolyData::RemoveIndex(unsigned int index) { this->Indices->erase(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractPolyData::RemoveAllIndices() { this->Indices->clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractPolyData::CopySubTree(vtkCompositeDataIterator* loc, vtkMultiBlockDataSet* output, vtkMultiBlockDataSet* input) { vtkDataObject* inputNode = input->GetDataSet(loc); if (!inputNode->IsA("vtkCompositeDataSet")) { vtkDataObject* clone = inputNode->NewInstance(); clone->ShallowCopy(inputNode); output->SetDataSet(loc, clone); clone->Delete(); } else { vtkCompositeDataSet* cinput = vtkCompositeDataSet::SafeDownCast(inputNode); vtkCompositeDataSet* coutput = vtkCompositeDataSet::SafeDownCast( output->GetDataSet(loc)); vtkCompositeDataIterator* iter = cinput->NewIterator(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkDataObject* curNode = iter->GetCurrentDataObject(); vtkDataObject* clone = curNode->NewInstance(); clone->ShallowCopy(curNode); coutput->SetDataSet(iter, clone); clone->Delete(); } iter->Delete(); } } //---------------------------------------------------------------------------- int vtkExtractPolyData::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkInformation *inInfo = inputVector[0]->GetInformationObject ( 0 ); vtkInformation *outInfo = outputVector->GetInformationObject ( 0 ); vtkMultiBlockDataSet *input = vtkMultiBlockDataSet::SafeDownCast ( inInfo->Get ( vtkDataObject::DATA_OBJECT() ) ); vtkPolyData *polyOutput = vtkPolyData::SafeDownCast ( outInfo->Get ( vtkDataObject::DATA_OBJECT() ) ); vtkMultiBlockDataSet *selectedItems = vtkMultiBlockDataSet::New(); selectedItems->DeepCopy(input); // Copy selected blocks over to the output. vtkCompositeDataIterator* iter = input->NewIterator(); iter->VisitOnlyLeavesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { if (this->Indices->find(iter->GetCurrentFlatIndex()) != this->Indices->end()) { this->CopySubTree(iter, selectedItems, input); // TODO: avoid copying if subtree has already been copied over. } } iter->Delete(); if (this->PruneOutput) { // Now prune the output tree. // Since in case multiple processes are involved, this process may have some // data-set pointers NULL. Hence, pruning cannot simply trim NULL ptrs, since // in that case we may end up with different structures on different // processess, which is a big NO-NO. Hence, we first flag nodes based on // whether they are being pruned or not. iter = selectedItems->NewIterator(); iter->VisitOnlyLeavesOff(); iter->SkipEmptyNodesOff(); //iter->SkipEmptyNodesOn(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { if (this->Indices->find(iter->GetCurrentFlatIndex()) != this->Indices->end()) { iter->GetCurrentMetaData()->Set(DONT_PRUNE(), 1); } else if (iter->HasCurrentMetaData() && iter->GetCurrentMetaData()->Has(DONT_PRUNE())) { iter->GetCurrentMetaData()->Remove(DONT_PRUNE()); } } iter->Delete(); // Do the actual pruning. Only those branches are pruned which don't have // DONT_PRUNE flag set. this->Prune(selectedItems); } if(selectedItems->GetNumberOfBlocks() <= 0) { // Ensure empty output vtkPolyData *temp = vtkPolyData::New(); polyOutput->ShallowCopy(temp); temp->Delete(); selectedItems->Delete(); return 1; } // Final PolyData output object vtkAppendPolyData *polyDataGroup = vtkAppendPolyData::New(); // Append all blocks to the PolyData output vtkCompositeDataIterator *iter2 = selectedItems->NewIterator(); iter2->VisitOnlyLeavesOn(); iter2->TraverseSubTreeOn(); while( !iter2->IsDoneWithTraversal() ) { polyDataGroup->AddInput(vtkPolyData::SafeDownCast( iter2->GetCurrentDataObject() ) ); iter2->GoToNextItem(); } iter2->Delete(); polyDataGroup->Update(); // Copy points & cells & properties polyOutput->ShallowCopy(polyDataGroup->GetOutput()); polyDataGroup->Delete(); selectedItems->Delete(); return 1; } //---------------------------------------------------------------------------- bool vtkExtractPolyData::Prune(vtkDataObject* branch) { if (branch->IsA("vtkMultiBlockDataSet")) { return this->Prune(vtkMultiBlockDataSet::SafeDownCast(branch)); } else if (branch->IsA("vtkMultiPieceDataSet")) { return this->Prune(vtkMultiPieceDataSet::SafeDownCast(branch)); } return true; } //---------------------------------------------------------------------------- bool vtkExtractPolyData::Prune(vtkMultiPieceDataSet* mpiece) { // * Remove any children on mpiece that don't have DONT_PRUNE set. vtkMultiPieceDataSet* clone = vtkMultiPieceDataSet::New(); unsigned int index=0; unsigned int numChildren = mpiece->GetNumberOfPieces(); for (unsigned int cc=0; cc<numChildren; cc++) { if (mpiece->HasMetaData(cc) && mpiece->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetPiece(index, mpiece->GetPiece(cc)); clone->GetMetaData(index)->Copy(mpiece->GetMetaData(cc)); index++; } } mpiece->ShallowCopy(clone); clone->Delete(); // tell caller to prune mpiece away if num of pieces is 0. return (mpiece->GetNumberOfPieces() == 0); } //---------------------------------------------------------------------------- bool vtkExtractPolyData::Prune(vtkMultiBlockDataSet* mblock) { vtkMultiBlockDataSet* clone = vtkMultiBlockDataSet::New(); unsigned int index=0; unsigned int numChildren = mblock->GetNumberOfBlocks(); for (unsigned int cc=0; cc < numChildren; cc++) { vtkDataObject* block = mblock->GetBlock(cc); if (mblock->HasMetaData(cc) && mblock->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetBlock(index, block); clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); index++; } else if (block) { bool prune = this->Prune(block); if (!prune) { vtkMultiBlockDataSet* prunedBlock = vtkMultiBlockDataSet::SafeDownCast(block); if (prunedBlock && prunedBlock->GetNumberOfBlocks()==1) { // shrink redundant branches. clone->SetBlock(index, prunedBlock->GetBlock(0)); if (prunedBlock->HasMetaData(static_cast<unsigned int>(0))) { clone->GetMetaData(index)->Copy(prunedBlock->GetMetaData( static_cast<unsigned int>(0))); } } else { clone->SetBlock(index, block); if (mblock->HasMetaData(cc)) { clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); } } index++; } } } mblock->ShallowCopy(clone); clone->Delete(); return (mblock->GetNumberOfBlocks() == 0); } //---------------------------------------------------------------------------- void vtkExtractPolyData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "PruneOutput: " << this->PruneOutput << endl; } int vtkExtractPolyData::FillInputPortInformation(int, vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkMultiBlockDataSet"); return 1; } /*int vtkExtractPolyData::FillOutputPortInformation(int, vtkInformation *info) { info->Set(vtkAlgorithm::O, "vtkMultiBlockDataSet"); return 1; }*/
30.996721
88
0.613074
[ "object" ]
f1a793242117e677d98d5ac55afe2bbdfd69212e
1,149
cpp
C++
woff2_dec.cpp
alimilhim/woff2-wasm
78c679a73d6cb40056896842121297948aaec8b8
[ "MIT" ]
1
2020-02-21T16:34:22.000Z
2020-02-21T16:34:22.000Z
woff2_dec.cpp
alimilhim/woff2-wasm
78c679a73d6cb40056896842121297948aaec8b8
[ "MIT" ]
null
null
null
woff2_dec.cpp
alimilhim/woff2-wasm
78c679a73d6cb40056896842121297948aaec8b8
[ "MIT" ]
null
null
null
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ #include <string> #include "woff2/src/file.h" #include <woff2/decode.h> #include <vector> #include <emscripten.h> #include <emscripten/bind.h> //#include <emscripten/val.h> using namespace emscripten; using std::string; std::vector<unsigned char> woff2_dec(string woff2buf, size_t bufSize) { string input = woff2buf; const uint8_t *raw_input = reinterpret_cast<const uint8_t *>(input.data()); string output(std::min(woff2::ComputeWOFF2FinalSize(raw_input, input.size()), woff2::kDefaultMaxSize), 0); woff2::WOFF2StringOut out(&output); const bool ok = woff2::ConvertWOFF2ToTTF(raw_input, input.size(), &out); if (!ok) { printf("somthing went wrong!\n"); } const std::vector<uint8_t> charvect(output.begin(), output.begin() + out.Size()); return charvect; } EMSCRIPTEN_BINDINGS(woff_2) { register_vector<uint8_t>("vector<uint8_t>"); function("woff2_dec", &woff2_dec); }
24.978261
85
0.673629
[ "vector" ]
f1a9cbbfb3c468e1953b4d9fabd5915a033ef025
38,069
cxx
C++
GPU/GPUTracking/Standalone/standalone.cxx
aknospe/AliRoot
96d76b2078d6b757a2843ae4a890a85021241e70
[ "BSD-3-Clause" ]
null
null
null
GPU/GPUTracking/Standalone/standalone.cxx
aknospe/AliRoot
96d76b2078d6b757a2843ae4a890a85021241e70
[ "BSD-3-Clause" ]
null
null
null
GPU/GPUTracking/Standalone/standalone.cxx
aknospe/AliRoot
96d76b2078d6b757a2843ae4a890a85021241e70
[ "BSD-3-Clause" ]
null
null
null
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file standalone.cxx /// \author David Rohr #include "utils/qconfig.h" #include "GPUReconstruction.h" #include "GPUReconstructionTimeframe.h" #include "GPUReconstructionConvert.h" #include "GPUChainTracking.h" #include "GPUTPCDef.h" #include "GPUQA.h" #include "GPUDisplayBackend.h" #include "genEvents.h" #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <chrono> #include <tuple> #include <algorithm> #include <thread> #include <future> #include <atomic> #ifdef WITH_OPENMP #include <omp.h> #endif #ifndef _WIN32 #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/select.h> #include <fenv.h> #include <clocale> #include <sys/stat.h> #endif #include "utils/timer.h" #include "utils/qmaths_helpers.h" #include "utils/vecpod.h" #include "TPCFastTransform.h" #include "GPUTPCGMMergedTrack.h" #include "GPUSettings.h" #include <vector> #include <xmmintrin.h> #include "GPUO2DataTypes.h" #ifdef HAVE_O2HEADERS #include "GPUChainITS.h" #endif #ifdef GPUCA_BUILD_EVENT_DISPLAY #ifdef _WIN32 #include "GPUDisplayBackendWindows.h" #else #include "GPUDisplayBackendX11.h" #include "GPUDisplayBackendGlfw.h" #endif #include "GPUDisplayBackendGlut.h" #endif using namespace GPUCA_NAMESPACE::gpu; //#define BROKEN_EVENTS GPUReconstruction *rec, *recAsync, *recPipeline; GPUChainTracking *chainTracking, *chainTrackingAsync, *chainTrackingPipeline; #ifdef HAVE_O2HEADERS GPUChainITS *chainITS, *chainITSAsync, *chainITSPipeline; #endif std::unique_ptr<char[]> outputmemory, outputmemoryPipeline; std::unique_ptr<GPUDisplayBackend> eventDisplay; std::unique_ptr<GPUReconstructionTimeframe> tf; int nEventsInDirectory = 0; std::atomic<unsigned int> nIteration, nIterationEnd; void SetCPUAndOSSettings() { #ifdef FE_DFL_DISABLE_SSE_DENORMS_ENV // Flush and load denormals to zero in any case fesetenv(FE_DFL_DISABLE_SSE_DENORMS_ENV); #else #ifndef _MM_FLUSH_ZERO_ON #define _MM_FLUSH_ZERO_ON 0x8000 #endif #ifndef _MM_DENORMALS_ZERO_ON #define _MM_DENORMALS_ZERO_ON 0x0040 #endif _mm_setcsr(_mm_getcsr() | (_MM_FLUSH_ZERO_ON | _MM_DENORMALS_ZERO_ON)); #endif } int ReadConfiguration(int argc, char** argv) { int qcRet = qConfigParse(argc, (const char**)argv); if (qcRet) { if (qcRet != qConfig::qcrHelp) { printf("Error parsing command line parameters\n"); } return 1; } if (configStandalone.printSettings) { qConfigPrint(); } #ifndef _WIN32 setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, ""); if (configStandalone.affinity != -1) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(configStandalone.affinity, &mask); printf("Setting affinitiy to restrict on CPU core %d\n", configStandalone.affinity); if (0 != sched_setaffinity(0, sizeof(mask), &mask)) { printf("Error setting CPU affinity\n"); return 1; } } if (configStandalone.fifo) { printf("Setting FIFO scheduler\n"); sched_param param; sched_getparam(0, &param); param.sched_priority = 1; if (0 != sched_setscheduler(0, SCHED_FIFO, &param)) { printf("Error setting scheduler\n"); return 1; } } if (configStandalone.fpe) { feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW); } if (configStandalone.flushDenormals) { disable_denormals(); } #else if (configStandalone.affinity != -1) { printf("Affinity setting not supported on Windows\n"); return 1; } if (configStandalone.fifo) { printf("FIFO Scheduler setting not supported on Windows\n"); return 1; } if (configStandalone.fpe) { printf("FPE not supported on Windows\n"); return 1; } #endif #ifndef HAVE_O2HEADERS configStandalone.configRec.runTRD = configStandalone.configRec.rundEdx = configStandalone.configRec.runCompression = configStandalone.configRec.runTransformation = configStandalone.testSyncAsync = configStandalone.testSync = 0; configStandalone.configRec.ForceEarlyTPCTransform = 1; #endif #ifndef GPUCA_TPC_GEOMETRY_O2 configStandalone.configRec.mergerReadFromTrackerDirectly = 0; #endif #ifndef GPUCA_BUILD_QA if (configStandalone.qa || configStandalone.eventGenerator) { printf("QA not enabled in build\n"); return 1; } #endif if (configStandalone.qa) { if (getenv("LC_NUMERIC")) { printf("Please unset the LC_NUMERIC env variable, otherwise ROOT will not be able to fit correctly\n"); // BUG: ROOT Problem return 1; } } #ifndef GPUCA_BUILD_EVENT_DISPLAY if (configStandalone.eventDisplay) { printf("EventDisplay not enabled in build\n"); return 1; } #endif if (configStandalone.configProc.doublePipeline && configStandalone.testSyncAsync) { printf("Cannot run asynchronous processing with double pipeline\n"); return 1; } if (configStandalone.configProc.doublePipeline && (configStandalone.runs < 3 || !configStandalone.outputcontrolmem)) { printf("Double pipeline mode needs at least 3 runs per event and external output\n"); return 1; } if (configStandalone.configTF.bunchSim && configStandalone.configTF.nMerge) { printf("Cannot run --MERGE and --SIMBUNCHES togeterh\n"); return 1; } if (configStandalone.configTF.bunchSim > 1) { configStandalone.configTF.timeFrameLen = 1.e9 * configStandalone.configTF.bunchSim / configStandalone.configTF.interactionRate; } if (configStandalone.configTF.nMerge) { double len = configStandalone.configTF.nMerge - 1; if (configStandalone.configTF.randomizeDistance) { len += 0.5; } if (configStandalone.configTF.shiftFirstEvent) { len += 0.5; } configStandalone.configTF.timeFrameLen = (len * configStandalone.configTF.averageDistance / GPUReconstructionTimeframe::TPCZ + 1) * GPUReconstructionTimeframe::DRIFT_TIME; } if (configStandalone.configQA.inputHistogramsOnly && configStandalone.configQA.compareInputs.size() == 0) { printf("Can only produce QA pdf output when input files are specified!\n"); return 1; } if (configStandalone.eventDisplay) { configStandalone.noprompt = 1; } if (configStandalone.DebugLevel >= 4) { configStandalone.OMPThreads = 1; } #ifdef WITH_OPENMP if (configStandalone.OMPThreads != -1) { omp_set_num_threads(configStandalone.OMPThreads); } else { configStandalone.OMPThreads = omp_get_max_threads(); } if (configStandalone.OMPThreads != omp_get_max_threads()) { printf("Cannot set number of OMP threads!\n"); return 1; } #else configStandalone.OMPThreads = 1; #endif if (configStandalone.outputcontrolmem) { bool forceEmptyMemory = getenv("LD_PRELOAD") && strstr(getenv("LD_PRELOAD"), "valgrind") != nullptr; outputmemory.reset(new char[configStandalone.outputcontrolmem]); if (forceEmptyMemory) { printf("Valgrind detected, emptying GPU output memory to avoid false positive undefined reads"); memset(outputmemory.get(), 0, configStandalone.outputcontrolmem); } if (configStandalone.configProc.doublePipeline) { outputmemoryPipeline.reset(new char[configStandalone.outputcontrolmem]); if (forceEmptyMemory) { memset(outputmemoryPipeline.get(), 0, configStandalone.outputcontrolmem); } } } #if !(defined(CUDA_ENABLED) || defined(OPENCL1_ENABLED) || defined(HIP_ENABLED)) if (configStandalone.runGPU) { printf("GPU disables at build time!\n"); printf("Press a key to exit!\n"); getchar(); return 1; } #endif return (0); } int SetupReconstruction() { if (!configStandalone.eventGenerator) { char filename[256]; snprintf(filename, 256, "events/%s/", configStandalone.EventsDir); if (rec->ReadSettings(filename)) { printf("Error reading event config file\n"); return 1; } printf("Read event settings from dir %s (solenoidBz: %f, home-made events %d, constBz %d, maxTimeBin %d)\n", filename, rec->GetEventSettings().solenoidBz, (int)rec->GetEventSettings().homemadeEvents, (int)rec->GetEventSettings().constBz, rec->GetEventSettings().continuousMaxTimeBin); if (configStandalone.testSyncAsync) { recAsync->ReadSettings(filename); } if (configStandalone.configProc.doublePipeline) { recPipeline->ReadSettings(filename); } } GPUSettingsEvent ev = rec->GetEventSettings(); GPUSettingsRec recSet; GPUSettingsDeviceProcessing devProc; GPURecoStepConfiguration steps; if (configStandalone.eventGenerator) { ev.homemadeEvents = true; } if (configStandalone.solenoidBz != -1e6f) { ev.solenoidBz = configStandalone.solenoidBz; } if (configStandalone.constBz) { ev.constBz = true; } if (configStandalone.configTF.nMerge || configStandalone.configTF.bunchSim) { if (ev.continuousMaxTimeBin) { printf("ERROR: requested to overlay continuous data - not supported\n"); return 1; } if (!configStandalone.cont) { printf("Continuous mode forced\n"); configStandalone.cont = true; } if (chainTracking->GetTPCTransform()) { ev.continuousMaxTimeBin = configStandalone.configTF.timeFrameLen * ((double)GPUReconstructionTimeframe::TPCZ / (double)GPUReconstructionTimeframe::DRIFT_TIME) / chainTracking->GetTPCTransform()->getVDrift(); } } if (configStandalone.cont && ev.continuousMaxTimeBin == 0) { ev.continuousMaxTimeBin = -1; } if (rec->GetDeviceType() == GPUReconstruction::DeviceType::CPU) { printf("Standalone Test Framework for CA Tracker - Using CPU\n"); } else { printf("Standalone Test Framework for CA Tracker - Using GPU\n"); } recSet.SetMinTrackPt(GPUCA_MIN_TRACK_PT_DEFAULT); recSet.NWays = configStandalone.nways; recSet.NWaysOuter = configStandalone.nwaysouter; recSet.RejectMode = configStandalone.rejectMode; recSet.SearchWindowDZDR = configStandalone.dzdr; recSet.GlobalTracking = configStandalone.configRec.globalTracking; recSet.DisableRefitAttachment = configStandalone.configRec.disableRefitAttachment; recSet.ForceEarlyTPCTransform = configStandalone.configRec.ForceEarlyTPCTransform; recSet.fwdTPCDigitsAsClusters = configStandalone.configRec.fwdTPCDigitsAsClusters; recSet.dropLoopers = configStandalone.configRec.dropLoopers; if (configStandalone.configRec.mergerCovSource != -1) { recSet.mergerCovSource = configStandalone.configRec.mergerCovSource; } if (configStandalone.configRec.mergerInterpolateErrors != -1) { recSet.mergerInterpolateErrors = configStandalone.configRec.mergerInterpolateErrors; } if (configStandalone.referenceX < 500.) { recSet.TrackReferenceX = configStandalone.referenceX; } recSet.tpcZSthreshold = configStandalone.zsThreshold; if (configStandalone.configRec.fitInProjections != -1) { recSet.fitInProjections = configStandalone.configRec.fitInProjections; } if (configStandalone.configRec.fitPropagateBzOnly != -1) { recSet.fitPropagateBzOnly = configStandalone.configRec.fitPropagateBzOnly; } if (configStandalone.configRec.retryRefit != -1) { recSet.retryRefit = configStandalone.configRec.retryRefit; } recSet.loopInterpolationInExtraPass = configStandalone.configRec.loopInterpolationInExtraPass; recSet.mergerReadFromTrackerDirectly = configStandalone.configRec.mergerReadFromTrackerDirectly; if (!recSet.mergerReadFromTrackerDirectly) { devProc.fullMergerOnGPU = false; } if (configStandalone.OMPThreads != -1) { devProc.nThreads = configStandalone.OMPThreads; } devProc.deviceNum = configStandalone.cudaDevice; devProc.forceMemoryPoolSize = (configStandalone.forceMemorySize == 1 && configStandalone.eventDisplay) ? 2 : configStandalone.forceMemorySize; devProc.debugLevel = configStandalone.DebugLevel; devProc.allocDebugLevel = configStandalone.allocDebugLevel; devProc.deviceTimers = configStandalone.DeviceTiming; devProc.runQA = configStandalone.qa; devProc.runMC = configStandalone.configProc.runMC; devProc.ompKernels = configStandalone.configProc.ompKernels; devProc.runCompressionStatistics = configStandalone.compressionStat; devProc.memoryScalingFactor = configStandalone.memoryScalingFactor; devProc.alternateBorderSort = configStandalone.alternateBorderSort; devProc.doublePipeline = configStandalone.configProc.doublePipeline; if (configStandalone.eventDisplay) { #ifdef GPUCA_BUILD_EVENT_DISPLAY #ifdef _WIN32 if (configStandalone.eventDisplay == 1) { printf("Enabling event display (windows backend)\n"); eventDisplay.reset(new GPUDisplayBackendWindows); } #else if (configStandalone.eventDisplay == 1) { eventDisplay.reset(new GPUDisplayBackendX11); printf("Enabling event display (X11 backend)\n"); } if (configStandalone.eventDisplay == 3) { eventDisplay.reset(new GPUDisplayBackendGlfw); printf("Enabling event display (GLFW backend)\n"); } #endif else if (configStandalone.eventDisplay == 2) { eventDisplay.reset(new GPUDisplayBackendGlut); printf("Enabling event display (GLUT backend)\n"); } #endif devProc.eventDisplay = eventDisplay.get(); } devProc.nDeviceHelperThreads = configStandalone.helperThreads; devProc.globalInitMutex = configStandalone.gpuInitMutex; devProc.gpuDeviceOnly = configStandalone.oclGPUonly; devProc.memoryAllocationStrategy = configStandalone.allocationStrategy; devProc.registerStandaloneInputMemory = configStandalone.registerInputMemory; if (configStandalone.configRec.tpcReject != -1) { recSet.tpcRejectionMode = configStandalone.configRec.tpcReject; } if (configStandalone.configRec.tpcRejectThreshold != 0.f) { recSet.tpcRejectQPt = 1.f / configStandalone.configRec.tpcRejectThreshold; } recSet.tpcCompressionModes = configStandalone.configRec.tpcCompression; recSet.tpcCompressionSortOrder = configStandalone.configRec.tpcCompressionSort; if (configStandalone.configProc.nStreams >= 0) { devProc.nStreams = configStandalone.configProc.nStreams; } if (configStandalone.configProc.constructorPipeline >= 0) { devProc.trackletConstructorInPipeline = configStandalone.configProc.constructorPipeline; } if (configStandalone.configProc.selectorPipeline >= 0) { devProc.trackletSelectorInPipeline = configStandalone.configProc.selectorPipeline; } devProc.mergerSortTracks = configStandalone.configProc.mergerSortTracks; devProc.tpcCompressionGatherMode = configStandalone.configProc.tpcCompressionGatherMode; steps.steps = GPUDataTypes::RecoStep::AllRecoSteps; if (configStandalone.configRec.runTRD != -1) { steps.steps.setBits(GPUDataTypes::RecoStep::TRDTracking, configStandalone.configRec.runTRD > 0); } else if (chainTracking->GetTRDGeometry() == nullptr) { steps.steps.setBits(GPUDataTypes::RecoStep::TRDTracking, false); } if (configStandalone.configRec.rundEdx != -1) { steps.steps.setBits(GPUDataTypes::RecoStep::TPCdEdx, configStandalone.configRec.rundEdx > 0); } if (configStandalone.configRec.runCompression != -1) { steps.steps.setBits(GPUDataTypes::RecoStep::TPCCompression, configStandalone.configRec.runCompression > 0); } if (configStandalone.configRec.runTransformation != -1) { steps.steps.setBits(GPUDataTypes::RecoStep::TPCConversion, configStandalone.configRec.runTransformation > 0); } if (!configStandalone.merger) { steps.steps.setBits(GPUDataTypes::RecoStep::TPCMerging, false); steps.steps.setBits(GPUDataTypes::RecoStep::TRDTracking, false); steps.steps.setBits(GPUDataTypes::RecoStep::TPCdEdx, false); steps.steps.setBits(GPUDataTypes::RecoStep::TPCCompression, false); } if (configStandalone.configTF.bunchSim || configStandalone.configTF.nMerge) { steps.steps.setBits(GPUDataTypes::RecoStep::TRDTracking, false); } steps.inputs.set(GPUDataTypes::InOutType::TPCClusters, GPUDataTypes::InOutType::TRDTracklets); if (ev.needsClusterer) { steps.inputs.setBits(GPUDataTypes::InOutType::TPCRaw, true); steps.inputs.setBits(GPUDataTypes::InOutType::TPCClusters, false); } else { steps.steps.setBits(GPUDataTypes::RecoStep::TPCClusterFinding, false); } if (configStandalone.configProc.recoSteps >= 0) { steps.steps &= configStandalone.configProc.recoSteps; } if (configStandalone.configProc.recoStepsGPU >= 0) { steps.stepsGPUMask &= configStandalone.configProc.recoStepsGPU; } steps.outputs.clear(); steps.outputs.setBits(GPUDataTypes::InOutType::TPCSectorTracks, steps.steps.isSet(GPUDataTypes::RecoStep::TPCSliceTracking) && !recSet.mergerReadFromTrackerDirectly); steps.outputs.setBits(GPUDataTypes::InOutType::TPCMergedTracks, steps.steps.isSet(GPUDataTypes::RecoStep::TPCMerging)); steps.outputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, steps.steps.isSet(GPUDataTypes::RecoStep::TPCCompression)); steps.outputs.setBits(GPUDataTypes::InOutType::TRDTracks, steps.steps.isSet(GPUDataTypes::RecoStep::TRDTracking)); steps.outputs.setBits(GPUDataTypes::InOutType::TPCClusters, steps.steps.isSet(GPUDataTypes::RecoStep::TPCClusterFinding)); steps.steps.setBits(GPUDataTypes::RecoStep::TPCDecompression, false); steps.inputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, false); if (configStandalone.testSyncAsync || configStandalone.testSync) { // Set settings for synchronous steps.steps.setBits(GPUDataTypes::RecoStep::TPCdEdx, 0); recSet.useMatLUT = false; if (configStandalone.testSyncAsync) { devProc.eventDisplay = nullptr; } } rec->SetSettings(&ev, &recSet, &devProc, &steps); if (configStandalone.configProc.doublePipeline) { recPipeline->SetSettings(&ev, &recSet, &devProc, &steps); } if (configStandalone.testSyncAsync) { // Set settings for asynchronous steps.steps.setBits(GPUDataTypes::RecoStep::TPCDecompression, true); steps.steps.setBits(GPUDataTypes::RecoStep::TPCdEdx, true); steps.steps.setBits(GPUDataTypes::RecoStep::TPCCompression, false); steps.steps.setBits(GPUDataTypes::RecoStep::TPCClusterFinding, false); steps.inputs.setBits(GPUDataTypes::InOutType::TPCRaw, false); steps.inputs.setBits(GPUDataTypes::InOutType::TPCClusters, false); steps.inputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, true); steps.outputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, false); devProc.runMC = false; devProc.runQA = false; devProc.eventDisplay = eventDisplay.get(); devProc.runCompressionStatistics = 0; recSet.DisableRefitAttachment = 0xFF; recSet.loopInterpolationInExtraPass = 0; recSet.MaxTrackQPt = CAMath::Min(recSet.MaxTrackQPt, recSet.tpcRejectQPt); recSet.useMatLUT = true; recAsync->SetSettings(&ev, &recSet, &devProc, &steps); } if (configStandalone.outputcontrolmem) { rec->SetOutputControl(outputmemory.get(), configStandalone.outputcontrolmem); if (configStandalone.configProc.doublePipeline) { recPipeline->SetOutputControl(outputmemoryPipeline.get(), configStandalone.outputcontrolmem); } } if (rec->Init()) { printf("Error initializing GPUReconstruction!\n"); return 1; } if (configStandalone.outputcontrolmem && rec->IsGPU()) { if (rec->registerMemoryForGPU(outputmemory.get(), configStandalone.outputcontrolmem) || (configStandalone.configProc.doublePipeline && recPipeline->registerMemoryForGPU(outputmemoryPipeline.get(), configStandalone.outputcontrolmem))) { printf("ERROR registering memory for the GPU!!!\n"); return 1; } } if (configStandalone.DebugLevel >= 4) { rec->PrintKernelOccupancies(); } return (0); } int ReadEvent(int n) { char filename[256]; snprintf(filename, 256, "events/%s/" GPUCA_EVDUMP_FILE ".%d.dump", configStandalone.EventsDir, n); int r = chainTracking->ReadData(filename); if (r) { return r; } if (chainTracking->mIOPtrs.clustersNative && (configStandalone.configTF.bunchSim || configStandalone.configTF.nMerge || !configStandalone.configRec.runTransformation)) { if (configStandalone.DebugLevel >= 2) { printf("Converting Native to Legacy ClusterData for overlaying - WARNING: No raw clusters produced - Compression etc will not run!!!\n"); } chainTracking->ConvertNativeToClusterDataLegacy(); } return 0; } void OutputStat(GPUChainTracking* t, long long int* nTracksTotal = nullptr, long long int* nClustersTotal = nullptr) { int nTracks = 0, nAttachedClusters = 0, nAttachedClustersFitted = 0, nAdjacentClusters = 0; for (unsigned int k = 0; k < t->mIOPtrs.nMergedTracks; k++) { if (t->mIOPtrs.mergedTracks[k].OK()) { nTracks++; nAttachedClusters += t->mIOPtrs.mergedTracks[k].NClusters(); nAttachedClustersFitted += t->mIOPtrs.mergedTracks[k].NClustersFitted(); } } unsigned int nCls = configStandalone.configProc.doublePipeline ? t->mIOPtrs.clustersNative->nClustersTotal : t->GetTPCMerger().NMaxClusters(); for (unsigned int k = 0; k < nCls; k++) { int attach = t->mIOPtrs.mergedTrackHitAttachment[k]; if (attach & GPUTPCGMMergerTypes::attachFlagMask) { nAdjacentClusters++; } } if (nTracksTotal && nClustersTotal) { *nTracksTotal += nTracks; *nClustersTotal += t->mIOPtrs.nMergedTrackHits; } char trdText[1024] = ""; if (t->GetRecoSteps() & GPUDataTypes::RecoStep::TRDTracking) { int nTracklets = 0; for (unsigned int k = 0; k < t->mIOPtrs.nTRDTracks; k++) { auto& trk = t->mIOPtrs.trdTracks[k]; nTracklets += trk.GetNtracklets(); } snprintf(trdText, 1024, " - TRD Tracker reconstructed %d tracks (%d tracklets)", t->mIOPtrs.nTRDTracks, nTracklets); } printf("Output Tracks: %d (%d / %d / %d / %d clusters (fitted / attached / adjacent / total))%s\n", nTracks, nAttachedClustersFitted, nAttachedClusters, nAdjacentClusters, nCls, trdText); } int RunBenchmark(GPUReconstruction* recUse, GPUChainTracking* chainTrackingUse, int runs, const GPUTrackingInOutPointers& ioPtrs, long long int* nTracksTotal, long long int* nClustersTotal, int threadId = 0, HighResTimer* timerPipeline = nullptr) { int iRun = 0, iteration = 0; while ((iteration = nIteration.fetch_add(1)) < runs) { if (configStandalone.runs > 1) { printf("Run %d (thread %d)\n", iteration + 1, threadId); } recUse->SetResetTimers(iRun < configStandalone.runsInit); if (configStandalone.outputcontrolmem) { recUse->SetOutputControl(threadId ? outputmemoryPipeline.get() : outputmemory.get(), configStandalone.outputcontrolmem); } if (configStandalone.testSyncAsync) { printf("Running synchronous phase\n"); } chainTrackingUse->mIOPtrs = ioPtrs; if (iteration == (configStandalone.configProc.doublePipeline ? 1 : (configStandalone.runs - 1))) { if (configStandalone.configProc.doublePipeline) { timerPipeline->Start(); } if (configStandalone.controlProfiler) { rec->startGPUProfiling(); } } int tmpRetVal = recUse->RunChains(); int iterationEnd = nIterationEnd.fetch_add(1); if (iterationEnd == configStandalone.runs - 1) { if (configStandalone.configProc.doublePipeline) { timerPipeline->Stop(); } if (configStandalone.controlProfiler) { rec->endGPUProfiling(); } } if (tmpRetVal == 0 || tmpRetVal == 2) { OutputStat(chainTrackingUse, iRun == 0 ? nTracksTotal : nullptr, iRun == 0 ? nClustersTotal : nullptr); if (configStandalone.memoryStat) { recUse->PrintMemoryStatistics(); } else if (configStandalone.DebugLevel >= 2) { recUse->PrintMemoryOverview(); } } #ifdef HAVE_O2HEADERS if (tmpRetVal == 0 && configStandalone.testSyncAsync) { if (configStandalone.testSyncAsync) { printf("Running asynchronous phase\n"); } vecpod<char> compressedTmpMem(chainTracking->mIOPtrs.tpcCompressedClusters->totalDataSize); memcpy(compressedTmpMem.data(), (const void*)chainTracking->mIOPtrs.tpcCompressedClusters, chainTracking->mIOPtrs.tpcCompressedClusters->totalDataSize); chainTrackingAsync->mIOPtrs = ioPtrs; chainTrackingAsync->mIOPtrs.tpcCompressedClusters = (o2::tpc::CompressedClustersFlat*)compressedTmpMem.data(); chainTrackingAsync->mIOPtrs.tpcZS = nullptr; chainTrackingAsync->mIOPtrs.tpcPackedDigits = nullptr; chainTrackingAsync->mIOPtrs.mcInfosTPC = nullptr; chainTrackingAsync->mIOPtrs.nMCInfosTPC = 0; chainTrackingAsync->mIOPtrs.mcLabelsTPC = nullptr; chainTrackingAsync->mIOPtrs.nMCLabelsTPC = 0; for (int i = 0; i < chainTracking->NSLICES; i++) { chainTrackingAsync->mIOPtrs.clusterData[i] = nullptr; chainTrackingAsync->mIOPtrs.nClusterData[i] = 0; chainTrackingAsync->mIOPtrs.rawClusters[i] = nullptr; chainTrackingAsync->mIOPtrs.nRawClusters[i] = 0; } chainTrackingAsync->mIOPtrs.clustersNative = nullptr; recAsync->SetResetTimers(iRun < configStandalone.runsInit); tmpRetVal = recAsync->RunChains(); if (tmpRetVal == 0 || tmpRetVal == 2) { OutputStat(chainTrackingAsync, nullptr, nullptr); if (configStandalone.memoryStat) { recAsync->PrintMemoryStatistics(); } } recAsync->ClearAllocatedMemory(); } #endif if (!configStandalone.configProc.doublePipeline) { recUse->ClearAllocatedMemory(); } if (tmpRetVal == 2) { configStandalone.continueOnError = 0; // Forced exit from event display loop configStandalone.noprompt = 1; } if (tmpRetVal && !configStandalone.continueOnError) { if (tmpRetVal != 2) { printf("Error occured\n"); } return 1; } iRun++; } if (configStandalone.configProc.doublePipeline) { recUse->ClearAllocatedMemory(); } return 0; } int main(int argc, char** argv) { std::unique_ptr<GPUReconstruction> recUnique, recUniqueAsync, recUniquePipeline; SetCPUAndOSSettings(); if (ReadConfiguration(argc, argv)) { return 1; } recUnique.reset(GPUReconstruction::CreateInstance(configStandalone.runGPU ? configStandalone.gpuType : GPUReconstruction::DEVICE_TYPE_NAMES[GPUReconstruction::DeviceType::CPU], configStandalone.runGPUforce)); rec = recUnique.get(); if (configStandalone.testSyncAsync) { recUniqueAsync.reset(GPUReconstruction::CreateInstance(configStandalone.runGPU ? configStandalone.gpuType : GPUReconstruction::DEVICE_TYPE_NAMES[GPUReconstruction::DeviceType::CPU], configStandalone.runGPUforce, rec)); recAsync = recUniqueAsync.get(); } if (configStandalone.configProc.doublePipeline) { recUniquePipeline.reset(GPUReconstruction::CreateInstance(configStandalone.runGPU ? configStandalone.gpuType : GPUReconstruction::DEVICE_TYPE_NAMES[GPUReconstruction::DeviceType::CPU], configStandalone.runGPUforce, rec)); recPipeline = recUniquePipeline.get(); } if (rec == nullptr || (configStandalone.testSyncAsync && recAsync == nullptr)) { printf("Error initializing GPUReconstruction\n"); return 1; } rec->SetDebugLevelTmp(configStandalone.DebugLevel); chainTracking = rec->AddChain<GPUChainTracking>(); if (configStandalone.testSyncAsync) { if (configStandalone.DebugLevel >= 3) { recAsync->SetDebugLevelTmp(configStandalone.DebugLevel); } chainTrackingAsync = recAsync->AddChain<GPUChainTracking>(); } if (configStandalone.configProc.doublePipeline) { if (configStandalone.DebugLevel >= 3) { recPipeline->SetDebugLevelTmp(configStandalone.DebugLevel); } chainTrackingPipeline = recPipeline->AddChain<GPUChainTracking>(); } #ifdef HAVE_O2HEADERS if (!configStandalone.configProc.doublePipeline) { chainITS = rec->AddChain<GPUChainITS>(0); if (configStandalone.testSyncAsync) { chainITSAsync = recAsync->AddChain<GPUChainITS>(0); } } #endif if (SetupReconstruction()) { return 1; } std::unique_ptr<std::thread> pipelineThread; if (configStandalone.configProc.doublePipeline) { pipelineThread.reset(new std::thread([]() { rec->RunPipelineWorker(); })); } // hlt.SetRunMerger(configStandalone.merger); //TODO! if (configStandalone.seed == -1) { std::random_device rd; configStandalone.seed = (int)rd(); printf("Using random seed %d\n", configStandalone.seed); } srand(configStandalone.seed); for (nEventsInDirectory = 0; true; nEventsInDirectory++) { std::ifstream in; char filename[256]; snprintf(filename, 256, "events/%s/" GPUCA_EVDUMP_FILE ".%d.dump", configStandalone.EventsDir, nEventsInDirectory); in.open(filename, std::ifstream::binary); if (in.fail()) { break; } in.close(); } if (configStandalone.configTF.bunchSim || configStandalone.configTF.nMerge) { tf.reset(new GPUReconstructionTimeframe(chainTracking, ReadEvent, nEventsInDirectory)); } if (configStandalone.eventGenerator) { genEvents::RunEventGenerator(chainTracking); return 1; } else { int nEvents = configStandalone.NEvents; if (configStandalone.configTF.bunchSim) { nEvents = configStandalone.NEvents > 0 ? configStandalone.NEvents : 1; } else { if (nEvents == -1 || nEvents > nEventsInDirectory) { if (nEvents >= 0) { printf("Only %d events available in directors %s (%d events requested)\n", nEventsInDirectory, configStandalone.EventsDir, nEvents); } nEvents = nEventsInDirectory; } if (configStandalone.configTF.nMerge > 1) { nEvents /= configStandalone.configTF.nMerge; } } for (int iRun = 0; iRun < configStandalone.runs2; iRun++) { if (configStandalone.configQA.inputHistogramsOnly) { chainTracking->ForceInitQA(); break; } if (configStandalone.runs2 > 1) { printf("RUN2: %d\n", iRun); } long long int nTracksTotal = 0; long long int nClustersTotal = 0; int nEventsProcessed = 0; for (int iEvent = configStandalone.StartEvent; iEvent < nEvents; iEvent++) { if (iEvent != configStandalone.StartEvent) { printf("\n"); } HighResTimer timerLoad; timerLoad.Start(); if (configStandalone.configTF.bunchSim) { if (tf->LoadCreateTimeFrame(iEvent)) { break; } } else if (configStandalone.configTF.nMerge) { if (tf->LoadMergedEvents(iEvent)) { break; } } else { if (ReadEvent(iEvent)) { break; } } bool encodeZS = configStandalone.encodeZS == -1 ? (chainTracking->mIOPtrs.tpcPackedDigits && !chainTracking->mIOPtrs.tpcZS) : (bool)configStandalone.encodeZS; bool zsFilter = configStandalone.zsFilter == -1 ? (!encodeZS && chainTracking->mIOPtrs.tpcPackedDigits) : (bool)configStandalone.zsFilter; if (encodeZS || zsFilter) { if (!chainTracking->mIOPtrs.tpcPackedDigits) { printf("Need digit input to run ZS\n"); goto breakrun; } if (zsFilter) { chainTracking->ConvertZSFilter(configStandalone.zs12bit); } if (encodeZS) { chainTracking->ConvertZSEncoder(configStandalone.zs12bit); } } if (!configStandalone.configRec.runTransformation) { chainTracking->mIOPtrs.clustersNative = nullptr; } else { for (int i = 0; i < chainTracking->NSLICES; i++) { if (chainTracking->mIOPtrs.rawClusters[i]) { if (configStandalone.DebugLevel >= 2) { printf("Converting Legacy Raw Cluster to Native\n"); } chainTracking->ConvertRun2RawToNative(); break; } } } if (configStandalone.stripDumpedEvents) { if (chainTracking->mIOPtrs.tpcZS) { chainTracking->mIOPtrs.tpcPackedDigits = nullptr; } } if (configStandalone.dumpEvents) { char fname[1024]; sprintf(fname, "event.%d.dump", nEventsProcessed); chainTracking->DumpData(fname); if (nEventsProcessed == 0) { rec->DumpSettings(); } } if (configStandalone.overrideMaxTimebin && (chainTracking->mIOPtrs.clustersNative || chainTracking->mIOPtrs.tpcPackedDigits || chainTracking->mIOPtrs.tpcZS)) { GPUSettingsEvent ev = rec->GetEventSettings(); if (ev.continuousMaxTimeBin == 0) { printf("Cannot override max time bin for non-continuous data!\n"); } else { ev.continuousMaxTimeBin = chainTracking->mIOPtrs.tpcZS ? GPUReconstructionConvert::GetMaxTimeBin(*chainTracking->mIOPtrs.tpcZS) : chainTracking->mIOPtrs.tpcPackedDigits ? GPUReconstructionConvert::GetMaxTimeBin(*chainTracking->mIOPtrs.tpcPackedDigits) : GPUReconstructionConvert::GetMaxTimeBin(*chainTracking->mIOPtrs.clustersNative); printf("Max time bin set to %d\n", (int)ev.continuousMaxTimeBin); rec->UpdateEventSettings(&ev); } } if (!rec->GetParam().earlyTpcTransform && chainTracking->mIOPtrs.clustersNative == nullptr && chainTracking->mIOPtrs.tpcPackedDigits == nullptr && chainTracking->mIOPtrs.tpcZS == nullptr) { printf("Need cluster native data for on-the-fly TPC transform\n"); goto breakrun; } printf("Loading time: %'d us\n", (int)(1000000 * timerLoad.GetCurrentElapsedTime())); printf("Processing Event %d\n", iEvent); GPUTrackingInOutPointers ioPtrSave = chainTracking->mIOPtrs; nIteration.store(0); nIterationEnd.store(0); double pipelineWalltime = 1.; if (configStandalone.configProc.doublePipeline) { HighResTimer timerPipeline; if (RunBenchmark(rec, chainTracking, 1, ioPtrSave, &nTracksTotal, &nClustersTotal)) { goto breakrun; } nIteration.store(1); nIterationEnd.store(1); auto pipeline1 = std::async(std::launch::async, RunBenchmark, rec, chainTracking, configStandalone.runs, ioPtrSave, &nTracksTotal, &nClustersTotal, 0, &timerPipeline); auto pipeline2 = std::async(std::launch::async, RunBenchmark, recPipeline, chainTrackingPipeline, configStandalone.runs, ioPtrSave, &nTracksTotal, &nClustersTotal, 1, &timerPipeline); if (pipeline1.get() || pipeline2.get()) { goto breakrun; } pipelineWalltime = timerPipeline.GetElapsedTime() / (configStandalone.runs - 1); printf("Pipeline wall time: %f, %d iterations, %f per event\n", timerPipeline.GetElapsedTime(), configStandalone.runs - 1, pipelineWalltime); } else { if (RunBenchmark(rec, chainTracking, configStandalone.runs, ioPtrSave, &nTracksTotal, &nClustersTotal)) { goto breakrun; } } nEventsProcessed++; if (configStandalone.timeFrameTime) { double nClusters = chainTracking->GetTPCMerger().NMaxClusters(); if (nClusters > 0) { double nClsPerTF = 550000. * 1138.3; double timePerTF = (configStandalone.configProc.doublePipeline ? pipelineWalltime : ((configStandalone.DebugLevel ? rec->GetStatKernelTime() : rec->GetStatWallTime()) / 1000000.)) * nClsPerTF / nClusters; double nGPUsReq = timePerTF / 0.02277; char stat[1024]; snprintf(stat, 1024, "Sync phase: %.2f sec per 256 orbit TF, %.1f GPUs required", timePerTF, nGPUsReq); if (configStandalone.testSyncAsync) { timePerTF = (configStandalone.DebugLevel ? recAsync->GetStatKernelTime() : recAsync->GetStatWallTime()) / 1000000. * nClsPerTF / nClusters; snprintf(stat + strlen(stat), 1024 - strlen(stat), " - Async phase: %f sec per TF", timePerTF); } printf("%s (Measured %s time - Extrapolated from %d clusters to %d)\n", stat, configStandalone.DebugLevel ? "kernel" : "wall", (int)nClusters, (int)nClsPerTF); } } } if (nEventsProcessed > 1) { printf("Total: %lld clusters, %lld tracks\n", nClustersTotal, nTracksTotal); } } } breakrun: if (rec->GetDeviceProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) { rec->PrintMemoryMax(); } #ifndef _WIN32 if (configStandalone.qa && configStandalone.fpe) { fedisableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW); } #endif if (configStandalone.configProc.doublePipeline) { rec->TerminatePipelineWorker(); pipelineThread->join(); } rec->Finalize(); if (configStandalone.outputcontrolmem && rec->IsGPU()) { if (rec->unregisterMemoryForGPU(outputmemory.get()) || (configStandalone.configProc.doublePipeline && recPipeline->unregisterMemoryForGPU(outputmemoryPipeline.get()))) { printf("Error unregistering memory\n"); } } rec->Exit(); if (!configStandalone.noprompt) { printf("Press a key to exit!\n"); getchar(); } return (0); }
40.030494
346
0.702829
[ "vector", "transform" ]
f1ac324fb2023affe4a487177b999a89135075c2
1,240
cpp
C++
codes/CF/1487/B.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CF/1487/B.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CF/1487/B.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <list> #include <queue> #include <stack> //#include <unordered_map> //#include <unordered_set> #include <functional> #define max_v 1100 #define int_max 0x3f3f3f3f #define cont continue #define pow_2(n) (1 << (n)) #define ll long long //tree #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define LOG2(n) ((int)(ceil(log2((n))))) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } int main(){ cin.tie(0) -> sync_with_stdio(0); int t; cin >> t; while(t--){ ll n, k; cin >> n >> k; if(n%2ll == 0ll){ ll ans = (k)%n; cout << (ans ? ans : n) << endl; cont; } ll x = n/2ll; k--; k %= (n * x); //k is now 0 based ll skipped = k/x; ll should = k%n; ll ans = skipped + should + 1ll; ans %= n; if(ans) cout << ans; else cout << ans + n; cout << endl; } return 0; }
19.375
51
0.575
[ "vector" ]
f1b28ea179abef4a5ca44d541b5aa721b074b217
15,843
cpp
C++
libNCUI/module/dll/JsTypeMapHandler.cpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
24
2018-11-20T14:45:57.000Z
2021-12-30T13:38:42.000Z
libNCUI/module/dll/JsTypeMapHandler.cpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
null
null
null
libNCUI/module/dll/JsTypeMapHandler.cpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
11
2018-11-29T00:09:14.000Z
2021-11-23T08:13:17.000Z
#include "stdafx.h" #include "module/dll/JsTypeMapHandler.h" #include <windows.h> #include <amo/string.hpp> #include <amo/logger.hpp> #include "module/dll/TypeMapManager.h" #include "module/dll/DllValueHandler.h" namespace amo { template < typename T > void createHandler(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { CefRefPtr<DllValueHandler<T> > handler = new DllValueHandler<T>(); handler->val(object, arguments, retval, except); retval = handler->getV8Object(); } JsTypeMapHandler::JsTypeMapHandler() { setHandlerName("window"); } void JsTypeMapHandler::BOOL(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<bool>(object, arguments, retval, except); } void JsTypeMapHandler::INT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int32_t>(object, arguments, retval, except); } void JsTypeMapHandler::INT8(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int8_t>(object, arguments, retval, except); } void JsTypeMapHandler::INT16(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int16_t>(object, arguments, retval, except); } void JsTypeMapHandler::INT32(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int32_t>(object, arguments, retval, except); } void JsTypeMapHandler::INT64(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int64_t>(object, arguments, retval, except); } void JsTypeMapHandler::UINT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<uint32_t>(object, arguments, retval, except); } void JsTypeMapHandler::UINT8(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<uint8_t>(object, arguments, retval, except); } void JsTypeMapHandler::UINT16(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<uint16_t>(object, arguments, retval, except); } void JsTypeMapHandler::UINT32(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<uint32_t>(object, arguments, retval, except); } void JsTypeMapHandler::UINT64(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<uint64_t>(object, arguments, retval, except); } void JsTypeMapHandler::CHAR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<char>(object, arguments, retval, except); } void JsTypeMapHandler::LONG(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<long>(object, arguments, retval, except); } void JsTypeMapHandler::ULONG(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<unsigned long>(object, arguments, retval, except); } void JsTypeMapHandler::FLOAT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<float>(object, arguments, retval, except); } void JsTypeMapHandler::DOUBLE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<double>(object, arguments, retval, except); } void JsTypeMapHandler::LDOUBLE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<long double>(object, arguments, retval, except); } void JsTypeMapHandler::STR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<std::string>(object, arguments, retval, except); } void JsTypeMapHandler::NIL(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<amo::nil>(object, arguments, retval, except); } void JsTypeMapHandler::BYTE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<::BYTE>(object, arguments, retval, except); } void JsTypeMapHandler::BSTR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::COLORREF(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::DWORD(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<::DWORD>(object, arguments, retval, except); } void JsTypeMapHandler::HANDLE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HBITMAP(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HBRUSH(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HCURSOR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HDC(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HFILE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HFONT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HHOOK(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HKEY(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HPEN(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::HWND(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LONGLONG(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<::LONGLONG>(object, arguments, retval, except); } void JsTypeMapHandler::LPARAM(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPBOOL(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPBYTE(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPCOLOREF(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPCSTR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPCTSTR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPVOID(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::LPDWORD(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::SHORT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<::SHORT>(object, arguments, retval, except); } void JsTypeMapHandler::VARIANT(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::WORD(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<::WORD>(object, arguments, retval, except); } void JsTypeMapHandler::WPARAM(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { } void JsTypeMapHandler::INT_PTR(CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& except) { createHandler<int*>(object, arguments, retval, except); } }
40.415816
74
0.461339
[ "object" ]
f1b853d707c49fd56301f799aced8881580937bc
6,206
cpp
C++
GDML/GDML/GMLParser.cpp
gopi487krishna/GML
06d8ee9f056af09e4034b2fa0fe11653a70d097c
[ "MIT" ]
1
2020-03-19T04:24:09.000Z
2020-03-19T04:24:09.000Z
GDML/GDML/GMLParser.cpp
gopi487krishna/GML
06d8ee9f056af09e4034b2fa0fe11653a70d097c
[ "MIT" ]
null
null
null
GDML/GDML/GMLParser.cpp
gopi487krishna/GML
06d8ee9f056af09e4034b2fa0fe11653a70d097c
[ "MIT" ]
null
null
null
#include "GDML.h" const std::string& gml::ParsingTools::trim(std::string& tag_text, char trimchar) { auto it = std::remove(tag_text.begin(), tag_text.end(), trimchar); tag_text.erase(it, tag_text.end()); return tag_text; } std::vector<std::string> gml::ParsingTools::splitIntoTokens(const std::string& tag_text, const char seperator) { std::vector<std::string> tag_collection; std::string tag; if (tag_text.empty()) { return tag_collection; } for (auto character : tag_text) { if (character == seperator) { tag_collection.push_back(tag); tag.clear(); continue; } tag += character; } if (!tag.empty()) { tag_collection.push_back(tag); } return tag_collection; } std::optional<std::pair<std::string, std::string>> gml::ParsingTools::splitIntoToken(const std::string& text, const char seperator, const std::vector<char>forbidden_list) { auto textbeg = text.begin(); auto textend = text.end(); //default position auto seperator_pos = textend; for (auto iterator = textbeg; iterator != textend; iterator++) { if (!isalpha(*iterator)) { if (*iterator == seperator && seperator_pos == textend) { seperator_pos = iterator; } // For any other kind of character this function should not work else if ((std::find(forbidden_list.begin(), forbidden_list.end(), *iterator) != forbidden_list.end()) && seperator_pos == textend) { return std::nullopt; } } } if (seperator_pos == textend) { return std::nullopt; } else if (seperator_pos == textbeg) { return std::nullopt; } else if (seperator_pos == textend - 1) { return std::make_pair(std::string(textbeg, textend - 1), std::string()); } else { return std::make_pair(std::string(textbeg, seperator_pos), std::string(seperator_pos + 1, textend)); } } bool gml::ParsingTools::isClosed(const std::string& s1, const std::string& s2, char closing_character, char seperation_character) { if (*s2.begin() != closing_character) { return false; } auto split_tag_value = splitIntoToken(s1, seperation_character, {}); return std::equal(split_tag_value->first.begin(), split_tag_value->first.end(), s2.begin() + 1, s2.end()); } bool gml::ParsingTools::isClosed(std::string& str, char closing_character) { return str[0] == closing_character; } std::pair<gml::RawRecord, bool> gml::ParsingTools::fetchRawRecord(std::string::const_iterator stream_pos, const std::string::const_iterator end_pos, const gml::GDML_SYMBOL_PROFILE& syntax_profile) { RawRecord gml_record; // Gets the OpenBrace and CloseBrace position from the token_stream auto getBraceOpenandClosePos = [&syntax_profile](std::string::const_iterator stream_start, std::string::const_iterator stream_end) { auto open_brace_pos = std::find(stream_start, stream_end, syntax_profile.getOpenTag()); if (!(open_brace_pos == stream_end)) { auto close_brace_pos = std::find(open_brace_pos, stream_end, syntax_profile.getCloseTag()); if (!(close_brace_pos == stream_end)) { return std::make_pair(open_brace_pos, close_brace_pos); } } return std::make_pair(stream_end, stream_end); }; auto OTAG_brace_positions = getBraceOpenandClosePos(stream_pos, end_pos); if (!(OTAG_brace_positions.first == end_pos || OTAG_brace_positions.second == end_pos)) { // All the tokens inside [] are obtained gml_record.open_tag_token_stream = std::string(OTAG_brace_positions.first + 1, OTAG_brace_positions.second); trim(gml_record.open_tag_token_stream); //*********************************** // Part for closing tag //*********************************** //-------------------------------------------------------------------------------------------------------------------------- auto CTAG_brace_positions = getBraceOpenandClosePos(OTAG_brace_positions.second + 1, end_pos); if (!(CTAG_brace_positions.first == end_pos || CTAG_brace_positions.second == end_pos)) { // All the tokens inside [/] are obtained gml_record.close_tag_token_stream = std::string(CTAG_brace_positions.first + 1, CTAG_brace_positions.second); trim(gml_record.close_tag_token_stream); if (gml::ParsingTools::isClosed( gml_record.close_tag_token_stream, syntax_profile.getClosingCharacter() ) || gml::ParsingTools::isClosed( gml_record.open_tag_token_stream, gml_record.close_tag_token_stream, syntax_profile.getClosingCharacter(), syntax_profile.getTagValueSeperator() ) ) { gml_record.inner_data = std::string(OTAG_brace_positions.second + 1, CTAG_brace_positions.first); gml_record.record_end_position = CTAG_brace_positions.second; return { gml_record,true }; } } } return { RawRecord(),false }; } std::optional<std::pair<std::string, gml::TagValue_T>> gml::ParsingTools::processSplitToken(const std::string& text, const GDML_SYMBOL_PROFILE& syntax_profile) { auto tag_value_pair = splitIntoToken(text, syntax_profile.getTagValueSeperator(), { syntax_profile.getAttributeListOpen(),syntax_profile.getAttributeListClose() }); if (tag_value_pair.has_value()) { if ((!tag_value_pair->second.empty()) && *tag_value_pair->second.begin() == syntax_profile.getAttributeListOpen()) { auto attribute_list_close_pos = std::find(tag_value_pair->second.begin(), tag_value_pair->second.end(), syntax_profile.getAttributeListClose()); //Covers the case if along with attribute list some other text was also specified like [print:{color:blue} This is not allowed] Hello [/] if (!(attribute_list_close_pos == tag_value_pair->second.end() || attribute_list_close_pos != tag_value_pair->second.end() - 1)) { std::string parse_string(tag_value_pair->second.begin() + 1, attribute_list_close_pos); auto attributelist = splitIntoTokens(parse_string, syntax_profile.getAttributeSeperator()); std::map<std::string, std::string> my_map; for (auto& tag : attributelist) { auto x = splitIntoToken(tag, syntax_profile.getTagValueSeperator(), {}); my_map[x->first] = x->second; } return std::make_pair(tag_value_pair->first, std::move(my_map)); } return std::nullopt; } return std::make_pair(tag_value_pair->first, tag_value_pair->second); } return std::nullopt; }
29.273585
198
0.700129
[ "vector" ]
f1bc8507b9b3e1b6cfff2a9b014dfef776866fd2
1,827
hpp
C++
include/depthai/pipeline/datatype/StereoDepthConfig.hpp
SpectacularAI/depthai-core
7516ca0d179c5f0769ecdab0020ac3a6de09cab9
[ "MIT" ]
null
null
null
include/depthai/pipeline/datatype/StereoDepthConfig.hpp
SpectacularAI/depthai-core
7516ca0d179c5f0769ecdab0020ac3a6de09cab9
[ "MIT" ]
null
null
null
include/depthai/pipeline/datatype/StereoDepthConfig.hpp
SpectacularAI/depthai-core
7516ca0d179c5f0769ecdab0020ac3a6de09cab9
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <vector> #include "depthai-shared/datatype/RawStereoDepthConfig.hpp" #include "depthai/pipeline/datatype/Buffer.hpp" namespace dai { /** * StereoDepthConfig message. */ class StereoDepthConfig : public Buffer { std::shared_ptr<RawBuffer> serialize() const override; RawStereoDepthConfig& cfg; public: /** * Construct StereoDepthConfig message. */ StereoDepthConfig(); explicit StereoDepthConfig(std::shared_ptr<RawStereoDepthConfig> ptr); virtual ~StereoDepthConfig() = default; /** * Confidence threshold for disparity calculation * @param confThr Confidence threshold value 0..255 */ void setConfidenceThreshold(int confThr); /** * Get confidence threshold for disparity calculation */ int getConfidenceThreshold() const; /** * @param median Set kernel size for disparity/depth median filtering, or disable */ void setMedianFilter(dai::MedianFilter median); /** * Get median filter setting */ dai::MedianFilter getMedianFilter() const; /** * A larger value of the parameter means that farther colors within the pixel neighborhood will be mixed together, * resulting in larger areas of semi-equal color. * @param sigma Set sigma value for 5x5 bilateral filter. 0..65535 */ void setBilateralFilterSigma(uint16_t sigma); /** * Get sigma value for 5x5 bilateral filter */ uint16_t getBilateralFilterSigma() const; /** * @param threshold Set threshold for left-right, right-left disparity map combine, 0..255 */ void setLeftRightCheckThreshold(int threshold); /** * Get threshold for left-right check combine */ int getLeftRightCheckThreshold() const; }; } // namespace dai
27.268657
118
0.68856
[ "vector" ]
f1be3d4b7b374af763594ae60d8c495a470f04f6
19,859
cpp
C++
RadeonGPUAnalyzerBackend/Src/beUtils.cpp
jeongjoonyoo/AMD_RGA
26c6bfdf83f372eeadb1874420aa2ed55569d50f
[ "MIT" ]
null
null
null
RadeonGPUAnalyzerBackend/Src/beUtils.cpp
jeongjoonyoo/AMD_RGA
26c6bfdf83f372eeadb1874420aa2ed55569d50f
[ "MIT" ]
null
null
null
RadeonGPUAnalyzerBackend/Src/beUtils.cpp
jeongjoonyoo/AMD_RGA
26c6bfdf83f372eeadb1874420aa2ed55569d50f
[ "MIT" ]
null
null
null
//================================================================= // Copyright 2017 Advanced Micro Devices, Inc. All rights reserved. //================================================================= // C++. #include <algorithm> #include <sstream> #include <fstream> #include <iostream> #include <cctype> #include <cwctype> // Infra. #ifdef _WIN32 #pragma warning(push) #pragma warning(disable:4309) #endif #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTOSWrappers/Include/osFilePath.h> #include <AMDTOSWrappers/Include/osFile.h> #include <AMDTOSWrappers/Include/osApplication.h> #ifdef _WIN32 #pragma warning(pop) #endif // Local. #include <RadeonGPUAnalyzerBackend/Include/beUtils.h> #include <RadeonGPUAnalyzerBackend/Include/beStringConstants.h> #include <DeviceInfoUtils.h> #include <DeviceInfo.h> // CLI. #include <RadeonGPUAnalyzerCLI/Src/kcUtils.h> // Constants. static const char* STR_ERROR_CODE_OBJECT_PARSE_FAILURE = "Error: failed to parse Code Object .text section."; static const char* STR_ERROR_LC_DISASSEMBLER_LAUNCH_FAILURE = "Error: failed to launch the LC disassembler."; // *** INTERNALLY-LINKED AUXILIARY FUNCTIONS - BEGIN *** // Converts string to its lower-case version. std::string ToLower(const std::string& str) { std::string lstr = str; std::transform(lstr.begin(), lstr.end(), lstr.begin(), [](const char& c) {return std::tolower(c); }); return lstr; } // Retrieves the list of devices according to the given HW generation. static void AddGenerationDevices(GDT_HW_GENERATION hwGen, std::vector<GDT_GfxCardInfo>& cardList, std::set<std::string> &uniqueNamesOfPublishedDevices, bool convertToLower = false) { std::vector<GDT_GfxCardInfo> cardListBuffer; if (AMDTDeviceInfoUtils::Instance()->GetAllCardsInHardwareGeneration(hwGen, cardListBuffer)) { cardList.insert(cardList.end(), cardListBuffer.begin(), cardListBuffer.end()); for (const GDT_GfxCardInfo& cardInfo : cardListBuffer) { uniqueNamesOfPublishedDevices.insert(convertToLower ? ToLower(cardInfo.m_szCALName) : cardInfo.m_szCALName); } } } // *** INTERNALLY-LINKED AUXILIARY FUNCTIONS - END *** bool beUtils::GdtHwGenToNumericValue(GDT_HW_GENERATION hwGen, size_t& gfxIp) { const size_t BE_GFX_IP_6 = 6; const size_t BE_GFX_IP_7 = 7; const size_t BE_GFX_IP_8 = 8; const size_t BE_GFX_IP_9 = 9; const size_t BE_GFX_IP_10 = 10; bool ret = true; switch (hwGen) { case GDT_HW_GENERATION_SOUTHERNISLAND: gfxIp = BE_GFX_IP_6; break; case GDT_HW_GENERATION_SEAISLAND: gfxIp = BE_GFX_IP_7; break; case GDT_HW_GENERATION_VOLCANICISLAND: gfxIp = BE_GFX_IP_8; break; case GDT_HW_GENERATION_GFX9: gfxIp = BE_GFX_IP_9; break; case GDT_HW_GENERATION_GFX10: gfxIp = BE_GFX_IP_10; break; case GDT_HW_GENERATION_NONE: case GDT_HW_GENERATION_NVIDIA: case GDT_HW_GENERATION_LAST: default: // We should not get here. GT_ASSERT_EX(false, L"Unsupported HW Generation."); ret = false; break; } return ret; } bool beUtils::GdtHwGenToString(GDT_HW_GENERATION hwGen, std::string& hwGenAsStr) { const char* BE_GFX_IP_6 = "SI"; const char* BE_GFX_IP_7 = "CI"; const char* BE_GFX_IP_8 = "VI"; bool ret = true; switch (hwGen) { case GDT_HW_GENERATION_SOUTHERNISLAND: hwGenAsStr = BE_GFX_IP_6; break; case GDT_HW_GENERATION_SEAISLAND: hwGenAsStr = BE_GFX_IP_7; break; case GDT_HW_GENERATION_VOLCANICISLAND: hwGenAsStr = BE_GFX_IP_8; break; case GDT_HW_GENERATION_NONE: case GDT_HW_GENERATION_NVIDIA: case GDT_HW_GENERATION_LAST: default: // We should not get here. GT_ASSERT_EX(false, L"Unsupported HW Generation."); ret = false; break; } return ret; } bool beUtils::GfxCardInfoSortPredicate(const GDT_GfxCardInfo& a, const GDT_GfxCardInfo& b) { // Generation is the primary key. if (a.m_generation < b.m_generation) { return true; } if (a.m_generation > b.m_generation) { return false; } // CAL name is next. int ret = ::strcmp(a.m_szCALName, b.m_szCALName); if (ret < 0) { return true; } if (ret > 0) { return false; } // Marketing name next. ret = ::strcmp(a.m_szMarketingName, b.m_szMarketingName); if (ret < 0) { return true; } if (ret > 0) { return false; } // DeviceID last. return a.m_deviceID < b.m_deviceID; } struct lex_compare { bool operator() (const int64_t& lhs, const int64_t& rhs) const { } }; bool beUtils::GetAllGraphicsCards(std::vector<GDT_GfxCardInfo>& cardList, std::set<std::string>& uniqueNamesOfPublishedDevices, bool convertToLower /*= false*/) { // Retrieve the list of devices for every relevant hardware generations. AddGenerationDevices(GDT_HW_GENERATION_SOUTHERNISLAND, cardList, uniqueNamesOfPublishedDevices, convertToLower); AddGenerationDevices(GDT_HW_GENERATION_SEAISLAND, cardList, uniqueNamesOfPublishedDevices, convertToLower); AddGenerationDevices(GDT_HW_GENERATION_VOLCANICISLAND, cardList, uniqueNamesOfPublishedDevices, convertToLower); AddGenerationDevices(GDT_HW_GENERATION_GFX9, cardList, uniqueNamesOfPublishedDevices, convertToLower); AddGenerationDevices(GDT_HW_GENERATION_GFX10, cardList, uniqueNamesOfPublishedDevices, convertToLower); return (!cardList.empty() && !uniqueNamesOfPublishedDevices.empty()); } bool beUtils::GetMarketingNameToCodenameMapping(std::map<std::string, std::set<std::string>>& cardsMap) { std::vector<GDT_GfxCardInfo> cardList; std::set<std::string> uniqueNames; // Retrieve the list of all supported cards. bool ret = GetAllGraphicsCards(cardList, uniqueNames); if (ret) { for (const GDT_GfxCardInfo& card : cardList) { if (card.m_szMarketingName != nullptr && card.m_szCALName != nullptr && (strlen(card.m_szMarketingName) > 1) && (strlen(card.m_szCALName) > 1)) { // Create the key string. std::string displayName; ret = AMDTDeviceInfoUtils::Instance()->GetHardwareGenerationDisplayName(card.m_generation, displayName); if (ret) { std::stringstream nameBuilder; nameBuilder << card.m_szCALName << " (" << displayName << ")"; // Add this item to the relevant container in the map. cardsMap[nameBuilder.str()].insert(card.m_szMarketingName); } } } } return ret; } void beUtils::DeleteOutputFiles(const beProgramPipeline& outputFilePaths) { DeleteFileFromDisk(outputFilePaths.m_vertexShader); DeleteFileFromDisk(outputFilePaths.m_tessControlShader); DeleteFileFromDisk(outputFilePaths.m_tessEvaluationShader); DeleteFileFromDisk(outputFilePaths.m_geometryShader); DeleteFileFromDisk(outputFilePaths.m_fragmentShader); DeleteFileFromDisk(outputFilePaths.m_computeShader); } void beUtils::DeleteFileFromDisk(const gtString& filePath) { osFilePath osPath(filePath); if (osPath.exists()) { osFile osFile(osPath); osFile.deleteFile(); } } void beUtils::DeleteFileFromDisk(const std::string& filePath) { gtString gPath; gPath << filePath.c_str(); return DeleteFileFromDisk(gPath); } bool beUtils::IsFilePresent(const std::string& fileName) { bool ret = true; if (!fileName.empty()) { std::ifstream file(fileName); ret = (file.good() && file.peek() != std::ifstream::traits_type::eof()); } return ret; } std::string beUtils::GetFileExtension(const std::string& fileName) { size_t offset = fileName.rfind('.'); const std::string& ext = (offset != std::string::npos && ++offset < fileName.size()) ? fileName.substr(offset) : ""; return ext; } bool beUtils::ReadBinaryFile(const std::string& fileName, std::vector<char>& content) { bool ret = false; std::ifstream input; input.open(fileName.c_str(), std::ios::binary); if (input.is_open()) { content = std::vector<char>(std::istreambuf_iterator<char>(input), {}); ret = !content.empty(); } return ret; } bool beUtils::IsFilesIdentical(const std::string& fileName1, const std::string& fileName2) { std::vector<char> content1; std::vector<char> content2; bool isFileRead1 = beUtils::ReadBinaryFile(fileName1, content1); bool isFileRead2 = beUtils::ReadBinaryFile(fileName2, content2); return (isFileRead1 && isFileRead2 && std::equal(content1.begin(), content1.end(), content2.begin())); } void beUtils::PrintCmdLine(const std::string & cmdLine, bool doPrint) { if (doPrint) { std::cout << std::endl << BE_STR_LAUNCH_EXTERNAL_PROCESS << cmdLine << std::endl << std::endl; } } void beUtils::splitString(const std::string& str, char delim, std::vector<std::string>& dst) { std::stringstream ss; ss.str(str); std::string substr; while (std::getline(ss, substr, delim)) { dst.push_back(substr); } } bool beUtils::DeviceNameLessThan(const std::string& a, const std::string& b) { const char* GFX_NOTATION_TOKEN = "gfx"; bool ret = true; size_t szA = a.find(GFX_NOTATION_TOKEN); size_t szB = b.find(GFX_NOTATION_TOKEN); if (szA == std::string::npos && szB == std::string::npos) { // Neither name is in gfx-notation, compare using standard string logic. ret = a.compare(b) < 0; } else if (!(szA != std::string::npos && szB != std::string::npos)) { // Only one name has the gfx notation, assume that it is a newer generation. ret = (szB != std::string::npos); } else { // Both names are in gfx notation, compare according to the number. std::vector<std::string> splitA; std::vector<std::string> splitB; beUtils::splitString(a, 'x', splitA); beUtils::splitString(b, 'x', splitB); assert(splitA.size() > 1); assert(splitB.size() > 1); if (splitA.size() > 1 && splitB.size() > 1) { try { int numA = std::stoi(splitA[1], nullptr); int numB = std::stoi(splitB[1], nullptr); ret = ((numB - numA) > 0); } catch (...) { ret = false; } } } return ret; } bool beUtils::DisassembleCodeObject(const std::string& coFileName, bool shouldPrintCmd, std::string& disassemblyWhole, std::string& disassemblyText, std::string& errorMsg) { // Build the command. std::stringstream cmd; cmd << coFileName; osFilePath lcDisassemblerExe; long exitCode = 0; osGetCurrentApplicationPath(lcDisassemblerExe, false); lcDisassemblerExe.appendSubDirectory(LC_DISASSEMBLER_DIR); lcDisassemblerExe.setFileName(LC_DISASSEMBLER_EXE); // Clear the error message buffer. errorMsg.clear(); std::string outText; kcUtils::ProcessStatus status = kcUtils::LaunchProcess(lcDisassemblerExe.asString().asASCIICharArray(), cmd.str(), "", PROCESS_WAIT_INFINITE, shouldPrintCmd, outText, errorMsg, exitCode); // Extract the .text disassembly. assert(!outText.empty()); disassemblyWhole = outText; if (!disassemblyWhole.empty()) { // Find where the .text section starts. size_t textOffsetStart = disassemblyWhole.find(".text"); assert(textOffsetStart != std::string::npos); assert(textOffsetStart != std::string::npos && textOffsetStart < disassemblyWhole.size() + 5); if (textOffsetStart < disassemblyWhole.size() + 5) { // Skip .text identifier. textOffsetStart += 5; // Find where the relevant portion of the disassembly ends. size_t textOffsetEnd = disassemblyWhole.find("s_code_end"); assert(textOffsetEnd != std::string::npos); if (textOffsetEnd != std::string::npos) { // Extract the relevant section. size_t numCharacters = textOffsetEnd - textOffsetStart; assert(numCharacters > 0); assert(numCharacters < disassemblyWhole.size() - textOffsetStart); if (numCharacters > 0 && numCharacters < disassemblyWhole.size() - textOffsetStart) { disassemblyText = disassemblyWhole.substr(textOffsetStart, numCharacters); } else if (errorMsg.empty()) { errorMsg = STR_ERROR_CODE_OBJECT_PARSE_FAILURE; } } else if (errorMsg.empty()) { errorMsg = STR_ERROR_CODE_OBJECT_PARSE_FAILURE; } } } if (disassemblyText.empty()) { if (status == kcUtils::ProcessStatus::Success && errorMsg.empty()) { errorMsg = STR_ERROR_LC_DISASSEMBLER_LAUNCH_FAILURE; } } return (status == kcUtils::ProcessStatus::Success ? beStatus_SUCCESS : beStatus_dx12BackendLaunchFailure); } static bool ExtractAttributeValue(const std::string &disassemblyWhole, size_t kdPos, const std::string& attributeName, uint32_t& value) { bool ret = false; bool shouldAbort = false; bool isBefore = false; try { // Offset where our attribute is within the string. size_t startPosTemp = 0; // The reference symbol. const std::string KD_SYMBOL_TOKEN = ".symbol:"; if (attributeName < KD_SYMBOL_TOKEN) { // Look before the reference symbol. startPosTemp = disassemblyWhole.rfind(attributeName, kdPos); isBefore = true; } else if (attributeName > KD_SYMBOL_TOKEN) { // Look after the reference symbol. startPosTemp = disassemblyWhole.find(attributeName, kdPos); } else { // We shouldn't get here. assert(false); shouldAbort = true; } if (!shouldAbort) { startPosTemp += attributeName.size(); assert((isBefore && startPosTemp < kdPos) || (!isBefore && startPosTemp > kdPos)); if ((isBefore && startPosTemp < kdPos) || (!isBefore && startPosTemp > kdPos)) { while (std::iswspace(disassemblyWhole[++startPosTemp])); assert((isBefore && startPosTemp < kdPos) || (!isBefore && startPosTemp > kdPos)); if ((isBefore && startPosTemp < kdPos) || (!isBefore && startPosTemp > kdPos)) { size_t endPos = startPosTemp; while (!std::iswspace(disassemblyWhole[++endPos])); assert(startPosTemp < endPos); if (startPosTemp < endPos) { // Extract the string representing the value and convert to non-negative decimal number. std::string valueAsStr = disassemblyWhole.substr(startPosTemp, endPos - startPosTemp); std::stringstream conversionStream; conversionStream << std::hex << valueAsStr; conversionStream >> value; ret = true; } } } } } catch (...) { // Failure occurred. ret = false; } return ret; } bool beUtils::ExtractCodeObjectStatistics(const std::string& disassemblyWhole, std::map<std::string, beKA::AnalysisData>& dataMap) { bool ret = false; dataMap.clear(); const char* KERNEL_SYMBOL_TOKEN = ".kd"; size_t startPos = disassemblyWhole.find(KERNEL_SYMBOL_TOKEN); while (startPos != std::string::npos) { // Extract the kernel name. std::string kernelName; size_t startPosTemp = startPos; std::stringstream kernelNameStream; while (--startPosTemp > 0 && !std::iswspace(disassemblyWhole[startPosTemp])); assert(startPosTemp + 1 < startPos - 1); if (startPosTemp + 1 < startPos - 1) { kernelName = disassemblyWhole.substr(startPosTemp + 1, startPos - startPosTemp - 1); auto iter = dataMap.find(kernelName); assert(iter == dataMap.end()); if (iter == dataMap.end()) { // LDS. const std::string LDS_USAGE_TOKEN = ".group_segment_fixed_size:"; uint32_t ldsUsage = 0; bool isOk = ExtractAttributeValue(disassemblyWhole, startPos, LDS_USAGE_TOKEN, ldsUsage); assert(isOk); // SGPR count. const std::string SGPR_COUNT_TOKEN = ".sgpr_count:"; uint32_t sgprCount = 0; isOk = ExtractAttributeValue(disassemblyWhole, startPos, SGPR_COUNT_TOKEN, sgprCount); assert(isOk); // SGPR spill count. const std::string SGPR_SPILL_COUNT_TOKEN = ".sgpr_spill_count:"; uint32_t sgprSpillCount = 0; isOk = ExtractAttributeValue(disassemblyWhole, startPos, SGPR_SPILL_COUNT_TOKEN, sgprSpillCount); assert(isOk); // VGPR count. const std::string VGPR_COUNT_TOKEN = ".vgpr_count:"; uint32_t vgprCount = 0; isOk = ExtractAttributeValue(disassemblyWhole, startPos, VGPR_COUNT_TOKEN, vgprCount); assert(isOk); // VGPR spill count. const std::string VGPR_SPILL_COUNT_TOKEN = ".vgpr_spill_count"; uint32_t vgprSpillCount = 0; isOk = ExtractAttributeValue(disassemblyWhole, startPos, VGPR_SPILL_COUNT_TOKEN, vgprSpillCount); assert(isOk); // Wavefront size. const std::string WAVEFRONT_SIZE_TOKEN = ".wavefront_size:"; uint32_t wavefrontSize = 0; isOk = ExtractAttributeValue(disassemblyWhole, startPos, WAVEFRONT_SIZE_TOKEN, wavefrontSize); assert(isOk); // Add values which were extracted from the Code Object meta data. AnalysisData data; data.LDSSizeUsed = ldsUsage; data.numSGPRsUsed = sgprCount; data.numSGPRSpills = sgprSpillCount; data.numVGPRsUsed = vgprCount; data.numVGPRSpills = vgprSpillCount; data.wavefrontSize = wavefrontSize; // Add fixed values. data.LDSSizeAvailable = 65536; data.numVGPRsAvailable = 256; data.numSGPRsAvailable = 104; // Add the kernel's stats to the map. dataMap[kernelName] = data; // Move to the next kernel. startPos = disassemblyWhole.find(KERNEL_SYMBOL_TOKEN, startPos + 1); } } } ret = !dataMap.empty(); return ret; }
33.831346
136
0.597412
[ "object", "vector", "transform" ]
f1bfcc6028dc8c54b084b8874faf843daee7e3be
2,445
cpp
C++
main.cpp
lukaszplk/conv_hex_to_dec_and_back
d2a15f77effcdae525aca3840dd42ca776efb7df
[ "MIT" ]
null
null
null
main.cpp
lukaszplk/conv_hex_to_dec_and_back
d2a15f77effcdae525aca3840dd42ca776efb7df
[ "MIT" ]
null
null
null
main.cpp
lukaszplk/conv_hex_to_dec_and_back
d2a15f77effcdae525aca3840dd42ca776efb7df
[ "MIT" ]
null
null
null
#include <string> #include<iostream> #include<vector> #include <algorithm> #include <math.h> using namespace std; int strtoi(string x) { int num = 0; for (int i = 0; i < x.length(); i++) { num = num * 10 + (int(x[i]) - 48); } return num; } string conv(int n, int m) { string num = ""; int rest; if(n == 0){ num +='0'; } while (n != 0) { rest = n % m; if (rest > 9) num += rest + 55; else num += rest + 48; n /= m; } reverse(num.begin(), num.end()); return num; } int main(){ vector<string> vec; string input_string = "0", hex_num_str, final_hex; int dec_num; while(input_string.compare("-1") != 0){ cin >> input_string; dec_num = 0; if(input_string[0] == '0' && input_string[1] == 'x'){ for(int i = input_string.size()-1; i > 1; i--){ if(input_string.substr(i,1) == "A"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 10; }else if(input_string.substr(i,1) == "B"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 11; }else if(input_string.substr(i,1)=="C"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 12; }else if(input_string.substr(i,1)=="D"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 13; }else if(input_string.substr(i,1)=="E"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 14; }else if(input_string.substr(i,1)=="F"){ dec_num += (pow(16, (((input_string.size()-1)-i)))) * 15; }else{ dec_num += pow(16, (((input_string.size()-1)-i))) * strtoi(input_string.substr(i,1)); } } vec.push_back(conv(dec_num, 10)); }else{ dec_num = strtoi(input_string); hex_num_str = conv(dec_num, 16); final_hex = "0x"; for(int i=0; i < hex_num_str.length(); i++){ final_hex.push_back(hex_num_str[i]); } vec.push_back(final_hex); } } for(int i = 0; i < vec.size()-1; i++){ cout << vec[i] << "\n"; } }
29.817073
106
0.428221
[ "vector" ]
f1c8955c0f9d1855d4e9cf4470253161b3321bf4
2,623
cpp
C++
src/boost_python_exception/standard_exception_translator.cpp
abingham/boost_python_exception
7882d5e8df051494498a58c06e046cb52421620b
[ "BSL-1.0" ]
1
2015-03-28T08:28:56.000Z
2015-03-28T08:28:56.000Z
src/boost_python_exception/standard_exception_translator.cpp
abingham/boost_python_exception
7882d5e8df051494498a58c06e046cb52421620b
[ "BSL-1.0" ]
3
2015-01-08T08:10:55.000Z
2015-01-08T10:20:42.000Z
src/boost_python_exception/standard_exception_translator.cpp
abingham/boost_python_exception
7882d5e8df051494498a58c06e046cb52421620b
[ "BSL-1.0" ]
2
2018-11-13T07:42:31.000Z
2020-03-10T22:43:31.000Z
#include <boost_python_exception/standard_exception_translator.hpp> #include <sstream> #include <boost/python/extract.hpp> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <boost_python_exception/exceptions.hpp> #include <boost_python_exception/python_compat.hpp> #include <boost_python_exception/util.hpp> namespace bp = boost::python; namespace boost_python_exception { namespace { std::string make_syntax_error_message(bp::object error) { std::string const module_name = bp::extract<std::string>(error.attr("filename")); std::string const code = bp::extract<std::string>(error.attr("text")); // for some reason, extract<long> does not work while a python error is set, so do it with CPython long const line_number = python_integral_as_long(bp::object(error.attr("lineno")).ptr()); long const pos_in_line = python_integral_as_long(bp::object(error.attr("offset")).ptr()); std::ostringstream message; message << "In module \"" << module_name << "\", line " << line_number << ", position " << pos_in_line << ":\n"; message << "Offending code: " << code; message << " " << std::string(pos_in_line-1, ' ') << "^"; return message.str(); } void throw_syntax_error(exception_info const & exc_info) { throw syntax_error( extract_exception_type(exc_info.type), make_syntax_error_message(exc_info.value), extract_traceback(exc_info.traceback)); } } exception_translator create_standard_exception_translator() { exception_translator translator; typedef std::map<std::string const, exception_translator::thrower> translation_map; // To add new translations, simply update the contents of this map. translation_map translations = boost::assign::map_list_of ("AttributeError", throw_with_python_info<attribute_error>) ("ImportError", throw_with_python_info<import_error>) ("IndexError", throw_with_python_info<index_error>) ("IOError", throw_with_python_info<io_error>) ("KeyError", throw_with_python_info<key_error>) ("TypeError", throw_with_python_info<type_error>) ("ReferenceError", throw_with_python_info<reference_error>) ("ValueError", throw_with_python_info<value_error>) ("StopIteration", throw_with_python_info<stop_iteration>) ("SyntaxError", throw_syntax_error) ; BOOST_FOREACH(translation_map::value_type const & mapping, translations) { translator.add( builtins().attr(mapping.first.c_str()), mapping.second); } return translator; } }
33.628205
116
0.704156
[ "object" ]
f1d3fcf1f0d57a1cdc202b51dc9b5dbe920f16a7
1,071
hpp
C++
src/topfd/common/topfd_process.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/topfd/common/topfd_process.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/topfd/common/topfd_process.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //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 TOPPIC_TOPFD_COMMON_TOPFD_PROCESS_HPP_ #define TOPPIC_TOPFD_COMMON_TOPFD_PROCESS_HPP_ #include <string> #include <vector> #include "topfd/common/topfd_para.hpp" namespace toppic { namespace topfd_process { int processOneFile(TopfdParaPtr para_ptr, const std::string &spec_file_name, int frac_id); int process(TopfdParaPtr para_ptr, std::vector<std::string> spec_file_lst); } } #endif
27.461538
74
0.734827
[ "vector" ]
f1d5f302161b7e083e2968340de5b65336f768a8
3,580
cpp
C++
src/prelude.cpp
mpetri/ans-large-alphabet
416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff
[ "Apache-2.0" ]
null
null
null
src/prelude.cpp
mpetri/ans-large-alphabet
416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff
[ "Apache-2.0" ]
null
null
null
src/prelude.cpp
mpetri/ans-large-alphabet
416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff
[ "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 <iostream> #include <vector> #define RECORD_STATS 1 #include "cutil.hpp" #include "methods.hpp" #include "stats.hpp" #include "util.hpp" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/regex.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; po::variables_map parse_cmdargs(int argc, char const* argv[]) { po::variables_map vm; po::options_description desc("Allowed options"); // clang-format off desc.add_options() ("help,h", "produce help message") ("text,t", "text input (default is uint32_t binary)") ("input,i",po::value<std::string>()->required(), "the input dir"); // clang-format on try { po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << "\n"; exit(EXIT_SUCCESS); } po::notify(vm); } catch (const po::required_option& e) { std::cout << desc; std::cerr << "Missing required option: " << e.what() << std::endl; exit(EXIT_FAILURE); } catch (po::error& e) { std::cout << desc; std::cerr << "Error parsing cmdargs: " << e.what() << std::endl; exit(EXIT_FAILURE); } return vm; } int main(int argc, char const* argv[]) { auto cmdargs = parse_cmdargs(argc, argv); auto input_dir = cmdargs["input"].as<std::string>(); boost::regex input_file_filter(".*\\.u32"); if (cmdargs.count("text")) { input_file_filter = boost::regex(".*\\.txt"); } // single file also works! boost::filesystem::path p(input_dir); if (boost::filesystem::is_regular_file(p)) { input_file_filter = boost::regex(p.filename().string()); input_dir = p.parent_path().string(); } boost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end for (boost::filesystem::directory_iterator i(input_dir); i != end_itr; ++i) { if (!boost::filesystem::is_regular_file(i->status())) continue; boost::smatch what; if (!boost::regex_match( i->path().filename().string(), what, input_file_filter)) continue; std::string file_name = i->path().string(); std::vector<uint32_t> input_u32s; if (cmdargs.count("text")) { input_u32s = read_file_text(file_name); } else { input_u32s = read_file_u32(file_name); } std::string short_name = i->path().stem().string(); uint32_t max_sigma = 0; for (auto x : input_u32s) max_sigma = std::max(x, max_sigma); std::cout << short_name << "\t " << max_sigma << std::endl; } return EXIT_SUCCESS; }
32.252252
74
0.623743
[ "vector" ]
f1d66dff5c0604dab89dd84f2ad1a740e3b74f42
5,469
cpp
C++
source/DrawArea.cpp
X-141/JpDrawApplication
365bd934bf907465f9dcd0d331c8f0ebb350c2c3
[ "MIT" ]
1
2021-06-08T00:01:17.000Z
2021-06-08T00:01:17.000Z
source/DrawArea.cpp
X-141/JpDrawApplication
365bd934bf907465f9dcd0d331c8f0ebb350c2c3
[ "MIT" ]
null
null
null
source/DrawArea.cpp
X-141/JpDrawApplication
365bd934bf907465f9dcd0d331c8f0ebb350c2c3
[ "MIT" ]
null
null
null
#include "DrawArea.hpp" #include <QPainter> #include <QMouseEvent> #include <QPixmap> #include <QDir> #include <QVector> #include <QRegularExpression> #include "ImageProcessMethods.hpp" #include "opencv2/imgproc.hpp" #include "Log.hpp" std::string resourcePath = "../resource/"; DrawArea::DrawArea(QWidget* parent) : QLabel(parent), mCurrentlyDrawing(false), mHardLayer(this->size(), 0), mVirtualLayer(this->size(), 0), mId(1), mPenWidth(30), mKnn(cv::ml::KNearest::load(resourcePath + "kNN_ETL_Subset.opknn")), mKnnDictFilepath(resourcePath + "kNNDictionary.txt") { this->clear(); mHardLayer.fill(); // set to white. this->setPixmap(mHardLayer); mVirtualLayerVector.reserve(32); pResourceCharacterImages(); } void DrawArea::mousePressEvent(QMouseEvent* event) { // qDebug() << "Mouse press: " << event->pos() << "\n"; //mVirtualLayer = DrawLayer(this->size(), mId++); mVirtualLayer.setId(mId++); mVirtualLayer.fill(Qt::transparent); updateDrawArea(); // Indicate that we are beginning to draw. mCurrentlyDrawing = true; // Draw the starting point. mPrevPoint = event->pos(); pDrawPoint(event->pos()); } void DrawArea::mouseReleaseEvent(QMouseEvent* event) { // qDebug() << "Mouse release: " << event->pos() << "\n"; // Add the finished layer to layer vector mVirtualLayer.setEnableStatus(true); mVirtualLayerVector.append(mVirtualLayer); // Call update handle to let other objects or owner // know of the changes. layerUpdateHandle(); // We have finished drawing the layer mCurrentlyDrawing = false; // Indicate that the mPrevPoint is invalid. mPrevPoint = QPoint(-1,-1); } void DrawArea::mouseMoveEvent(QMouseEvent *event) { if(mCurrentlyDrawing) pDrawPoint(event->pos()); } void DrawArea::resizeDrawArea(QSize aSize) { // First clear out current label and resize this->clear(); resize(aSize); // Be careful, We are not really copying any pixel data // from the original pixmap(s), we are just resizing. mHardLayer = DrawLayer(aSize, mHardLayer.getId()); mVirtualLayer = DrawLayer(aSize, mVirtualLayer.getId()); // Set the pixmap in this object (recall we are a QLabel). this->setPixmap(mHardLayer); } void DrawArea::updateDrawArea() { this->clear(); //mHardLayer = DrawLayer(this->size(), mVirtualLayer.getId()); mHardLayer.fill(); QPainter painter = QPainter(&mHardLayer); for(const auto& layers: mVirtualLayerVector) if(layers.isEnabled()) painter.drawPixmap(0,0, layers); this->setPixmap(mHardLayer); painter.end(); } QImage DrawArea::generateImage() { return mHardLayer.toImage(); } void DrawArea::setPenWidth(int width) { if (width >= 1) mPenWidth = width; else LOG(level::warning, "DrawArea::setPenWidth()","Tried to set pen width < 1."); } int DrawArea::compareLayer() { // we will get the entire draw area. cv::Mat hardLayerMat = ImageMethods::qImageToCvMat(generateImage().copy(0,0, 384, 384)); // for our image we do need to invert the colors from white-bg black-fg to white-fg black-bg cv::bitwise_not(hardLayerMat, hardLayerMat); //return TechniqueMethods::ROITranslocation(mKnn, hardLayerMat, true); auto scaledImages = TechniqueMethods::ROIRescaling(hardLayerMat, true); return ImageMethods::passThroughKNNModel(mKnn, scaledImages); } QImage DrawArea::getResourceCharacterImage(int index) { return mComparisonImagesDict[index]; } void DrawArea::undoLayer() { uint vectorSize = mVirtualLayerVector.size(); if (vectorSize) { mVirtualLayerVector.remove(vectorSize - 1); updateDrawArea(); } } void DrawArea::pDrawPoint(QPoint aPoint) { auto painter_hard = QPainter(&mHardLayer); auto painter_virt = QPainter(&mVirtualLayer); QPen pen = QPen(Qt::black, mPenWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); painter_hard.setPen(pen); painter_virt.setPen(pen); painter_hard.drawLine(mPrevPoint, aPoint); painter_virt.drawLine(mPrevPoint, aPoint); mPrevPoint = aPoint; painter_hard.end(); painter_virt.end(); this->setPixmap(mHardLayer); } void DrawArea::pResourceCharacterImages() { QFile knnDictFile = QFile(mKnnDictFilepath.c_str()); if(!knnDictFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QDir resourceDir = QDir(QString(resourcePath.c_str())); QStringList images = resourceDir.entryList(QStringList() << "*.png" << "*.PNG", QDir::Files); QTextStream in(&knnDictFile); QRegularExpression reg_txt("(?<character>\\w+),(?<number>\\d+)"); QRegularExpression reg_png("(?<character>\\w+).png"); while(!in.atEnd()) { QString line = in.readLine(); auto match_txt = reg_txt.match(line); for(auto png : images) { auto match_png = reg_png.match(png); if (match_png.captured("character") == match_txt.captured("character")) { LOG(level::standard, "DrawArea::pResourceCharacterImages()", QString(match_png.captured("character") + " " + match_txt.captured("number"))); mComparisonImagesDict.insert(match_txt.captured("number").toInt(), QImage(resourceDir.filePath(png))); images.removeOne(png); break; } } } }
29.722826
99
0.659353
[ "object", "vector" ]
f1d88caa3b81a0aa9be33b6645a8efb206141884
7,706
hpp
C++
ad_map_access/impl/include/ad/map/lane/BorderOperation.hpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/include/ad/map/lane/BorderOperation.hpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/include/ad/map/lane/BorderOperation.hpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #pragma once #include "ad/map/lane/Types.hpp" #include "ad/map/point/ECEFOperation.hpp" #include "ad/map/point/ENUOperation.hpp" #include "ad/map/point/GeoOperation.hpp" #include "ad/map/point/HeadingOperation.hpp" /** @brief namespace ad */ namespace ad { /** @brief namespace map */ namespace map { /** @brief namespace lane */ namespace lane { /** * @brief Get the ENUEdge between the given border with corresponding lateralAlignment * * @param[in] border the ENU border, the edge is calculated from * @param[in] lateralAlignment the lateral alignment as TParam [0.;1.] used to calculate the resulting edge. * The lateral alignment is relative to the left edge. If lateralAlignment is 1., the left edge is returned, * if lateralAlignment is 0., the right edge is returned * * @throws std::invalid_argument if the lateralAlignment parameter is smaller than 0. or larger than 1. */ point::ENUEdge getLateralAlignmentEdge(ENUBorder const &border, physics::ParametricValue const lateralAlignment); /** * @brief Get the distance between an ENU point and the lateral alignment edge * * @param[in] enuPoint is the point for which the distance should be calculated * @param[in] lateralAlignmentEdge the lateral alignment in ENU form * * @return calculated Distance */ physics::Distance getDistanceEnuPointToLateralAlignmentEdge(point::ENUPoint const &enuPoint, point::ENUEdge const &lateralAlignmentEdge); /** * @brief normalizes the border * * At first the left and right edges of the border are checked for irregular directional vectors * (scalarproduct of the vectors of three consecutive edge points has to be positive) * Irregular points are dropped. * * Then, the number of points of the left and right edge of the border are made equal by extending the smaller edge. * If an edge has less than 2 points, nothing is done. * * The previousBorder (optional parameter) is used to extend the irregular directional vector check to the beginning * of the border edges; here leading to an potential overwrite of the first edge point by the end of the previousBorder. */ void normalizeBorder(ENUBorder &border, ENUBorder const *previousBorder = nullptr); /** * @brief operation to make the transition between two edges continuous * * If the end point of \c first is near (<=0.1m) to the end point of \c second or one of the edges has less than two * points, nothing is done. * Otherwise the first point of the second edge will exchanged by the last point of the first edge. * The second point of the second edge is placed at some distance along the edge which is calculated using: * - the distance of the displacement of the two edges * - the direction of the displacement of the two edges compared to the the corresponding direction of the edges * * @param[in] first the first edge (is untouched by the algorithm) * @param[in] second the second edge to be adapted if required to make the transition continuous */ void makeTransitionToSecondEdgeContinuous(point::ENUEdge const &first, point::ENUEdge &second); /** * @brief operation to make the transition between two borders continuous * * This executes the makeTransitionToSecondEdgeContinuous() for left and right edges. * In addition, adds interpolation points to the respective other edge if required. * * @param[in] first the first border (is untouched by the algorithm) * @param[in] second the second border to be adapted if required to make the transition continuous */ void makeTransitionToSecondBorderContinuous(ENUBorder const &first, ENUBorder &second); /** * @brief operation to make the transition between two edges continuous * * If the end point of \c first is near (<=0.1m) to the end point of \c second or one of the edges has less than two * points, nothing is done. * Otherwise the first point of the second edge will exchanged by the last point of the first edge. * The second point of the second edge is placed at some distance along the edge which is calculated using: * - the distance of the displacement of the two edges * - the direction of the displacement of the two edges compared to the the corresponding direction of the edges * * @param[in] first the first edge to be adapted if required to make the transition continuous * @param[in] second the second edge (is untouched by the algorithm) */ void makeTransitionFromFirstEdgeContinuous(point::ENUEdge &first, point::ENUEdge const &second); /** * @brief operation to make the transition between two borders continuous * * This executes the makeTransitionToSecondEdgeContinuous() for left and right edges. * In addition, adds interpolation points to the respective other edge if required. * * @param[in] first the first border to be adapted if required to make the transition continuous * @param[in] second the second border (is untouched by the algorithm) */ void makeTransitionFromFirstBorderContinuous(ENUBorder &first, ENUBorder const &second); /** @brief calculate the length of the provided border as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within Cartesian ENU coordinate frame. */ inline physics::Distance calcLength(ENUBorder const &border) { return (calcLength(border.left) + calcLength(border.right)) / 2.; } /** @brief calculate the length of the provided border as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within Cartesian ECEF coordinate frame. */ inline physics::Distance calcLength(ECEFBorder const &border) { return (calcLength(border.left) + calcLength(border.right)) / 2.; } /** @brief calculate the length of the provided border as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within Cartesian ECEF coordinate frame. */ inline physics::Distance calcLength(GeoBorder const &border) { return (calcLength(border.left) + calcLength(border.right)) / 2.; } /** @brief calculate the length out of the provided ENU border List as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within Cartesian ENU coordinate frame. */ physics::Distance calcLength(ENUBorderList const &borderList); /** @brief calculate the length out of the provided ECEF border List as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within Cartesian ECEF coordinate frame. */ physics::Distance calcLength(ECEFBorderList const &borderList); /** @brief calculate the length out of the provided GEO border List as distance value * * For length calculation the average between left and right edge of the border is returned. * Length calculation is performed within GEO coordinate frame. */ physics::Distance calcLength(GeoBorderList const &borderList); /** @brief calculate the ENUHeading of the vector<ENUBorder> at the given ENUPoint * * If the given ENUPoint is not within the given borders, * an ENUHeading(2*M_PI) is returned. */ point::ENUHeading getENUHeading(ENUBorderList const &borderList, point::ENUPoint const &enuPoint); } // namespace lane } // namespace map } // namespace ad
44.287356
120
0.748897
[ "vector" ]
f1da6a17933a50cff2d41a6ca0e62a6e5fae16ed
3,356
cpp
C++
example/main.cpp
pqrs-org/cpp-osx-iokit_hid_device
8a96acd1944303cb264dd8f73c0f0c1484ce46b2
[ "BSL-1.0" ]
null
null
null
example/main.cpp
pqrs-org/cpp-osx-iokit_hid_device
8a96acd1944303cb264dd8f73c0f0c1484ce46b2
[ "BSL-1.0" ]
null
null
null
example/main.cpp
pqrs-org/cpp-osx-iokit_hid_device
8a96acd1944303cb264dd8f73c0f0c1484ce46b2
[ "BSL-1.0" ]
null
null
null
#include <IOKit/hid/IOHIDElement.h> #include <IOKit/hid/IOHIDUsageTables.h> #include <csignal> #include <pqrs/osx/iokit_hid_device.hpp> #include <pqrs/osx/iokit_hid_manager.hpp> namespace { auto global_wait = pqrs::make_thread_wait(); } int main(void) { std::signal(SIGINT, [](int) { global_wait->notify(); }); auto time_source = std::make_shared<pqrs::dispatcher::hardware_time_source>(); auto dispatcher = std::make_shared<pqrs::dispatcher::dispatcher>(time_source); std::vector<pqrs::cf::cf_ptr<CFDictionaryRef>> matching_dictionaries{ pqrs::osx::iokit_hid_manager::make_matching_dictionary( pqrs::hid::usage_page::generic_desktop, pqrs::hid::usage::generic_desktop::keyboard), }; auto hid_manager = std::make_unique<pqrs::osx::iokit_hid_manager>(dispatcher, matching_dictionaries); hid_manager->device_matched.connect([](auto&& registry_entry_id, auto&& device_ptr) { if (device_ptr) { auto hid_device = pqrs::osx::iokit_hid_device(*device_ptr); std::cout << "device_matched registry_entry_id:" << registry_entry_id << std::endl; if (hid_device.conforms_to(pqrs::hid::usage_page::generic_desktop, pqrs::hid::usage::generic_desktop::keyboard)) { std::cout << " conforms_to keyboard" << std::endl; } if (auto manufacturer = hid_device.find_manufacturer()) { std::cout << " manufacturer:" << *manufacturer << std::endl; } if (auto product = hid_device.find_product()) { std::cout << " product:" << *product << std::endl; } if (auto serial_number = hid_device.find_serial_number()) { std::cout << " serial_number:" << *serial_number << std::endl; } if (auto vendor_id = hid_device.find_vendor_id()) { std::cout << " vendor_id:" << *vendor_id << std::endl; } if (auto product_id = hid_device.find_product_id()) { std::cout << " product_id:" << *product_id << std::endl; } if (auto location_id = hid_device.find_location_id()) { std::cout << " location_id:" << *location_id << std::endl; } if (auto country_code = hid_device.find_country_code()) { std::cout << " country_code:" << *country_code << std::endl; } #if 0 std::cout << " "; for (const auto& e : hid_device.make_elements()) { std::cout << IOHIDElementGetUsagePage(*e) << "," << IOHIDElementGetUsage(*e) << " (" << IOHIDElementGetLogicalMin(*e) << " - " << IOHIDElementGetLogicalMax(*e) << "), "; } std::cout << std::endl; #endif } }); hid_manager->device_terminated.connect([](auto&& registry_entry_id) { std::cout << "device_terminated registry_entry_id:" << registry_entry_id << std::endl; }); hid_manager->error_occurred.connect([](auto&& message, auto&& kern_return) { std::cerr << "error_occurred " << message << " " << kern_return << std::endl; }); hid_manager->async_start(); // ============================================================ global_wait->wait_notice(); // ============================================================ hid_manager = nullptr; dispatcher->terminate(); dispatcher = nullptr; std::cout << "finished" << std::endl; return 0; }
35.702128
110
0.592074
[ "vector" ]
f1e7bbfc3c05d50a11929640481213fae20d1958
5,609
cxx
C++
panda/src/tinydisplay/tinyGraphicsBuffer.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/tinydisplay/tinyGraphicsBuffer.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/tinydisplay/tinyGraphicsBuffer.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: tinyGraphicsBuffer.cxx // Created by: drose (08Aug08) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pandabase.h" #include "tinyGraphicsBuffer.h" #include "config_tinydisplay.h" #include "tinyGraphicsStateGuardian.h" #include "pStatTimer.h" TypeHandle TinyGraphicsBuffer::_type_handle; //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// TinyGraphicsBuffer:: TinyGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, const string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsStateGuardian *gsg, GraphicsOutput *host) : GraphicsBuffer(engine, pipe, name, fb_prop, win_prop, flags, gsg, host) { _frame_buffer = NULL; } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::Destructor // Access: Public, Virtual // Description: //////////////////////////////////////////////////////////////////// TinyGraphicsBuffer:: ~TinyGraphicsBuffer() { } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::begin_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // before beginning rendering for a given frame. It // should do whatever setup is required, and return true // if the frame should be rendered, or false if it // should be skipped. //////////////////////////////////////////////////////////////////// bool TinyGraphicsBuffer:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); if (_gsg == (GraphicsStateGuardian *)NULL) { return false; } TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_R(tinygsg, _gsg, false); tinygsg->_current_frame_buffer = _frame_buffer; tinygsg->reset_if_new(); _gsg->set_current_properties(&get_fb_properties()); return _gsg->begin_frame(current_thread); } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::end_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // after rendering is completed for a given frame. It // should do whatever finalization is required. //////////////////////////////////////////////////////////////////// void TinyGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); nassertv(_gsg != (GraphicsStateGuardian *)NULL); if (mode == FM_render) { // end_render_texture(); copy_to_textures(); } _gsg->end_frame(current_thread); if (mode == FM_render) { trigger_flip(); clear_cube_map_selection(); } } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::close_buffer // Access: Protected, Virtual // Description: Closes the buffer right now. Called from the buffer // thread. //////////////////////////////////////////////////////////////////// void TinyGraphicsBuffer:: close_buffer() { if (_gsg != (GraphicsStateGuardian *)NULL) { TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_V(tinygsg, _gsg); tinygsg->_current_frame_buffer = NULL; _gsg.clear(); } _is_valid = false; } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::open_buffer // Access: Protected, Virtual // Description: Opens the buffer right now. Called from the buffer // thread. Returns true if the buffer is successfully // opened, or false if there was a problem. //////////////////////////////////////////////////////////////////// bool TinyGraphicsBuffer:: open_buffer() { // GSG Creation/Initialization TinyGraphicsStateGuardian *tinygsg; if (_gsg == 0) { // There is no old gsg. Create a new one. tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, NULL); _gsg = tinygsg; } else { DCAST_INTO_R(tinygsg, _gsg, false); } create_frame_buffer(); if (_frame_buffer == NULL) { tinydisplay_cat.error() << "Could not create frame buffer.\n"; return false; } tinygsg->_current_frame_buffer = _frame_buffer; tinygsg->reset_if_new(); if (!tinygsg->is_valid()) { close_buffer(); return false; } _is_valid = true; return true; } //////////////////////////////////////////////////////////////////// // Function: TinyGraphicsBuffer::create_frame_buffer // Access: Private // Description: Creates a suitable frame buffer for the current // window size. //////////////////////////////////////////////////////////////////// void TinyGraphicsBuffer:: create_frame_buffer() { if (_frame_buffer != NULL) { ZB_close(_frame_buffer); _frame_buffer = NULL; } _frame_buffer = ZB_open(get_fb_x_size(), get_fb_y_size(), ZB_MODE_RGBA, 0, 0, 0, 0); }
32.235632
86
0.543769
[ "3d" ]
f1e9abbfab1b10b3bb4453f664bbbe41089575d6
998
cpp
C++
plugins/renderer/directx11/src/DirectX11/util/directx11pixelshader.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
plugins/renderer/directx11/src/DirectX11/util/directx11pixelshader.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
plugins/renderer/directx11/src/DirectX11/util/directx11pixelshader.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#include "../directx11lib.h" #include "directx11pixelshader.h" #include "../directx11rendercontext.h" namespace Engine { namespace Render { DirectX11PixelShader::DirectX11PixelShader(ID3DBlob *pShaderBlob) { sDevice->CreatePixelShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), nullptr, &mShader); } DirectX11PixelShader::DirectX11PixelShader(DirectX11PixelShader &&other) : mShader(std::exchange(other.mShader, nullptr)) { } DirectX11PixelShader::~DirectX11PixelShader() { reset(); } DirectX11PixelShader &DirectX11PixelShader::operator=(DirectX11PixelShader &&other) { std::swap(mShader, other.mShader); return *this; } void DirectX11PixelShader::reset() { if (mShader) { mShader->Release(); mShader = nullptr; } } void DirectX11PixelShader::bind() { sDeviceContext->PSSetShader(mShader, nullptr, 0); } } }
22.177778
117
0.647295
[ "render" ]
f1eb59edbba9f0de34320b726947a8ac8652c586
6,374
cpp
C++
tests/main.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
tests/main.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
tests/main.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
#include "tensor.h" #include "tests.h" int main(int argc, char* argv[]) { int ret; int total_tests; int total_tests_passed; bool run_on_gpu = false; const char* MNIST_training_images; const char* MNIST_training_labels; const char* MNIST_test_images; const char* MNIST_test_labels; total_tests = 0; total_tests_passed = 0; if (argc < 5) { printf("Usage: test path_to_MNIST_training_images path_to_MNIST_training_labels path_to_MNIST_test_images path_to_MNIST_test_labels [-gpu]\n"); return -1; } else { MNIST_training_images = argv[1]; MNIST_training_labels = argv[2]; MNIST_test_images = argv[3]; MNIST_test_labels = argv[4]; if (argc > 5) { #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) if (!_strcmpi(argv[5], "-gpu")) #else if (!strcasecmp(argv[5], "-GPU")) #endif { run_on_gpu = true; } } } if(run_on_gpu) { printf("running unit tests on GPU\n"); } else { printf("running unit tests on CPU\n"); } ret = add_test_1(run_on_gpu); total_tests++; if (ret) { printf("tensor addition test 1 failed\n"); } else { total_tests_passed++; printf("tensor addition test 1 passed\n"); } ret = add_test_2(run_on_gpu); total_tests++; if (ret) { printf("tensor ddition test 2 failed\n"); } else { total_tests_passed++; printf("tensor addition test 2 passed\n"); } ret = sub_test_1(run_on_gpu); total_tests++; if (ret) { printf("tensor subtraction test 1 failed\n"); } else { total_tests_passed++; printf("tensor subtraction test 1 passed\n"); } ret = sub_test_1(run_on_gpu); total_tests++; if (ret) { printf("tensor subtraction test 2 failed\n"); } else { total_tests_passed++; printf("tensor subtraction test 2 passed\n"); } ret = sub_test_1_uint8(); total_tests++; if (ret) { printf("tensor uint8 subtraction test 1 failed\n"); } else { total_tests_passed++; printf("tensor uint8 subtraction test 1 passed\n"); } ret = sub_test_2_uint8(); total_tests++; if (ret) { printf("tensor uint8 subtraction test 2 failed\n"); } else { total_tests_passed++; printf("tensor uint8 subtraction test 2 passed\n"); } ret = mul_test_1(run_on_gpu); total_tests++; if (ret) { printf("tensor element-wise multiplication test 1 failed\n"); } else { total_tests_passed++; printf("tensor element-wise multiplication test 1 passed\n"); } ret = mul_test_2(run_on_gpu); total_tests++; if (ret) { printf("tensor element-wise multiplication test 2 failed\n"); } else { total_tests_passed++; printf("tensor element-wise multiplication test 2 passed\n"); } ret = mul_test_1_int32(); total_tests++; if (ret) { printf("tensor int32 element-wise multiplication test 2 failed\n"); } else { total_tests_passed++; printf("tensor int32 element-wise multiplication test 2 passed\n"); } ret = div_test_1(run_on_gpu); total_tests++; if (ret) { printf("tensor division test 1 failed\n"); } else { total_tests_passed++; printf("tensor division test 1 passed\n"); } ret = div_test_2(run_on_gpu); total_tests++; if (ret) { printf("tensor division test 2 failed\n"); } else { total_tests_passed++; printf("tensor division test 2 passed\n"); } ret = matmul_test(run_on_gpu); total_tests++; if (ret) { printf("tensor matrix-multiplication test failed\n"); } else { total_tests_passed++; printf("tensor matrix-multiplication test passed\n"); } ret = exp_test(run_on_gpu); total_tests++; if (ret) { printf("tensor exp test failed\n"); } else { total_tests_passed++; printf("tensor exp test passed\n"); } ret = log_test(run_on_gpu); total_tests++; if (ret) { printf("tensor log test failed\n"); } else { total_tests_passed++; printf("tensor log test passed\n"); } ret = sig_test(run_on_gpu); total_tests++; if (ret) { printf("tensor sigmoid test failed\n"); } else { total_tests_passed++; printf("tensor sigmoid test passed\n"); } ret = tanh_test(run_on_gpu); total_tests++; if (ret) { printf("tensor tanh test failed\n"); } else { total_tests_passed++; printf("tensor tanh test passed\n"); } ret = scalar_mul(run_on_gpu); total_tests++; if (ret) { printf("tensor scalar multiplication test failed\n"); } else { total_tests_passed++; printf("tensor scalar multiplication test passed\n"); } ret = sum_test(run_on_gpu); total_tests++; if (ret) { printf("tensor sum test failed\n"); } else { total_tests_passed++; printf("tensor sum test passed\n"); } ret = fc_test(run_on_gpu); total_tests++; if (ret) { printf("tensor fully-connected layer test failed\n"); } else { total_tests_passed++; printf("tensor fully-connected layer test passed\n"); } if (!run_on_gpu) { ret = neural_network_test(); total_tests++; if (ret) { printf("training regression model failed\n"); } else { total_tests_passed++; printf("training regression model passed\n"); } ret = MNIST_test(MNIST_training_images, MNIST_training_labels, MNIST_test_images, MNIST_test_labels); total_tests++; if (ret) { printf("training MNIST model failed\n"); } else { total_tests_passed++; printf("training MNIST model passed\n"); } } if (run_on_gpu) { ret = MNIST_test_gpu(MNIST_training_images, MNIST_training_labels, MNIST_test_images, MNIST_test_labels); total_tests++; if (ret) { printf("training MNIST model failed\n"); } else { total_tests_passed++; printf("training MNIST model passed\n"); } } if (!run_on_gpu) { ret = quantized_MNIST_test(MNIST_training_images, MNIST_training_labels, MNIST_test_images, MNIST_test_labels); total_tests++; if (ret) { printf("quantization test failed\n"); } else { total_tests_passed++; printf("quantization test passed\n"); } } printf("\n------------\nTotal : %d\nPassed: %d\nFailed: %d\n------------\n", total_tests, total_tests_passed, total_tests - total_tests_passed); return 0; }
18.52907
146
0.635708
[ "model" ]
f1f9a2b7a215f07e00d353a1d4319629dae18fbe
1,484
cc
C++
tests/titan/externalFunctionsC.cc
gusgonnet/minimalistThermostat
6ee1e3a5434340ba8a5e2684cb40607d763482cc
[ "MIT" ]
7
2016-03-28T19:18:39.000Z
2017-05-15T07:32:38.000Z
tests/titan/externalFunctionsC.cc
gusgonnet/minimalistThermostat
6ee1e3a5434340ba8a5e2684cb40607d763482cc
[ "MIT" ]
null
null
null
tests/titan/externalFunctionsC.cc
gusgonnet/minimalistThermostat
6ee1e3a5434340ba8a5e2684cb40607d763482cc
[ "MIT" ]
7
2016-04-29T01:19:39.000Z
2019-12-16T15:00:35.000Z
#include <iostream> #include <fstream> #include <sstream> #include "TTCN3.hh" #include <time.h> #include <unistd.h> #include <vector> namespace externalFunctions { using namespace std; string executeOnShell(const string& command); string streamRead(FILE* stream); string executeOnShell(const string& command){ FILE* localFile = popen(command.c_str(), "r"); return streamRead(localFile); } string streamRead(FILE* stream){ char tempChar = getc( stream ); string tempString; while( tempChar != EOF) { tempString += tempChar; tempChar = getc( stream ); } pclose(stream); return tempString; } CHARSTRING executeCommand(const CHARSTRING& command){ string tempCommand = (const char*) command; string tempResult; TTCN_Logger::log(TTCN_DEBUG,"executeCommand - command to shell: %s",tempCommand.c_str()); tempResult = executeOnShell(tempCommand); TTCN_Logger::log(TTCN_DEBUG,"executeCommand - response from shell: %s",tempResult.c_str()); return tempResult.c_str(); } INTEGER indexOfSubstring(const CHARSTRING& s1, const CHARSTRING& s2, const INTEGER& offset) { if(s2.lengthof()==0) return 0; if(s1.lengthof()==0) return -1; if(offset<0) return -1; if(s1.lengthof()<=offset) return -1; const char* str1=(const char*)s1+(int)offset; const char* str2=(const char*)s2; const char* first=strstr(str1,str2); if(first) return first-str1+(int)offset; return -1; } }
27.481481
95
0.681267
[ "vector" ]
f1fa719b410cc4ea430d3b26cc5b7ab4008418cc
3,734
cpp
C++
src/LoggingBase.cpp
ess-dmsc/graylog-logger
56cadc4a91fb4d31b3c6f6e4b62f38350c408a35
[ "BSD-2-Clause" ]
10
2018-01-10T08:18:16.000Z
2022-02-01T10:33:00.000Z
src/LoggingBase.cpp
ess-dmsc/graylog-logger
56cadc4a91fb4d31b3c6f6e4b62f38350c408a35
[ "BSD-2-Clause" ]
21
2017-03-24T18:56:57.000Z
2022-01-20T07:35:58.000Z
src/LoggingBase.cpp
ess-dmsc/graylog-logger
56cadc4a91fb4d31b3c6f6e4b62f38350c408a35
[ "BSD-2-Clause" ]
2
2017-03-23T15:57:18.000Z
2020-04-07T10:12:09.000Z
/* Copyright (C) 2018 European Spallation Source, ERIC. See LICENSE file */ //===----------------------------------------------------------------------===// /// /// \file /// /// \brief Implementation of the base logging class. /// //===----------------------------------------------------------------------===// #include "graylog_logger/LoggingBase.hpp" #include "Semaphore.hpp" #include <chrono> #include <ciso646> #include <sys/types.h> #include <thread> #ifdef _WIN32 #include <WinSock2.h> #include <codecvt> #include <locale> #include <process.h> // clang-format off #include <Windows.h> // clang-format on #define getpid _getpid #else #include <unistd.h> #endif namespace Log { #ifdef _WIN32 std::string get_process_name() { std::wstring buf; buf.resize(260); do { size_t len = GetModuleFileNameW(nullptr, &buf[0], static_cast<size_t>(buf.size())); if (len < buf.size()) { buf.resize(len); break; } buf.resize(buf.size() * 2); } while (buf.size() < 65536); int lastSlash = buf.rfind(L'\"'); if (std::string::npos != lastSlash) { buf = buf.substr(lastSlash + 1, buf.size() - 1); } using convert_typeX = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_typeX, wchar_t> converterX; return converterX.to_bytes(buf); } #elif defined(__APPLE__) || defined(__APPLE_CC__) #include <cstring> #include <mach-o/dyld.h> #include <sys/syslimits.h> std::string get_process_name() { std::string buf; buf.resize(PATH_MAX); while (true) { auto size = static_cast<uint32_t>(buf.size()); if (_NSGetExecutablePath(&buf[0], &size) == 0) { buf.resize(std::strlen(&buf[0])); break; } buf.resize(size); } auto lastSlash = buf.rfind('/'); if (std::string::npos == lastSlash) { return buf; } return buf.substr(lastSlash + 1, buf.size() - 1); } #else #include <vector> std::string get_process_name() { std::vector<std::string> filePaths = {"/proc/self/exe", "/proc/curproc/file", "/proc/curproc/exe"}; char pathBuffer[1024]; for (auto &path : filePaths) { int nameLen = readlink(path.c_str(), pathBuffer, sizeof(pathBuffer) - 1); if (-1 != nameLen) { std::string tempPath(pathBuffer, nameLen); auto lastSlash = tempPath.rfind("/"); if (std::string::npos == lastSlash) { return tempPath; } return tempPath.substr(lastSlash + 1, tempPath.size() - 1); } } return std::to_string(getpid()); } #endif LoggingBase::LoggingBase() { Executor.SendWork([=]() { const int StringBufferSize = 100; std::array<char, StringBufferSize> StringBuffer{}; const int res = gethostname(static_cast<char *>(StringBuffer.data()), StringBufferSize); if (0 == res) { BaseMsg.Host = std::string(static_cast<char *>(StringBuffer.data())); } BaseMsg.ProcessId = getpid(); BaseMsg.ProcessName = get_process_name(); }); } LoggingBase::~LoggingBase() { LoggingBase::removeAllHandlers(); } void LoggingBase::addLogHandler(const LogHandler_P &Handler) { Semaphore Check; Executor.SendWork([=, &Check]() { Handlers.push_back(Handler); Check.notify(); }); Check.wait(); } void LoggingBase::removeAllHandlers() { Semaphore Check; Executor.SendWork([=, &Check]() { Handlers.clear(); Check.notify(); }); Check.wait(); } std::vector<LogHandler_P> LoggingBase::getHandlers() { return Handlers; } void LoggingBase::setMinSeverity(Severity Level) { auto WorkDone = std::make_shared<std::promise<void>>(); auto WorkDoneFuture = WorkDone->get_future(); Executor.SendWork( [=, WorkDone{std::move(WorkDone)}]() { MinSeverity = Level; }); WorkDoneFuture.wait(); } } // namespace Log
26.295775
80
0.617836
[ "vector" ]
7b01a8492930a1f9b5758dcc7edc8ba20f4fc81c
8,102
cpp
C++
lib/smurff-cpp/SmurffCpp/Utils/Distribution.cpp
msteijaert/smurff
e6066d51e1640e9aad0118628ba72c9d662919fb
[ "MIT" ]
null
null
null
lib/smurff-cpp/SmurffCpp/Utils/Distribution.cpp
msteijaert/smurff
e6066d51e1640e9aad0118628ba72c9d662919fb
[ "MIT" ]
null
null
null
lib/smurff-cpp/SmurffCpp/Utils/Distribution.cpp
msteijaert/smurff
e6066d51e1640e9aad0118628ba72c9d662919fb
[ "MIT" ]
null
null
null
// From: // http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c #include <iostream> #include <chrono> #include <functional> #include "ThreadVector.hpp" #include "omp_util.h" #ifdef USE_BOOST_RANDOM #include <boost/random.hpp> #define MERSENNE_TWISTER boost::random::mt19937 #define UNIFORM_REAL_DISTRIBUTION boost::random::uniform_real_distribution<double> #define GAMMA_DISTRIBUTION boost::random::gamma_distribution<double> #else #include <random> #define MERSENNE_TWISTER std::mt19937 #define UNIFORM_REAL_DISTRIBUTION std::uniform_real_distribution<double> #define GAMMA_DISTRIBUTION std::gamma_distribution<double> #endif #include <Eigen/Dense> #include "Distribution.h" using namespace Eigen; static smurff::thread_vector<MERSENNE_TWISTER> bmrngs; double smurff::randn0() { return smurff::bmrandn_single_thread(); } double smurff::randn(double) { return smurff::bmrandn_single_thread(); } void smurff::bmrandn(double* x, long n) { #pragma omp parallel { UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0); auto& bmrng = bmrngs.local(); #pragma omp for schedule(static) for (long i = 0; i < n; i += 2) { double x1, x2, w; do { x1 = unif(bmrng); x2 = unif(bmrng); w = x1 * x1 + x2 * x2; } while ( w >= 1.0 ); w = std::sqrt( (-2.0 * std::log( w ) ) / w ); x[i] = x1 * w; if (i + 1 < n) { x[i+1] = x2 * w; } } } } void smurff::bmrandn(Eigen::MatrixXd & X) { long n = X.rows() * (long)X.cols(); smurff::bmrandn(X.data(), n); } double smurff::bmrandn_single_thread() { //TODO: add bmrng as input UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0); auto& bmrng = bmrngs.local(); double x1, x2, w; do { x1 = unif(bmrng); x2 = unif(bmrng); w = x1 * x1 + x2 * x2; } while ( w >= 1.0 ); w = std::sqrt( (-2.0 * std::log( w ) ) / w ); return x1 * w; } // to be called within OpenMP parallel loop (also from serial code is fine) void smurff::bmrandn_single_thread(double* x, long n) { UNIFORM_REAL_DISTRIBUTION unif(-1.0, 1.0); auto& bmrng = bmrngs.local(); for (long i = 0; i < n; i += 2) { double x1, x2, w; do { x1 = unif(bmrng); x2 = unif(bmrng); w = x1 * x1 + x2 * x2; } while ( w >= 1.0 ); w = std::sqrt( (-2.0 * std::log( w ) ) / w ); x[i] = x1 * w; if (i + 1 < n) { x[i+1] = x2 * w; } } } void smurff::bmrandn_single_thread(Eigen::VectorXd & x) { smurff::bmrandn_single_thread(x.data(), x.size()); } void smurff::bmrandn_single_thread(Eigen::MatrixXd & X) { long n = X.rows() * (long)X.cols(); smurff::bmrandn_single_thread(X.data(), n); } void smurff::init_bmrng() { using namespace std::chrono; auto ms = (duration_cast< milliseconds >(system_clock::now().time_since_epoch())).count(); smurff::init_bmrng(ms); } void smurff::init_bmrng(int seed) { std::vector<MERSENNE_TWISTER> v; for (int i = 0; i < threads::get_max_threads(); i++) { v.push_back(MERSENNE_TWISTER(seed + i * 1999)); } bmrngs.init(v); } double smurff::rand_unif() { UNIFORM_REAL_DISTRIBUTION unif(0.0, 1.0); auto& bmrng = bmrngs.local(); return unif(bmrng); } double smurff::rand_unif(double low, double high) { UNIFORM_REAL_DISTRIBUTION unif(low, high); auto& bmrng = bmrngs.local(); return unif(bmrng); } // returns random number according to Gamma distribution // with the given shape (k) and scale (theta). See wiki. double smurff::rgamma(double shape, double scale) { GAMMA_DISTRIBUTION gamma(shape, scale); return gamma(bmrngs.local()); } auto smurff::nrandn(int n) -> decltype(Eigen::VectorXd::NullaryExpr(n, std::cref(randn))) { return Eigen::VectorXd::NullaryExpr(n, std::cref(randn)); } auto smurff::nrandn(int n, int m) -> decltype(Eigen::ArrayXXd::NullaryExpr(n, m, std::cref(randn))) { return Eigen::ArrayXXd::NullaryExpr(n, m, std::cref(randn)); } Eigen::MatrixXd WishartUnit(int m, int df) { Eigen::MatrixXd c(m,m); c.setZero(); auto& rng = bmrngs.local(); for ( int i = 0; i < m; i++ ) { GAMMA_DISTRIBUTION gam(0.5*(df - i)); c(i,i) = std::sqrt(2.0 * gam(rng)); Eigen::VectorXd r = smurff::nrandn(m-i-1); c.block(i,i+1,1,m-i-1) = r.transpose(); } Eigen::MatrixXd ret = c.transpose() * c; #ifdef TEST_MVNORMAL cout << "WISHART UNIT {\n" << endl; cout << " m:\n" << m << endl; cout << " df:\n" << df << endl; cout << " ret;\n" << ret << endl; cout << " c:\n" << c << endl; cout << "}\n" << ret << endl; #endif return ret; } MatrixXd Wishart(const Eigen::MatrixXd &sigma, const int df) { // Get R, the upper triangular Cholesky factor of SIGMA. auto chol = sigma.llt(); Eigen::MatrixXd r = chol.matrixL(); // Get AU, a sample from the unit Wishart distribution. Eigen::MatrixXd au = WishartUnit(sigma.cols(), df); // Construct the matrix A = R' * AU * R. Eigen::MatrixXd a = r * au * chol.matrixU(); #ifdef TEST_MVNORMAL cout << "WISHART {\n" << endl; cout << " sigma:\n" << sigma << endl; cout << " r:\n" << r << endl; cout << " au:\n" << au << endl; cout << " df:\n" << df << endl; cout << " a:\n" << a << endl; cout << "}\n" << endl; #endif return a; } // from julia package Distributions: conjugates/normalwishart.jl std::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::NormalWishart(const Eigen::VectorXd & mu, double kappa, const Eigen::MatrixXd & T, double nu) { Eigen::MatrixXd Lam = Wishart(T, nu); Eigen::MatrixXd mu_o = smurff::MvNormal_prec(Lam * kappa, mu); #ifdef TEST_MVNORMAL cout << "NORMAL WISHART {\n" << endl; cout << " mu:\n" << mu << endl; cout << " kappa:\n" << kappa << endl; cout << " T:\n" << T << endl; cout << " nu:\n" << nu << endl; cout << " mu_o\n" << mu_o << endl; cout << " Lam\n" << Lam << endl; cout << "}\n" << endl; #endif return std::make_pair(mu_o , Lam); } std::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::CondNormalWishart(const int N, const Eigen::MatrixXd &NS, const Eigen::VectorXd &NU, const Eigen::VectorXd &mu, const double kappa, const Eigen::MatrixXd &T, const int nu) { int nu_c = nu + N; double kappa_c = kappa + N; auto mu_c = (kappa * mu + NU) / (kappa + N); auto X = (T + NS + kappa * mu * mu.adjoint() - kappa_c * mu_c * mu_c.adjoint()); Eigen::MatrixXd T_c = X.inverse(); return NormalWishart(mu_c, kappa_c, T_c, nu_c); } std::pair<Eigen::VectorXd, Eigen::MatrixXd> smurff::CondNormalWishart(const Eigen::MatrixXd &U, const Eigen::VectorXd &mu, const double kappa, const Eigen::MatrixXd &T, const int nu) { auto N = U.cols(); auto NS = U * U.adjoint(); auto NU = U.rowwise().sum(); return CondNormalWishart(N, NS, NU, mu, kappa, T, nu); } // Normal(0, Lambda^-1) for nn columns MatrixXd smurff::MvNormal_prec(const Eigen::MatrixXd & Lambda, int ncols) { int nrows = Lambda.rows(); // Dimensionality (rows) LLT<Eigen::MatrixXd> chol(Lambda); Eigen::MatrixXd r(nrows, ncols); smurff::bmrandn(r); return chol.matrixU().solve(r); } Eigen::MatrixXd smurff::MvNormal_prec(const Eigen::MatrixXd & Lambda, const Eigen::VectorXd & mean, int nn) { Eigen::MatrixXd r = MvNormal_prec(Lambda, nn); return r.colwise() + mean; } // Draw nn samples from a size-dimensional normal distribution // with a specified mean and covariance Eigen::MatrixXd smurff::MvNormal(const Eigen::MatrixXd covar, const Eigen::VectorXd mean, int nn) { int size = mean.rows(); // Dimensionality (rows) Eigen::MatrixXd normTransform(size,size); LLT<Eigen::MatrixXd> cholSolver(covar); normTransform = cholSolver.matrixL(); auto normSamples = Eigen::MatrixXd::NullaryExpr(size, nn, std::cref(randn)); Eigen::MatrixXd samples = (normTransform * normSamples).colwise() + mean; return samples; }
25.884984
223
0.611331
[ "shape", "vector" ]
7b05e0a46fd8e4c17e6b98d2127e37c09f6505e4
6,632
cpp
C++
src/master/worker.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
20
2015-05-14T19:44:01.000Z
2018-04-14T15:25:08.000Z
src/master/worker.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
11
2015-04-15T19:51:06.000Z
2017-01-03T14:57:49.000Z
src/master/worker.cpp
abudnik/prun
643a6bf49249e220f08317b8a4739570faf7b2ae
[ "Apache-2.0" ]
7
2015-05-08T12:44:38.000Z
2021-12-10T18:00:01.000Z
/* =========================================================================== This software is licensed under the Apache 2 license, quoted below. Copyright (C) 2013 Andrey Budnik <budnik27@gmail.com> 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 "worker.h" namespace master { void WorkerJob::AddTask( int64_t jobId, int taskId ) { jobs_[ jobId ].insert( taskId ); } bool WorkerJob::DeleteTask( int64_t jobId, int taskId ) { auto it = jobs_.find( jobId ); if ( it != jobs_.end() ) { Tasks &tasks = it->second; auto it_tasks = tasks.find( taskId ); if ( it_tasks != tasks.end() ) { tasks.erase( it_tasks ); if ( tasks.empty() ) { jobs_.erase( it ); if ( IsExclusive() && jobs_.empty() ) { SetExclusive( false ); } } return true; } } return false; } bool WorkerJob::DeleteJob( int64_t jobId ) { auto it = jobs_.find( jobId ); if ( it != jobs_.end() ) { jobs_.erase( it ); if ( IsExclusive() && jobs_.empty() ) { SetExclusive( false ); } return true; } return false; } bool WorkerJob::HasTask( int64_t jobId, int taskId ) const { auto it = jobs_.find( jobId ); if ( it != jobs_.end() ) { const Tasks &tasks = it->second; auto it_tasks = tasks.find( taskId ); return it_tasks != tasks.end(); } return false; } bool WorkerJob::HasJob( int64_t jobId ) const { return jobs_.find( jobId ) != jobs_.end(); } bool WorkerJob::GetTasks( int64_t jobId, Tasks &tasks ) const { auto it = jobs_.find( jobId ); if ( it != jobs_.end() ) { tasks = it->second; return true; } return false; } void WorkerJob::GetTasks( std::vector< WorkerTask > &tasks ) const { for( auto it = jobs_.cbegin(); it != jobs_.cend(); ++it ) { const Tasks &t = it->second; Tasks::const_iterator it_tasks = t.begin(); for( ; it_tasks != t.end(); ++it_tasks ) { int taskId = *it_tasks; tasks.emplace_back( it->first, taskId ); } } } void WorkerJob::GetJobs( std::set<int64_t> &jobs ) const { for( auto it = jobs_.cbegin(); it != jobs_.cend(); ++it ) { jobs.insert( it->first ); } } int64_t WorkerJob::GetJobId() const { if ( jobs_.empty() ) return -1; auto it = jobs_.cbegin(); return it->first; } int WorkerJob::GetNumJobs() const { return jobs_.size(); } int WorkerJob::GetTotalNumTasks() const { int num = 0; for( auto it = jobs_.cbegin(); it != jobs_.cend(); ++it ) { const Tasks &tasks = it->second; num += static_cast<int>( tasks.size() ); } return num; } int WorkerJob::GetNumTasks( int64_t jobId ) const { auto it = jobs_.find( jobId ); if ( it != jobs_.end() ) { const Tasks &tasks = it->second; return static_cast<int>( tasks.size() ); } return 0; } WorkerJob &WorkerJob::operator += ( const WorkerJob &workerJob ) { std::vector< WorkerTask > tasks; workerJob.GetTasks( tasks ); for( const auto &task : tasks ) { AddTask( task.GetJobId(), task.GetTaskId() ); } if ( workerJob.IsExclusive() ) { SetExclusive( true ); } return *this; } void WorkerJob::SetExclusive( bool exclusive ) { exclusive_ = exclusive; } bool WorkerJob::IsExclusive() const { return exclusive_; } void WorkerJob::Reset() { jobs_.clear(); exclusive_ = false; } void WorkerList::AddWorker( Worker *worker ) { workers_.emplace_back( worker ); } void WorkerList::DeleteWorker( const std::string &host ) { for( auto it = workers_.begin(); it != workers_.end(); ) { WorkerPtr &w = *it; if ( w->GetHost() == host ) { w->SetState( WORKER_STATE_DISABLED ); ipToWorker_.erase( w->GetIP() ); it = workers_.erase( it ); } else ++it; } } void WorkerList::Clear() { for( auto &w : workers_ ) { w->SetState( WORKER_STATE_DISABLED ); } workers_.clear(); ipToWorker_.clear(); } bool WorkerList::GetWorker( const char *host, WorkerPtr &worker ) { for( auto &w : workers_ ) { if ( w->GetHost() == host ) { worker = w; return true; } } return false; } bool WorkerList::SetWorkerIP( WorkerPtr &worker, const std::string &ip ) { for( const auto &w : workers_ ) { if ( worker == w ) { worker->SetIP( ip ); ipToWorker_[ip] = worker; return true; } } return false; } bool WorkerList::GetWorkerByIP( const std::string &ip, WorkerPtr &worker ) const { auto it = ipToWorker_.find( ip ); if ( it != ipToWorker_.end() ) { worker = it->second; return true; } return false; } int WorkerList::GetTotalWorkers() const { int num = 0; for( const auto &worker : workers_ ) { if ( worker->IsAvailable() ) { ++num; } } return num; } int WorkerList::GetTotalCPU() const { int num = 0; for( const auto &worker : workers_ ) { if ( worker->IsAvailable() ) { num += worker->GetNumCPU(); } } return num; } int WorkerList::GetNumWorkers( int stateMask ) const { int num = 0; for( const auto &worker : workers_ ) { int state = static_cast<int>( worker->GetState() ); if ( state & stateMask ) { ++num; } } return num; } int WorkerList::GetNumCPU( int stateMask ) const { int num = 0; for( const auto &worker : workers_ ) { int state = static_cast<int>( worker->GetState() ); if ( state & stateMask ) { num += worker->GetNumCPU(); } } return num; } } // namespace master
21.121019
80
0.539505
[ "vector" ]
7b07ac766c8e40b8a8b0ca08dec89948783aec50
1,043
cpp
C++
DistinctPowers.cpp
AlirezaKamyab/ProjectEuler
7237d2813ec2fe851c77960e41cd2e8e1520bf9f
[ "MIT" ]
null
null
null
DistinctPowers.cpp
AlirezaKamyab/ProjectEuler
7237d2813ec2fe851c77960e41cd2e8e1520bf9f
[ "MIT" ]
null
null
null
DistinctPowers.cpp
AlirezaKamyab/ProjectEuler
7237d2813ec2fe851c77960e41cd2e8e1520bf9f
[ "MIT" ]
1
2020-12-28T16:49:06.000Z
2020-12-28T16:49:06.000Z
//Created on: Dec 21, 2020 by Alireza #include<iostream> #include<vector> #include<set> #include<cmath> using namespace std; bool isPrime(int number); vector<int> PrimeDivisions(int number, int power); int main(int argc, char ** argv){ set<vector<int>> answers; for(int i = 2; i <= 100; ++i){ for(int j = 2; j <= 100; ++j){ vector<int> item = PrimeDivisions(i, j); answers.insert(item); } } cout << "The answer is " << answers.size() << endl; return 0; } vector<int> PrimeDivisions(int number, int power){ vector<int> temp; if(isPrime(number)){ for(int pwr = 0; pwr < power; pwr++){ temp.push_back(number); } return temp; } for(int i = 2; i <= ceil(number / 2); i++){ if(isPrime(i)){ int n = number; while(n % i == 0){ for(int repeat = 0; repeat < power; repeat++) temp.push_back(i); n /= i; } } } return temp; } bool isPrime(int number){ if(number <= 1) { return false; } for(int i = 2; i < (int)sqrt(number) + 1; i++){ if(number % i == 0){ return false; } } return true; }
19.314815
68
0.596357
[ "vector" ]
7b0c19989e7528fd79c474e2fb12589b6dba298c
5,555
cpp
C++
test/container_test.cpp
cjgdev/jemallocator
5512eb10c4ab8a268cfd6d992bddd6199be41779
[ "MIT" ]
1
2015-11-06T03:27:05.000Z
2015-11-06T03:27:05.000Z
test/container_test.cpp
cjgdev/jemallocator
5512eb10c4ab8a268cfd6d992bddd6199be41779
[ "MIT" ]
null
null
null
test/container_test.cpp
cjgdev/jemallocator
5512eb10c4ab8a268cfd6d992bddd6199be41779
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015 Christopher Gilbert <christopher.john.gilbert@gmail.com> * * 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 "catch.hpp" #include <jemallocator/jemallocator.hpp> #include <deque> #include <forward_list> #include <list> #include <vector> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <queue> #include <stack> #include <string> namespace je = jemallocator; namespace jepolicy = jemallocator::jepolicy; /* * Useful allocator alias */ template<class T> using basic_allocator = je::jemallocator<T, jepolicy::empty::policy>; template<class T> using default_allocator = basic_allocator<T>; /* * Useful container aliases */ template<class T, class Alloc = default_allocator<T>> using forward_list = std::forward_list<T, Alloc>; template<class T, class Alloc = default_allocator<T>> using deque = std::deque<T, Alloc>; template<class T, class Alloc = default_allocator<T>> using list = std::list<T, Alloc>; template<class T, class Alloc = default_allocator<T>> using vector = std::vector<T, Alloc>; template<class Key, class T, class Alloc = default_allocator<std::pair<const Key, T>>> using map = std::map<Key, T, std::less<Key>, Alloc>; template<class Key, class T, class Alloc = default_allocator<std::pair<const Key, T>>> using multimap = std::multimap<Key, T, std::less<Key>, Alloc>; template<class T, class Alloc = default_allocator<T>> using multiset = std::multiset<T, std::less<T>, Alloc>; template<class T, class Alloc = default_allocator<T>> using set = std::set<T, std::less<T>, Alloc>; template<class Key, class T, class Alloc = default_allocator<std::pair<const Key, T>>> using unordered_map = std::unordered_map<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; template<class Key, class T, class Alloc = default_allocator<std::pair<const Key, T>>> using unordered_multimap = std::unordered_multimap<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; template<class Key, class Alloc = default_allocator<Key>> using unordered_multiset = std::unordered_multiset<Key, std::hash<Key>, std::equal_to<Key>, Alloc>; template<class Key, class Alloc = default_allocator<Key>> using unordered_set = std::unordered_set<Key, std::hash<Key>, std::equal_to<Key>, Alloc>; template<class T, class Alloc = default_allocator<T>> using stack = std::stack<T, Alloc>; template<class T, class Alloc = default_allocator<T>> using queue = std::queue<T, Alloc>; template<class T, class Alloc = default_allocator<T>> using priority_queue = std::priority_queue<T, std::vector<T, Alloc>, std::less<typename std::vector<T, Alloc>::value_type>>; template<class T, class Alloc = default_allocator<T>> using basic_string = std::basic_string<T, std::char_traits<T>, Alloc>; using string = basic_string<char>; using wstring = basic_string<wchar_t>; using u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; TEST_CASE("jemallocator will work with standard containers", "[containers]") { SECTION("sequence containers") { SECTION("forward_list") { forward_list<int> container; container.push_front(0); } SECTION("deque") { deque<int> container; container.push_back(0); } SECTION("list") { list<int> container; container.push_back(0); } SECTION("vector") { vector<int> container; container.push_back(0); } } SECTION("associative containers") { SECTION("map") { map<int, int> container; container[0] = 0; } SECTION("multimap") { multimap<int, int> container; container.insert(std::make_pair(0, 0)); } SECTION("multiset") { multiset<int> container; container.insert(0); } SECTION("set") { set<int> container; container.insert(0); } } SECTION("unordered associative containers") { SECTION("unordered_map") { unordered_map<int, int> container; container[0] = 0; } SECTION("unordered_multimap") { unordered_multimap<int, int> container; container.insert(std::make_pair(0, 0)); } SECTION("unordered_multiset") { unordered_multiset<int> container; container.insert(0); } SECTION("unordered_set") { unordered_set<int> container; container.insert(0); } } SECTION("container adaptors") { SECTION("stack") { stack<int> container; } SECTION("queue") { queue<int> container; } SECTION("priority_queue") { priority_queue<int> container; } } SECTION("strings") { SECTION("string") { basic_string<char> container; } SECTION("wstring") { basic_string<wchar_t> container; } } }
30.355191
124
0.719532
[ "vector" ]
7b0cc432f391dad2d4a357455457362015763468
7,526
cc
C++
paddle/fluid/operators/strided_slice_op.cc
jhjiangcs/Paddle
fcf53e55ff22c54175efdb32ac367c6e04f19900
[ "Apache-2.0" ]
3
2019-07-17T09:30:31.000Z
2021-12-27T03:16:55.000Z
paddle/fluid/operators/strided_slice_op.cc
cryoco/Paddle
39ac41f137d685af66078adf2f35d65473978b4a
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/strided_slice_op.cc
cryoco/Paddle
39ac41f137d685af66078adf2f35d65473978b4a
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019 PaddlePaddle 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. */ #include "paddle/fluid/operators/strided_slice_op.h" #include <algorithm> #include <memory> #include <vector> namespace paddle { namespace operators { using Tensor = framework::Tensor; class StridedSliceOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true, "Input (Input) of slice op should not be null."); PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true, "Output (Out) of slice op should not be null."); auto in_dims = ctx->GetInputDim("Input"); PADDLE_ENFORCE_LT(in_dims.size(), 7, "The rank of input should be less than 7."); auto starts = ctx->Attrs().Get<std::vector<int>>("starts"); auto ends = ctx->Attrs().Get<std::vector<int>>("ends"); auto strides = ctx->Attrs().Get<std::vector<int>>("strides"); auto axes = ctx->Attrs().Get<std::vector<int>>("axes"); PADDLE_ENFORCE_EQ(starts.size(), ends.size(), "starts and ends dim size must to be same"); PADDLE_ENFORCE_EQ(ends.size(), strides.size(), "ends and strides dim size must to be same"); PADDLE_ENFORCE_EQ(ends.size(), axes.size(), "axes, end and start dim size must to be same"); // we need to analysis strided slice op is valid for // the parameter that we get from python front int stride_index, start_index, end_index; std::vector<int> out_dims_vector(in_dims.size()); for (int i = 0; i < in_dims.size(); i++) { out_dims_vector[i] = in_dims[i]; } for (size_t i = 0; i < starts.size(); i++) { PADDLE_ENFORCE_NE(strides[i], 0, "stride must not to be zero"); int axes_index = axes[i]; start_index = starts[i]; end_index = ends[i]; stride_index = strides[i]; int axis_size = in_dims[axes_index]; if (axis_size < 0) { continue; } if (start_index < 0) { start_index = start_index + axis_size; } if (end_index < 0) { end_index = end_index + axis_size; } if (stride_index < 0) { start_index = start_index + 1; end_index = end_index + 1; } bool zero_dim_condition = ((stride_index < 0 && (start_index <= end_index)) || (stride_index > 0 && (start_index >= end_index))); PADDLE_ENFORCE_EQ(zero_dim_condition, false, "starts and end must meet requirement in different " "stride conditiont"); int left = std::max(0, std::min(start_index, end_index)); int right = std::min(axis_size, std::max(start_index, end_index)); int step = std::abs(stride_index); auto out_dims_index = (std::abs(right - left) + step - 1) / step; out_dims_vector[axes_index] = out_dims_index; } framework::DDim out_dims(framework::make_ddim(out_dims_vector)); ctx->SetOutputDim("Out", out_dims); ctx->ShareLoD("Input", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(ctx.Input<Tensor>("Input")->type(), ctx.Input<Tensor>("Input")->place()); } }; class StridedSliceOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Input", "Tensor of data to extract slices from."); AddOutput("Out", "Sliced data tensor."); AddAttr<std::vector<int>>( "axes", "(list<int> Axes stride from the start to the end)"); AddAttr<std::vector<int>>( "starts", "(list<int>) start that the tensor slice start."); AddAttr<std::vector<int>>("ends", "(list<int>) end that the tensor slice end"); AddAttr<std::vector<int>>( "strides", "(list<int> stride stride from the start to the end)"); AddComment(R"DOC( Strided Slice Operator. Instead of calling this op directly most users will want to use the NumPy-style slicing syntax. For Example: data = fluid.layers.fill_constant(shape=[3, 3], value=0, dtype='int64') y = fluid.layers.strided_slice(data, [0, 1], [1,0], [2, 3], [1, 1]) )DOC"); } }; class StridedSliceOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true, "Input should not be null"); PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName("Out")), true, "Input(Out@GRAD) should not be null"); auto x_dims = ctx->GetInputDim("Input"); auto x_grad_name = framework::GradVarName("Input"); if (ctx->HasOutput(x_grad_name)) { ctx->SetOutputDim(x_grad_name, x_dims); } } framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( ctx.Input<framework::Tensor>(framework::GradVarName("Out"))->type(), ctx.GetPlace()); } }; class StridedSliceOpGradMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { auto* bind = new framework::OpDesc(); bind->SetInput(framework::GradVarName("Out"), OutputGrad("Out")); bind->SetInput("Input", Input("Input")); bind->SetOutput(framework::GradVarName("Input"), InputGrad("Input")); bind->SetAttrMap(Attrs()); bind->SetType("strided_slice_grad"); return std::unique_ptr<framework::OpDesc>(bind); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERENCE( StridedSliceOpGradNoNeedBufferVarsInference, "Input"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(strided_slice, ops::StridedSliceOp, ops::StridedSliceOpMaker, ops::StridedSliceOpGradMaker); REGISTER_OPERATOR(strided_slice_grad, ops::StridedSliceOpGrad, ops::StridedSliceOpGradNoNeedBufferVarsInference); REGISTER_OP_CPU_KERNEL( strided_slice, ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, int>, ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, float>, ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_CPU_KERNEL( strided_slice_grad, ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, int>, ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, float>, ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, double>);
38.397959
80
0.671273
[ "shape", "vector" ]
7b11c0d5f8079531740db5b29aa96e443871a411
3,356
cc
C++
tensorflow/compiler/xla/service/xla_debug_info_manager.cc
mcx/tensorflow
d7e521a1ad21681855b439b9c2a05837c804e488
[ "Apache-2.0" ]
1
2022-03-18T17:36:11.000Z
2022-03-18T17:36:11.000Z
tensorflow/compiler/xla/service/xla_debug_info_manager.cc
mcx/tensorflow
d7e521a1ad21681855b439b9c2a05837c804e488
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/service/xla_debug_info_manager.cc
mcx/tensorflow
d7e521a1ad21681855b439b9c2a05837c804e488
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 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. ==============================================================================*/ #include "tensorflow/compiler/xla/service/xla_debug_info_manager.h" #include <memory> #include <string> #include <utility> #include "tensorflow/compiler/xla/service/hlo_proto_util.h" namespace xla { void XlaDebugInfoManager::RegisterModule( ModuleIdentifier module_id, std::shared_ptr<const HloModule> hlo_module, std::shared_ptr<const BufferAssignmentProto> buffer_assignment) { CHECK(hlo_module != nullptr && module_id == hlo_module->unique_id()); absl::MutexLock lock(&mutex_); auto result = modules_.try_emplace(module_id); CHECK(result.second); XlaModuleEntry& m = result.first->second; m.hlo_module = std::move(hlo_module); m.buffer_assignment = std::move(buffer_assignment); m.active = true; } // Unregister an active module, when the last active module of the same // module id is out of scope, we remove it from our database. // However during tracing, we will defer the cleanup after serialization. void XlaDebugInfoManager::UnregisterModule(ModuleIdentifier module_id) { absl::MutexLock lock(&mutex_); auto it = modules_.find(module_id); CHECK(it != modules_.end()); if (!tracing_active_) { modules_.erase(it); } else { XlaModuleEntry& m = it->second; m.active = false; } } void XlaDebugInfoManager::StartTracing() { absl::MutexLock lock(&mutex_); tracing_active_ = true; } void XlaDebugInfoManager::StopTracing( std::vector<std::unique_ptr<HloProto>>* module_debug_info) { std::vector<XlaModuleEntry> modules_to_serialize; { absl::MutexLock lock(&mutex_); if (!tracing_active_) return; tracing_active_ = false; // Copy all modules so we can serialize without holding the lock, and remove // all inactive modules. modules_to_serialize.reserve(modules_.size()); for (auto it = modules_.begin(); it != modules_.end();) { auto& m = it->second; if (!m.active) { modules_to_serialize.emplace_back(std::move(m)); modules_.erase(it++); } else { modules_to_serialize.emplace_back(m); ++it; } } } if (module_debug_info) { module_debug_info->clear(); for (const auto& m : modules_to_serialize) { // In real world, hlo_module and buffer_assignment will always be // non-nullptr. Due to the inconvenience of creation of buffer_assignment // object in test, we set it to nullptr and guard this for it. auto hlo_proto = absl::make_unique<HloProto>(MakeHloProto(*m.hlo_module)); if (m.buffer_assignment != nullptr) { *hlo_proto->mutable_buffer_assignment() = *m.buffer_assignment; } module_debug_info->emplace_back(std::move(hlo_proto)); } } } } // namespace xla
34.244898
80
0.699344
[ "object", "vector" ]
7b260d63f8ac23ffd4a3cce3011ff1aa2c4bf59a
4,800
cpp
C++
src/OpenGLUtils.cpp
QuanHBui/OpenGL-Compute
db746c78e60b36ea41261e7d2325a9df1d60ea44
[ "MIT" ]
null
null
null
src/OpenGLUtils.cpp
QuanHBui/OpenGL-Compute
db746c78e60b36ea41261e7d2325a9df1d60ea44
[ "MIT" ]
null
null
null
src/OpenGLUtils.cpp
QuanHBui/OpenGL-Compute
db746c78e60b36ea41261e7d2325a9df1d60ea44
[ "MIT" ]
null
null
null
#include "OpenGLUtils.h" #include <cstdio> #include <fstream> #include <iostream> namespace oglutils { std::string readFileAsString(const std::string &fileName) { std::string result; std::ifstream fileHandle(fileName); if (fileHandle.is_open()) { fileHandle.seekg(0, std::ios::end); result.reserve((size_t)fileHandle.tellg()); fileHandle.seekg(0, std::ios::beg); result.assign((std::istreambuf_iterator<char>(fileHandle)), std::istreambuf_iterator<char>()); } else { throw std::runtime_error("Could not open file: " + fileName); } return result; } void getComputeShaderInfo() { GLint intArray[3]; glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0, &intArray[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1, &intArray[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, &intArray[2]); printf("Max global (total) work group counts x:%i y:%i z:%i\n", intArray[0], intArray[1], intArray[2]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0, &intArray[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &intArray[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &intArray[2]); printf("Max local (in one shader) work group size x:%i y:%i z:%i \n", intArray[0], intArray[1], intArray[2]); GLint justSomeInt; glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &justSomeInt); printf("Max local work group invocations: %i\n", justSomeInt); glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &justSomeInt); printf("Max shader storage buffer bindings: %i\n", justSomeInt); glGetIntegerv(GL_MAX_COMPUTE_SHARED_MEMORY_SIZE, &justSomeInt); printf("Max total shared variables storage size (in bytes): %i\n", justSomeInt); } void getUboInfo() { GLint returnInt; // Each shader stage has a limit on the number of seperate uniform buffer binding locations glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &returnInt); printf("Max vertex uniform blocks or binding locations: %i\n", returnInt); glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &returnInt); printf("Max geometry uniform blocks or binding locations: %i\n", returnInt); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &returnInt); printf("Max fragment uniform blocks or binding locations: %i\n", returnInt); // Limitation on the available storage per uniform buffer glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &returnInt); printf("Max uniform block size (in bytes): %i\n", returnInt); // When bind uniform buffer with glBindBufferRange, offset field must be multiple of GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &returnInt); printf("Uniform buffer offset alignment: %i\n", returnInt); } // @source: https://learnopengl.com/In-Practice/Debugging void APIENTRY debugOutputMessageCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char *message, const void *pUserParam ) { // Ignore non-significant error/warning codes if (id == 131169 || id == 131185 || id == 131218 || id == 131204) return; std::cerr << "---------------\n" << "Debug message (" << id << "): " << message << '\n'; switch (source) { case GL_DEBUG_SOURCE_API: std::cerr << "Source: API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: std::cerr << "Source: Window System"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: std::cerr << "Source: Shader Compiler"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: std::cerr << "Source: Third Party"; break; case GL_DEBUG_SOURCE_APPLICATION: std::cerr << "Source: Application"; break; case GL_DEBUG_SOURCE_OTHER: std::cerr << "Source: Other"; break; } std::cerr << '\n'; switch (type) { case GL_DEBUG_TYPE_ERROR: std::cerr << "Type: Error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cerr << "Type: Deprecated Behaviour"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cerr << "Type: Undefined Behaviour"; break; case GL_DEBUG_TYPE_PORTABILITY: std::cerr << "Type: Portability"; break; case GL_DEBUG_TYPE_PERFORMANCE: std::cerr << "Type: Performance"; break; case GL_DEBUG_TYPE_MARKER: std::cerr << "Type: Marker"; break; case GL_DEBUG_TYPE_PUSH_GROUP: std::cerr << "Type: Push Group"; break; case GL_DEBUG_TYPE_POP_GROUP: std::cerr << "Type: Pop Group"; break; case GL_DEBUG_TYPE_OTHER: std::cerr << "Type: Other"; break; } std::cerr << '\n'; switch (severity) { case GL_DEBUG_SEVERITY_HIGH: std::cerr << "Severity: High"; break; case GL_DEBUG_SEVERITY_MEDIUM: std::cerr << "Severity: Medium"; break; case GL_DEBUG_SEVERITY_LOW: std::cerr << "Severity: Low"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: std::cerr << "Severity: Notification"; break; } std::cerr << '\n' << std::endl; __debugbreak(); } }
37.209302
120
0.719375
[ "geometry" ]
7b2eaa8f9ddd993d5874f1736516e9f6d9e2ea1c
2,260
cpp
C++
187.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
187.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
187.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include <unordered_set> #include <vector> #include <algorithm> #include <climits> #include <stack> #include <sstream> #include <numeric> #include <unordered_map> #include <array> using namespace std; class Solution { public: const int len = 10; vector<string> findRepeatedDnaSequences(string s) { unordered_map<int,int> dict; int n = s.length(); for (int i = 0; i < n - len + 1; ++ i) { string subs = s.substr(i, len); int val = str2int(subs); if (dict.find(val) == dict.end()) dict[val] = 1; else dict[val] += 1; } vector<int> numbers; for (auto it = dict.begin(); it != dict.end(); ++ it) if (it->second > 1) numbers.push_back(it->first); vector<string> ans; for (auto it = numbers.begin(); it != numbers.end(); ++ it) ans.push_back(int2str(*it)); return ans; } int str2int(const string& s) { int val = 0; for (int i = 0; i < s.length(); ++ i) val = val * 4 + char2int(s[i]); return val; } int char2int(char ch) { int val = 0; switch (ch) { case 'A': val = 0; break; case 'C': val = 1; break; case 'G': val = 2; break; case 'T': val = 3; break; } return val; } string int2str(int num) { string s = ""; do { s = int2char(num % 4) + s; num = num / 4; } while (num > 0); if (s.length() < len) s = string(len - s.length(), 'A') + s; return s; } char int2char(int num) { char ch; switch (num) { case 0: ch = 'A'; break; case 1: ch = 'C'; break; case 2: ch = 'G'; break; case 3: ch = 'T'; break; } return ch; } }; int main() { // Solution slo; // string s = "CTAGT"; // cout << slo.str2int(s) << endl; // int n = slo.str2int(s); // cout << slo.int2str(n) << endl; string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; vector<string> ans = Solution().findRepeatedDnaSequences(s); for (int i = 0; i < ans.size(); ++ i) cout << ans[i] << endl; return 0; }
16.028369
64
0.495133
[ "vector" ]
7b3351b4b2fa6738c84fa0c38d3953835f1c2cab
10,264
cc
C++
src/SOE.cc
grayvalley/soe
ac484973b0ce8890310cc17764dd27a7e1e18507
[ "Apache-2.0" ]
null
null
null
src/SOE.cc
grayvalley/soe
ac484973b0ce8890310cc17764dd27a7e1e18507
[ "Apache-2.0" ]
null
null
null
src/SOE.cc
grayvalley/soe
ac484973b0ce8890310cc17764dd27a7e1e18507
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Juha-Samuli Hellén * * 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 <iostream> #include <grayvalley/soe/SOE.hh> namespace GVT::SOE { std::map<std::string, SOE::MESSAGE_TYPE> soe_enum_map = { {"X", SOE::MESSAGE_TYPE_ORDER_CANCELED}, {"E", SOE::MESSAGE_TYPE_ORDER_EXECUTED}, {"Y", SOE::MESSAGE_TYPE_ORDER_ACCEPTED}, {"R", SOE::MESSAGE_TYPE_ORDER_REJECTED} }; } namespace GVT::SOE { std::map<std::string, SIDE> map_str_side_to_enum = { {"B", SIDE::B}, {"S", SIDE::S} }; } namespace GVT::SOE { std::map<SIDE, std::string> map_enum_side_to_str = { {SIDE::B, "B"}, {SIDE::S, "S"} }; } namespace GVT::SOE { std::map<std::string, ORDER_TYPE> map_str_order_type_to_enum = { {"LMT", ORDER_TYPE::LIMIT}, {"MKT", ORDER_TYPE::MARKET} }; } namespace GVT::SOE { std::map<ORDER_TYPE, std::string> map_enum_order_type_to_str = { {ORDER_TYPE::LIMIT, "LMT"}, {ORDER_TYPE::MARKET, "MKT"} }; } /** * Populates the body of the message from a buffer * * @param buffer: pointer to the beginning of a buffer * @param len: length of the message */ namespace GVT::SOE { void Message::from(char* buffer, size_t len) { m_body = nlohmann::json::parse(buffer, buffer + len); } } /** * Return type id of the message * * @return: integer id */ namespace GVT::SOE { int Message::type() const { if(m_body.empty()){ return MESSAGE_TYPE_EMPTY; } try { auto value = m_body["message-type"].get<std::string>(); return soe_enum_map.find(value)->second; } catch (nlohmann::json::exception& e) { return MESSAGE_TYPE_INVALID; } } } /** * Return an item from the message body */ namespace GVT::SOE { template <typename T> T Message::get(std::string key) { return m_body[key].get<T>(); } } namespace GVT::SOE { std::string Message::dump() { return m_body.dump(); } } /** * Get nlohmann::json object from OrderAddMessage. */ namespace GVT::SOE { nlohmann::json OrderNewMessage::to_json() { nlohmann::json payload; payload["message-type"] = "A"; payload["instrument"] = Instrument; payload["price"] = Price; payload["quantity"] = Quantity; payload["side"] = map_enum_side_to_str[Side]; payload["order-type"] = map_enum_order_type_to_str[OrderType]; return payload; } } /** * Get nlohmann::json object from OrderCancelMessage. */ namespace GVT::SOE { nlohmann::json OrderCancelMessage::to_json() { nlohmann::json payload; payload["message-type"] = "X"; payload["order-id"] = OrderId; return payload; } } /** * Get OrderAcceptedMessage from generic IMessage. */ namespace GVT::SOE { void OrderAcceptedMessage::get(IMessage* p_imessage) { auto* p_message = reinterpret_cast<GVT::SOE::Message*>(p_imessage); Instrument = p_message->get<std::string>("instrument"); OrderId = p_message->get<uint64_t>("order-id"); Price = p_message->get<uint64_t>("price"); Quantity = p_message->get<uint64_t>("quantity"); auto side = p_message->get<std::string>("side"); Side = map_str_side_to_enum.find(side)->second; auto order_type = p_message->get<std::string>("order-type"); OrderType = map_str_order_type_to_enum.find(order_type)->second; } } /** * Get SOE OrderAcceptedEvent from OrderAcceptedMessage. */ namespace GVT::SOE { void OrderAcceptedMessage::put(IOrderAcceptedEvent* p_event){ p_event->Exchange = "sandbox"; p_event->Instrument = Instrument; p_event->OrderId = OrderId; p_event->Price = Price; p_event->Quantity = Quantity; p_event->Side = Side; p_event->OrderType = OrderType; } } /** * Get SOE OrderRejectedMessage from generic IMessage. */ namespace GVT::SOE { void OrderRejectedMessage::get(IMessage* p_imessage) { auto* p_message = reinterpret_cast<GVT::SOE::Message*>(p_imessage); Instrument = p_message->get<std::string>("instrument"); Price = p_message->get<uint64_t>("price"); Quantity = p_message->get<uint64_t>("quantity"); auto side = p_message->get<std::string>("side"); Side = map_str_side_to_enum[side]; auto order_type = p_message->get<std::string>("order-type"); OrderType = map_str_order_type_to_enum[order_type]; Reason = p_message->get<std::string>("reason"); } } /** * Get OrderRejectedEvent from OrderRejectedMessage. */ namespace GVT::SOE { void OrderRejectedMessage::put(IOrderRejectedEvent* p_event){ p_event->Exchange = "sandbox"; p_event->Instrument = Instrument; p_event->Price = Price; p_event->Quantity = Quantity; p_event->Side = Side; p_event->OrderType = OrderType; p_event->Reason = Reason; } } /** * Get OrderExecutedMessage from generic IMessage. */ namespace GVT::SOE { void OrderExecutedMessage::get(IMessage* p_imessage) { auto* p_message = reinterpret_cast<GVT::SOE::Message*>(p_imessage); Instrument = p_message->get<std::string>("instrument"); OrderId = p_message->get<uint64_t>("order-id"); Price = p_message->get<uint64_t>("price"); Quantity = p_message->get<uint64_t>("quantity"); auto side = p_message->get<std::string>("side"); Side = map_str_side_to_enum.find(side)->second; } } /** * Get OrderExecutedEvent from OrderExecutedMessage. */ namespace GVT::SOE { void OrderExecutedMessage::put(IOrderExecutedEvent* p_event){ p_event->Exchange = "sandbox"; p_event->Instrument = Instrument; p_event->OrderId = OrderId; p_event->Price = Price; p_event->Quantity = Quantity; p_event->Side = Side; } } /** * Get OrderCanceledMessage from generic IMessage. */ namespace GVT::SOE { void OrderCanceledMessage::get(IMessage* p_imessage) { auto* p_message = reinterpret_cast<GVT::SOE::Message*>(p_imessage); OrderId = p_message->get<uint64_t>("order-id"); Price = p_message->get<uint64_t>("price"); Quantity = p_message->get<uint64_t>("quantity"); auto side = p_message->get<std::string>("side"); Side = map_str_side_to_enum.find(side)->second; Reason = p_message->get<std::string>("reason"); } } /** * Get OrderExecutedEvent from OrderExecutedMessage. */ namespace GVT::SOE { void OrderCanceledMessage::put(IOrderCanceledEvent* p_event) { p_event->Exchange = "sandbox"; p_event->Instrument = Instrument; p_event->OrderId = OrderId; p_event->Price = Price; p_event->Quantity = Quantity; p_event->Side = Side; p_event->Reason = Reason; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderNewMessage& order){ s << " --- [OrderAddMessage] ---" << std::endl; s << "Instrument: " << order.Instrument << std::endl; s << "Price: " << order.Price << std::endl; s << "Quantity: " << order.Quantity << std::endl; s << "Side: " << map_enum_side_to_str[order.Side] << std::endl; s << "OrderType: " << map_enum_order_type_to_str[order.OrderType] << std::endl; return s; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderCancelMessage& order){ s << " --- [OrderCancelMessage] ---" << std::endl; s << "OrderId: " << order.OrderId << std::endl; return s; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderAcceptedMessage& order){ s << " --- [OrderAcceptedMessage] ---" << std::endl; s << "OrderId: " << order.OrderId << std::endl; s << "Price: " << order.Price << std::endl; s << "Quantity: " << order.Quantity << std::endl; s << "Side: " << map_enum_side_to_str[order.Side] << std::endl; s << "OrderType: " << map_enum_order_type_to_str[order.OrderType] << std::endl; return s; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderRejectedMessage& order){ s << " --- [OrderRejectedMessage] ---" << std::endl; s << "Price: " << order.Price << std::endl; s << "Quantity: " << order.Quantity << std::endl; s << "Side: " << map_enum_side_to_str[order.Side] << std::endl; s << "OrderType: " << map_enum_order_type_to_str[order.OrderType] << std::endl; s << "Reason: " << order.Reason << std::endl; return s; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderExecutedMessage& order){ s << " --- [OrderExecutedMessage] ---" << std::endl; s << "OrderId: " << order.OrderId << std::endl; s << "Price: " << order.Price << std::endl; s << "Quantity: " << order.Quantity << std::endl; return s; } } namespace GVT::SOE { std::ostream &operator<<(std::ostream& s, const OrderCanceledMessage& order){ s << " --- [OrderCanceledMessage] ---" << std::endl; s << "OrderId: " << order.OrderId << std::endl; s << "Price: " << order.Price << std::endl; s << "Quantity: " << order.Quantity << std::endl; s << "Side: " << map_enum_side_to_str[order.Side] << std::endl; return s; }; }
31.975078
88
0.59509
[ "object" ]
7b36e974dd6a000cacab821bba4856cab38f7a0b
1,377
cpp
C++
seek-test.cpp
LaurentBerger/libseek
d26a1ed76770c8e5ef2116b41a52300da6d9dac7
[ "MIT" ]
68
2015-01-13T21:43:28.000Z
2021-05-31T13:28:42.000Z
seek-test.cpp
kkalya/seek
84e726c1e7955ae5bd7a5fa69988db417824b047
[ "MIT" ]
10
2015-11-20T11:22:26.000Z
2020-11-19T06:33:43.000Z
seek-test.cpp
kkalya/seek
84e726c1e7955ae5bd7a5fa69988db417824b047
[ "MIT" ]
29
2015-03-13T04:37:20.000Z
2020-07-14T15:50:05.000Z
#include <thread> #include <chrono> #include <fstream> #include <sstream> #include <vector> #include "seek.hpp" using namespace std; using namespace LibSeek; inline void sleep(float secs) { chrono::milliseconds dura(int(1000*secs)); this_thread::sleep_for(dura); } int main() { setbuf(stdout, NULL); Imager iface; iface.init(); Frame frame; iface.frame_init(frame); for (int i = 0; i < 71370537; i++) { //break; iface.frame_acquire(frame); int h = frame.height(); int w = frame.width(); vector<uint16_t> img(w*h); { int _max = 0; int _min = 0xffff; #if 0 for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { uint16_t v = frame.data()[y*w+x]; if (v > _max) _max = v; if (v < _min) _min = v; } } #elif 0 _max = 0x8200; _min = 0x7e00; #else _max = 0xffff; _min = 0x0; #endif for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { #if 1 float v = float(frame.data()[y*w+x] - _min) / (_max - _min); if (v < 0.0) { v = 0; } if (v > 1.0) { v = 1; } uint16_t o = 0xffff * v; #else uint16_t o = frame.data()[y*w+x]; #endif //fprintf(stderr, " %4x", o); img[y*w+x] = o; } //fprintf(stderr, "\n"); } //fprintf(stderr, "\n"); fwrite((uint8_t*)img.data(), sizeof(uint16_t), w*h, stdout); } } iface.frame_exit(frame); iface.exit(); }
17.43038
65
0.545389
[ "vector" ]
7b3a62e14e800f3f0db7a4b3b9e6b26d2fc9ae8d
2,160
cpp
C++
Cthulhu/src/TypeRegistryLocal.cpp
Yunusbcr/labgraph
a00ae7098b7b0e0eda8ce2e7e62dae86854616fb
[ "MIT" ]
124
2021-07-14T21:25:59.000Z
2022-03-08T20:40:16.000Z
Cthulhu/src/TypeRegistryLocal.cpp
VanEdward/labgraph
9488feac59f9ef86091befdeaddb69d84e4d6fb3
[ "MIT" ]
46
2021-07-16T18:41:11.000Z
2022-03-31T20:53:00.000Z
Cthulhu/src/TypeRegistryLocal.cpp
VanEdward/labgraph
9488feac59f9ef86091befdeaddb69d84e4d6fb3
[ "MIT" ]
22
2021-07-16T18:34:56.000Z
2022-03-31T15:12:06.000Z
// Copyright 2004-present Facebook. All Rights Reserved. #include "TypeRegistryLocal.h" #define DEFAULT_LOG_CHANNEL "Cthulhu" #include <logging/Log.h> namespace cthulhu { TypeInfoInterfacePtr TypeRegistryLocal::findSampleType(const std::type_index& sampleType) const { auto it = sampleTypeMap_.find(sampleType); if (it != sampleTypeMap_.end()) { return types_.at(it->second); } return TypeInfoInterfacePtr(); } TypeInfoInterfacePtr TypeRegistryLocal::findConfigType(const std::type_index& configType) const { auto it = configTypeMap_.find(configType); if (it != configTypeMap_.end()) { return types_.at(it->second); } return TypeInfoInterfacePtr(); } TypeInfoInterfacePtr TypeRegistryLocal::findTypeName(const std::string& typeName) const { auto it = streamNameMap_.find(typeName); if (it != streamNameMap_.end()) { return types_.at(it->second); } return TypeInfoInterfacePtr(); } TypeInfoInterfacePtr TypeRegistryLocal::findTypeID(uint32_t typeID) const { if (typeID > 0 && typeID <= types_.size()) { return types_.at(typeID - 1); } return TypeInfoInterfacePtr(); } std::vector<std::string> TypeRegistryLocal::typeNames() const { std::vector<std::string> typeNames; for (const auto& type : streamNameMap_) { typeNames.push_back(type.first); } return typeNames; } void TypeRegistryLocal::registerType(TypeDefinition definition) { for (const auto& type : types_) { if (type->typeName().compare(definition.typeName) == 0) { auto str = "Attempted to register type: [" + type->typeName() + "] which was detected as duplicate."; XR_LOGE("{}", str); throw std::runtime_error(str); } } if (definition.sampleType != typeid(nullptr)) { sampleTypeMap_[definition.sampleType] = types_.size(); } if (definition.configType && *definition.configType != typeid(nullptr)) { configTypeMap_[*definition.configType] = types_.size(); } streamNameMap_[definition.typeName] = types_.size(); types_.push_back(std::shared_ptr<TypeInfoLocal>( new TypeInfoLocal{std::move(definition), static_cast<uint32_t>(types_.size())})); } } // namespace cthulhu
30.422535
100
0.710185
[ "vector" ]
7b3b032c285ec2450813b1b2329425e71b3aa905
711
cpp
C++
leetcode_archived_cpp/LeetCode_72.cpp
Sean10/Algorithm_code
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
[ "BSD-3-Clause" ]
null
null
null
leetcode_archived_cpp/LeetCode_72.cpp
Sean10/Algorithm_code
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
[ "BSD-3-Clause" ]
7
2021-03-19T04:41:21.000Z
2021-10-19T15:46:36.000Z
leetcode_archived_cpp/LeetCode_72.cpp
Sean10/Algorithm_code
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
[ "BSD-3-Clause" ]
null
null
null
class Solution { public: int minDistance(string word1, string word2) { vector<vector<int>> dp(word1.size()+1, vector<int>(word2.size()+1, 0)); for (int i = 0;i <= word1.size(); i++) dp[i][0] = i; for (int j = 0;j <= word2.size(); j++) dp[0][j] = j; for (int i = 1;i <= word1.size(); i++) for (int j = 1;j <= word2.size(); j++) { if (word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1]; else dp[i][j] = 1 + min({dp[i-1][j-1], dp[i][j-1], dp[i-1][j]}); } return dp[word1.size()][word2.size()]; } };
29.625
79
0.376934
[ "vector" ]
7b4070199c78378d3bfaf8a4bcd6f435e3a707cb
106
cpp
C++
samples/tests/src/ownheaderbeforestandardgood.cpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
4
2018-06-15T12:54:10.000Z
2020-09-22T16:01:35.000Z
samples/tests/src/ownheaderbeforestandardgood.cpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
null
null
null
samples/tests/src/ownheaderbeforestandardgood.cpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
null
null
null
#include "test.h" #include "otherHeader.h" #include <vector> //This works fine int main() { return 0; }
13.25
24
0.669811
[ "vector" ]
0da81a567eb1a9e59a0c12b6f523f7f7b5b33ef3
15,418
cc
C++
cpp/src/arrow/flight/transport.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2021-12-14T06:44:19.000Z
2021-12-14T06:44:19.000Z
cpp/src/arrow/flight/transport.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2
2021-11-17T14:36:51.000Z
2022-01-23T16:49:53.000Z
cpp/src/arrow/flight/transport.cc
davisusanibar/arrow
07ac9fd86c6225f493943e4ab0ff35b0fdbfb2ae
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
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 "arrow/flight/transport.h" #include <sstream> #include <unordered_map> #include "arrow/flight/client_auth.h" #include "arrow/flight/transport_server.h" #include "arrow/flight/types.h" #include "arrow/ipc/message.h" #include "arrow/result.h" #include "arrow/status.h" #include "arrow/util/make_unique.h" namespace arrow { namespace flight { namespace internal { ::arrow::Result<std::unique_ptr<ipc::Message>> FlightData::OpenMessage() { return ipc::Message::Open(metadata, body); } bool TransportDataStream::ReadData(internal::FlightData*) { return false; } arrow::Result<bool> TransportDataStream::WriteData(const FlightPayload&) { return Status::NotImplemented("Writing data for this stream"); } Status TransportDataStream::WritesDone() { return Status::OK(); } bool ClientDataStream::ReadPutMetadata(std::shared_ptr<Buffer>*) { return false; } Status ClientDataStream::Finish(Status st) { auto server_status = DoFinish(); if (server_status.ok()) return st; return Status::FromDetailAndArgs(server_status.code(), server_status.detail(), server_status.message(), ". Client context: ", st.ToString()); } Status ClientTransport::Authenticate(const FlightCallOptions& options, std::unique_ptr<ClientAuthHandler> auth_handler) { return Status::NotImplemented("Authenticate for this transport"); } arrow::Result<std::pair<std::string, std::string>> ClientTransport::AuthenticateBasicToken(const FlightCallOptions& options, const std::string& username, const std::string& password) { return Status::NotImplemented("AuthenticateBasicToken for this transport"); } Status ClientTransport::DoAction(const FlightCallOptions& options, const Action& action, std::unique_ptr<ResultStream>* results) { return Status::NotImplemented("DoAction for this transport"); } Status ClientTransport::ListActions(const FlightCallOptions& options, std::vector<ActionType>* actions) { return Status::NotImplemented("ListActions for this transport"); } Status ClientTransport::GetFlightInfo(const FlightCallOptions& options, const FlightDescriptor& descriptor, std::unique_ptr<FlightInfo>* info) { return Status::NotImplemented("GetFlightInfo for this transport"); } arrow::Result<std::unique_ptr<SchemaResult>> ClientTransport::GetSchema( const FlightCallOptions& options, const FlightDescriptor& descriptor) { return Status::NotImplemented("GetSchema for this transport"); } Status ClientTransport::ListFlights(const FlightCallOptions& options, const Criteria& criteria, std::unique_ptr<FlightListing>* listing) { return Status::NotImplemented("ListFlights for this transport"); } Status ClientTransport::DoGet(const FlightCallOptions& options, const Ticket& ticket, std::unique_ptr<ClientDataStream>* stream) { return Status::NotImplemented("DoGet for this transport"); } Status ClientTransport::DoPut(const FlightCallOptions& options, std::unique_ptr<ClientDataStream>* stream) { return Status::NotImplemented("DoPut for this transport"); } Status ClientTransport::DoExchange(const FlightCallOptions& options, std::unique_ptr<ClientDataStream>* stream) { return Status::NotImplemented("DoExchange for this transport"); } class TransportRegistry::Impl final { public: arrow::Result<std::unique_ptr<ClientTransport>> MakeClient( const std::string& scheme) const { auto it = client_factories_.find(scheme); if (it == client_factories_.end()) { return Status::KeyError("No client transport implementation for ", scheme); } return it->second(); } arrow::Result<std::unique_ptr<ServerTransport>> MakeServer( const std::string& scheme, FlightServerBase* base, std::shared_ptr<MemoryManager> memory_manager) const { auto it = server_factories_.find(scheme); if (it == server_factories_.end()) { return Status::KeyError("No server transport implementation for ", scheme); } return it->second(base, std::move(memory_manager)); } Status RegisterClient(const std::string& scheme, ClientFactory factory) { auto it = client_factories_.insert({scheme, std::move(factory)}); if (!it.second) { return Status::Invalid("Client transport already registered for ", scheme); } return Status::OK(); } Status RegisterServer(const std::string& scheme, ServerFactory factory) { auto it = server_factories_.insert({scheme, std::move(factory)}); if (!it.second) { return Status::Invalid("Server transport already registered for ", scheme); } return Status::OK(); } private: std::unordered_map<std::string, TransportRegistry::ClientFactory> client_factories_; std::unordered_map<std::string, TransportRegistry::ServerFactory> server_factories_; }; TransportRegistry::TransportRegistry() { impl_ = arrow::internal::make_unique<Impl>(); } TransportRegistry::~TransportRegistry() = default; arrow::Result<std::unique_ptr<ClientTransport>> TransportRegistry::MakeClient( const std::string& scheme) const { return impl_->MakeClient(scheme); } arrow::Result<std::unique_ptr<ServerTransport>> TransportRegistry::MakeServer( const std::string& scheme, FlightServerBase* base, std::shared_ptr<MemoryManager> memory_manager) const { return impl_->MakeServer(scheme, base, std::move(memory_manager)); } Status TransportRegistry::RegisterClient(const std::string& scheme, ClientFactory factory) { return impl_->RegisterClient(scheme, std::move(factory)); } Status TransportRegistry::RegisterServer(const std::string& scheme, ServerFactory factory) { return impl_->RegisterServer(scheme, std::move(factory)); } TransportRegistry* GetDefaultTransportRegistry() { static TransportRegistry kRegistry; return &kRegistry; } //------------------------------------------------------------ // Error propagation helpers TransportStatus TransportStatus::FromStatus(const Status& arrow_status) { if (arrow_status.ok()) { return TransportStatus{TransportStatusCode::kOk, ""}; } TransportStatusCode code = TransportStatusCode::kUnknown; std::string message = arrow_status.message(); if (arrow_status.detail()) { message += ". Detail: "; message += arrow_status.detail()->ToString(); } std::shared_ptr<FlightStatusDetail> flight_status = FlightStatusDetail::UnwrapStatus(arrow_status); if (flight_status) { switch (flight_status->code()) { case FlightStatusCode::Internal: code = TransportStatusCode::kInternal; break; case FlightStatusCode::TimedOut: code = TransportStatusCode::kTimedOut; break; case FlightStatusCode::Cancelled: code = TransportStatusCode::kCancelled; break; case FlightStatusCode::Unauthenticated: code = TransportStatusCode::kUnauthenticated; break; case FlightStatusCode::Unauthorized: code = TransportStatusCode::kUnauthorized; break; case FlightStatusCode::Unavailable: code = TransportStatusCode::kUnavailable; break; default: break; } } else if (arrow_status.IsKeyError()) { code = TransportStatusCode::kNotFound; } else if (arrow_status.IsInvalid()) { code = TransportStatusCode::kInvalidArgument; } else if (arrow_status.IsCancelled()) { code = TransportStatusCode::kCancelled; } else if (arrow_status.IsNotImplemented()) { code = TransportStatusCode::kUnimplemented; } else if (arrow_status.IsAlreadyExists()) { code = TransportStatusCode::kAlreadyExists; } return TransportStatus{code, std::move(message)}; } TransportStatus TransportStatus::FromCodeStringAndMessage(const std::string& code_str, std::string message) { int code_int = 0; try { code_int = std::stoi(code_str); } catch (...) { return TransportStatus{ TransportStatusCode::kUnknown, message + ". Also, server sent unknown or invalid Arrow status code " + code_str}; } switch (code_int) { case static_cast<int>(TransportStatusCode::kOk): case static_cast<int>(TransportStatusCode::kUnknown): case static_cast<int>(TransportStatusCode::kInternal): case static_cast<int>(TransportStatusCode::kInvalidArgument): case static_cast<int>(TransportStatusCode::kTimedOut): case static_cast<int>(TransportStatusCode::kNotFound): case static_cast<int>(TransportStatusCode::kAlreadyExists): case static_cast<int>(TransportStatusCode::kCancelled): case static_cast<int>(TransportStatusCode::kUnauthenticated): case static_cast<int>(TransportStatusCode::kUnauthorized): case static_cast<int>(TransportStatusCode::kUnimplemented): case static_cast<int>(TransportStatusCode::kUnavailable): return TransportStatus{static_cast<TransportStatusCode>(code_int), std::move(message)}; default: { return TransportStatus{ TransportStatusCode::kUnknown, message + ". Also, server sent unknown or invalid Arrow status code " + code_str}; } } } Status TransportStatus::ToStatus() const { switch (code) { case TransportStatusCode::kOk: return Status::OK(); case TransportStatusCode::kUnknown: { std::stringstream ss; ss << "Flight RPC failed with message: " << message; return Status::UnknownError(ss.str()).WithDetail( std::make_shared<FlightStatusDetail>(FlightStatusCode::Failed)); } case TransportStatusCode::kInternal: return Status::IOError("Flight returned internal error, with message: ", message) .WithDetail(std::make_shared<FlightStatusDetail>(FlightStatusCode::Internal)); case TransportStatusCode::kInvalidArgument: return Status::Invalid("Flight returned invalid argument error, with message: ", message); case TransportStatusCode::kTimedOut: return Status::IOError("Flight returned timeout error, with message: ", message) .WithDetail(std::make_shared<FlightStatusDetail>(FlightStatusCode::TimedOut)); case TransportStatusCode::kNotFound: return Status::KeyError("Flight returned not found error, with message: ", message); case TransportStatusCode::kAlreadyExists: return Status::AlreadyExists("Flight returned already exists error, with message: ", message); case TransportStatusCode::kCancelled: return Status::Cancelled("Flight cancelled call, with message: ", message) .WithDetail(std::make_shared<FlightStatusDetail>(FlightStatusCode::Cancelled)); case TransportStatusCode::kUnauthenticated: return Status::IOError("Flight returned unauthenticated error, with message: ", message) .WithDetail( std::make_shared<FlightStatusDetail>(FlightStatusCode::Unauthenticated)); case TransportStatusCode::kUnauthorized: return Status::IOError("Flight returned unauthorized error, with message: ", message) .WithDetail( std::make_shared<FlightStatusDetail>(FlightStatusCode::Unauthorized)); case TransportStatusCode::kUnimplemented: return Status::NotImplemented("Flight returned unimplemented error, with message: ", message); case TransportStatusCode::kUnavailable: return Status::IOError("Flight returned unavailable error, with message: ", message) .WithDetail( std::make_shared<FlightStatusDetail>(FlightStatusCode::Unavailable)); default: return Status::UnknownError("Flight failed with error code ", static_cast<int>(code), " and message: ", message); } } Status ReconstructStatus(const std::string& code_str, const Status& current_status, util::optional<std::string> message, util::optional<std::string> detail_message, util::optional<std::string> detail_bin, std::shared_ptr<FlightStatusDetail> detail) { // Bounce through std::string to get a proper null-terminated C string StatusCode status_code = current_status.code(); std::stringstream status_message; try { const auto code_int = std::stoi(code_str); switch (code_int) { case static_cast<int>(StatusCode::OutOfMemory): case static_cast<int>(StatusCode::KeyError): case static_cast<int>(StatusCode::TypeError): case static_cast<int>(StatusCode::Invalid): case static_cast<int>(StatusCode::IOError): case static_cast<int>(StatusCode::CapacityError): case static_cast<int>(StatusCode::IndexError): case static_cast<int>(StatusCode::Cancelled): case static_cast<int>(StatusCode::UnknownError): case static_cast<int>(StatusCode::NotImplemented): case static_cast<int>(StatusCode::SerializationError): case static_cast<int>(StatusCode::RError): case static_cast<int>(StatusCode::CodeGenError): case static_cast<int>(StatusCode::ExpressionValidationError): case static_cast<int>(StatusCode::ExecutionError): case static_cast<int>(StatusCode::AlreadyExists): { status_code = static_cast<StatusCode>(code_int); break; } default: { status_message << ". Also, server sent unknown or invalid Arrow status code " << code_str; break; } } } catch (...) { status_message << ". Also, server sent unknown or invalid Arrow status code " << code_str; } status_message << (message.has_value() ? *message : current_status.message()); if (detail_message.has_value()) { status_message << ". Detail: " << *detail_message; } if (detail_bin.has_value()) { if (!detail) { detail = std::make_shared<FlightStatusDetail>(FlightStatusCode::Internal); } detail->set_extra_info(std::move(*detail_bin)); } return Status(status_code, status_message.str(), std::move(detail)); } } // namespace internal } // namespace flight } // namespace arrow
43.067039
90
0.680568
[ "vector" ]
0daba9f4117a5205216f13ea572acde76e2c8021
4,568
hpp
C++
crogine/include/crogine/graphics/Image.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
crogine/include/crogine/graphics/Image.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
crogine/include/crogine/graphics/Image.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
/*----------------------------------------------------------------------- Matt Marchant 2017 - 2020 http://trederia.blogspot.com crogine - Zlib license. 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. -----------------------------------------------------------------------*/ #pragma once #include <crogine/Config.hpp> #include <crogine/detail/Types.hpp> #include <crogine/detail/glm/vec2.hpp> #include <string> #include <vector> namespace cro { class Colour; /*! \brief CPU side representation of an image. Images can be loaded from file formats BMP, GIF, JPEG, LBM, PCX, PNG, PNM, TGA (desktop platforms can load all formats supported by SDL2_image). Images can have their pixels manipulated directly, but can only be drawn once they have been loaded on to the GPU via cro::Texture. Unlike texture Images are copyable - although this is a heavy operation. */ class CRO_EXPORT_API Image final { public: /*! \brief Constructor. Images are invalid until either create() or load*() functions have been called and returned successfully. */ explicit Image(bool flipOnLoad = false); /*! \brief Creates an empty image. \param width Width of image to create. On mobile platforms this should be pow2 \param height Height of image to create. On mobile platforms this should be pow2 \param colour Colour to fill image with \param format Image Format. Can be RGB or RGBA, defaults to RGBA */ void create(std::uint32_t width, std::uint32_t height, Colour colour, ImageFormat::Type format = ImageFormat::RGBA); /*! \brief Attempts to load an image from a file on disk. On mobile platforms images should have power 2 dimensions. \returns true on success, else false */ bool loadFromFile(const std::string& path); /*! \brief Attemps to load an image from raw pixels in memory. Pixels must be 8-bit and in RGB or RGBA format \param px Pointer to array of pixels in memory \param width Width of image to create. On mobile platforms this should be pow2 \param height Height of image to create. On mobile platforms this should be pow2 \param format Image Format. Can be RGB or RGBA */ bool loadFromMemory(const std::uint8_t* px, std::uint32_t width, std::uint32_t height, ImageFormat::Type format); /*! \brief Sets pixels of a particular colour to transparent. Only works on RGBA format images which have been successfully loaded. \param colour Pixels this colour will be made transparent */ void setTransparencyColour(Colour colour); /*! \brief Returns the dimensions of the image. */ glm::uvec2 getSize() const; /*! \brief Returns the currently loaded image format. */ ImageFormat::Type getFormat() const; /*! \brief Returns a pointer to the underlying pixel data */ const std::uint8_t* getPixelData() const; /*! \brief Saves this image to the given path \returns true on success else false */ bool write(const std::string& path); /*! \brief Sets the pixel at the given position to the given colour \param x The x coordinate of the pixel \param y The y coordinate of the pixel \param colour The colour to set the pixel to. */ void setPixel(std::size_t x, std::size_t y, cro::Colour colour); private: glm::uvec2 m_size = glm::uvec2(0); ImageFormat::Type m_format; std::vector<std::uint8_t> m_data; bool m_flipped; bool m_flipOnLoad; }; }
34.606061
124
0.648205
[ "vector" ]
0db7fc3d7cb2f18eb1da5ebd2ecbfaab417c309b
2,413
cpp
C++
nfc-i2c-tool.cpp
linkineo/ntag-nfc-i2c-tool
6a1d6e830839a50313f8658121fc67085a405322
[ "MIT" ]
3
2019-07-26T17:54:34.000Z
2021-10-16T18:30:46.000Z
nfc-i2c-tool.cpp
linkineo/ntag-nfc-i2c-tool
6a1d6e830839a50313f8658121fc67085a405322
[ "MIT" ]
null
null
null
nfc-i2c-tool.cpp
linkineo/ntag-nfc-i2c-tool
6a1d6e830839a50313f8658121fc67085a405322
[ "MIT" ]
null
null
null
#include "i2c-dev.h" #include <iostream> #include <string> #include <fcntl.h> #include <unistd.h> #include <bitset> #include <vector> const uint8_t page_size_bytes = 16; void read_nfc(int fd,uint8_t page) { uint8_t values[16]; uint8_t res = i2c_smbus_read_i2c_block_data(fd, page, page_size_bytes, &values[0]); std::string ascii = ""; for(int i=0;i<page_size_bytes;i++) { std::cout << "[" << i << "] -> 0x" << std::hex << (int)values[i] << std::endl;; if((int)values[i] >= 32 && (int)values[i] < 128) { ascii += values[i]; }else { ascii += "_"; } } std::cout << "ASCII= " << ascii << std::endl; } void write_nfc(int fd, uint8_t page, std::string s) { std::vector<uint8_t> vals(s.begin(), s.begin()+page_size_bytes); for(int p=0;p<(16-vals.size());p++) { vals.push_back(' '); } uint8_t res = i2c_smbus_write_i2c_block_data(fd, page,page_size_bytes, &vals[0]); if(!res) { std::cout << "Write successful [Page=" << (int)page << "]" << std::endl; }else { std::cout << "WRITE ERROR" << std::endl; } } int main(int argc, char* argv[]) { uint8_t page = 0x0; int i2cDeviceFd = 0; int i2cAdapterNumber = 1; uint8_t i2cSlaveAddress = 0x55; //default address; std::string i2cDevice; i2cDevice = "/dev/i2c-" + std::to_string(i2cAdapterNumber); i2cDeviceFd = open(i2cDevice.c_str(), O_RDWR); std::cout << "Reading NXP I2C-NFC tags" << std::endl; std::cout << "Usage: [app] r page_number" << std::endl; std::cout << "Usage: [app] w page_number string" << std::endl; std::cout << "----------------------------------------" << std::endl; if(argc < 2) { return -1; }else { if (i2cDeviceFd < 0) { std::cout << "ERROR: file descriptor" << std::endl; return -1; } int ioCtlHandle = ioctl(i2cDeviceFd, I2C_SLAVE_FORCE, i2cSlaveAddress); if (ioCtlHandle < 0){ std::cout << "ERROR: IOCTL" << std::endl; return -1; } if(*argv[1] == 'r'){ uint8_t page = std::atoi(argv[2]); std::cout << "Reading 16 bytes [Slave=0x" << std::hex << (int)i2cSlaveAddress << ",Page=" << (int)page << "]" << std::endl; read_nfc(i2cDeviceFd,page); } if(*argv[1] == 'w'){ uint8_t page = std::atoi(argv[2]); write_nfc(i2cDeviceFd,page,std::string(argv[3])); } } return 0; }
23.891089
131
0.556569
[ "vector" ]
0dbd34cdcc3b3c7eb09064bc0ead763d2ac3e1b8
6,145
cpp
C++
src/ekf.cpp
nobunoby/EKF
610ac2ca1958173c771e1150992cea1e5d5d9da4
[ "MIT" ]
null
null
null
src/ekf.cpp
nobunoby/EKF
610ac2ca1958173c771e1150992cea1e5d5d9da4
[ "MIT" ]
null
null
null
src/ekf.cpp
nobunoby/EKF
610ac2ca1958173c771e1150992cea1e5d5d9da4
[ "MIT" ]
null
null
null
#include <algorithm> #include <math.h> #include <random> #include "ekf.hpp" #include "matplotlibcpp.h" namespace plt = matplotlibcpp; namespace prediction { void plot(Eigen::Vector4d truth, Eigen::Vector4d pred, Eigen::Vector4d obs) { // plot planned path static std::vector<double> truth_x(1), truth_y(1); truth_x.push_back(truth(State::X)); truth_y.push_back(truth(State::Y)); plt::plot(truth_x, truth_y, "r-"); static std::vector<double> pred_x(1), pred_y(1); pred_x.push_back(pred(State::X)); pred_y.push_back(pred(State::Y)); plt::plot(pred_x, pred_y, "k-"); std::vector<double> obs_x(1), obs_y(1); obs_x.push_back(obs(State::X)); obs_y.push_back(obs(State::Y)); plt::scatter(obs_x, obs_y, 16.0); plt::pause(0.01); //plt::show(); plt::save("../doc/groundtruth_state_predicted_states.png"); } EKF::EKF() { initializeKF(); estimate(); } void EKF::initializeKF() { // covariance matrix of process noise [x y yaw v] Q << 0.15, 0, 0, 0, 0, 0.15, 0, 0, 0, 0, 0.21, 0, 0, 0, 0, 0.25; // prediction covariance matrix Pest << Eigen::Matrix4d::Identity() * 0.01; //Eigen::MatrixXd Pest = Eigen::Matrix<double, 4, 4>::Identity(); } void EKF::estimate() { double dt = 0.1; double end_time = 90; int cnt = 0; for (double time = .0; time < end_time; time += dt) { cnt++; //update simulated ground truth and get new control inputs simulate(time, dt); // prediction step with new control inputs predictionUpdate(time, u); //std::cout << std::endl << "xTruth:\n" << xTruth << std::endl // << "xEst:\n" << xEst << std::endl; if (cnt%1 == 0) { // observation vector [x y yaw v] Eigen::Vector4d z; z = getObservation(); // get contaminated sensor data // covariance of observation noise Eigen::Matrix4d R; R << 0.515, 0, 0, 0, 0, 0.515, 0, 0, 0, 0, 0.51, 0, 0, 0, 0, 0.55; // update step observationUpdate(z, R); if (cnt%10 == 0) plot(xTruth, xEst, z); } //std::cout << "Pest:\n" << Pest << std::endl; //std::cout << std::endl << "xTruth:\n" << xTruth << std::endl // << "xEst:\n" << xEst << std::endl; } } void EKF::observationUpdate(Eigen::Vector4d z, Eigen::Matrix4d R) { // observation matrix Eigen::Matrix4d H = Eigen::Matrix4d::Identity(); // Kalman gain Eigen::MatrixXd K = Pest * H.transpose() * (H * Pest * H.transpose() + R).inverse(); xEst = xEst + K * (z - H * xEst); Pest = (Eigen::Matrix4d::Identity() - K * H) * Pest; } void EKF::predictionUpdate(const double& current_time, Eigen::Vector2d u) { static double last_time = .0; double dt = current_time - last_time; last_time = current_time; // prediction step: update predicted states //Eigen::Vector4d imu_data = getImu(); motionUpdate(dt, xEst, u); //std::cout << "xEst:" << std::endl << xEst << std::endl; // jacobian of state function dA/dx Eigen::Matrix4d F = Eigen::Matrix4d::Identity(); F(0, 2) = - u(IMU::VX_IN) * sin(xEst(State::YAW)) * dt; F(0, 3) = cos(xEst(State::YAW)) * dt; F(1, 2) = u(IMU::VX_IN) * cos(xEst(State::YAW)) * dt; F(1, 3) = sin(xEst(State::YAW)) * dt; std::cout << std::endl; //std::cout << "dA/dx:\n" << F << std::endl; std::cout << "Pest:\n" << Pest << std::endl; std::cout << "F * Pest * F.transpose():\n" << F * Pest * F.transpose() << std::endl; //std::cout << "Q:\n" << Q << std::endl; std::cout << "F * Pest * F.transpose() + Q:\n" << F * Pest * F.transpose() + Q << std::endl; //std::cout << "Pest:" << std::endl << Pest << std::endl; Pest = F * Pest * F.transpose() + Q; //std::cout << "updated Pest:" << std::endl << Pest << std::endl; } /** * @brief update simulated control inputs and simulated ground truth * * @param time */ void EKF::simulate(const double& time, const double& dt) { // control input [v yaw_rate] u << 1.0 * (1 - exp(-time / 10.0)), 0.05 * (1 - exp(-time / 10.0)); //std::cout << "\nu:\n" << u << std::endl; Eigen::Vector2d uTruth(u); // R Eigen::Vector2d contCov{0.52232,0.39225}; std::random_device device_random; std::default_random_engine generator(device_random()); for (int i=0; i < uTruth.size(); i++){ std::normal_distribution<double> noise(0, contCov(i)); uTruth(i) += noise(generator); } //std::cout << "uTruth:\n" << uTruth << std::endl; // update ground truth poses motionUpdate(dt, xTruth, uTruth); } /** * @brief update state vecotr by feeding last state, control inputs and current time step * * @param current_time time when this function called. Used for calculating time step * @param x [x y yaw v] updated states * @param cont control inputs */ void EKF::motionUpdate(const double& dt, //current_time, Eigen::Vector4d& x, const Eigen::Vector2d& cont) { //static double last_time = .0; // dicretized time step //double dt = current_time - last_time; // dynamics Eigen::Matrix4d A; A << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0; Eigen::Matrix<double, 4, 2> B; B << dt * cos(x(State::YAW)), 0, dt * sin(x(State::YAW)), 0, 0, dt, 1, 0; //std::cout << "B\n" << B << std::endl; x = A * x + B * cont; //std::cout << x(State::YAW) << std::endl; //last_time = current_time; } Eigen::Vector4d EKF::getObservation() { /* Simulation parameters */ // R Eigen::Vector4d obsCov{0.515, 0.515, 0.527, 0.225}; Eigen::Vector4d obs{xTruth}; // noise std::random_device device_random; std::default_random_engine generator(device_random()); for (int i=0; i < obs.size(); i++){ std::normal_distribution<double> noise(0, obsCov(i)); obs(i) += noise(generator); } //std::cout << "obs truth: " << std::endl << xTruth << std::endl // << "obs contaminated: " << std::endl << obs << std::endl; return obs; } } // namespace prediction int main() { prediction::EKF kf; return 0; }
27.070485
94
0.572335
[ "vector" ]
0dd998e8c2b56b7f2bf36d0ba0874afd3f2c054c
37,962
cpp
C++
engine.cpp
vkvd/polyedit
07eb56571bb6b53a5f87b5ac1480b7454622d37e
[ "MIT" ]
21
2016-10-13T21:49:03.000Z
2021-08-07T21:56:31.000Z
engine.cpp
vkvd/polyedit
07eb56571bb6b53a5f87b5ac1480b7454622d37e
[ "MIT" ]
1
2018-08-01T06:37:10.000Z
2018-08-02T14:03:02.000Z
engine.cpp
vkvd/polyedit
07eb56571bb6b53a5f87b5ac1480b7454622d37e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "engine.h" #include "poly.h" #include "tinyfiledialogs.h" #include "json/json.h" #include <iomanip> #include "imgui/imgui.h" #include "imgui/imconfig.h" #include "imgui-backends/SFML/imgui-events-SFML.h" #include "imgui-backends/SFML/imgui-rendering-SFML.h" #include "imgui/imguicolorpicker.h" #include <cmath> #include "guiConstants.h" // Fixes for windows #ifdef _WIN32 #define strdup _strdup #define snprintf sprintf_s // Comment this out if it causes issues, not totally sure of how it works #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") // Don't open console with window #endif // The title of the window set in the constructor. #define WINDOWTITLE "Lowpoly Editor" // Starting window size. #define WINDOW_X 1280 #define WINDOW_Y 720 // Fixed framerate set in the engine constructor. #define FRAMERATE 144 // Range in pixels to snap to already existing points. #define GRABDIST 10 // Number of decimals to care about when using randdbl. // RPRECISION should equal 10^x where x is the relevant decimal count. #define RPRECISION 10000 // Returns a random double between a and b. #define randdbl(a,b) ((rand()%(RPRECISION*(b-a)))/(RPRECISION*((float)b-a))+a) // Returns the distance between two vectors. float v2fdistance(sf::Vector2f a, sf::Vector2f b){ return std::sqrt((b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)); } // Constructor for the main engine. // Sets up renderwindow variables and loads an image. Engine::Engine(int aaLevel) { BGColor = sf::Color(125, 125, 125, 255); sf::ContextSettings settings; settings.antialiasingLevel = aaLevel; window = new sf::RenderWindow(sf::VideoMode(WINDOW_X, WINDOW_Y), WINDOWTITLE, sf::Style::Default, settings); window->setFramerateLimit(FRAMERATE); window->setVerticalSyncEnabled(false); window->setKeyRepeatEnabled(false); // Call load, get result pointIdleColor = sf::Color::Green; pointSelectedColor = sf::Color::Blue; if (load() != 0){ std::exit(1); } // Set view standard and load the image view.reset(sf::FloatRect(0, 0, WINDOW_X, WINDOW_Y)); window->setView(view); drawimg.setTexture(image); // Initialize GUI and backend ImGui::SFML::SetRenderTarget(*window); ImGui::SFML::InitImGuiRendering(); ImGui::SFML::SetWindow(*window); ImGui::SFML::InitImGuiEvents(); } // Destructor for the main engine. // Deletes the window. Engine::~Engine() { delete window; } // Main loop of the engine. // Delegates events to the Engine::handleEvents() function, // Saves on exit, // and delegates update/draw as well. void Engine::run() { ImGuiIO& io = ImGui::GetIO(); ImFontConfig imcfg; //io.Fonts->Fonts[0]->Scale = 1.5f; io.IniFilename = "polyedit_gui_config.ini"; while (window->isOpen()) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::Closed) { saveJSON(); ImGui::SFML::Shutdown(); window->close(); std::exit(1); } // Handle events in relation to the GUI handleGUItoggleEvent(event); // If the GUI is open pass events to it and block left clicks for all GUIS if (showColorPickerGUI || showSettingsGUI || showHelp) { ImGui::SFML::ProcessEvent(event); if (!(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left)){ handleEvents(event); } } /*// Actually do -> // Dont block left clicks with help open if (showHelp) { ImGui::SFML::ProcessEvent(event); handleEvents(event); }*/ // If the GUI is closed, run all events regardless else { handleEvents(event); } } window->clear(BGColor); // If a GUI is up update them if (showColorPickerGUI || showSettingsGUI || showHelp) { ImGui::SFML::UpdateImGui(); ImGui::SFML::UpdateImGuiRendering(); //ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); //ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8,8)); ImGuiStyle& style = ImGui::GetStyle(); applyGuiStyle(style); if (showColorPickerGUI){ createColorPickerGUI(); } if (showSettingsGUI){ createSettingsGUI(); ImGui::ShowStyleEditor(); } if (showHelp) { createHelpGUI(); } } // Main loop update(); draw(); // Render UI if (showColorPickerGUI || showSettingsGUI || showHelp) { ImGui::Render(); } window->display(); } } // Loads an image into the engine variables, // storing the names of the files to save into vfile and sfile. // If the files do not exist, they are created. int Engine::load(){ const char* filter[3] = { "*.png", "*.jpg", "*.gif" }; const char* filenamecc = tinyfd_openFileDialog("Select image: ", "./", 3, filter, NULL, 0); if (filenamecc == NULL){ return 1; } std::string filename = filenamecc; // Strip extension size_t lastindex = filename.find_last_of("."); std::string filenoext = filename.substr(0, lastindex); // Add new extensions const std::string sfext = ".svg"; const std::string vfext = ".vertices"; vfile = filenoext + vfext; sfile = filenoext + sfext; // Open/create based on if the file exists std::fstream vstream; vstream.open(vfile, std::ios::in); if (!vstream){ vstream.open(vfile, std::ios::out); } std::fstream sstream; sstream.open(sfile, std::ios::in); if (!sstream){ sstream.open(sfile, std::ios::out); } // Fail if the images do not open correctly if (!(image.loadFromFile(filename))){ return 1; } if (!(img.loadFromFile(filename))){ return 1; } // Load json containing points, etc. loadJSON(); vstream.close(); sstream.close(); return 0; } // Check if the GUI is being toggled; pause other inputs if it is void Engine::handleGUItoggleEvent(sf::Event event) { if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::C) { showColorPickerGUI = !showColorPickerGUI; } if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { showSettingsGUI = !showSettingsGUI; showHelp = !showHelp; } } // Handles the events that the sfml window recieves. // The following events are handled: // Single press events (and their releases) // Click events (and their releases) // Scrolling // Resizing void Engine::handleEvents(sf::Event event){ // On single press event if (event.type == sf::Event::KeyPressed) { std::string text; // Toggles image smoothing if (event.key.code == sf::Keyboard::Slash){ smoothnessToggle(); imgsmooth ? text = "on" : text = "off"; std::cout << "Image smoothing " << text << " (Slash)\n"; } // Wireframe toggle for polygons if (event.key.code == sf::Keyboard::W){ wireframe = !wireframe; wireframe ? text = "on" : text = "off"; std::cout << "Wireframe " << text << " (W)\n"; } // Hides background if (event.key.code == sf::Keyboard::H){ hideimage = !hideimage; hideimage ? text = "hidden" : text = "shown"; std::cout << "Background " << text << " (H)\n"; } if (event.key.code == sf::Keyboard::X){ showcenters = !showcenters; showcenters ? text = "Showing" : text = "Hiding"; std::cout << text << " centers. (X)\n"; } if (event.key.code == sf::Keyboard::P){ showrvectors = !showrvectors; showrvectors ? text = "Showing" : text = "Hiding"; std::cout << text << " points. (P)\n"; } // Clears current selection if (event.key.code == sf::Keyboard::Space){ clearSelection(); std::cout << "Clearing selection (Spacebar) \n"; } // Saves the file as a set of a SVG and ".vertices" file if (event.key.code == sf::Keyboard::S){ saveVector(file); saveJSON(); std::cout << "Saving file (S) \n"; } // Camera panning without mousewheelclick if (event.key.code == sf::Keyboard::LControl){ std::cout << "Panning while button held (LControl)\n"; sf::Vector2i pointi = sf::Mouse::getPosition(*window); sf::Vector2f point; point.x = (float)pointi.x; point.y = (float)pointi.y; point = windowToGlobalPos(point); vdraginitpt = point; vdragflag = true; } // Deletes selected points, polys if (event.key.code == sf::Keyboard::Delete){ std::cout << "Deleting selection (Delete) \n"; deleteSelection(); } // Reaverage colors if (event.key.code == sf::Keyboard::A) { std::cout << "Re-averaging color in polygon (A) \n"; if (spoly != NULL){ pR polyRecolor; polyRecolor.polyColor = spoly->fillcolor; for (int i = 0; i < polygons.size(); ++i) { if (polygons[i].center == spoly->center) { polyRecolor.polyIndex = i; } } undoBuffer.push_back(UndoAction(polyRecolor)); spoly->fillcolor = sf::Color(avgClr(rpoints[spoly->rpointIndices[0]], rpoints[spoly->rpointIndices[1]], rpoints[spoly->rpointIndices[2]], 10)); } else { "Can't change color - no polygon selected (C) \n"; } } // Get color at mouse if (event.key.code == sf::Keyboard::O) { std::cout << "Setting selected polygon color to color at mouse (O)\n"; if (spoly != NULL){ sf::Vector2f point = getMPosFloat(); point = windowToGlobalPos(point); point = getClampedImgPoint(point); sf::Color color = img.getPixel(point.x, point.y); pR polyRecolor; polyRecolor.polyColor = spoly->fillcolor; for (int i = 0; i < polygons.size(); ++i) { if (polygons[i].center == spoly->center) { polyRecolor.polyIndex = i; } } undoBuffer.push_back(UndoAction(polyRecolor)); spoly->fillcolor = color; } else { "Can't change color - no polygon selected (C) \n"; } } // Send overlapping element to end of list if (event.key.code == sf::Keyboard::Comma){ std::cout << "Sending triangle to the back of the draw order (,)\n"; if (spoly != NULL){ for (unsigned i = 0; i < polygons.size(); i++){ if (polygons[i].selected == true){ polygons.insert(polygons.begin(), polygons[i]); polygons.erase(1 + polygons.begin() + i); } } clearSelection(); } } // Send overlapping element to the beginning of the list if (event.key.code == sf::Keyboard::Period){ std::cout << "Sending triangle to the front of the draw order (.)\n"; if (spoly != NULL){ for (unsigned i = 0; i < polygons.size(); i++){ if (polygons[i].selected == true){ polygons.push_back(polygons[i]); polygons.erase(polygons.begin() + i); } } clearSelection(); } } //dbgPrint info if (event.key.code == sf::Keyboard::BackSlash) { std::cout << "=== Undo Buffer Dump ===" << std::endl; std::cout << "=== Actions: " << undoBuffer.size() << " ===" << std::endl; int index = 0; for (auto e : undoBuffer) { std::cout << "#" << index << " "; e.print(); ++index; } } if (event.key.code == sf::Keyboard::Z) { std::cout << "Undo\n"; undo(); } if (event.key.code == sf::Keyboard::RBracket) { undoBuffer.clear(); } } // On release event (used for disabling flags) if (event.type == sf::Event::KeyReleased){ if (event.key.code == sf::Keyboard::LControl){ vdragflag = false; } } // On click if (event.type == sf::Event::MouseButtonPressed) { sf::Vector2f click = sf::Vector2f((float)event.mouseButton.x, (float)event.mouseButton.y); sf::Vector2f point = windowToGlobalPos(click); if (event.mouseButton.button == sf::Mouse::Left) { onLeftClick(point); if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { clearSelection(); onLeftClick(point); deleteSelection(); } } if (event.mouseButton.button == sf::Mouse::Right){ onRightClick(point); } if (event.mouseButton.button == sf::Mouse::Middle){ onMiddleClick(point); } } // On click release (used for disabling flags) if (event.type == sf::Event::MouseButtonReleased){ if (event.mouseButton.button == sf::Mouse::Left){ dragflag = false; } if (event.mouseButton.button == sf::Mouse::Middle){ vdragflag = false; } } // On scroll (used for zooming) if (event.type == sf::Event::MouseWheelScrolled){ if (event.mouseWheelScroll.delta < 0){ viewzoom *= 1.5; view.zoom(1.5); window->setView(view); } else if (event.mouseWheelScroll.delta > 0){ viewzoom *= 0.75; view.zoom(0.75); window->setView(view); } } // On window resize if (event.type == sf::Event::Resized){ view.reset(sf::FloatRect(0, 0, (float)event.size.width, (float)event.size.height)); viewzoom = 1; window->setView(view); } } // Handles logic directly before drawing. // This function runs every frame. void Engine::update(){ handleCamera(); if (wireframe == true && (wireframe != wireframels)){ for (Poly& polygon : polygons){ polygon.isWireframe = true; } wireframels = wireframe; } else if (wireframe != true && (wireframe != wireframels)){ for (Poly& polygon : polygons){ polygon.isWireframe = false; } wireframels = wireframe; } if (dragflag){ sf::Vector2f point = getMPosFloat(); point = windowToGlobalPos(point); sf::Vector2f rpoint = rpoints[nindex].vector; rpoints[nindex].vector = (pdragoffset + point); } if (vdragflag){ sf::Vector2f point = getMPosFloat(); point = windowToGlobalPos(point); vdragoffset.x = (vdraginitpt.x - point.x); vdragoffset.y = (vdraginitpt.y - point.y); view.move(vdragoffset); window->setView(view); } for (Poly& polygon : polygons) { polygon.updateCShape(viewzoom); polygon.updateCenter(); } for (Point& point : rpoints) { point.colorSelected = pointSelectedColor; point.colorIdle = pointIdleColor; point.updateCShape(viewzoom); point.vector = getClampedImgPoint(point.vector); } } // Draws the objects to the screen. // This function runs every frame, preceded by Engine::update(). void Engine::draw(){ // Reset view incase other objects change it window->setView(view); if (!hideimage){ window->draw(drawimg); } for (Poly polygon : polygons){ if (polygon.selected == false){ window->draw(polygon.cshape); } } if (showrvectors){ for (Point& point : rpoints){ window->draw(point.cshape); } } for (Poly polygon : polygons){ if (polygon.selected == true){ window->draw(polygon.cshape); } } if (showcenters){ for (Poly polygon : polygons){ sf::CircleShape cshape = sf::CircleShape(2*viewzoom); cshape.setPosition(polygon.center); cshape.setFillColor(centerdrawcolor); window->draw(cshape); } } } // Create GUI elements for color picker void Engine::createColorPickerGUI() { ImGui::Begin("Color Picker"); if (spoly != NULL){ float spolycolor[3]; spolycolor[0] = spoly->fillcolor.r / 255.0f; spolycolor[1] = spoly->fillcolor.g / 255.0f; spolycolor[2] = spoly->fillcolor.b / 255.0f; if (ColorPicker3(spolycolor)){ spoly->fillcolor = sf::Color(spolycolor[0] * 255.0f, spolycolor[1] * 255.0f, spolycolor[2] * 255.0f, 255); } } else { ImGui::Text("No polygon selected."); } ImGui::End(); } void Engine::createSettingsGUI(){ ImGui::Begin("Settings"); if (ImGui::CollapsingHeader("Points: Unselected")){ float colorIdle[3]; colorIdle[0] = rpoints[0].colorIdle.r / 255.0f; colorIdle[1] = rpoints[0].colorIdle.g / 255.0f; colorIdle[2] = rpoints[0].colorIdle.b / 255.0f; if (ColorPicker3(colorIdle)){ pointIdleColor = sf::Color(colorIdle[0] * 255.0f, colorIdle[1] * 255.0f, colorIdle[2] * 255.0f, 255); } } if (ImGui::CollapsingHeader("Points: Selected")){ float colorSelected[3]; colorSelected[0] = rpoints[0].colorSelected.r / 255.0f; colorSelected[1] = rpoints[0].colorSelected.g / 255.0f; colorSelected[2] = rpoints[0].colorSelected.b / 255.0f; if (ColorPicker3(colorSelected)){ pointSelectedColor = sf::Color(colorSelected[0] * 255.0f, colorSelected[1] * 255.0f, colorSelected[2] * 255.0f, 255); /*for (Point& p : rpoints){ p.colorSelected = sf::Color(colorSelected[0] * 255.0f, colorSelected[1] * 255.0f, colorSelected[2] * 255.0f, 255); }*/ } } if (ImGui::CollapsingHeader("Centers")){ float center[4]; center[0] = centerdrawcolor.r / 255.0f; center[1] = centerdrawcolor.g / 255.0f; center[2] = centerdrawcolor.b / 255.0f; center[3] = centerdrawcolor.a / 255.0f; if (ColorPicker4(center, true)){ centerdrawcolor = sf::Color(center[0]*255.0f, center[1]*255.0f, center[2]*255.0f, center[3]*255.0f); } } if (ImGui::CollapsingHeader("Background Color")) { float bg[3]; bg[0] = BGColor.r / 255.0f; bg[1] = BGColor.g / 255.0f; bg[2] = BGColor.b / 255.0f; if (ColorPicker3(bg)) { BGColor = sf::Color(bg[0] * 255.0f, bg[1] * 255.0f, bg[2] * 255.0f,255.0f); } } ImGui::End(); } void Engine::createHelpGUI() { helpGuiText(); } // Checks input for arrow keys and +/- for camera movement void Engine::handleCamera() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && window->hasFocus()) { view.move(sf::Vector2f(-2 * viewzoom, 0)); window->setView(view); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && window->hasFocus()) { view.move(sf::Vector2f(2 * viewzoom, 0)); window->setView(view); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && window->hasFocus()) { view.move(sf::Vector2f(0, -2 * viewzoom)); window->setView(view); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && window->hasFocus()) { view.move(sf::Vector2f(0, 2 * viewzoom)); window->setView(view); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Dash) && window->hasFocus()) { viewzoom *= 1.01f; view.zoom(1.01f); window->setView(view); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Equal) && window->hasFocus()) { viewzoom *= 0.99f; view.zoom(0.99f); window->setView(view); } } /*//////////////////////////////////////////////////////////////////////////// //// Input functions: //// Callbacks from Engine::handleEvents(). *///////////////////////////////////////////////////////////////////////////// // On spacebar void Engine::clearSelection() { nspoints.clear(); spointsin.clear(); spoly = NULL; for (unsigned n = 0; n < rpoints.size(); n++) { nspoints.push_back(&(rpoints[n])); rpoints[n].selected = false; } for (unsigned i = 0; i < polygons.size(); i++) { polygons[i].selected = false; } } // On slash void Engine::smoothnessToggle() { image.setSmooth(!imgsmooth); imgsmooth = !imgsmooth; drawimg.setTexture(image); } // On delete void Engine::deleteSelection() { if (spointsin.size() == 0 && spoly == NULL) {} else { std::vector<int> polyIndices; std::vector<int> rpointsIndices; for (unsigned i = 0; i < polygons.size(); i++) { if (polygons[i].selected == true) { polyIndices.push_back(i); } } for (unsigned i = 0; i < spointsin.size(); i++) { for (unsigned j = 0; j < polygons.size(); j++) { for (unsigned k = 0; k < 3; k++) { if (polygons[j].rpointIndices[k] == spointsin[i]) { polyIndices.push_back(j); } } } rpointsIndices.push_back(spointsin[i]); } // Sort vectors and erase duplicates std::sort(polyIndices.begin(), polyIndices.end()); polyIndices.erase(std::unique(polyIndices.begin(), polyIndices.end()), polyIndices.end()); std::sort(rpointsIndices.begin(), rpointsIndices.end()); rpointsIndices.erase(std::unique(rpointsIndices.begin(), rpointsIndices.end()), rpointsIndices.end()); // Reverse indices for easier deletion of elements std::reverse(rpointsIndices.begin(), rpointsIndices.end()); std::reverse(polyIndices.begin(), polyIndices.end()); // Get polys to re-add in deletion of a point if (spointsin.size() > 0 && spoly == NULL) { // get deleted points PD pointDeletion = PD(); for (int i : spointsin) { pointDeletion.deletedPoints.push_back(std::make_pair(rpoints[i],i)); } for (int i : polyIndices) { pointDeletion.cPointColors.push_back(polygons[i].fillcolor); auto arrayLoc = polygons[i].rpointIndices; int p1 = arrayLoc[0]; int p2 = arrayLoc[1]; int p3 = arrayLoc[2]; //std::cout << p1 << p2 << p3 << "\n"; pointDeletion.cPointPolysIndices.push_back(std::make_tuple(p1, p2, p3)); } undoBuffer.push_back(UndoAction(pointDeletion)); } for (unsigned i = 0; i < polyIndices.size(); i++) { polygons.erase(polygons.begin() + polyIndices[i]); } for (unsigned i = 0; i < rpointsIndices.size(); i++) { rpoints.erase(rpoints.begin() + rpointsIndices[i]); } for (unsigned p = 0; p < polygons.size(); p++) { // For each polygon for (int i = 0; i < 3; i++) { // For every point inside a polygon int counter = 0; for (unsigned rp = 0; rp < rpointsIndices.size(); rp++) { if (polygons[p].rpointIndices[i] > rpointsIndices[rp]) { counter++; } } polygons[p].rpointIndices[i] -= counter; } } polyIndices.clear(); rpointsIndices.clear(); clearSelection(); for (Poly& poly : polygons){ poly.updatePointers(rpoints); } } } // On left click void Engine::onLeftClick(sf::Vector2f point) { for (Poly& polygon : polygons) { polygon.selected = false; } bool ispointnear = false; nindex = -1; for (unsigned i = 0; i < rpoints.size(); i++) { Point& rpoint = rpoints[i]; sf::Vector2f rpv = rpoint.vector; int clickdist = GRABDIST; // Check if mouse is in snapping range; then set near appropriately if ((point.x - rpv.x < clickdist*viewzoom && point.x - rpv.x > -clickdist*viewzoom) && (point.y - rpv.y < clickdist*viewzoom && point.y - rpv.y > -clickdist*viewzoom)) { ispointnear = true; nindex = i; } } // If its near another, snap to it -> shared edges if (ispointnear) { sf::Vector2f mpos = getMPosFloat(); mpos = windowToGlobalPos(mpos); // Init values for dragging, used above pdraginitpt = mpos; pdragoffset.x = rpoints[nindex].vector.x - mpos.x; pdragoffset.y = rpoints[nindex].vector.y - mpos.y; dragflag = true; // When dragflag is true then dragging occurs // Set mouse position to middle of desired selected point // This fixes mouse clicks moving points on accident // Check for snapping the same point twice for a new poly and catch it bool exists = false; for (unsigned i = 0; i < spointsin.size(); i++) { if (spointsin[i] == nindex) { exists = true; } } // If they didn't click the same point twice if (!exists) { spointsin.push_back(nindex); if (spointsin.size() == 3) { int p1, p2, p3; p1 = spointsin[spointsin.size() - 3]; p2 = spointsin[spointsin.size() - 2]; p3 = spointsin[spointsin.size() - 1]; Point *po1 = &rpoints[(spointsin[0])]; Point *po2 = &rpoints[(spointsin[1])]; Point *po3 = &rpoints[(spointsin[2])]; Poly pg = Poly(po1, po2, po3, p1, p2, p3, sf::Color::Green); polygons.push_back(pg); int offset = polygons.size() - 1; polygons[offset].fillcolor = avgClr(rpoints[polygons[offset].rpointIndices[0]], rpoints[polygons[offset].rpointIndices[1]], rpoints[polygons[offset].rpointIndices[2]], 10); // Add undo pA polyAddition = pA(); polyAddition.polyIndex = offset; undoBuffer.push_back(UndoAction(polyAddition)); clearSelection(); } } } // Create a new point if (!ispointnear) { point = getClampedImgPoint(point); rpoints.push_back(Point(point, 5)); // Add undo PA pointAddUndoAction = PA(); pointAddUndoAction.pointIndex = rpoints.size()-1; undoBuffer.push_back(UndoAction(pointAddUndoAction)); spointsin.push_back(rpoints.size() - 1); if (spointsin.size() == 3) { int p1, p2, p3; p1 = spointsin[spointsin.size() - 3]; p2 = spointsin[spointsin.size() - 2]; p3 = spointsin[spointsin.size() - 1]; Point *po1 = &rpoints[(spointsin[0])]; Point *po2 = &rpoints[(spointsin[1])]; Point *po3 = &rpoints[(spointsin[2])]; // Create new polygon at last 3 points, assign it starting index // so that it can find itself in the vector after memory updates polygons.push_back(Poly(po1,po2,po3,p1,p2,p3,sf::Color::Green)); int offset = polygons.size() - 1; polygons[offset].fillcolor = avgClr(rpoints[polygons[offset].rpointIndices[0]], rpoints[polygons[offset].rpointIndices[1]], rpoints[polygons[offset].rpointIndices[2]], 10); // Add undo pA polyAddition = pA(); polyAddition.polyIndex = offset; undoBuffer.push_back(UndoAction(polyAddition)); clearSelection(); } } // Only update polygon point-pointers on click // because the memory is only moved on click for (Poly& p : polygons) { p.updatePointers(rpoints); } for (auto& inspoint : nspoints) { inspoint->selected = false; } for (auto& ispoint : spointsin) { rpoints[ispoint].selected = true; } } // On right click void Engine::onRightClick(sf::Vector2f point) { if (polygons.size() > 0) { clearSelection(); float dist = 100000000.0f; int pindex = -1; for (unsigned p = 0; p < polygons.size(); p++) { float cdist = v2fdistance(point, polygons[p].center); if (cdist < dist) { dist = cdist; pindex = p; } } polygons[pindex].selected = true; spoly = &polygons[pindex]; } } // On middle wheel click void Engine::onMiddleClick(sf::Vector2f point) { vdragflag = true; vdragoffset = sf::Vector2f(0, 0); vdraginitpt = point; } void Engine::undo() { if (undoBuffer.size() > 0) { UndoAction ua = undoBuffer.back(); undoBuffer.pop_back(); PA dPA; PD dPD; pD dpD; pA dpA; pR dpR; switch (ua.action) { // Simply delete the last added point // Not exactly simple, as the delete function only runs off the current selection // Hacky workaround for just deleting a point: select it, delete selection, clear case Action::pointAddition: dPA = ua.pointAddition; clearSelection(); spoint = &rpoints[dPA.pointIndex]; spointsin.push_back(dPA.pointIndex); deleteSelection(); // Manually deselect the last two points and pop the deletion action undoBuffer.pop_back(); (&rpoints[dPA.pointIndex - 2])->selected = false; (&rpoints[dPA.pointIndex - 3])->selected = false; break; case Action::pointDeletion: // there's either going to be one or two points deleted dPD = ua.pointDeletion; clearSelection(); // Re-add the deleted points for (auto& p : dPD.deletedPoints) { rpoints.push_back(p.first); //std::cout << "Added point " << (rpoints.size()-1) << ";\n"; nspoints.push_back(&p.first); } // Reconstruct polygons that were caught in the point deletion for (int index = 0; index < dPD.cPointPolysIndices.size(); ++index) { // is dp2 active (were 2 points deleted) bool dp2a = true; // Polygon color sf::Color pcolor = dPD.cPointColors[index]; // Indices of old deleted points int dp1, dp2; // Indices of the whole polygon deleted int i1, i2, i3; // Pointers to points of the new polygon Point *p1, *p2, *p3; // Offset to end of rpoints int offset = rpoints.size() - 1; // Get destroyed polygon indices (its in a tuple<int,int,int>) i1 = std::get<0>(dPD.cPointPolysIndices[index]); i2 = std::get<1>(dPD.cPointPolysIndices[index]); i3 = std::get<2>(dPD.cPointPolysIndices[index]); // Find if one or two points were deleted, set dp2a on results dp1 = dPD.deletedPoints[0].second; (dPD.deletedPoints.size() > 1) ? dp2 = dPD.deletedPoints[1].second : dp2a = false; // Find which point in the deleted-by-consequence polygon was the deleted point // and update a new polygon replacing the deleted point with the newly added point int oi1, oi2, oi3; oi1 = i1; oi2 = i2; oi3 = i3; if (i1 > dp1) i1 -= 1; if (i2 > dp1) i2 -= 1; if (i3 > dp1) i3 -= 1; if (dp2a) { if (oi1 > dp2) i1 -= 1; if (oi2 > dp2) i2 -= 1; if (oi3 > dp2) i3 -= 1; } p1 = &rpoints[i1]; p2 = &rpoints[i2]; p3 = &rpoints[i3]; if (!dp2a) { if (oi1 == dp1) { p1 = &rpoints[offset]; i1 = offset; } else if (oi2 == dp1) { p2 = &rpoints[offset]; i2 = offset; } else if (oi3 == dp1) { p3 = &rpoints[offset]; i3 = offset; } } if (dp2a) { if (oi1 == dp1) { p1 = &rpoints[offset - 1]; i1 = offset - 1; } else if (oi2 == dp1) { p2 = &rpoints[offset - 1]; i2 = offset - 1; } else if (oi3 == dp1) { p3 = &rpoints[offset - 1]; i3 = offset -1; } if (oi1 == dp2) { p1 = &rpoints[offset]; i1 = offset; } else if (oi2 == dp2) { p2 = &rpoints[offset]; i2 = offset; } else if (oi3 == dp2) { p3 = &rpoints[offset]; i3 = offset; } } //std::cout << "New Points: " << i1 << i2 << i3 << '\n'; polygons.push_back(Poly(p1, p2, p3, i1, i2, i3, pcolor)); } break; // Select the polygon -> delete selection -> clear. case Action::polyAddition: dpA = ua.polyAddition; clearSelection(); spoly = &polygons[dpA.polyIndex]; (&polygons[dpA.polyIndex])->selected = true; deleteSelection(); break; case Action::polyRecolor: dpR = ua.polyRecolor; polygons[dpR.polyIndex].fillcolor = dpR.polyColor; break; case Action::polyDeletion: dpD = ua.polyDeletion; Point *p1, *p2, *p3; int i1 = dpD.pointIndices[0]; int i2 = dpD.pointIndices[1]; int i3 = dpD.pointIndices[2]; p1 = &(rpoints[i1]); p2 = &(rpoints[i2]); p3 = &(rpoints[i3]); polygons.push_back(Poly(p1, p2, p3, i1, i2, i3, dpD.polyColor)); break; } clearSelection(); } } /*///////////////////////////////////////////////////////////////////////////// //// Utility functions *////////////////////////////////////////////////////////////////////////////// // Returns the average color from the area between 3 points. // Due to speed, it uses random samples. sf::Color Engine::avgClr(Point& p1, Point& p2, Point& p3, int samples){ int r = 0; int g = 0; int b = 0; for (int i = 0; i < samples; i++){ sf::Vector2f pixel = randPt(p1, p2, p3); sf::Color color = img.getPixel(pixel.x, pixel.y); r += color.r; g += color.g; b += color.b; } r /= samples; g /= samples; b /= samples; return sf::Color(r, g, b, 255); } // Return a random point inside 3 points. sf::Vector2f Engine::randPt(Point& p1, Point& p2, Point& p3){ sf::Vector2f point; double r1 = randdbl(0, 1); double r2 = randdbl(0, 1); point.x = (1 - sqrt(r1)) * p1.vector.x + (sqrt(r1) * (1 - r2)) * p2.vector.x + (sqrt(r1) * r2) * p3.vector.x; point.y = (1 - sqrt(r1)) * p1.vector.y + (sqrt(r1) * (1 - r2)) * p2.vector.y + (sqrt(r1) * r2) * p3.vector.y; return point; } // Convert window (view) coordinates to global (real) coordinates. sf::Vector2f Engine::windowToGlobalPos(const sf::Vector2f& vec) { sf::Vector2u winSize = window->getSize(); sf::Vector2f center = view.getCenter(); sf::Vector2f point = vec; point.x -= winSize.x / 2; point.y -= winSize.y / 2; point.x *= viewzoom; point.y *= viewzoom; point.x += center.x; point.y += center.y; return point; }; // Convert global (real) coordiantes to window (view) coordinates. sf::Vector2f Engine::globalToWindowPos(const sf::Vector2f& vec) { sf::Vector2u winSize = window->getSize(); sf::Vector2f center = view.getCenter(); sf::Vector2f point = vec; point.x -= center.x; point.y -= center.y; point.x /= viewzoom; point.y /= viewzoom; point.x += winSize.x / 2; point.y += winSize.y / 2; return point; }; // Get the mouse position as a float. sf::Vector2f Engine::getMPosFloat() { sf::Vector2i mposi = sf::Mouse::getPosition(*window); sf::Vector2f mpos; mpos.x = mposi.x; mpos.y = mposi.y; return mpos; } // Clamps a point to the image boundaries. sf::Vector2f Engine::getClampedImgPoint(const sf::Vector2f& vec){ sf::Vector2f result = vec; if (result.x < 0 || result.x > img.getSize().x){ if (result.x < 0){ result.x = 0; } else if (result.x > img.getSize().x) { result.x = img.getSize().x; } } if (result.y < 0 || result.y > img.getSize().y){ if (result.y < 0){ result.y = 0; } else if (result.y > img.getSize().y){ result.y = img.getSize().y; } } return result; } /*//////////////////////////////////////////////////////////////////////////// //// Saving functions *///////////////////////////////////////////////////////////////////////////// // Saves the SVG of the image. void Engine::saveVector(std::string filename){ std::fstream sfilestrm; sfilestrm.open(sfile, std::ios::out | std::fstream::trunc); char headerc[350]; const char *hdr = "<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"%d\" height=\"%d\" viewBox=\"0 0 %d %d\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n<style type=\"text/css\"> polygon { stroke-width: .5; stroke-linejoin: round; } </style>"; snprintf(headerc, sizeof(headerc), hdr, image.getSize().x, image.getSize().y, image.getSize().x, image.getSize().y); std::string header = headerc; std::string footer = "\n</svg>"; sfilestrm << header; for (unsigned i = 0; i < polygons.size(); i++){ Poly& p = polygons[i]; std::string pointslist = ""; for (int j = 0; j < 3; j++){ pointslist += std::to_string(rpoints[p.rpointIndices[j]].vector.x); pointslist += ","; pointslist += std::to_string(rpoints[p.rpointIndices[j]].vector.y); pointslist += " "; } std::string color = "rgb("; color += std::to_string(p.fillcolor.r); color += ","; color += std::to_string(p.fillcolor.g); color += ","; color += std::to_string(p.fillcolor.b); color += ")"; std::string polygon = ""; polygon += "<polygon style=\"fill:"; polygon += color; polygon += ";stroke:"; polygon += color; polygon += "\""; polygon += " points=\""; polygon += pointslist; polygon += "\"/>\n"; sfilestrm << polygon; } sfilestrm << footer; } // Saves the JSON of the points, polygons, colors void Engine::saveJSON(){ // Clamp all points to bounds for (Point& point : rpoints){ point.vector = getClampedImgPoint(point.vector); } Json::Value rootobj; for (unsigned i = 0; i < rpoints.size(); i++){ rootobj["rpoints"][i]["vector"]["x"] = rpoints[i].vector.x; rootobj["rpoints"][i]["vector"]["y"] = rpoints[i].vector.y; rootobj["rpoints"][i]["size"] = rpoints[i].size; } for (unsigned i = 0; i < polygons.size(); i++){ for (int j = 0; j < 3; j++){ rootobj["polygons"][i]["pointindices"][j] = polygons[i].rpointIndices[j]; } rootobj["polygons"][i]["color"] = polygons[i].fillcolor.toInteger(); } rootobj["centerdrawcolor"] = centerdrawcolor.toInteger(); rootobj["bgcolor"] = BGColor.toInteger(); rootobj["colorIdle"] = pointIdleColor.toInteger(); rootobj["colorSelected"] = pointSelectedColor.toInteger(); std::fstream vfilestrm; vfilestrm.open(vfile, std::ios::out | std::ios::trunc); vfilestrm << rootobj << std::endl; vfilestrm.close(); } // Loads the JSON into the engine variables. void Engine::loadJSON(){ rpoints.clear(); polygons.clear(); std::fstream vfilestrm; vfilestrm.open(vfile, std::ios::in); Json::Value rootobj; if (vfilestrm.peek() == std::fstream::traits_type::eof()) { return; } vfilestrm >> rootobj; Json::Value jsonpolygons; Json::Value jsonrpoints; jsonpolygons = rootobj["polygons"]; jsonrpoints = rootobj["rpoints"]; for (unsigned i = 0; i < jsonrpoints.size(); i++){ Point p; p.vector.x = rootobj["rpoints"][i]["vector"]["x"].asFloat(); p.vector.y = rootobj["rpoints"][i]["vector"]["y"].asFloat(); p.size = rootobj["rpoints"][i]["size"].asFloat(); // Init the color to default before reading user-set because of backwards compatibility p.colorIdle = sf::Color::Green; p.colorSelected = sf::Color::Blue; centerdrawcolor = sf::Color(255, 255, 255, 127); // Read JSON for colors rpoints.push_back(p); } for (unsigned i = 0; i < jsonpolygons.size(); i++){ int ptl[3]; for (int j = 0; j < 3; j++){ ptl[j] = rootobj["polygons"][i]["pointindices"][j].asInt(); } int c = rootobj["polygons"][i]["color"].asInt64(); sf::Color color = sf::Color(c); Poly p = Poly(&rpoints[ptl[0]], &rpoints[ptl[1]], &rpoints[ptl[2]], ptl[0], ptl[1], ptl[2], color); p.updateCenter(); p.updateCShape(viewzoom); polygons.push_back(p); } if (rootobj["bgcolor"].asInt64() != 0) { BGColor = sf::Color(rootobj["bgcolor"].asInt64()); } int color = rootobj["centerdrawcolor"].asInt64(); if (color != 0) { centerdrawcolor = sf::Color(color); } pointIdleColor = sf::Color::Green; pointSelectedColor = sf::Color::Blue; color = rootobj["colorIdle"].asInt64(); if (color != 0) { pointIdleColor = sf::Color(color); } color = rootobj["colorSelected"].asInt64(); if (color != 0) { pointSelectedColor = sf::Color(color); } std ::cout << "total polygons loaded: " << polygons.size() << "\n"; vfilestrm.close(); }
31.582363
365
0.606211
[ "render", "vector" ]
0ddf79d5133bc416b13632f9a3a190ecb61820cc
1,729
cpp
C++
robot_control/src/tools/src/reference_client.cpp
SjoerdKoop/vicon_control
26d10318999ae686d76eca2c63a0f2f1e7ad4191
[ "BSD-3-Clause" ]
2
2019-03-14T14:19:40.000Z
2019-10-24T10:33:50.000Z
robot_control/src/tools/src/reference_client.cpp
SjoerdKoop/vicon_control
26d10318999ae686d76eca2c63a0f2f1e7ad4191
[ "BSD-3-Clause" ]
null
null
null
robot_control/src/tools/src/reference_client.cpp
SjoerdKoop/vicon_control
26d10318999ae686d76eca2c63a0f2f1e7ad4191
[ "BSD-3-Clause" ]
2
2018-10-08T09:16:34.000Z
2020-01-10T07:25:24.000Z
// Components #include "peer.h" // Peer // System #include <cstdlib> // EXIT_*, std::exit #include <iostream> // std::cout, std::endl #include <signal.h> // sigaction #include <string> // std::stoi // Tools #include "tools.h" // isValidIP, isValidPort // Checks whether provided arguments are correct bool checkArguments(int argc, char* argv[]) { // If the number of arguments is correct if (argc == 3) { // If IP address and port are valid if (isValidIp(argv[1]) && isValidPort(argv[2])) { return true; } else { return false; } } else { return false; } } // SIGINT handler void handleUserInterrupt(int sig_num) { // Exit the program std::exit(EXIT_SUCCESS); } // Main function int main(int argc, char* argv[]) { // Check whether provided arguments are correct if (checkArguments(argc, argv)) { // Create peer Peer* peer = new Peer(argv[1], std::stoi(argv[2])); // Register program for user interrupt struct sigaction act; act.sa_handler = handleUserInterrupt; sigaction(SIGINT, &act, NULL); char* msg; // Holds received message std::vector<float> ref; // Holds reference // Main loop while (true) { std::cout << "Ready to receive..." << std::endl; // Receive message msg = peer->receiveMessage(); // Convert message to reference ref = messageToReference(msg); // Print reference std::cout << "Received reference: "; for (float var : ref) { std::cout << var << " "; } std::cout << std::endl; } } else { // Show fatal error std::cout << "Please specify correct arguments: reference_client <user IP address> <user PC port>" << std::endl; // Return failure status code return EXIT_FAILURE; } }
20.104651
114
0.637363
[ "vector" ]
0de16b59c9d1890ea7a7437f05aff43464510eae
9,681
cpp
C++
gazebo_ros_soft_hand/test/adaptive_synergy_transmission_loader_test.cpp
hamalMarino/pisa-iit-soft-hand
004145301bb71b82cca4d08ffb27b77cce36b7ea
[ "BSD-3-Clause" ]
14
2017-01-23T15:14:18.000Z
2021-12-16T14:41:22.000Z
gazebo_ros_soft_hand/test/adaptive_synergy_transmission_loader_test.cpp
CentroEPiaggio/pisa-iit-soft-hand
174eebc6e9e33c886cab7995f749830a436de3e8
[ "BSD-3-Clause" ]
17
2015-02-04T11:08:24.000Z
2020-05-14T16:33:09.000Z
gazebo_ros_soft_hand/test/adaptive_synergy_transmission_loader_test.cpp
hamalMarino/pisa-iit-soft-hand
004145301bb71b82cca4d08ffb27b77cce36b7ea
[ "BSD-3-Clause" ]
19
2015-03-25T03:12:30.000Z
2021-02-04T09:46:47.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013, PAL Robotics S.L. // Copyright (c) 2014, Research Center "E. Piaggio" // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of PAL Robotics S.L. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////////////// // \author Adolfo Rodriguez Tsouroukdissian // \author Carlos Rosales, based on templates of other transmissions #include <string> #include <boost/foreach.hpp> #include <gtest/gtest.h> #include <pluginlib/class_loader.h> #include <adaptive_transmission/adaptive_synergy_transmission.h> #include <transmission_interface/transmission_loader.h> #include "./read_file.h" #include <adaptive_transmission/loader_utils.h> TEST(AdaptiveSynergyTransmissionLoaderTest, FullSpec) { // Parse transmission info std::vector<TransmissionInfo> infos = parseUrdf("test/urdf/adaptive_synergy_transmission_loader_full.urdf"); ASSERT_EQ(1, infos.size()); // Transmission loader TransmissionPluginLoader loader; boost::shared_ptr<TransmissionLoader> transmission_loader = loader.create(infos.front().type_); ASSERT_TRUE(0 != transmission_loader); TransmissionPtr transmission; const TransmissionInfo& info = infos.front(); transmission = transmission_loader->load(info); ASSERT_TRUE(0 != transmission); // Validate transmission AdaptiveSynergyTransmission* adaptive_synergy_transmission = dynamic_cast<AdaptiveSynergyTransmission*>(transmission.get()); ASSERT_TRUE(0 != adaptive_synergy_transmission); const std::vector<double>& actuator_reduction = adaptive_synergy_transmission->getActuatorReduction(); EXPECT_EQ( 30.0, actuator_reduction[0]); const std::vector<double>& joint_reduction = adaptive_synergy_transmission->getJointReduction(); EXPECT_EQ( 2.0, joint_reduction[0]); EXPECT_EQ( 2.0, joint_reduction[1]); EXPECT_EQ( 2.0, joint_reduction[2]); EXPECT_EQ( 2.0, joint_reduction[3]); EXPECT_EQ( 2.0, joint_reduction[4]); EXPECT_EQ( 2.0, joint_reduction[5]); EXPECT_EQ( 2.0, joint_reduction[6]); EXPECT_EQ( 2.0, joint_reduction[7]); EXPECT_EQ( 2.0, joint_reduction[8]); EXPECT_EQ( 2.0, joint_reduction[9]); EXPECT_EQ( 2.0, joint_reduction[10]); EXPECT_EQ( 2.0, joint_reduction[11]); EXPECT_EQ( 2.0, joint_reduction[12]); EXPECT_EQ( 2.0, joint_reduction[13]); EXPECT_EQ( 2.0, joint_reduction[14]); EXPECT_EQ( 2.0, joint_reduction[15]); EXPECT_EQ( 2.0, joint_reduction[16]); EXPECT_EQ( 2.0, joint_reduction[17]); EXPECT_EQ( 2.0, joint_reduction[18]); const std::vector<double>& joint_elastic = adaptive_synergy_transmission->getJointElastic(); EXPECT_EQ( 3.0, joint_elastic[0]); EXPECT_EQ( 3.0, joint_elastic[1]); EXPECT_EQ( 3.0, joint_elastic[2]); EXPECT_EQ( 3.0, joint_elastic[3]); EXPECT_EQ( 3.0, joint_elastic[4]); EXPECT_EQ( 3.0, joint_elastic[5]); EXPECT_EQ( 3.0, joint_elastic[6]); EXPECT_EQ( 3.0, joint_elastic[7]); EXPECT_EQ( 3.0, joint_elastic[8]); EXPECT_EQ( 3.0, joint_elastic[9]); EXPECT_EQ( 3.0, joint_elastic[10]); EXPECT_EQ( 3.0, joint_elastic[11]); EXPECT_EQ( 3.0, joint_elastic[12]); EXPECT_EQ( 3.0, joint_elastic[13]); EXPECT_EQ( 3.0, joint_elastic[14]); EXPECT_EQ( 3.0, joint_elastic[15]); EXPECT_EQ( 3.0, joint_elastic[16]); EXPECT_EQ( 3.0, joint_elastic[17]); EXPECT_EQ( 3.0, joint_elastic[18]); const std::vector<double>& joint_offset = adaptive_synergy_transmission->getJointOffset(); EXPECT_EQ( -0.5, joint_offset[0]); EXPECT_EQ( -0.5, joint_offset[1]); EXPECT_EQ( -0.5, joint_offset[2]); EXPECT_EQ( -0.5, joint_offset[3]); EXPECT_EQ( -0.5, joint_offset[4]); EXPECT_EQ( -0.5, joint_offset[5]); EXPECT_EQ( -0.5, joint_offset[6]); EXPECT_EQ( -0.5, joint_offset[7]); EXPECT_EQ( -0.5, joint_offset[8]); EXPECT_EQ( -0.5, joint_offset[9]); EXPECT_EQ( -0.5, joint_offset[10]); EXPECT_EQ( -0.5, joint_offset[11]); EXPECT_EQ( -0.5, joint_offset[12]); EXPECT_EQ( -0.5, joint_offset[13]); EXPECT_EQ( -0.5, joint_offset[14]); EXPECT_EQ( -0.5, joint_offset[15]); EXPECT_EQ( -0.5, joint_offset[16]); EXPECT_EQ( -0.5, joint_offset[17]); EXPECT_EQ( -0.5, joint_offset[18]); } TEST(AdaptiveSynergyTransmissionLoaderTest, MinimalSpec) { // Parse transmission info std::vector<TransmissionInfo> infos = parseUrdf("test/urdf/adaptive_synergy_transmission_loader_minimal.urdf"); ASSERT_EQ(1, infos.size()); // Transmission loader TransmissionPluginLoader loader; boost::shared_ptr<TransmissionLoader> transmission_loader = loader.create(infos.front().type_); ASSERT_TRUE(0 != transmission_loader); TransmissionPtr transmission; const TransmissionInfo& info = infos.front(); transmission = transmission_loader->load(info); ASSERT_TRUE(0 != transmission); // Validate transmission AdaptiveSynergyTransmission* adaptive_synergy_transmission = dynamic_cast<AdaptiveSynergyTransmission*>(transmission.get()); const std::vector<double>& actuator_reduction = adaptive_synergy_transmission->getActuatorReduction(); EXPECT_EQ( 30.0, actuator_reduction[0]); const std::vector<double>& joint_reduction = adaptive_synergy_transmission->getJointReduction(); EXPECT_EQ( 1.0, joint_reduction[0]); EXPECT_EQ( 1.0, joint_reduction[1]); EXPECT_EQ( 1.0, joint_reduction[2]); EXPECT_EQ( 1.0, joint_reduction[3]); EXPECT_EQ( 1.0, joint_reduction[4]); EXPECT_EQ( 1.0, joint_reduction[5]); EXPECT_EQ( 1.0, joint_reduction[6]); EXPECT_EQ( 1.0, joint_reduction[7]); EXPECT_EQ( 1.0, joint_reduction[8]); EXPECT_EQ( 1.0, joint_reduction[9]); EXPECT_EQ( 1.0, joint_reduction[10]); EXPECT_EQ( 1.0, joint_reduction[11]); EXPECT_EQ( 1.0, joint_reduction[12]); EXPECT_EQ( 1.0, joint_reduction[13]); EXPECT_EQ( 1.0, joint_reduction[14]); EXPECT_EQ( 1.0, joint_reduction[15]); EXPECT_EQ( 1.0, joint_reduction[16]); EXPECT_EQ( 1.0, joint_reduction[17]); EXPECT_EQ( 1.0, joint_reduction[18]); const std::vector<double>& joint_elastic = adaptive_synergy_transmission->getJointElastic(); EXPECT_EQ( 1.0, joint_elastic[0]); EXPECT_EQ( 1.0, joint_elastic[1]); EXPECT_EQ( 1.0, joint_elastic[2]); EXPECT_EQ( 1.0, joint_elastic[3]); EXPECT_EQ( 1.0, joint_elastic[4]); EXPECT_EQ( 1.0, joint_elastic[5]); EXPECT_EQ( 1.0, joint_elastic[6]); EXPECT_EQ( 1.0, joint_elastic[7]); EXPECT_EQ( 1.0, joint_elastic[8]); EXPECT_EQ( 1.0, joint_elastic[9]); EXPECT_EQ( 1.0, joint_elastic[10]); EXPECT_EQ( 1.0, joint_elastic[11]); EXPECT_EQ( 1.0, joint_elastic[12]); EXPECT_EQ( 1.0, joint_elastic[13]); EXPECT_EQ( 1.0, joint_elastic[14]); EXPECT_EQ( 1.0, joint_elastic[15]); EXPECT_EQ( 1.0, joint_elastic[16]); EXPECT_EQ( 1.0, joint_elastic[17]); EXPECT_EQ( 1.0, joint_elastic[18]); const std::vector<double>& joint_offset = adaptive_synergy_transmission->getJointOffset(); EXPECT_EQ( 0.0, joint_offset[0]); EXPECT_EQ( 0.0, joint_offset[1]); EXPECT_EQ( 0.0, joint_offset[2]); EXPECT_EQ( 0.0, joint_offset[3]); EXPECT_EQ( 0.0, joint_offset[4]); EXPECT_EQ( 0.0, joint_offset[5]); EXPECT_EQ( 0.0, joint_offset[6]); EXPECT_EQ( 0.0, joint_offset[7]); EXPECT_EQ( 0.0, joint_offset[8]); EXPECT_EQ( 0.0, joint_offset[9]); EXPECT_EQ( 0.0, joint_offset[10]); EXPECT_EQ( 0.0, joint_offset[11]); EXPECT_EQ( 0.0, joint_offset[12]); EXPECT_EQ( 0.0, joint_offset[13]); EXPECT_EQ( 0.0, joint_offset[14]); EXPECT_EQ( 0.0, joint_offset[15]); EXPECT_EQ( 0.0, joint_offset[16]); EXPECT_EQ( 0.0, joint_offset[17]); EXPECT_EQ( 0.0, joint_offset[18]); } TEST(AdaptiveSynergyTransmissionLoaderTest, InvalidSpec) { // Parse transmission info std::vector<TransmissionInfo> infos = parseUrdf("test/urdf/adaptive_synergy_transmission_loader_invalid.urdf"); ASSERT_EQ(12, infos.size()); // Transmission loader TransmissionPluginLoader loader; boost::shared_ptr<TransmissionLoader> transmission_loader = loader.create(infos.front().type_); ASSERT_TRUE(0 != transmission_loader); BOOST_FOREACH(const TransmissionInfo& info, infos) { TransmissionPtr transmission; transmission = transmission_loader->load(info); ASSERT_TRUE(0 == transmission); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
39.353659
126
0.722033
[ "vector" ]
0deaaca09c00cc879f692ee53a17a97e6b752458
26,547
hpp
C++
vpp/algorithms/line_tracker_4_sfm/sfm/structure_from_motion.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
vpp/algorithms/line_tracker_4_sfm/sfm/structure_from_motion.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
vpp/algorithms/line_tracker_4_sfm/sfm/structure_from_motion.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#include "structure_from_motion.hh" namespace vpp { //from http://www.mip.informatik.uni-kiel.de/tiki-index.php?page=Lilian+Zhang void pose_estimation_from_line_correspondence(Eigen::MatrixXf start_points, Eigen::MatrixXf end_points, Eigen::MatrixXf directions, Eigen::MatrixXf points, Eigen::MatrixXf &rot_cw, Eigen::VectorXf &pos_cw) { int n = start_points.cols(); if(n != directions.cols()) { return; } if(n<4) { return; } float condition_err_threshold = 1e-3; Eigen::VectorXf cosAngleThreshold(3); cosAngleThreshold << 1.1, 0.9659, 0.8660; Eigen::MatrixXf optimumrot_cw(3,3); Eigen::VectorXf optimumpos_cw(3); std::vector<float> lineLenVec(n,1); vfloat3 l1; vfloat3 l2; vfloat3 nc1; vfloat3 Vw1; vfloat3 Xm; vfloat3 Ym; vfloat3 Zm; Eigen::MatrixXf Rot(3,3); std::vector<vfloat3> nc_bar(n,vfloat3(0,0,0)); std::vector<vfloat3> Vw_bar(n,vfloat3(0,0,0)); std::vector<vfloat3> n_c(n,vfloat3(0,0,0)); Eigen::MatrixXf Rx(3,3); int line_id; for(int HowToChooseFixedTwoLines = 1 ; HowToChooseFixedTwoLines <=3 ; HowToChooseFixedTwoLines++) { if(HowToChooseFixedTwoLines==1) { #pragma omp parallel for for(int i = 0; i < n ; i++ ) { // to correct float lineLen = 10; lineLenVec[i] = lineLen; } std::vector<float>::iterator result; result = std::max_element(lineLenVec.begin(), lineLenVec.end()); line_id = std::distance(lineLenVec.begin(), result); vfloat3 temp; temp = start_points.col(0); start_points.col(0) = start_points.col(line_id); start_points.col(line_id) = temp; temp = end_points.col(0); end_points.col(0) = end_points.col(line_id); end_points.col(line_id) = temp; temp = directions.col(line_id); directions.col(0) = directions.col(line_id); directions.col(line_id) = temp; temp = points.col(0); points.col(0) = points.col(line_id); points.col(line_id) = temp; lineLenVec[line_id] = lineLenVec[1]; lineLenVec[1] = 0; l1 = start_points.col(0) - end_points.col(0); l1 = l1/l1.norm(); } for(int i = 1; i < n; i++) { std::vector<float>::iterator result; result = std::max_element(lineLenVec.begin(), lineLenVec.end()); line_id = std::distance(lineLenVec.begin(), result); l2 = start_points.col(line_id) - end_points.col(line_id); l2 = l2/l2.norm(); lineLenVec[line_id] = 0; MatrixXf cosAngle(3,3); cosAngle = (l1.transpose()*l2).cwiseAbs(); if(cosAngle.maxCoeff() < cosAngleThreshold[HowToChooseFixedTwoLines]) { break; } } vfloat3 temp; temp = start_points.col(1); start_points.col(1) = start_points.col(line_id); start_points.col(line_id) = temp; temp = end_points.col(1); end_points.col(1) = end_points.col(line_id); end_points.col(line_id) = temp; temp = directions.col(1); directions.col(1) = directions.col(line_id); directions.col(line_id) = temp; temp = points.col(1); points.col(1) = points.col(line_id); points.col(line_id) = temp; lineLenVec[line_id] = lineLenVec[1]; lineLenVec[1] = 0; // The rotation matrix R_wc is decomposed in way which is slightly different from the description in the paper, // but the framework is the same. // R_wc = (Rot') * R * Rot = (Rot') * (Ry(theta) * Rz(phi) * Rx(psi)) * Rot nc1 = x_cross(start_points.col(1),end_points.col(1)); nc1 = nc1/nc1.norm(); Vw1 = directions.col(1); Vw1 = Vw1/Vw1.norm(); //the X axis of Model frame Xm = x_cross(nc1,Vw1); Xm = Xm/Xm.norm(); //the Y axis of Model frame Ym = nc1; //the Z axis of Model frame Zm = x_cross(Xm,Zm); Zm = Zm/Zm.norm(); //Rot * [Xm, Ym, Zm] = I. Rot.col(0) = Xm; Rot.col(1) = Ym; Rot.col(2) = Zm; Rot = Rot.transpose(); //rotate all the vector by Rot. //nc_bar(:,i) = Rot * nc(:,i) //Vw_bar(:,i) = Rot * Vw(:,i) #pragma omp parallel for for(int i = 0 ; i < n ; i++) { vfloat3 nc = x_cross(start_points.col(1),end_points.col(1)); nc = nc/nc.norm(); n_c[i] = nc; nc_bar[i] = Rot * nc; Vw_bar[i] = Rot * directions.col(i); } //Determine the angle psi, it is the angle between z axis and Vw_bar(:,1). //The rotation matrix Rx(psi) rotates Vw_bar(:,1) to z axis float cospsi = (Vw_bar[1])[2];//the angle between z axis and Vw_bar(:,1); cospsi=[0,0,1] * Vw_bar(:,1);. float sinpsi= sqrt(1 - cospsi*cospsi); Rx.row(0) = vfloat3(1,0,0); Rx.row(1) = vfloat3(0,cospsi,-sinpsi); Rx.row(2) = vfloat3(0,sinpsi,cospsi); vfloat3 Zaxis = Rx * Vw_bar[1]; if(1-fabs(Zaxis[3]) > 1e-5) { Rx = Rx.transpose(); } //estimate the rotation angle phi by least square residual. //i.e the rotation matrix Rz(phi) vfloat3 Vm2 = Rx * Vw_bar[1]; float A2 = Vm2[0]; float B2 = Vm2[1]; float C2 = Vm2[2]; float x2 = (nc_bar[1])[0]; float y2 = (nc_bar[1])[1]; float z2 = (nc_bar[1])[2]; Eigen::PolynomialSolver<double, Eigen::Dynamic> solver; Eigen::VectorXf coeff(9); std::vector<float> coef(9,0); //coefficients of equation (7) Eigen::VectorXf polyDF = VectorXf::Zero(16); //%dF = ployDF(1) * t^15 + ployDF(2) * t^14 + ... + ployDF(15) * t + ployDF(16); //construct the polynomial F' #pragma omp parallel for for(int i = 3 ; i < n ; i++) { vfloat3 Vm3 = Rx*Vw_bar[i]; float A3 = Vm3[0]; float B3 = Vm3[1]; float C3 = Vm3[2]; float x3 = (nc_bar[i])[0]; float y3 = (nc_bar[i])[1]; float z3 = (nc_bar[i])[2]; float u11 = -z2*A2*y3*B3 + y2*B2*z3*A3; float u12 = -y2*A2*z3*B3 + z2*B2*y3*A3; float u13 = -y2*B2*z3*B3 + z2*B2*y3*B3 + y2*A2*z3*A3 - z2*A2*y3*A3; float u14 = -y2*B2*x3*C3 + x2*C2*y3*B3; float u15 = x2*C2*y3*A3 - y2*A2*x3*C3; float u21 = -x2*A2*y3*B3 + y2*B2*x3*A3; float u22 = -y2*A2*x3*B3 + x2*B2*y3*A3; float u23 = x2*B2*y3*B3 - y2*B2*x3*B3 - x2*A2*y3*A3 + y2*A2*x3*A3; float u24 = y2*B2*z3*C3 - z2*C2*y3*B3; float u25 = y2*A2*z3*C3 - z2*C2*y3*A3; float u31 = -x2*A2*z3*A3 + z2*A2*x3*A3; float u32 = -x2*B2*z3*B3 + z2*B2*x3*B3; float u33 = x2*A2*z3*B3 - z2*A2*x3*B3 + x2*B2*z3*A3 - z2*B2*x3*A3; float u34 = z2*A2*z3*C3 + x2*A2*x3*C3 - z2*C2*z3*A3 - x2*C2*x3*A3; float u35 = -z2*B2*z3*C3 - x2*B2*x3*C3 + z2*C2*z3*B3 + x2*C2*x3*B3; float u36 = -x2*C2*z3*C3 + z2*C2*x3*C3; float a4 = u11*u11 + u12*u12 - u13*u13 - 2*u11*u12 + u21*u21 + u22*u22 - u23*u23 -2*u21*u22 - u31*u31 - u32*u32 + u33*u33 + 2*u31*u32; float a3 =2*(u11*u14 - u13*u15 - u12*u14 + u21*u24 - u23*u25 - u22*u24 - u31*u34 + u33*u35 + u32*u34); float a2 =-2*u12*u12 + u13*u13 + u14*u14 - u15*u15 + 2*u11*u12 - 2*u22*u22 + u23*u23 + u24*u24 - u25*u25 +2*u21*u22+ 2*u32*u32 - u33*u33 - u34*u34 + u35*u35 -2*u31*u32- 2*u31*u36 + 2*u32*u36; float a1 =2*(u12*u14 + u13*u15 + u22*u24 + u23*u25 - u32*u34 - u33*u35 - u34*u36); float a0 = u12*u12 + u15*u15+ u22*u22 + u25*u25 - u32*u32 - u35*u35 - u36*u36 - 2*u32*u36; float b3 =2*(u11*u13 - u12*u13 + u21*u23 - u22*u23 - u31*u33 + u32*u33); float b2 =2*(u11*u15 - u12*u15 + u13*u14 + u21*u25 - u22*u25 + u23*u24 - u31*u35 + u32*u35 - u33*u34); float b1 =2*(u12*u13 + u14*u15 + u22*u23 + u24*u25 - u32*u33 - u34*u35 - u33*u36); float b0 =2*(u12*u15 + u22*u25 - u32*u35 - u35*u36); float d0 = a0*a0 - b0*b0; float d1 = 2*(a0*a1 - b0*b1); float d2 = a1*a1 + 2*a0*a2 + b0*b0 - b1*b1 - 2*b0*b2; float d3 = 2*(a0*a3 + a1*a2 + b0*b1 - b1*b2 - b0*b3); float d4 = a2*a2 + 2*a0*a4 + 2*a1*a3 + b1*b1 + 2*b0*b2 - b2*b2 - 2*b1*b3; float d5 = 2*(a1*a4 + a2*a3 + b1*b2 + b0*b3 - b2*b3); float d6 = a3*a3 + 2*a2*a4 + b2*b2 - b3*b3 + 2*b1*b3; float d7 = 2*(a3*a4 + b2*b3); float d8 = a4*a4 + b3*b3; std::vector<float> v { a4, a3, a2, a1, a0, b3, b2, b1, b0 }; Eigen::VectorXf vp; vp << a4, a3, a2, a1, a0, b3, b2, b1, b0 ; //coef = coef + v; coeff = coeff + vp; polyDF[0] = polyDF[0] + 8*d8*d8; polyDF[1] = polyDF[1] + 15* d7*d8; polyDF[2] = polyDF[2] + 14* d6*d8 + 7*d7*d7; polyDF[3] = polyDF[3] + 13*(d5*d8 + d6*d7); polyDF[4] = polyDF[4] + 12*(d4*d8 + d5*d7) + 6*d6*d6; polyDF[5] = polyDF[5] + 11*(d3*d8 + d4*d7 + d5*d6); polyDF[6] = polyDF[6] + 10*(d2*d8 + d3*d7 + d4*d6) + 5*d5*d5; polyDF[7] = polyDF[7] + 9 *(d1*d8 + d2*d7 + d3*d6 + d4*d5); polyDF[8] = polyDF[8] + 8 *(d1*d7 + d2*d6 + d3*d5) + 4*d4*d4 + 8*d0*d8; polyDF[9] = polyDF[9] + 7 *(d1*d6 + d2*d5 + d3*d4) + 7*d0*d7; polyDF[10] = polyDF[10] + 6 *(d1*d5 + d2*d4) + 3*d3*d3 + 6*d0*d6; polyDF[11] = polyDF[11] + 5 *(d1*d4 + d2*d3)+ 5*d0*d5; polyDF[12] = polyDF[12] + 4 * d1*d3 + 2*d2*d2 + 4*d0*d4; polyDF[13] = polyDF[13] + 3 * d1*d2 + 3*d0*d3; polyDF[14] = polyDF[14] + d1*d1 + 2*d0*d2; polyDF[15] = polyDF[15] + d0*d1; } Eigen::VectorXd coefficientPoly = VectorXd::Zero(16); for(int j =0; j < 16 ; j++) { coefficientPoly[j] = polyDF[15-j]; } //solve polyDF solver.compute(coefficientPoly); const Eigen::PolynomialSolver<double, Eigen::Dynamic>::RootsType & r = solver.roots(); Eigen::VectorXd rs(r.rows()); Eigen::VectorXd is(r.rows()); std::vector<float> min_roots; for(int j =0;j<r.rows();j++) { rs[j] = fabs(r[j].real()); is[j] = fabs(r[j].imag()); } float maxreal = rs.maxCoeff(); for(int j = 0 ; j < rs.rows() ; j++ ) { if(is[j]/maxreal <= 0.001) { min_roots.push_back(rs[j]); } } std::vector<float> temp_v(15); std::vector<float> poly(15); for(int j = 0 ; j < 15 ; j++) { temp_v[j] = j+1; } for(int j = 0 ; j < 15 ; j++) { poly[j] = polyDF[j]*temp_v[j]; } Eigen::Matrix<double,16,1> polynomial; Eigen::VectorXd evaluation(min_roots.size()); for( int j = 0; j < min_roots.size(); j++ ) { evaluation[j] = poly_eval( polynomial, min_roots[j] ); } std::vector<float> minRoots; for( int j = 0; j < min_roots.size(); j++ ) { if(!evaluation[j]<=0) { minRoots.push_back(min_roots[j]); } } if(minRoots.size()==0) { cout << "No solution" << endl; return; } int numOfRoots = minRoots.size(); //for each minimum, we try to find a solution of the camera pose, then //choose the one with the least reprojection residual as the optimum of the solution. float minimalReprojectionError = 100; // In general, there are two solutions which yields small re-projection error // or condition error:"n_c * R_wc * V_w=0". One of the solution transforms the // world scene behind the camera center, the other solution transforms the world // scene in front of camera center. While only the latter one is correct. // This can easily be checked by verifying their Z coordinates in the camera frame. // P_c(Z) must be larger than 0 if it's in front of the camera. for(int rootId = 0 ; rootId < numOfRoots ; rootId++) { float cosphi = minRoots[rootId]; float sign1 = sign_of_number(coeff[0] * pow(cosphi,4) + coeff[1] * pow(cosphi,3) + coeff[2] * pow(cosphi,2) + coeff[3] * cosphi + coeff[4]); float sign2 = sign_of_number(coeff[5] * pow(cosphi,3) + coeff[6] * pow(cosphi,2) + coeff[7] * cosphi + coeff[8]); float sinphi= -sign1*sign2*sqrt(abs(1-cosphi*cosphi)); Eigen::MatrixXf Rz(3,3); Rz.row(0) = vfloat3(cosphi,-sinphi,0); Rz.row(1) = vfloat3(sinphi,cosphi,0); Rz.row(2) = vfloat3(0,0,1); //now, according to Sec4.3, we estimate the rotation angle theta //and the translation vector at a time. Eigen::MatrixXf RzRxRot(3,3); RzRxRot = Rz*Rx*Rot; //According to the fact that n_i^C should be orthogonal to Pi^c and Vi^c, we //have: scalarproduct(Vi^c, ni^c) = 0 and scalarproduct(Pi^c, ni^c) = 0. //where Vi^c = Rwc * Vi^w, Pi^c = Rwc *(Pi^w - pos_cw) = Rwc * Pi^w - pos; //Using the above two constraints to construct linear equation system Mat about //[costheta, sintheta, tx, ty, tz, 1]. Eigen::MatrixXf Matrice(2*n-1,6); #pragma omp parallel for for(int i = 0 ; i < n ; i++) { float nxi = (nc_bar[i])[0]; float nyi = (nc_bar[i])[1]; float nzi = (nc_bar[i])[2]; Eigen::VectorXf Vm(3); Vm = RzRxRot * directions.col(i); float Vxi = Vm[0]; float Vyi = Vm[1]; float Vzi = Vm[2]; Eigen::VectorXf Pm(3); Pm = RzRxRot * points.col(i); float Pxi = Pm(1); float Pyi = Pm(2); float Pzi = Pm(3); //apply the constraint scalarproduct(Vi^c, ni^c) = 0 //if i=1, then scalarproduct(Vi^c, ni^c) always be 0 if(i>1) { Matrice(2*i-3, 0) = nxi * Vxi + nzi * Vzi; Matrice(2*i-3, 1) = nxi * Vzi - nzi * Vxi; Matrice(2*i-3, 5) = nyi * Vyi; } //apply the constraint scalarproduct(Pi^c, ni^c) = 0 Matrice(2*i-2, 0) = nxi * Pxi + nzi * Pzi; Matrice(2*i-2, 1) = nxi * Pzi - nzi * Pxi; Matrice(2*i-2, 2) = -nxi; Matrice(2*i-2, 3) = -nyi; Matrice(2*i-2, 4) = -nzi; Matrice(2*i-2, 5) = nyi * Pyi; } //solve the linear system Mat * [costheta, sintheta, tx, ty, tz, 1]' = 0 using SVD, JacobiSVD<MatrixXf> svd(Matrice, ComputeThinU | ComputeThinV); Eigen::MatrixXf VMat = svd.matrixV(); Eigen::VectorXf vec(2*n-1); //the last column of Vmat; vec = VMat.col(5); //the condition that the last element of vec should be 1. vec = vec/vec[5]; //the condition costheta^2+sintheta^2 = 1; float normalizeTheta = 1/sqrt(vec[0]*vec[1]+vec[1]*vec[1]); float costheta = vec[0]*normalizeTheta; float sintheta = vec[1]*normalizeTheta; Eigen::MatrixXf Ry(3,3); Ry << costheta, 0, sintheta , 0, 1, 0 , -sintheta, 0, costheta; //now, we get the rotation matrix rot_wc and translation pos_wc Eigen::MatrixXf rot_wc(3,3); rot_wc = (Rot.transpose()) * (Ry * Rz * Rx) * Rot; Eigen::VectorXf pos_wc(3); pos_wc = - Rot.transpose() * vec.segment(2,4); //now normalize the camera pose by 3D alignment. We first translate the points //on line in the world frame Pw to points in the camera frame Pc. Then we project //Pc onto the line interpretation plane as Pc_new. So we could call the point //alignment algorithm to normalize the camera by aligning Pc_new and Pw. //In order to improve the accuracy of the aligment step, we choose two points for each //lines. The first point is Pwi, the second point is the closest point on line i to camera center. //(Pw2i = Pwi - (Pwi'*Vwi)*Vwi.) Eigen::MatrixXf Pw2(3,n); Pw2.setZero(); Eigen::MatrixXf Pc_new(3,n); Pc_new.setZero(); Eigen::MatrixXf Pc2_new(3,n); Pc2_new.setZero(); for(int i = 0 ; i < n ; i++) { vfloat3 nci = n_c[i]; vfloat3 Pwi = points.col(i); vfloat3 Vwi = directions.col(i); //first point on line i vfloat3 Pci; Pci = rot_wc * Pwi + pos_wc; Pc_new.col(i) = Pci - (Pci.transpose() * nci) * nci; //second point is the closest point on line i to camera center. vfloat3 Pw2i; Pw2i = Pwi - (Pwi.transpose() * Vwi) * Vwi; Pw2.col(i) = Pw2i; vfloat3 Pc2i; Pc2i = rot_wc * Pw2i + pos_wc; Pc2_new.col(i) = Pc2i - ( Pc2i.transpose() * nci ) * nci; } MatrixXf XXc(Pc_new.rows(), Pc_new.cols()+Pc2_new.cols()); XXc << Pc_new, Pc2_new; MatrixXf XXw(points.rows(), points.cols()+Pw2.cols()); XXw << points, Pw2; int nm = points.cols()+Pw2.cols(); cal_campose(XXc,XXw,nm,rot_wc,pos_wc); pos_cw = -rot_wc.transpose() * pos_wc; //check the condition n_c^T * rot_wc * V_w = 0; float conditionErr = 0; for(int i =0 ; i < n ; i++) { float val = ( (n_c[i]).transpose() * rot_wc * directions.col(i) ); conditionErr = conditionErr + val*val; } if(conditionErr/n < condition_err_threshold || HowToChooseFixedTwoLines ==3) { //check whether the world scene is in front of the camera. int numLineInFrontofCamera = 0; if(HowToChooseFixedTwoLines<3) { for(int i = 0 ; i < n ; i++) { vfloat3 P_c = rot_wc * (points.col(i) - pos_cw); if(P_c[2]>0) { numLineInFrontofCamera++; } } } else { numLineInFrontofCamera = n; } if(numLineInFrontofCamera > 0.5*n) { //most of the lines are in front of camera, then check the reprojection error. int reprojectionError = 0; for(int i =0; i < n ; i++) { //line projection function vfloat3 nc = rot_wc * x_cross(points.col(i) - pos_cw , directions.col(i)); float h1 = nc.transpose() * start_points.col(i); float h2 = nc.transpose() * end_points.col(i); float lineLen = (start_points.col(i) - end_points.col(i)).norm()/3; reprojectionError += lineLen * (h1*h1 + h1*h2 + h2*h2) / (nc[0]*nc[0]+nc[1]*nc[1]); } if(reprojectionError < minimalReprojectionError) { optimumrot_cw = rot_wc.transpose(); optimumpos_cw = pos_cw; minimalReprojectionError = reprojectionError; } } } } if(optimumrot_cw.rows()>0) { break; } } pos_cw = optimumpos_cw; rot_cw = optimumrot_cw; } inline void cal_campose(Eigen::MatrixXf XXc,Eigen::MatrixXf XXw, int n,Eigen::MatrixXf &R2,Eigen::VectorXf &t2) { //A Eigen::MatrixXf X = XXw; //B Eigen::MatrixXf Y = XXc; Eigen::MatrixXf eyen(n,n); eyen = Eigen::MatrixXf::Identity(n,n); Eigen::MatrixXf ones(n,n); ones.setOnes(); Eigen::MatrixXf K(n,n); K = eyen - ones/n; vfloat3 ux; for(int i =0; i < n; i++) { ux = ux + X.col(i); } ux = ux/n; vfloat3 uy; for(int i =0; i < n; i++) { uy = uy + Y.col(i); } uy = uy/n; Eigen::MatrixXf XK(3,n); XK = X*K; Eigen::MatrixXf XKarre(3,n); for(int i = 0 ; i < n ; i++) { XKarre(0,i) = XK(0,i)*XK(0,i); XKarre(1,i) = XK(1,i)*XK(1,i); XKarre(2,i) = XK(2,i)*XK(2,i); } Eigen::VectorXf sumXKarre(n); float sigmx2 = 0; for(int i = 0 ; i < n ; i++) { sumXKarre[i] = XKarre(0,i) + XKarre(1,i) + XKarre(2,i); sigmx2 += sumXKarre[i]; } sigmx2 /=n; Eigen::MatrixXf SXY(3,3); SXY = Y*K*(X.transpose())/n; JacobiSVD<MatrixXf> svd(SXY, ComputeThinU | ComputeThinV); Eigen::MatrixXf S(3,3); S = Eigen::MatrixXf::Identity(3,3); if(SXY.determinant() < 0) { S(3,3) = -1; } R2 = svd.matrixU() * S * (svd.matrixV()).transpose(); Eigen::MatrixXf D(3,3); D.setZero(); for(int i = 0 ; i < svd.singularValues().size() ; i++) { D(i,i) = (svd.singularValues())[i]; } float c2 = (D*S).trace()/sigmx2; t2 = uy - c2*R2*ux; vfloat3 Xx = R2.col(0); vfloat3 Yy = R2.col(1); vfloat3 Zz = R2.col(2); if((x_cross(Xx,Yy)-Zz).norm()>2e-2) { R2.col(2) = -Zz; } } inline void r_and_t(MatrixXf &rot_cw, VectorXf &pos_cw,MatrixXf start_points, MatrixXf end_points, MatrixXf P1w,MatrixXf P2w,MatrixXf initRot_cw,VectorXf initPos_cw, int maxIterNum,float TerminateTh,int nargin) { if(nargin<6) { return; } if(nargin<8) { maxIterNum = 8; TerminateTh = 1e-5; } int n = start_points.cols(); if(n != end_points.cols() || n!= P1w.cols() || n!= P2w.cols()) { return; } if(n<4) { return; } //first compute the weight of each line and the normal of //the interpretation plane passing through to camera center and the line VectorXf w = VectorXf::Zero(n); MatrixXf nc = MatrixXf::Zero(3,n); for(int i = 0 ; i < n ; i++) { //the weight of a line is the inverse of its image length w[i] = 1/(start_points.col(i)-end_points.col(i)).norm(); vfloat3 v1 = start_points.col(i); vfloat3 v2 = end_points.col(i); vfloat3 temp = v1.cross(v2); nc.col(i) = temp/temp.norm(); } MatrixXf rot_wc = initPos_cw.transpose(); MatrixXf pos_wc = - initRot_cw.transpose() * initPos_cw; for(int iter = 1 ; iter < maxIterNum ; iter++) { //construct the equation (31) MatrixXf A = MatrixXf::Zero(6,7); MatrixXf C = MatrixXf::Zero(3,3); MatrixXf D = MatrixXf::Zero(3,3); MatrixXf F = MatrixXf::Zero(3,3); vfloat3 c_bar = vfloat3(0,0,0); vfloat3 d_bar = vfloat3(0,0,0); for(int i = 0 ; i < n ; i++) { //for first point on line vfloat3 Pi = rot_wc * P1w.col(i); vfloat3 Ni = nc.col(i); float wi = w[i]; vfloat3 bi = Pi.cross(Ni); C = C + wi*Ni*Ni.transpose(); D = D + wi*bi*bi.transpose(); F = F + wi*Ni*bi.transpose(); vfloat3 tempi = Pi + pos_wc; float scale = Ni.transpose() * tempi; scale *= wi; c_bar = c_bar + scale * Ni; d_bar = d_bar + scale*bi; //for second point on line Pi = rot_wc * P2w.col(i); Ni = nc.col(i); wi = w[i]; bi = Pi.cross(Ni); C = C + wi*Ni*Ni.transpose(); D = D + wi*bi*bi.transpose(); F = F + wi*Ni*bi.transpose(); scale = (Ni.transpose() * (Pi + pos_wc)); scale *= wi; c_bar = c_bar + scale * Ni; d_bar = d_bar + scale * bi; } A.block<3,3>(0,0) = C; A.block<3,3>(0,3) = F; (A.col(6)).segment(0,2) = c_bar; A.block<3,3>(3,0) = F.transpose(); A.block<3,3>(2,2) = D; (A.col(6)).segment(3,5) = d_bar; //sovle the system by using SVD; JacobiSVD<MatrixXf> svd(A, ComputeThinU | ComputeThinV); VectorXf vec(7); //the last column of Vmat; vec = (svd.matrixV()).col(6); //the condition that the last element of vec should be 1. vec = vec/vec[6]; //update the rotation and translation parameters; vfloat3 dT = vec.segment(0,2); vfloat3 dOmiga = vec.segment(3,5); MatrixXf rtemp(3,3); rtemp << 1, -dOmiga[2], dOmiga[1], dOmiga[2], 1, -dOmiga[1], -dOmiga[1], dOmiga[0], 1; rot_wc = rtemp * rot_wc; //newRot_wc = ( I + [dOmiga]x ) oldRot_wc //may be we can compute new R using rodrigues(r+dr) pos_wc = pos_wc + dT; if(dT.norm() < TerminateTh && dOmiga.norm() < 0.1*TerminateTh) { break; } } rot_cw = rot_wc.transpose(); pos_cw = -rot_cw * pos_wc; } inline vfloat3 x_cross(vfloat3 a,vfloat3 b) { vfloat3 c; c[0] = a[1]*b[2]-a[2]*b[1]; c[1] = a[2]*b[0]-a[0]*b[2]; c[2] = a[0]*b[1]-a[1]*b[0]; return c; } }
35.538153
133
0.489472
[ "vector", "model", "3d" ]
0ded7225cc371075cb36df62a3fd533b52a8e5f5
2,827
cpp
C++
test/unit/math/mix/meta/return_type_test.cpp
HaoZeke/math
fdf7f70dceed60f3b3f93137c6ac123a457b80a3
[ "BSD-3-Clause" ]
1
2020-05-18T13:10:50.000Z
2020-05-18T13:10:50.000Z
test/unit/math/mix/meta/return_type_test.cpp
HaoZeke/math
fdf7f70dceed60f3b3f93137c6ac123a457b80a3
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/mix/meta/return_type_test.cpp
SteveBronder/math
3f21445458866897842878f65941c6bcb90641c2
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/mix.hpp> #include <gtest/gtest.h> #include <test/unit/util.hpp> #include <complex> #include <vector> using stan::return_type; using stan::math::fvar; using stan::math::var; using d_t = double; using v_t = var; using fd_t = fvar<double>; using ffd_t = fvar<fd_t>; using fv_t = fvar<var>; using ffv_t = fvar<fv_t>; using md_t = Eigen::MatrixXd; using vd_t = Eigen::VectorXd; using rvd_t = Eigen::RowVectorXd; template <typename R, typename... Ts> void expect_return() { test::expect_same_type<R, typename stan::return_type<Ts...>::type>(); test::expect_same_type<R, stan::return_type_t<Ts...>>(); } template <typename T> void test_return() { // scalar types expect_return<T, T>(); expect_return<T, T, int>(); expect_return<T, int, T>(); expect_return<T, d_t, T, d_t, int, d_t, float, float, float, T, int>(); // array types expect_return<T, std::vector<T>>(); expect_return<T, std::vector<T>, int>(); expect_return<T, double, std::vector<T>>(); // matrix types expect_return<T, Eigen::Matrix<T, -1, -1>>(); expect_return<T, Eigen::Matrix<T, -1, 1>>(); expect_return<T, Eigen::Matrix<T, -1, 1>, std::vector<double>>(); expect_return<T, Eigen::Matrix<T, 1, -1>>(); expect_return<T, Eigen::Matrix<T, 1, -1>, T>(); expect_return<T, T, Eigen::Matrix<T, 1, -1>, int>(); expect_return<T, double, Eigen::Matrix<T, 1, -1>>(); expect_return<T, Eigen::Matrix<T, 1, -1>, double>(); expect_return<T, Eigen::Matrix<T, 1, -1>, int, Eigen::Matrix<T, -1, -1>>(); expect_return<T, Eigen::Matrix<T, 1, -1>, int, std::vector<Eigen::Matrix<double, -1, -1>>>(); // complex types expect_return<std::complex<T>, std::complex<T>>(); expect_return<std::complex<T>, int, std::complex<T>>(); expect_return<std::complex<T>, std::complex<T>, int>(); expect_return<std::complex<T>, double, std::complex<T>>(); expect_return<std::complex<T>, std::complex<T>, double>(); expect_return<std::complex<T>, std::complex<double>, std::complex<T>>(); expect_return<std::complex<T>, std::complex<T>, std::complex<double>>(); expect_return<std::complex<T>, T, std::complex<T>>(); expect_return<std::complex<T>, std::complex<T>, T>(); expect_return<std::complex<T>, std::complex<T>, std::complex<T>>(); expect_return<std::complex<T>, std::complex<T>, std::complex<T>, T>(); } TEST(mathMetaMix, returnType) { // no-arg case expect_return<double>(); // 1-arg special cases where result is min double expect_return<double, float>(); expect_return<double, int>(); expect_return<double, std::vector<int>>(); expect_return<double, Eigen::Matrix<float, -1, 1>>(); // cases where result is given real type test_return<d_t>(); test_return<v_t>(); test_return<fd_t>(); test_return<ffd_t>(); test_return<fv_t>(); test_return<ffv_t>(); }
31.764045
77
0.65122
[ "vector" ]
0df4719c37fe278955b6b2eafb261d947a0f6f5a
7,971
cpp
C++
Funambol/source/common/base/util/EncodingHelper.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
Funambol/source/common/base/util/EncodingHelper.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
Funambol/source/common/base/util/EncodingHelper.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
[ "MIT" ]
null
null
null
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include <Funambol/base/util/utils.h> #include <Funambol/base/util/EncodingHelper.h> #include <Funambol/base/Log.h> #include <Funambol/spds/DataTransformerFactory.h> USE_NAMESPACE const char* const EncodingHelper::encodings::plain = "bin"; const char* const EncodingHelper::encodings::escaped = "b64"; const char* const EncodingHelper::encodings::des = "des;b64"; // Constructor EncodingHelper::EncodingHelper(const char* encoding, const char* encryption, const char* credential) { setEncoding(encoding); setEncryption(encryption); setCredential(credential ? credential : ""); from = encodings::plain; } EncodingHelper::~EncodingHelper() {} void EncodingHelper::setEncoding(const char* value) { encoding = encodings::encodingString(value); if (encoding == "") { encoding = encodings::plain; } } void EncodingHelper::setEncryption(const char* value) { encryption = value; } void EncodingHelper::setCredential(const char* value) { credential = value; } void EncodingHelper::setDataEncoding(const char* dataEnc) { dataEncoding = dataEnc; } long EncodingHelper::getMaxDataSizeToEncode(long size) { // ret = size is fine when encoding = encodings::plain long ret = size; if (encoding == encodings::escaped) { ret = ((unsigned long)(size/4)) * 3; } /*@TODO... if (encryption == "des") { int mod = (ret%8); ret = ret - 8 - mod; } */ return ret; } long EncodingHelper::getDataSizeAfterEncoding(long size) { long ret = size; if (encoding == encodings::escaped) { int modules = size % 3; if (modules == 0) { ret = 4 * (size/3); } else { ret = 4 * ((size/3) + 1); } } /*@TODO... if (encryption == "des") { int mod = (ret%8); ret = ret - 8 - mod; } */ return ret; } char* EncodingHelper::encode(const char* from, char* buffer, unsigned long *len) { return transform(from, buffer, len); } char* EncodingHelper::decode(const char* from, char* buffer, unsigned long *len) { return transform(from, buffer, len); } char* EncodingHelper::transform(const char* from, char* buffer, unsigned long *len) { char* ret = NULL; StringBuffer encToUse; char* pBuffer = buffer; StringBuffer originalEncoding(encodings::encodingString(from)); if (encryption == "des") { encToUse = encodings::des; } else { encToUse = encoding; } // nothing to be done? if (!buffer) { //!strcmp(encodings::encodingString(encoding), encodings::encodingString(encToUse))) LOG.info("EncodingHelper: nothing to be done: buffer NULL or lenght <= 0"); return ret; } if (len == 0) { ret = stringdup(""); //setDataEncoding(originalEncoding); LOG.debug("EncodingHelper: nothing to be done: buffer empty or lenght = 0"); return ret; } if (encToUse == originalEncoding) { ret = new char[*len + 1]; memcpy(ret, buffer, *len); ret[*len] = 0; setDataEncoding(originalEncoding); //LOG.debug("EncodingHelper: no transformation done. Only returned the new array"); return ret; } // sanity check: both encodings must be valid if (!encodings::isSupported(encToUse.c_str()) || !encodings::isSupported(encoding.c_str())) { LOG.error("EncodingHelper: encoding not supported"); return ret; } if (encToUse != originalEncoding) { // DECODING if (originalEncoding != encodings::plain) { if ((originalEncoding == encodings::escaped) || (originalEncoding == encodings::des)) { ret = transformData("b64", false, credential.c_str(), pBuffer, len); if (ret == NULL) { return ret; } pBuffer = ret; } if (originalEncoding == encodings::des) { ret = transformData("des", false, credential.c_str(), pBuffer, len); if (pBuffer != buffer) { delete [] pBuffer; } if (ret == NULL) { return ret; } } setDataEncoding(encodings::plain); } // ENCODING: convert to new encoding if (encToUse == encodings::des) { ret = transformData("des", true, credential.c_str(), pBuffer, len); if (ret == NULL) { return ret; } pBuffer = ret; } if (encToUse == encodings::escaped || encToUse == encodings::des ) { ret = transformData("b64", true, credential.c_str(), pBuffer, len); if (pBuffer != buffer) { // it means it was assigned pBuffer = ret since the pointer is differen delete [] pBuffer; } if (ret == NULL) { return ret; } } setDataEncoding(encToUse.c_str()); } return ret; } char* EncodingHelper::transformData(const char* name, bool encode, const char* password, char* buff, unsigned long *len) { char* buffer = NULL; DataTransformer *dt = encode ? DataTransformerFactory::getEncoder(name) : DataTransformerFactory::getDecoder(name); TransformationInfo info; int res = ERR_NONE; if (dt == NULL) { res = getLastErrorCode(); goto exit; } info.size = *len; info.password = password; buffer = dt->transform(buff, info); if (!buffer) { res = getLastErrorCode(); goto exit; } *len = info.size; if (info.newReturnedData == false) { buffer = new char[info.size + 1]; memset(buffer, 0, info.size + 1); memcpy(buffer, buff, info.size); } exit: delete dt; return buffer; }
32.271255
111
0.596036
[ "object", "transform" ]
df02fa32675347c7d9e9b09019ee84592f48b915
842
hpp
C++
include/class/brush.hpp
KusStar/-
8a7117e5d7b4f0dc9a4d34e12076f301f8bb37ec
[ "MIT" ]
null
null
null
include/class/brush.hpp
KusStar/-
8a7117e5d7b4f0dc9a4d34e12076f301f8bb37ec
[ "MIT" ]
null
null
null
include/class/brush.hpp
KusStar/-
8a7117e5d7b4f0dc9a4d34e12076f301f8bb37ec
[ "MIT" ]
null
null
null
#pragma once #ifndef __BRUSH_H__ #define __BRUSH_H__ #include <string> #include <vector> #include "escaper.hpp" class Brush { public: Brush() = default; ~Brush() { clear(); } void draw() { std::cout << oss_.str(); } void flush() { std::cout << escaper::erase::lines(lines()); clear(); } int lines() { int n = 0; const std::string content = oss_.str(); size_t pos = content.find("\n"); while (pos != std::string::npos) { pos = content.find("\n", pos + 1); n++; } return n; } void clear() { oss_.str(""); oss_.clear(); } template <class T> Brush& operator<<(const T& t) { oss_ << t; return *this; } private: std::ostringstream oss_; }; #endif // __BRUSH_H__
16.192308
52
0.495249
[ "vector" ]
df0882283d8acb542316ea1818d4589ebf699f1e
4,754
cpp
C++
webkit/WebCore/platform/graphics/haiku/ImageHaiku.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/platform/graphics/haiku/ImageHaiku.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/platform/graphics/haiku/ImageHaiku.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2006 Dirk Mueller <mueller@kde.org> * Copyright (C) 2006 Zack Rusin <zack@kde.org> * Copyright (C) 2006 Simon Hausmann <hausmann@kde.org> * Copyright (C) 2007 Ryan Leavengood <leavengood@gmail.com> * Copyright (C) 2008 Andrea Anzani <andrea.anzani@gmail.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Image.h" #include "BitmapImage.h" #include "FloatRect.h" #include "GraphicsContext.h" #include "NotImplemented.h" #include "PlatformString.h" #include <Application.h> #include <Bitmap.h> #include <View.h> // This function loads resources from WebKit Vector<char> loadResourceIntoArray(const char*); namespace WebCore { bool FrameData::clear(bool clearMetadata) { if (clearMetadata) m_haveMetadata = false; if (m_frame) { delete m_frame; m_frame = 0; m_duration = 0.0f; m_hasAlpha = true; return true; } return false; } WTF::PassRefPtr<Image> Image::loadPlatformResource(const char* name) { Vector<char> array = loadResourceIntoArray(name); WTF::PassRefPtr<BitmapImage> image = BitmapImage::create(); RefPtr<SharedBuffer> buffer = SharedBuffer::create(array.data(), array.size()); image->setData(buffer, true); return image; } void BitmapImage::initPlatformData() { } void BitmapImage::invalidatePlatformData() { } // Drawing Routines void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dst, const FloatRect& src, ColorSpace styleColorSpace, CompositeOperator op) { startAnimation(); BBitmap* image = nativeImageForCurrentFrame(); if (!image || !image->IsValid()) // If the image hasn't fully loaded. return; if (mayFillWithSolidColor()) { fillWithSolidColor(ctxt, dst, solidColor(), styleColorSpace, op); return; } ctxt->save(); ctxt->setCompositeOperation(op); BRect srcRect(src); BRect dstRect(dst); // Test using example site at // http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html ctxt->platformContext()->SetDrawingMode(B_OP_ALPHA); ctxt->platformContext()->DrawBitmap(image, srcRect & image->Bounds(), dstRect); ctxt->restore(); } void Image::drawPattern(GraphicsContext* context, const FloatRect& tileRect, const TransformationMatrix& patternTransform, const FloatPoint& srcPoint, ColorSpace, CompositeOperator op, const FloatRect& dstRect) { // FIXME: finish this to support also phased position (srcPoint) startAnimation(); BBitmap* image = nativeImageForCurrentFrame(); if (!image || !image->IsValid()) // If the image hasn't fully loaded. return; float currentW = 0; float currentH = 0; context->save(); context->platformContext()->SetDrawingMode(B_OP_ALPHA); context->clip(enclosingIntRect(dstRect)); while (currentW < dstRect.width()) { while (currentH < dstRect.height()) { context->platformContext()->DrawBitmap(image, BPoint(dstRect.x() + currentW, dstRect.y() + currentH)); currentH += tileRect.height(); } currentW += tileRect.width(); currentH = 0; } context->restore(); } void BitmapImage::checkForSolidColor() { // FIXME: need to check the RGBA32 buffer to see if it is 1x1. m_isSolidColor = false; m_checkedForSolidColor = true; } BBitmap* BitmapImage::getBBitmap() const { return const_cast<BitmapImage*>(this)->frameAtIndex(0); } } // namespace WebCore
31.071895
210
0.705301
[ "vector" ]
df0ca4af2eb7879524ed9d6ebdbc9334ed7229ad
24,528
cpp
C++
src/other/ext/openscenegraph/src/osgDB/ClassInterface.cpp
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/other/ext/openscenegraph/src/osgDB/ClassInterface.cpp
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/other/ext/openscenegraph/src/osgDB/ClassInterface.cpp
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2013 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgDB/ClassInterface> namespace osgDB // start of osgDB namespace { osgDB::BaseSerializer::Type getTypeEnumFromPtr(const osg::Object*) { return osgDB::BaseSerializer::RW_OBJECT; } const char* getTypeStringFromPtr(const osg::Object*) { return "OBJECT"; } osgDB::BaseSerializer::Type getTypeEnumFromPtr(const osg::Image*) { return osgDB::BaseSerializer::RW_IMAGE; } const char* getTypeStringFromPtr(const osg::Image*) { return "IMAGE"; } /////////////////////////////////////////////////////////////////// // // PropertyOutputIterator enables the get of class properties // class PropertyOutputIterator : public osgDB::OutputIterator { public: PropertyOutputIterator() { } virtual ~PropertyOutputIterator() {} virtual bool isBinary() const { return true; } template<typename T> inline void write(T t) { char* ptr = reinterpret_cast<char*>(&t); _str.insert(_str.size(), ptr, sizeof(T)); } virtual void writeBool( bool b ) { _str.push_back(static_cast<char>(b?1:0)); } virtual void writeChar( char c ) { _str.push_back(c); } virtual void writeUChar( unsigned char c ) { _str.push_back(static_cast<char>(c)); } virtual void writeShort( short s ) { write(s); } virtual void writeUShort( unsigned short s ) { write(s); } virtual void writeInt( int i ) { write(i); } virtual void writeUInt( unsigned int i ) { write(i); } virtual void writeLong( long l ) { write(l); } virtual void writeULong( unsigned long l ) { write(l); } virtual void writeFloat( float f ) { write(f); } virtual void writeDouble( double d ) { write(d); } virtual void writeInt64( GLint64 ll ) { write(ll); } virtual void writeUInt64( GLuint64 ull ) { write(ull); } virtual void writeString( const std::string& s ) { _str.insert(_str.end(), s.begin(), s.end()); } virtual void writeStream( std::ostream& (*)(std::ostream&) ) {} virtual void writeBase( std::ios_base& (*)(std::ios_base&) ) {} virtual void writeGLenum( const osgDB::ObjectGLenum& value ) { writeInt(value.get()); } virtual void writeProperty( const osgDB::ObjectProperty& prop ) { _propertyName = prop._name; } virtual void writeMark( const osgDB::ObjectMark& mark ) { _markName = mark._name; } virtual void writeCharArray( const char* s, unsigned int size) { _str.insert(std::string::npos, s, size); } virtual void writeWrappedString( const std::string& str ) { _str.insert(_str.end(), str.begin(), str.end()); } virtual void flush() { _str.clear(); _propertyName.clear(); _markName.clear(); } std::string _str; std::string _propertyName; std::string _markName; }; /////////////////////////////////////////////////////////////////// // // PropertyInputIterator enables the set of class properties // class OSGDB_EXPORT PropertyInputIterator : public osgDB::InputIterator { public: PropertyInputIterator(): _sstream(std::stringstream::binary), _bufferData(0), _currentPtr(0), _bufferSize(0) { setStream(&_sstream); } virtual ~PropertyInputIterator() { if (_bufferData) delete [] _bufferData; setStream(0); } virtual bool isBinary() const { return true; } template<typename T> void read(T& value) { memcpy(reinterpret_cast<char*>(&value), _currentPtr, sizeof(T)); _currentPtr += sizeof(T); } virtual void readBool( bool& b ) { char c; read(c); b = (c!=0); } virtual void readChar( char& c ) { read(c); } virtual void readSChar( signed char& c ) { read(c); } virtual void readUChar( unsigned char& c ) { read(c); } virtual void readShort( short& s ) { read(s); } virtual void readUShort( unsigned short& s ) { read(s); } virtual void readInt( int& i ) { read(i); } virtual void readUInt( unsigned int& i ) { read(i);} virtual void readLong( long& l ) { read(l); } virtual void readULong( unsigned long& l ) { read(l); } virtual void readFloat( float& f ) { read(f); } virtual void readDouble( double& d ) { read(d); } virtual void readString( std::string& s ) { s = std::string(_bufferData, _bufferSize); } virtual void readStream( std::istream& (*)(std::istream&) ) {} virtual void readBase( std::ios_base& (*)(std::ios_base&) ) {} virtual void readGLenum( ObjectGLenum& value ) { readUInt(value._value); } virtual void readProperty( ObjectProperty& ) {} virtual void readMark( ObjectMark&) {} virtual void readCharArray( char* s, unsigned int size ) { if ( size>0 ) _in->read( s, size ); } virtual void readWrappedString( std::string& str ) { readString(str); } virtual bool matchString( const std::string& /*str*/ ) { return false; } template<typename T> void set(const T& value) { if (_bufferData) delete [] _bufferData; _bufferData = new char[sizeof(T)]; _bufferSize = sizeof(T); _currentPtr = _bufferData; memcpy(_bufferData, reinterpret_cast<const char*>(&value), sizeof(T)); } void set(const void* ptr, unsigned int valueSize) { if (_bufferData) delete [] _bufferData; _bufferData = new char[valueSize]; _currentPtr = _bufferData; _bufferSize = valueSize; memcpy(_bufferData, reinterpret_cast<const char*>(ptr), valueSize); } std::stringstream _sstream; char* _bufferData; char* _currentPtr; unsigned int _bufferSize; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// // // ClassInterface class provides a generic mechanism for get/setting class properties using the osgDB serializers // ClassInterface::ClassInterface(): _outputStream(0), _inputStream(0) { _poi = new PropertyOutputIterator; _outputStream.setOutputIterator(_poi); _pii = new PropertyInputIterator; _inputStream.setInputIterator(_pii); // initialize the type maps #define TYPENAME(A) \ _typeToTypeNameMap[osgDB::BaseSerializer::RW_##A] = #A; \ _typeNameToTypeMap[#A] = osgDB::BaseSerializer::RW_##A; TYPENAME(UNDEFINED) TYPENAME(USER) TYPENAME(OBJECT) TYPENAME(IMAGE) TYPENAME(LIST) TYPENAME(BOOL) TYPENAME(CHAR) TYPENAME(UCHAR) TYPENAME(SHORT) TYPENAME(USHORT) TYPENAME(INT) TYPENAME(UINT) TYPENAME(FLOAT) TYPENAME(DOUBLE) TYPENAME(VEC2F) TYPENAME(VEC2D) TYPENAME(VEC3F) TYPENAME(VEC3D) TYPENAME(VEC4F) TYPENAME(VEC4D) TYPENAME(QUAT) TYPENAME(PLANE) TYPENAME(MATRIXF) TYPENAME(MATRIXD) TYPENAME(MATRIX) TYPENAME(BOUNDINGBOXF) TYPENAME(BOUNDINGBOXD) TYPENAME(BOUNDINGSPHEREF) TYPENAME(BOUNDINGSPHERED) TYPENAME(GLENUM) TYPENAME(STRING) TYPENAME(ENUM) TYPENAME(VEC2B) TYPENAME(VEC2UB) TYPENAME(VEC2S) TYPENAME(VEC2US) TYPENAME(VEC2I) TYPENAME(VEC2UI) TYPENAME(VEC3B) TYPENAME(VEC3UB) TYPENAME(VEC3S) TYPENAME(VEC3US) TYPENAME(VEC3I) TYPENAME(VEC3UI) TYPENAME(VEC4B) TYPENAME(VEC4UB) TYPENAME(VEC4S) TYPENAME(VEC4US) TYPENAME(VEC4I) TYPENAME(VEC4UI) TYPENAME(LIST) TYPENAME(VECTOR) TYPENAME(MAP) } bool ClassInterface::areTypesCompatible(osgDB::BaseSerializer::Type lhs, osgDB::BaseSerializer::Type rhs) const { if (lhs==rhs) return true; #ifdef OSG_USE_FLOAT_MATRIX if (lhs==osgDB::BaseSerializer::RW_MATRIX) lhs = osgDB::BaseSerializer::RW_MATRIXF; if (rhs==osgDB::BaseSerializer::RW_MATRIX) rhs = osgDB::BaseSerializer::RW_MATRIXF; #else if (lhs==osgDB::BaseSerializer::RW_MATRIX) lhs = osgDB::BaseSerializer::RW_MATRIXD; if (rhs==osgDB::BaseSerializer::RW_MATRIX) rhs = osgDB::BaseSerializer::RW_MATRIXD; #endif if (lhs==osgDB::BaseSerializer::RW_GLENUM) lhs = osgDB::BaseSerializer::RW_UINT; if (rhs==osgDB::BaseSerializer::RW_GLENUM) rhs = osgDB::BaseSerializer::RW_UINT; if (lhs==osgDB::BaseSerializer::RW_ENUM) lhs = osgDB::BaseSerializer::RW_INT; if (rhs==osgDB::BaseSerializer::RW_ENUM) rhs = osgDB::BaseSerializer::RW_INT; if (lhs==osgDB::BaseSerializer::RW_IMAGE) lhs = osgDB::BaseSerializer::RW_OBJECT; return lhs==rhs; } std::string ClassInterface::getTypeName(osgDB::BaseSerializer::Type type) const { TypeToTypeNameMap::const_iterator itr = _typeToTypeNameMap.find(type); if (itr != _typeToTypeNameMap.end()) return itr->second; else return std::string(); } osgDB::BaseSerializer::Type ClassInterface::getType(const std::string& typeName) const { TypeNameToTypeMap::const_iterator itr = _typeNameToTypeMap.find(typeName); if (itr != _typeNameToTypeMap.end()) return itr->second; else return osgDB::BaseSerializer::RW_UNDEFINED; } osgDB::ObjectWrapper* ClassInterface::getObjectWrapper(const osg::Object* object) const { return osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(object->getCompoundClassName()); } osgDB::BaseSerializer* ClassInterface::getSerializer(const osg::Object* object, const std::string& propertyName, osgDB::BaseSerializer::Type& type) const { osgDB::ObjectWrapper* ow = getObjectWrapper(object); return (ow!=0) ? ow->getSerializer(propertyName, type) : 0; } osg::Object* ClassInterface::createObject(const std::string& compoundClassName) const { osgDB::ObjectWrapper* ow = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(compoundClassName); if (ow) { osg::Object* object = ow->createInstance(); // OSG_NOTICE<<"ClassInterface::createObject("<<compoundClassName<<"), wrapper found, created object="<<object<<std::endl; return object; } else { OSG_NOTICE<<"ClassInterface::createObject("<<compoundClassName<<"), No object wrapper available."<<std::endl; return 0; } // return (ow!=0) ? ow->createInstance() : 0; } bool ClassInterface::copyPropertyDataFromObject(const osg::Object* object, const std::string& propertyName, void* valuePtr, unsigned int valueSize, osgDB::BaseSerializer::Type valueType) { _poi->flush(); osgDB::BaseSerializer::Type sourceType; osgDB::BaseSerializer* serializer = getSerializer(object, propertyName, sourceType); if (!serializer) return false; if (!areTypesCompatible(sourceType, valueType)) { OSG_NOTICE<<"ClassInterface::copyPropertyDataFromObject() Types are not compatible, valueType = "<<valueType<<", sourceType="<<sourceType<<std::endl; return false; } if (serializer->write(_outputStream, *object)) { unsigned int sourceSize = _poi->_str.size(); if (valueType==osgDB::BaseSerializer::RW_STRING) { std::string* string_ptr = reinterpret_cast<std::string*>(valuePtr); (*string_ptr) = _poi->_str; return true; } else if (sourceSize==valueSize) { memcpy(valuePtr, &(_poi->_str[0]), valueSize); return true; } else { OSG_NOTICE<<"ClassInterface::copyPropertyDataFromObject() Sizes not compatible, sourceSize = "<<sourceSize<<" valueSize = "<<valueSize<<std::endl; return false; } } else { OSG_INFO<<"ClassInterface::copyPropertyDataFromObject() serializer write failed."<<std::endl; return false; } } bool ClassInterface::copyPropertyDataToObject(osg::Object* object, const std::string& propertyName, const void* valuePtr, unsigned int valueSize, osgDB::BaseSerializer::Type valueType) { // copy data to PropertyInputIterator if (valueType==osgDB::BaseSerializer::RW_STRING) { const std::string* string_ptr = reinterpret_cast<const std::string*>(valuePtr); _pii->set(&((*string_ptr)[0]), string_ptr->size()); } else { _pii->set(valuePtr, valueSize); } osgDB::BaseSerializer::Type destinationType; osgDB::BaseSerializer* serializer = getSerializer(object, propertyName, destinationType); if (serializer) { if (areTypesCompatible(valueType, destinationType)) { return serializer->read(_inputStream, *object); } else { OSG_NOTICE<<"ClassInterface::copyPropertyDataToObject() Types are not compatible, valueType = "<<valueType<<" ["<<getTypeName(valueType)<<"] , destinationType="<<destinationType<<" ["<<getTypeName(destinationType)<<"]"<<std::endl; return false; } } else { OSG_INFO<<"ClassInterface::copyPropertyDataFromObject() no serializer available."<<std::endl; return false; } } bool ClassInterface::copyPropertyObjectFromObject(const osg::Object* object, const std::string& propertyName, void* valuePtr, unsigned int /*valueSize*/, osgDB::BaseSerializer::Type valueType) { osgDB::BaseSerializer::Type sourceType; osgDB::BaseSerializer* serializer = getSerializer(object, propertyName, sourceType); if (serializer) { if (areTypesCompatible(sourceType, valueType)) { return serializer->get(*object, valuePtr); } else { OSG_NOTICE<<"ClassInterface::copyPropertyObjectFromObject() Types are not compatible, valueType = "<<valueType<<" ["<<getTypeName(valueType)<<"] , sourceType="<<sourceType<<" ["<<getTypeName(sourceType)<<"]"<<std::endl; return false; } } else { OSG_INFO<<"ClassInterface::copyPropertyObjectFromObject() no serializer available."<<std::endl; return false; } } bool ClassInterface::copyPropertyObjectToObject(osg::Object* object, const std::string& propertyName, const void* valuePtr, unsigned int /*valueSize*/, osgDB::BaseSerializer::Type valueType) { osgDB::BaseSerializer::Type destinationType; osgDB::BaseSerializer* serializer = getSerializer(object, propertyName, destinationType); if (serializer) { if (areTypesCompatible(valueType, destinationType)) { return serializer->set(*object, const_cast<void*>(valuePtr)); } else { OSG_NOTICE<<"ClassInterface::copyPropertyObjectToObject() Types are not compatible, valueType = "<<valueType<<", destinationType="<<destinationType<<std::endl; return false; } } else { OSG_INFO<<"ClassInterface::copyPropertyObjectToObject() no serializer available."<<std::endl; return false; } } class GetPropertyType : public osg::ValueObject::GetValueVisitor { public: GetPropertyType(): type(osgDB::BaseSerializer::RW_UNDEFINED) {} osgDB::BaseSerializer::Type type; virtual void apply(bool /*value*/) { type = osgDB::BaseSerializer::RW_BOOL; } virtual void apply(char /*value*/) { type = osgDB::BaseSerializer::RW_CHAR; } virtual void apply(unsigned char /*value*/) { type = osgDB::BaseSerializer::RW_UCHAR; } virtual void apply(short /*value*/) { type = osgDB::BaseSerializer::RW_SHORT; } virtual void apply(unsigned short /*value*/) { type = osgDB::BaseSerializer::RW_USHORT; } virtual void apply(int /*value*/) { type = osgDB::BaseSerializer::RW_INT; } virtual void apply(unsigned int /*value*/) { type = osgDB::BaseSerializer::RW_UINT; } virtual void apply(float /*value*/) { type = osgDB::BaseSerializer::RW_FLOAT; } virtual void apply(double /*value*/) { type = osgDB::BaseSerializer::RW_DOUBLE; } virtual void apply(const std::string& /*value*/) { type = osgDB::BaseSerializer::RW_STRING; } virtual void apply(const osg::Vec2f& /*value*/) { type = osgDB::BaseSerializer::RW_VEC2F; } virtual void apply(const osg::Vec3f& /*value*/) { type = osgDB::BaseSerializer::RW_VEC3F; } virtual void apply(const osg::Vec4f& /*value*/) { type = osgDB::BaseSerializer::RW_VEC4F; } virtual void apply(const osg::Vec2d& /*value*/) { type = osgDB::BaseSerializer::RW_VEC2D; } virtual void apply(const osg::Vec3d& /*value*/) { type = osgDB::BaseSerializer::RW_VEC3D; } virtual void apply(const osg::Vec4d& /*value*/) { type = osgDB::BaseSerializer::RW_VEC4D; } virtual void apply(const osg::Quat& /*value*/) { type = osgDB::BaseSerializer::RW_QUAT; } virtual void apply(const osg::Plane& /*value*/) { type = osgDB::BaseSerializer::RW_PLANE; } virtual void apply(const osg::Matrixf& /*value*/) { type = osgDB::BaseSerializer::RW_MATRIXF; } virtual void apply(const osg::Matrixd& /*value*/) { type = osgDB::BaseSerializer::RW_MATRIXD; } virtual void apply(const osg::BoundingBoxf& /*value*/) { type = osgDB::BaseSerializer::RW_BOUNDINGBOXF; } virtual void apply(const osg::BoundingBoxd& /*value*/) { type = osgDB::BaseSerializer::RW_BOUNDINGBOXD; } virtual void apply(const osg::BoundingSpheref& /*value*/) { type = osgDB::BaseSerializer::RW_BOUNDINGSPHEREF; } virtual void apply(const osg::BoundingSphered& /*value*/) { type = osgDB::BaseSerializer::RW_BOUNDINGSPHERED; } }; bool ClassInterface::getPropertyType(const osg::Object* object, const std::string& propertyName, osgDB::BaseSerializer::Type& type) const { if (getSerializer(object, propertyName, type)!=0) return true; const osg::UserDataContainer* udc = object->getUserDataContainer(); const osg::Object* userObject = udc ? udc->getUserObject(propertyName) : 0; if (userObject) { const osg::ValueObject* valueObject = dynamic_cast<const osg::ValueObject*>(userObject); if (valueObject) { GetPropertyType gpt; valueObject->get(gpt); type = gpt.type; return gpt.type!=osgDB::BaseSerializer::RW_UNDEFINED; } } return false; } bool ClassInterface::getSupportedProperties(const osg::Object* object, PropertyMap& properties, bool searchAssociates) const { osgDB::ObjectWrapper* ow = getObjectWrapper(object); if (!ow) { return false; } std::string compoundClassName = object->getCompoundClassName(); ObjectPropertyMap::const_iterator wl_itr = _whiteList.find(compoundClassName); if (wl_itr != _whiteList.end()) { properties = wl_itr->second; } ObjectPropertyMap::const_iterator bl_itr = _blackList.find(compoundClassName); if (searchAssociates) { const ObjectWrapper::RevisionAssociateList& associates = ow->getAssociates(); for(ObjectWrapper::RevisionAssociateList::const_iterator aitr = associates.begin(); aitr != associates.end(); ++aitr) { osgDB::ObjectWrapper* associate_wrapper = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(aitr->_name); if (associate_wrapper) { const osgDB::ObjectWrapper::SerializerList& associate_serializers = associate_wrapper->getSerializerList(); unsigned int i=0; for(osgDB::ObjectWrapper::SerializerList::const_iterator sitr = associate_serializers.begin(); sitr != associate_serializers.end(); ++sitr, ++i) { const std::string& propertyName = (*sitr)->getName(); bool notBlackListed = (bl_itr == _blackList.end()) || (bl_itr->second.count(propertyName)==0); if (notBlackListed) properties[propertyName] = associate_wrapper->getTypeList()[i]; } } } } else { const osgDB::ObjectWrapper::SerializerList& serializers = ow->getSerializerList(); unsigned int i=0; for(osgDB::ObjectWrapper::SerializerList::const_iterator itr = serializers.begin(); itr != serializers.end(); ++itr, ++i) { const std::string& propertyName = (*itr)->getName(); bool notBlackListed = (bl_itr == _blackList.end()) || (bl_itr->second.count(propertyName)==0); if (notBlackListed) properties[propertyName] = ow->getTypeList()[i]; } } return true; } bool ClassInterface::isObjectOfType(const osg::Object* object, const std::string& compoundClassName) const { if (!object) return false; if (object->getCompoundClassName()==compoundClassName) return true; osgDB::ObjectWrapper* ow = getObjectWrapper(object); if (!ow) { return false; } const ObjectWrapper::RevisionAssociateList& associates = ow->getAssociates(); for(ObjectWrapper::RevisionAssociateList::const_iterator aitr = associates.begin(); aitr != associates.end(); ++aitr) { if ((aitr->_name)==compoundClassName) return true; } return false; } bool ClassInterface::run(void* objectPtr, const std::string& compoundClassName, const std::string& methodName, osg::Parameters& inputParameters, osg::Parameters& outputParameters) const { ObjectWrapper* ow = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(compoundClassName); if (!ow) return false; const ObjectWrapper::MethodObjectMap& ow_methodObjectMap = ow->getMethodObjectMap(); for(ObjectWrapper::MethodObjectMap::const_iterator itr = ow_methodObjectMap.find(methodName); (itr!=ow_methodObjectMap.end()) && (itr->first==methodName); ++itr) { MethodObject* mo = itr->second.get(); if (mo->run(objectPtr, inputParameters, outputParameters)) return true; } const ObjectWrapper::RevisionAssociateList& associates = ow->getAssociates(); for(ObjectWrapper::RevisionAssociateList::const_iterator aitr = associates.begin(); aitr != associates.end(); ++aitr) { osgDB::ObjectWrapper* aow = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(aitr->_name); if (aow) { const ObjectWrapper::MethodObjectMap& methodObjectMap = aow->getMethodObjectMap(); for(ObjectWrapper::MethodObjectMap::const_iterator itr = methodObjectMap.find(methodName); (itr!=methodObjectMap.end()) && (itr->first==methodName); ++itr) { MethodObject* mo = itr->second.get(); if (mo->run(objectPtr, inputParameters, outputParameters)) return true; } } } return false; } bool ClassInterface::run(osg::Object* object, const std::string& methodName, osg::Parameters& inputParameters, osg::Parameters& outputParameters) const { return run(object, object->getCompoundClassName(), methodName, inputParameters, outputParameters); } bool ClassInterface::hasMethod(const std::string& compoundClassName, const std::string& methodName) const { ObjectWrapper* ow = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(compoundClassName); if (!ow) return false; const ObjectWrapper::MethodObjectMap& ow_methodObjectMap = ow->getMethodObjectMap(); ObjectWrapper::MethodObjectMap::const_iterator oitr = ow_methodObjectMap.find(methodName); if (oitr!=ow_methodObjectMap.end()) return true; const ObjectWrapper::RevisionAssociateList& associates = ow->getAssociates(); for(ObjectWrapper::RevisionAssociateList::const_iterator aitr = associates.begin(); aitr != associates.end(); ++aitr) { osgDB::ObjectWrapper* aow = osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper(aitr->_name); if (aow) { const ObjectWrapper::MethodObjectMap& methodObjectMap = aow->getMethodObjectMap(); ObjectWrapper::MethodObjectMap::const_iterator itr = methodObjectMap.find(methodName); if (itr!=methodObjectMap.end()) return true; } } return false; } bool ClassInterface::hasMethod(const osg::Object* object, const std::string& methodName) const { return hasMethod(object->getCompoundClassName(), methodName); } } // end of osgDB namespace
37.677419
242
0.660144
[ "object", "vector" ]
df0e48f56584c5ad2aba8f1459b590a3c7c44901
10,888
cpp
C++
src/gtest/utils.cpp
lanamineh/qsl
7e339d2345297709ef817d78ae3a52a33b1c8614
[ "Apache-2.0" ]
null
null
null
src/gtest/utils.cpp
lanamineh/qsl
7e339d2345297709ef817d78ae3a52a33b1c8614
[ "Apache-2.0" ]
null
null
null
src/gtest/utils.cpp
lanamineh/qsl
7e339d2345297709ef817d78ae3a52a33b1c8614
[ "Apache-2.0" ]
null
null
null
/* * Authors: Lana Mineh and John Scott * Copyright 2021 Phasecraft Ltd. and John Scott * * 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 utils.cpp * \brief Contains tests for utility functions */ #include <gtest/gtest.h> #include <qsl/utils.hpp> #include <list> #include <sstream> #include <qsl/qubits.hpp> /** * \brief Typed test suite for the floating point utilities * * This test suite checks the utilities that depend on a floating * point parameter for both float and double. */ template <typename T> class FpUtilities : public testing::Test { public: using List = std::list<T>; static T shared_; T value_; }; /// List of floating point types to check using FpTypes = ::testing::Types<double, float>; /** * \brief Declare the test suite that depends on these types * * To use the test suite, write TYPED_TEST(FpUtilities... * and then use TypeParam wherever you would use a type from the * FpTypes list. The test suite will automatically be performed * for every type in the list. * */ TYPED_TEST_SUITE(FpUtilities, FpTypes); /// Test the combinations function TEST(Utilities, ChooseFunctionTest) { EXPECT_EQ(qsl::choose(1,1), 1); EXPECT_EQ(qsl::choose(4,3), 4); EXPECT_EQ(qsl::choose(10,3), 120); EXPECT_EQ(qsl::choose(10,10), 1); } /// Test overloaded vector substraction function TYPED_TEST(FpUtilities, VectorSubtraction) { const unsigned num_qubits{ 5 }; const std::vector<qsl::complex<TypeParam>> state1 = qsl::makeRandomState<TypeParam>(num_qubits); const std::vector<qsl::complex<TypeParam>> state2 = qsl::makeRandomState<TypeParam>(num_qubits + 1); // Cannot subtract vectors of different sizes EXPECT_THROW(state1 - state2, std::logic_error); } /// Test the convertState function TEST(Utilities, ConvertStateTest) { const unsigned num_qubits{ 5 }; // Make a random state of doubles const std::vector<qsl::complex<double>> state_double = qsl::makeRandomState<double>(num_qubits); // Convert it to floats const std::vector<qsl::complex<float>> state_float = qsl::convertState<float>(state_double); // Check the two states are equal by verifying all double val = 0; for (std::size_t n = 0; n < state_float.size(); n++) { val += std::abs(state_double[n].real - state_float[n].real); val += std::abs(state_double[n].imag - state_float[n].imag); } // What is a reasonable number to put here? EXPECT_NEAR(val,0,1e-5); } /// Test the convertVector function TEST(Utilities, ConvertVectorTest) { // Make a test vector const std::vector<double> vec{ 1,3.2,3,4.9,3.2 }; const std::vector<float> copy{ qsl::convertVector<float>(vec) }; // Check that the two are equal EXPECT_EQ(copy.size(), vec.size()); for (std::size_t n = 0; n < vec.size(); n++) { EXPECT_FLOAT_EQ(vec[n], copy[n]); } } /// Test the innerProduct function TYPED_TEST(FpUtilities, InnerProductTest) { const std::vector<qsl::complex<TypeParam>> a{ {1,1.2}, {1.2,1}, {1,1.5} }; const std::vector<qsl::complex<TypeParam>> b{ {1,0}, {0,-1}, {-1,0} }; const std::vector<qsl::complex<TypeParam>> c{ {1.2,0}, {1.2,-2.1}, {1.3,2}, {0,0} }; // Check that inner product throws exception for different sized vectors EXPECT_THROW(innerProduct(a,c), std::logic_error); } /// Test the checkStateSize function TYPED_TEST(FpUtilities, CheckStateSizeTest) { // Not a valid state size, should throw exception const std::vector<qsl::complex<TypeParam>> pretend_state{ {1,0}, {0,1}, {1,1} }; EXPECT_THROW(checkStateSize(pretend_state), std::logic_error); // Check that the function returns the correct state size const std::vector<qsl::complex<TypeParam>> state{ {1,0}, {0,1}, {1,0}, {0,1} }; EXPECT_EQ(checkStateSize(state), 2); } /// Test Fubini Study distance TYPED_TEST(FpUtilities, FubiniStudyTest) { std::vector<qsl::complex<TypeParam>> a{ {1,0}, {0,1}, {1,1} }; std::vector<qsl::complex<TypeParam>> TypeParam_a{ {2,0}, {0,2}, {2,2} }; std::vector<qsl::complex<TypeParam>> b{ {1.3,2}, {1,1.3}, {1.5,0.2} }; std::vector<qsl::complex<TypeParam>> TypeParam_b{ {2.6,4}, {2,2.6}, {3,0.4} }; // Test that distance between equal and scaled vectors is zero EXPECT_NEAR(fubiniStudy(a,a), 0, 1e-13); EXPECT_NEAR(fubiniStudy(TypeParam_a,a), 0, 1e-13); TypeParam distance_a_b = fubiniStudy(a,b); TypeParam scaled_distance_a_b = fubiniStudy(a,TypeParam_b); EXPECT_NEAR(std::abs(distance_a_b - scaled_distance_a_b), 0, 1e-13); } /// Simulator distances TYPED_TEST(FpUtilities, FubiniStudySimulatorTest) { qsl::Qubits<qsl::Type::Default, TypeParam> q1{3}; qsl::Qubits<qsl::Type::Resize, TypeParam> q2{3}; // Test that distance between equal simulators is zero EXPECT_NEAR(fubiniStudy(q1,q2), 0, 1e-13); // Perform some gates q1.rotateX(0, 1.2); q1.rotateY(1, -0.3); q1.rotateZ(2, 2.4); // Check that the fubini-study distance for the simulators // comes out the same as for the vectors TypeParam a = fubiniStudy(q1,q2); TypeParam b = fubiniStudy(q1.getState(),q2.getState()); EXPECT_NEAR(a, b, 1e-13); } /// Check the next (number with fixed number of ones) function TEST(Utilities, NextFunctionTest) { std::size_t x{ 0b111 }; qsl::next(x); EXPECT_EQ(x,0b1011); qsl::next(x); EXPECT_EQ(x,0b1101); qsl::next(x); EXPECT_EQ(x,0b1110); qsl::next(x); EXPECT_EQ(x,0b10011); qsl::next(x); EXPECT_EQ(x,0b10101); qsl::next(x); EXPECT_EQ(x,0b10110); qsl::next(x); EXPECT_EQ(x,0b11001); qsl::next(x); EXPECT_EQ(x,0b11010); qsl::next(x); EXPECT_EQ(x,0b11100); } /// Test the hamming weight function TEST(Utilities, HammingWeightTest) { EXPECT_EQ(qsl::hammingWeight(0b11011010), 5); EXPECT_EQ(qsl::hammingWeight(0b1010), 2); EXPECT_EQ(qsl::hammingWeight(0b1), 1); EXPECT_EQ(qsl::hammingWeight(0b0), 0); } /// Test the complex struct TYPED_TEST(FpUtilities, ComplexStructTest) { // Check explicit assignment qsl::complex<TypeParam> x0{ .real = 1, .imag = 3}; EXPECT_EQ(x0.real, 1); EXPECT_EQ(x0.imag, 3); // Check real,imag constructor qsl::complex<TypeParam> x1{-1,4.5}; EXPECT_EQ(x1.real, -1); EXPECT_EQ(x1.imag, 4.5); // Check default constructor qsl::complex<TypeParam> x2; EXPECT_EQ(x2.real, 0); EXPECT_EQ(x2.imag, 0); // Check substraction EXPECT_EQ((x0 - x1).real, 2); EXPECT_EQ((x0 - x1).imag, -1.5); } /// Test absolute value function TYPED_TEST(FpUtilities, AbsTest) { qsl::complex<TypeParam> x0; EXPECT_FLOAT_EQ(qsl::abs(x0), 0); qsl::complex<TypeParam> x1{1,0}; EXPECT_FLOAT_EQ(qsl::abs(x1), 1); qsl::complex<TypeParam> x2{0,1}; EXPECT_FLOAT_EQ(qsl::abs(x2), 1); qsl::complex<TypeParam> x3{0,-1}; EXPECT_FLOAT_EQ(qsl::abs(x3), 1); qsl::complex<TypeParam> x4{1,-1}; EXPECT_FLOAT_EQ(qsl::abs(x4), std::sqrt(2)); } /// Test the random number generator class TYPED_TEST(FpUtilities, RandomClassTest) { // Check that a zero length range works qsl::Random<TypeParam> rand{1.2,1.2}; EXPECT_FLOAT_EQ(rand.getNum(), 1.2); ///\todo How to check that the distribution is uniform and random? } /// Test the random state generator class TYPED_TEST(FpUtilities, MakeRandomStateTest) { // Number of qubits const unsigned nqubits{ 5 }; // Check that a zero length range works std::vector<qsl::complex<TypeParam>> state{ qsl::makeRandomState<TypeParam>(nqubits) }; // Check there are the correct number of elements EXPECT_EQ(state.size(), 1 << nqubits); // Check that the state is normalised EXPECT_FLOAT_EQ(qsl::norm(state), 1); } /// Test the function which test for number-preserving states TYPED_TEST(FpUtilities, CheckStateNPTest) { // Number-preserved state std::vector<qsl::complex<TypeParam>> s0 { {0,0}, {0,1}, {1,0}, {0,0} }; qsl::normalise(s0); EXPECT_EQ(checkStateNP(s0), 1); // Edge-case no ones std::vector<qsl::complex<TypeParam>> s1 { {1,0}, {0,0}, {0,0}, {0,0} }; qsl::normalise(s1); EXPECT_EQ(checkStateNP(s1), 0); // Edge-case all ones std::vector<qsl::complex<TypeParam>> s2 { {0,0}, {0,0}, {0,0}, {1,0} }; qsl::normalise(s2); EXPECT_EQ(checkStateNP(s2), 2); // Non-number-preserved state std::vector<qsl::complex<TypeParam>> s3 { {1,0}, {0,1}, {1,0}, {0,0} }; qsl::normalise(s3); EXPECT_THROW(checkStateNP(s3), std::logic_error); } /// Test the random number-preserving state generator function TYPED_TEST(FpUtilities, MakeRandomNPStateTest) { // Number of qubits const unsigned nqubits{ 5 }; const unsigned nones{ 3 }; // Make a random number preserved state std::vector<qsl::complex<TypeParam>> state{ qsl::makeRandomNPState<TypeParam>(nqubits, nones) }; EXPECT_EQ(state.size(), 1 << nqubits); // Correct dimension EXPECT_FLOAT_EQ(qsl::norm(state), 1); // Is normalised EXPECT_EQ(checkStateNP(state), nones); // Correct number of ones // Check that random number of ones variant std::vector<qsl::complex<TypeParam>> state_random{ qsl::makeRandomNPState<TypeParam>(nqubits) }; EXPECT_EQ(state_random.size(), 1 << nqubits); // Correct dimension EXPECT_FLOAT_EQ(qsl::norm(state_random), 1); // Is normalised EXPECT_LE(checkStateNP(state_random), nqubits); // Is NP and nones <= nqubits } /// Check the random phases function TYPED_TEST(FpUtilities, RandomPhasesTest) { const std::size_t length{ 35 }; // Make a list of random phases std::vector<TypeParam> phases{ qsl::makeRandomPhases<TypeParam>(length) }; EXPECT_EQ(phases.size(), length); // Check correct length for (std::size_t n = 0; n < length; n++) { // Check elements are within the range -pi to pi EXPECT_LE(phases[n], M_PI); EXPECT_GE(phases[n], -M_PI); } } /// Test overloaded vector printing TEST(Utilities, VectorPrinting) { std::stringstream ss1, ss2; std::vector<int> vec { 1,2,5,4,4 }; ss1 << vec; // Check the correct thing is printed ss2 << 1 << std::endl << 2 << std::endl << 5 << std::endl << 4 << std::endl << 4 << std::endl; EXPECT_EQ(ss1.str(), ss2.str()); }
27.704835
84
0.660176
[ "vector" ]
df15ab4489ed5f9e1c49fb30fe52f8493512507f
17,509
hpp
C++
src/mlpack/methods/cf/cf_impl.hpp
haritha1313/mlpack
3b7bbf0f14172cdb00fd16cbf12918b07c888b96
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/cf/cf_impl.hpp
haritha1313/mlpack
3b7bbf0f14172cdb00fd16cbf12918b07c888b96
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/cf/cf_impl.hpp
haritha1313/mlpack
3b7bbf0f14172cdb00fd16cbf12918b07c888b96
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file cf_impl.hpp * @author Mudit Raj Gupta * @author Sumedh Ghaisas * * Collaborative Filtering. * * Implementation of CF class to perform Collaborative Filtering on the * specified data set. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_CF_CF_IMPL_HPP #define MLPACK_METHODS_CF_CF_IMPL_HPP // In case it hasn't been included yet. #include "cf.hpp" namespace mlpack { namespace cf { // Default CF constructor. template<typename NormalizationType> CFType<NormalizationType>::CFType(const size_t numUsersForSimilarity, const size_t rank) : numUsersForSimilarity(numUsersForSimilarity), rank(rank) { // Validate neighbourhood size. if (numUsersForSimilarity < 1) { Log::Warn << "CFType::CFType(): neighbourhood size should be > 0 (" << numUsersForSimilarity << " given). Setting value to 5.\n"; // Set default value of 5. this->numUsersForSimilarity = 5; } } /** * Construct the CF object using an instantiated decomposition policy. */ template<typename NormalizationType> template<typename MatType, typename DecompositionPolicy> CFType<NormalizationType>::CFType(const MatType& data, DecompositionPolicy& decomposition, const size_t numUsersForSimilarity, const size_t rank, const size_t maxIterations, const double minResidue, const bool mit) : numUsersForSimilarity(numUsersForSimilarity), rank(rank) { // Validate neighbourhood size. if (numUsersForSimilarity < 1) { Log::Warn << "CFType::CFType(): neighbourhood size should be > 0 (" << numUsersForSimilarity << " given). Setting value to 5.\n"; // Set default value of 5. this->numUsersForSimilarity = 5; } Train(data, decomposition, maxIterations, minResidue, mit); } // Train when data is given in dense matrix form. template<typename NormalizationType> template<typename DecompositionPolicy> void CFType<NormalizationType>::Train(const arma::mat& data, DecompositionPolicy& decomposition, const size_t maxIterations, const double minResidue, const bool mit) { // Make a copy of data before performing normalization. arma::mat normalizedData(data); normalization.Normalize(normalizedData); CleanData(normalizedData, cleanedData); // Check if the user wanted us to choose a rank for them. if (rank == 0) { // This is a simple heuristic that picks a rank based on the density of the // dataset between 5 and 105. const double density = (cleanedData.n_nonzero * 100.0) / cleanedData.n_elem; const size_t rankEstimate = size_t(density) + 5; // Set to heuristic value. Log::Info << "No rank given for decomposition; using rank of " << rankEstimate << " calculated by density-based heuristic." << std::endl; this->rank = rankEstimate; } // Decompose the data matrix (which is in coordinate list form) to user and // data matrices. Timer::Start("cf_factorization"); decomposition.Apply(normalizedData, cleanedData, rank, w, h, maxIterations, minResidue, mit); Timer::Stop("cf_factorization"); } // Train when data is given as sparse matrix of user item table. template<typename NormalizationType> template<typename DecompositionPolicy> void CFType<NormalizationType>::Train(const arma::sp_mat& data, DecompositionPolicy& decomposition, const size_t maxIterations, const double minResidue, const bool mit) { // data is not used in the following decomposition.Apply() method, so we only // need to Normalize cleanedData. cleanedData = data; normalization.Normalize(cleanedData); // Check if the user wanted us to choose a rank for them. if (rank == 0) { // This is a simple heuristic that picks a rank based on the density of the // dataset between 5 and 105. const double density = (cleanedData.n_nonzero * 100.0) / cleanedData.n_elem; const size_t rankEstimate = size_t(density) + 5; // Set to heuristic value. Log::Info << "No rank given for decomposition; using rank of " << rankEstimate << " calculated by density-based heuristic." << std::endl; this->rank = rankEstimate; } // Decompose the data matrix (which is in coordinate list form) to user and // data matrices. Timer::Start("cf_factorization"); decomposition.Apply(data, cleanedData, rank, w, h, maxIterations, minResidue, mit); Timer::Stop("cf_factorization"); } template<typename NormalizationType> template<typename NeighborSearchPolicy, typename InterpolationPolicy> void CFType<NormalizationType>::GetRecommendations( const size_t numRecs, arma::Mat<size_t>& recommendations) { // Generate list of users. Maybe it would be more efficient to pass an empty // users list, and then have the other overload of GetRecommendations() assume // that if users is empty, then recommendations should be generated for all // users? arma::Col<size_t> users = arma::linspace<arma::Col<size_t> >(0, cleanedData.n_cols - 1, cleanedData.n_cols); // Call the main overload for recommendations. GetRecommendations<NeighborSearchPolicy, InterpolationPolicy>(numRecs, recommendations, users); } template<typename NormalizationType> template<typename NeighborSearchPolicy, typename InterpolationPolicy> void CFType<NormalizationType>::GetRecommendations( const size_t numRecs, arma::Mat<size_t>& recommendations, const arma::Col<size_t>& users) { // We want to avoid calculating the full rating matrix, so we will do nearest // neighbor search only on the H matrix, using the observation that if the // rating matrix X = W*H, then d(X.col(i), X.col(j)) = d(W H.col(i), W // H.col(j)). This can be seen as nearest neighbor search on the H matrix // with the Mahalanobis distance where M^{-1} = W^T W. So, we'll decompose // M^{-1} = L L^T (the Cholesky decomposition), and then multiply H by L^T. // Then we can perform nearest neighbor search. arma::mat l = arma::chol(w.t() * w); arma::mat stretchedH = l * h; // Due to the Armadillo API, l is L^T. // Now, we will use the decomposed w and h matrices to estimate what the user // would have rated items as, and then pick the best items. // Temporarily store feature vector of queried users. arma::mat query(stretchedH.n_rows, users.n_elem); // Select feature vectors of queried users. for (size_t i = 0; i < users.n_elem; i++) query.col(i) = stretchedH.col(users(i)); // Temporary storage for neighborhood of the queried users. arma::Mat<size_t> neighborhood; // Calculate the neighborhood of the queried users. Note that the query user // is part of the neighborhood---this is intentional. We want to use the // weighted sum of both the query user and the local neighborhood of the // query user. // Calculate the neighborhood of the queried users. NeighborSearchPolicy neighborSearch(stretchedH); arma::mat similarities; // Resulting similarities. neighborSearch.Search( query, numUsersForSimilarity, neighborhood, similarities); // Generate recommendations for each query user by finding the maximum numRecs // elements in the ratings vector. recommendations.set_size(numRecs, users.n_elem); arma::mat values(numRecs, users.n_elem); recommendations.fill(SIZE_MAX); values.fill(DBL_MAX); // Initialization of an InterpolationPolicy object should be put ahead of the // following loop, because the initialization may takes a relatively long // time and we don't want to repeat the initialization process in each loop. InterpolationPolicy interpolation(cleanedData); for (size_t i = 0; i < users.n_elem; i++) { // First, calculate the weighted sum of neighborhood values. arma::vec ratings; ratings.zeros(cleanedData.n_rows); // Calculate interpolation weights. arma::vec weights(numUsersForSimilarity); interpolation.GetWeights(weights, w, h, users(i), neighborhood.col(i), similarities.col(i), cleanedData); for (size_t j = 0; j < neighborhood.n_rows; ++j) ratings += weights(j) * (w * h.col(neighborhood(j, i))); // Let's build the list of candidate recomendations for the given user. // Default candidate: the smallest possible value and invalid item number. const Candidate def = std::make_pair(-DBL_MAX, cleanedData.n_rows); std::vector<Candidate> vect(numRecs, def); typedef std::priority_queue<Candidate, std::vector<Candidate>, CandidateCmp> CandidateList; CandidateList pqueue(CandidateCmp(), std::move(vect)); // Look through the ratings column corresponding to the current user. for (size_t j = 0; j < ratings.n_rows; ++j) { // Ensure that the user hasn't already rated the item. // The algorithm omits rating of zero. Thus, when normalizing original // ratings in Normalize(), if normalized rating equals zero, it is set // to the smallest positive double value. if (cleanedData(j, users(i)) != 0.0) continue; // The user already rated the item. // Is the estimated value better than the worst candidate? // Denormalize rating before comparison. double realRating = normalization.Denormalize(users(i), j, ratings[j]); if (realRating > pqueue.top().first) { Candidate c = std::make_pair(realRating, j); pqueue.pop(); pqueue.push(c); } } for (size_t p = 1; p <= numRecs; p++) { recommendations(numRecs - p, i) = pqueue.top().second; values(numRecs - p, i) = pqueue.top().first; pqueue.pop(); } // If we were not able to come up with enough recommendations, issue a // warning. if (recommendations(numRecs - 1, i) == def.second) Log::Warn << "Could not provide " << numRecs << " recommendations " << "for user " << users(i) << " (not enough un-rated items)!" << std::endl; } } // Predict the rating for a single user/item combination. template<typename NormalizationType> template<typename NeighborSearchPolicy, typename InterpolationPolicy> double CFType<NormalizationType>::Predict(const size_t user, const size_t item) const { // First, we need to find the nearest neighbors of the given user. // We'll use the same technique as for GetRecommendations(). // We want to avoid calculating the full rating matrix, so we will do nearest // neighbor search only on the H matrix, using the observation that if the // rating matrix X = W*H, then d(X.col(i), X.col(j)) = d(W H.col(i), W // H.col(j)). This can be seen as nearest neighbor search on the H matrix // with the Mahalanobis distance where M^{-1} = W^T W. So, we'll decompose // M^{-1} = L L^T (the Cholesky decomposition), and then multiply H by L^T. // Then we can perform nearest neighbor search. arma::mat l = arma::chol(w.t() * w); arma::mat stretchedH = l * h; // Due to the Armadillo API, l is L^T. // Now, we will use the decomposed w and h matrices to estimate what the user // would have rated items as, and then pick the best items. // Temporarily store feature vector of queried users. arma::mat query = stretchedH.col(user); // Temporary storage for neighborhood of the queried users. arma::Mat<size_t> neighborhood; // Calculate the neighborhood of the queried users. NeighborSearchPolicy neighborSearch(stretchedH); arma::mat similarities; // Resulting similarities. neighborSearch.Search( query, numUsersForSimilarity, neighborhood, similarities); arma::vec weights(numUsersForSimilarity); // Calculate interpolation weights. InterpolationPolicy interpolation(cleanedData); interpolation.GetWeights(weights, w, h, user, neighborhood.col(0), similarities.col(0), cleanedData); double rating = 0; // We'll take the weighted sum of neighborhood values. for (size_t j = 0; j < neighborhood.n_rows; ++j) { rating += weights(j) * arma::as_scalar(w.row(item) * h.col(neighborhood(j, 0))); } // Denormalize rating and return. double realRating = normalization.Denormalize(user, item, rating); return realRating; } // Predict the rating for a group of user/item combinations. template<typename NormalizationType> template<typename NeighborSearchPolicy, typename InterpolationPolicy> void CFType<NormalizationType>::Predict(const arma::Mat<size_t>& combinations, arma::vec& predictions) const { // First, for nearest neighbor search, stretch the H matrix. arma::mat l = arma::chol(w.t() * w); arma::mat stretchedH = l * h; // Due to the Armadillo API, l is L^T. // Now, we must determine those query indices we need to find the nearest // neighbors for. This is easiest if we just sort the combinations matrix. arma::Mat<size_t> sortedCombinations(combinations.n_rows, combinations.n_cols); arma::uvec ordering = arma::sort_index(combinations.row(0).t()); for (size_t i = 0; i < ordering.n_elem; ++i) sortedCombinations.col(i) = combinations.col(ordering[i]); // Now, we have to get the list of unique users we will be searching for. arma::Col<size_t> users = arma::unique(combinations.row(0).t()); // Assemble our query matrix from the stretchedH matrix. arma::mat queries(stretchedH.n_rows, users.n_elem); for (size_t i = 0; i < queries.n_cols; ++i) queries.col(i) = stretchedH.col(users[i]); // Temporary storage for neighborhood of the queried users. arma::Mat<size_t> neighborhood; // Now calculate the neighborhood of these users. NeighborSearchPolicy neighborSearch(stretchedH); arma::mat similarities; // Resulting similarities. neighborSearch.Search( queries, numUsersForSimilarity, neighborhood, similarities); arma::mat weights(numUsersForSimilarity, users.n_elem); // Calculate interpolation weights. InterpolationPolicy interpolation(cleanedData); for (size_t i = 0; i < users.n_elem; i++) { interpolation.GetWeights(weights.col(i), w, h, users[i], neighborhood.col(i), similarities.col(i), cleanedData); } // Now that we have the neighborhoods we need, calculate the predictions. predictions.set_size(combinations.n_cols); size_t user = 0; // Cumulative user count, because we are doing it in order. for (size_t i = 0; i < sortedCombinations.n_cols; ++i) { // Could this be made faster by calculating dot products for multiple items // at once? double rating = 0.0; // Map the combination's user to the user ID used for kNN. while (users[user] < sortedCombinations(0, i)) ++user; for (size_t j = 0; j < neighborhood.n_rows; ++j) { rating += weights(j, user) * arma::as_scalar( w.row(sortedCombinations(1, i)) * h.col(neighborhood(j, user))); } predictions(ordering[i]) = rating; } // Denormalize ratings. normalization.Denormalize(combinations, predictions); } template<typename NormalizationType> void CFType<NormalizationType>::CleanData(const arma::mat& data, arma::sp_mat& cleanedData) { // Generate list of locations for batch insert constructor for sparse // matrices. arma::umat locations(2, data.n_cols); arma::vec values(data.n_cols); for (size_t i = 0; i < data.n_cols; ++i) { // We have to transpose it because items are rows, and users are columns. locations(1, i) = ((arma::uword) data(0, i)); locations(0, i) = ((arma::uword) data(1, i)); values(i) = data(2, i); // The algorithm omits rating of zero. Thus, when normalizing original // ratings in Normalize(), if normalized rating equals zero, it is set // to the smallest positive double value. if (values(i) == 0) Log::Warn << "User rating of 0 ignored for user " << locations(1, i) << ", item " << locations(0, i) << "." << std::endl; } // Find maximum user and item IDs. const size_t maxItemID = (size_t) max(locations.row(0)) + 1; const size_t maxUserID = (size_t) max(locations.row(1)) + 1; // Fill sparse matrix. cleanedData = arma::sp_mat(locations, values, maxItemID, maxUserID); } //! Serialize the model. template<typename NormalizationType> template<typename Archive> void CFType<NormalizationType>::serialize(Archive& ar, const unsigned int /* version */) { // This model is simple; just serialize all the members. No special handling // required. ar & BOOST_SERIALIZATION_NVP(numUsersForSimilarity); ar & BOOST_SERIALIZATION_NVP(rank); ar & BOOST_SERIALIZATION_NVP(w); ar & BOOST_SERIALIZATION_NVP(h); ar & BOOST_SERIALIZATION_NVP(cleanedData); ar & BOOST_SERIALIZATION_NVP(normalization); } } // namespace cf } // namespace mlpack #endif
38.736726
80
0.676452
[ "object", "vector", "model" ]
b30da183c33863e1e9310912377d4f07c843f3ed
153
cpp
C++
ComputingTheLongestCommonPrefixArray/ComputingTheLongestCommonPrefixArray/CPPAppendix.cpp
TomoGudelj/Computing-the-longest-common-prefix
6fd891f8c51ffa1057a1394d404d6ee9a7c50c0c
[ "MIT" ]
null
null
null
ComputingTheLongestCommonPrefixArray/ComputingTheLongestCommonPrefixArray/CPPAppendix.cpp
TomoGudelj/Computing-the-longest-common-prefix
6fd891f8c51ffa1057a1394d404d6ee9a7c50c0c
[ "MIT" ]
null
null
null
ComputingTheLongestCommonPrefixArray/ComputingTheLongestCommonPrefixArray/CPPAppendix.cpp
TomoGudelj/Computing-the-longest-common-prefix
6fd891f8c51ffa1057a1394d404d6ee9a7c50c0c
[ "MIT" ]
null
null
null
#include "CPPAppendix.h" //template<typename T> int IndexOf(std::vector<T> &vec, T el) //{ // return find(vec.begin(), vec.end(), el) - vec.begin(); //}
25.5
61
0.627451
[ "vector" ]
b30e31765f18b51fa71206e8f4edcbd0c759f33e
17,642
hpp
C++
include/PSkelMap.hpp
lapesd/PSkel-MPPA-Async
b508a114d7e8ece2214337c568fb15738c5077b1
[ "BSD-3-Clause" ]
null
null
null
include/PSkelMap.hpp
lapesd/PSkel-MPPA-Async
b508a114d7e8ece2214337c568fb15738c5077b1
[ "BSD-3-Clause" ]
null
null
null
include/PSkelMap.hpp
lapesd/PSkel-MPPA-Async
b508a114d7e8ece2214337c568fb15738c5077b1
[ "BSD-3-Clause" ]
null
null
null
//------------------------------------------------------------------------------- // Copyright (c) 2015, Alyson D. Pereira <alyson.deives@outlook.com>, // Rodrigo C. O. Rocha <rcor.cs@gmail.com> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 PSKEL_MAP_HPP #define PSKEL_MAP_HPP #include <algorithm> #include <cmath> #ifdef PSKEL_TBB #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> #include <tbb/task_scheduler_init.h> #endif namespace PSkel{ #ifdef PSKEL_CUDA //******************************************************************************************** // Kernels CUDA. Chama o kernel implementado pelo usuario //******************************************************************************************** template<typename T1, class Args> __global__ void mapCU(Array<T1> input,Array<T1> output,Args args); template<typename T1, class Args> __global__ void mapCU2D(Array2D<T1> input,Array2D<T1> output,Args args); template<typename T1, class Args> __global__ void mapCU3D(Array3D<T1> input,Array3D<T1> output,Args args); //******************************************************************************************** // Kernels CUDA. Chama o kernel implementado pelo usuario //******************************************************************************************** template<typename T1, class Args> __global__ void mapCU(Array<T1> input,Array<T1> output, Args args){ size_t i = blockIdx.x*blockDim.x+threadIdx.x; if(i<input.getWidth()){ mapKernel(input, output, args, i); } } template<typename T1, class Args> __global__ void mapCU2D(Array2D<T1> input,Array2D<T1> output,Args args){ size_t w = blockIdx.x*blockDim.x+threadIdx.x; size_t h = blockIdx.y*blockDim.y+threadIdx.y; if(w<input.getWidth() && h<input.getHeight()){ mapKernel(input, output, args, h, w); } } template<typename T1, class Args> __global__ void mapCU3D(Array3D<T1> input,Array3D<T1> output,Args args){ size_t w = blockIdx.x*blockDim.x+threadIdx.x; size_t h = blockIdx.y*blockDim.y+threadIdx.y; size_t d = blockIdx.z*blockDim.z+threadIdx.z; if(w<input.getWidth() && h<input.getHeight() && d<input.getDepth()){ mapKernel(input, output, args, h, w,d); } } #endif //******************************************************************************************* // Stencil Base //******************************************************************************************* template<class Arrays, class Args> void MapBase<Arrays, Args>::runSequential(){ this->runSeq(this->input, this->output); } template<class Arrays, class Args> void MapBase<Arrays, Args>::runCPU(size_t numThreads){ numThreads = (numThreads==0)?omp_get_num_procs():numThreads; #ifdef PSKEL_TBB this->runTBB(this->input, this->output, numThreads); #else this->runOpenMP(this->input, this->output, numThreads); #endif } #ifdef PSKEL_CUDA template<class Arrays, class Args> void MapBase<Arrays, Args>::runGPU(size_t blockSize){ if(blockSize==0){ int device; cudaGetDevice(&device); cudaDeviceProp deviceProperties; cudaGetDeviceProperties(&deviceProperties, device); blockSize = deviceProperties.warpSize; } input.deviceAlloc(); output.deviceAlloc(); input.copyToDevice(); this->runCUDA(this->input, this->output, blockSize); output.copyToHost(); input.deviceFree(); output.deviceFree(); } #endif /* template<class Arrays, class Args> void MapBase<Arrays, Args>::runHybrid(float GPUPartition, size_t GPUBlockSize, size_t numThreads){ if(GPUPartition==0.0){ runCPU(numThreads); }else if(GPUPartition==1.0){ runGPU(GPUBlockSize); }else{ Arrays inputSliceGPU; Arrays outputSliceGPU; Arrays inputSliceCPU; Arrays outputSliceCPU; if(input.getHeight()>1){ size_t GPUHeight = size_t(this->input.getHeight()*GPUPartition); inputSliceGPU.hostSlice(this->input, 0, 0, 0, this->input.getWidth(), GPUHeight, this->input.getDepth()); outputSliceGPU.hostSlice(this->output, 0, 0, 0, this->output.getWidth(), GPUHeight, this->output.getDepth()); inputSliceCPU.hostSlice(this->input, 0, GPUHeight, 0, this->input.getWidth(), this->input.getHeight()-GPUHeight, this->input.getDepth()); outputSliceCPU.hostSlice(this->output, 0, GPUHeight, 0, this->output.getWidth(), this->output.getHeight()-GPUHeight, this->output.getDepth()); }else{ size_t GPUWidth= size_t(this->input.getWidth()*GPUPartition); inputSliceGPU.hostSlice(this->input, 0, 0, 0, GPUWidth, this->input.getHeight(), this->input.getDepth()); outputSliceGPU.hostSlice(this->output, 0, 0, 0, GPUWidth, this->output.getHeight(), this->output.getDepth()); inputSliceCPU.hostSlice(this->input, GPUWidth, 0, 0, this->input.getWidth()-GPUWidth, this->input.getHeight(), this->input.getDepth()); outputSliceCPU.hostSlice(this->output, GPUWidth, 0, 0, this->output.getWidth()-GPUWidth, this->output.getHeight(), this->output.getDepth()); } omp_set_num_threads(2); #pragma omp parallel sections { #pragma omp section { inputSliceGPU.deviceAlloc(); inputSliceGPU.copyToDevice(); outputSliceGPU.deviceAlloc(); this->runCUDA(inputSliceGPU, outputSliceGPU, GPUBlockSize); outputSliceGPU.copyToHost(); inputSliceGPU.deviceFree(); outputSliceGPU.deviceFree(); } #pragma omp section { this->runTBB(inputSliceCPU, outputSliceCPU,numThreads); } } } } */ template<class Arrays, class Args> void MapBase<Arrays, Args>::runIterativeSequential(size_t iterations){ Arrays inputCopy; inputCopy.hostClone(input); for(size_t it = 0; it<iterations; it++){ if(it%2==0) this->runSeq(inputCopy, this->output); else this->runSeq(this->output, inputCopy); } if((iterations%2)==0) output.hostMemCopy(inputCopy); inputCopy.hostFree(); } template<class Arrays, class Args> void MapBase<Arrays, Args>::runIterativeCPU(size_t iterations, size_t numThreads){ numThreads = (numThreads==0)?omp_get_num_procs():numThreads; Arrays inputCopy; inputCopy.hostClone(input); for(size_t it = 0; it<iterations; it++){ if(it%2==0){ #ifdef PSKEL_TBB this->runTBB(inputCopy, this->output, numThreads); #else this->runOpenMP(inputCopy, this->output, numThreads); #endif }else { #ifdef PSKEL_TBB this->runTBB(this->output, inputCopy, numThreads); #else this->runOpenMP(this->output, inputCopy, numThreads); #endif } } if((iterations%2)==0) output.hostMemCopy(inputCopy); inputCopy.hostFree(); } #ifdef PSKEL_CUDA template<class Arrays, class Args> void MapBase<Arrays, Args>::runIterativeGPU(size_t iterations, size_t blockSize){ if(blockSize==0){ int device; cudaGetDevice(&device); cudaDeviceProp deviceProperties; cudaGetDeviceProperties(&deviceProperties, device); blockSize = deviceProperties.warpSize; } input.deviceAlloc(); input.copyToDevice(); output.deviceAlloc(); for(size_t it = 0; it<iterations; it++){ if((it%2)==0) this->runCUDA(this->input, this->output, blockSize); else this->runCUDA(this->output, this->input, blockSize); } if((iterations%2)==1) output.copyToHost(); else output.copyFromDevice(input); input.deviceFree(); output.deviceFree(); } #endif /* template<class Arrays, class Args> void MapBase<Arrays, Args>::runIterativeHybrid(size_t iterations, float GPUPartition, size_t GPUBlockSize, size_t numThreads){ if(GPUPartition==0.0){ runIterativeCPU(iterations, numThreads); }else if(GPUPartition==1.0){ runIterativeGPU(iterations, GPUBlockSize); }else{ Arrays inputSliceGPU; Arrays outputSliceGPU; Arrays inputSliceCPU; Arrays outputSliceCPU; if(input.getHeight()>1){ size_t GPUHeight = size_t(this->input.getHeight()*GPUPartition); inputSliceGPU.hostSlice(this->input, 0, 0, 0, this->input.getWidth(), GPUHeight, this->input.getDepth()); outputSliceGPU.hostSlice(this->output, 0, 0, 0, this->output.getWidth(), GPUHeight, this->output.getDepth()); inputSliceCPU.hostSlice(this->input, 0, GPUHeight, 0, this->input.getWidth(), this->input.getHeight()-GPUHeight, this->input.getDepth()); outputSliceCPU.hostSlice(this->output, 0, GPUHeight, 0, this->output.getWidth(), this->output.getHeight()-GPUHeight, this->output.getDepth()); }else{ size_t GPUWidth= size_t(this->input.getWidth()*GPUPartition); inputSliceGPU.hostSlice(this->input, 0, 0, 0, GPUWidth, this->input.getHeight(), this->input.getDepth()); outputSliceGPU.hostSlice(this->output, 0, 0, 0, GPUWidth, this->output.getHeight(), this->output.getDepth()); inputSliceCPU.hostSlice(this->input, GPUWidth, 0, 0, this->input.getWidth()-GPUWidth, this->input.getHeight(), this->input.getDepth()); outputSliceCPU.hostSlice(this->output, GPUWidth, 0, 0, this->output.getWidth()-GPUWidth, this->output.getHeight(), this->output.getDepth()); } omp_set_num_threads(2); #pragma omp parallel sections { #pragma omp section { inputSliceGPU.deviceAlloc(); inputSliceGPU.copyToDevice(); outputSliceGPU.deviceAlloc(); for(size_t it = 0; it<iterations; it++){ if((it%2)==0) this->runCUDA(inputSliceGPU, outputSliceGPU, GPUBlockSize); else this->runCUDA(outputSliceGPU, inputSliceGPU, GPUBlockSize); } //outputSliceGPU.copyToHost(); //outputSliceGPU.deviceFree(); } #pragma omp section { Arrays inputCopy; inputCopy.hostClone(inputSliceCPU); for(size_t it = 0; it<iterations; it++){ if(it%2==0) this->runTBB(inputCopy, outputSliceCPU, numThreads); else this->runTBB(outputSliceCPU, inputCopy, numThreads); //std::swap(input,output); } if((iterations%2)==0) outputSliceCPU.hostMemCopy(inputCopy); inputCopy.hostFree(); } } if((iterations%2)==1) outputSliceGPU.copyToHost(); else outputSliceGPU.copyFromDevice(inputSliceGPU); inputSliceGPU.deviceFree(); outputSliceGPU.deviceFree(); } } */ //******************************************************************************************* // Map 3D //******************************************************************************************* template<class Arrays, class Args> Map3D<Arrays,Args>::Map3D(){} template<class Arrays, class Args> Map3D<Arrays,Args>::Map3D(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } #ifdef PSKEL_CUDA template<class Arrays, class Args> void Map3D<Arrays,Args>::runCUDA(Arrays in, Arrays out, size_t blockSize){ dim3 DimBlock(blockSize, blockSize, 1); dim3 DimGrid((in.getWidth() - 1)/blockSize + 1, ((in.getHeight()) - 1)/blockSize + 1, in.getDepth()); mapCU3D<<<DimGrid, DimBlock>>>(in, out, this->args); gpuErrchk( cudaPeekAtLastError() ); gpuErrchk( cudaDeviceSynchronize() ); } #endif template<class Arrays, class Args> void Map3D<Arrays,Args>::runSeq(Arrays in, Arrays out){ for(int h = 0; h<in.getHeight(); ++h){ for(int w = 0; w<in.getWidth(); ++w){ for(int d = 0; d<in.getDepth(); ++d){ mapKernel(in, out, this->args, h, w,d); }}} } template<class Arrays, class Args> void Map3D<Arrays,Args>::runOpenMP(Arrays in, Arrays out, size_t numThreads){ omp_set_num_threads(numThreads); #pragma omp parallel for for(int h = 0; h<in.getHeight(); ++h){ for(int w = 0; w<in.getWidth(); ++w){ for(int d = 0; d<in.getDepth(); ++d){ mapKernel(in, out, this->args, h, w,d); }}} } #ifdef PSKEL_TBB template<class Arrays, class Args> struct TBBMap3D{ Arrays input; Arrays output; Args args; TBBMap3D(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } void operator()(tbb::blocked_range<int> r)const{ for(int h = r.begin(); h!=r.end(); h++){ for(int w = 0; w<this->input.getWidth(); ++w){ for(int d = 0; d<this->input.getDepth(); ++d){ mapKernel(this->input, this->output, this->args, h, w,d); }}} } }; template<class Arrays, class Args> void Map3D<Arrays, Args>::runTBB(Arrays in, Arrays out, size_t numThreads){ TBBMap3D<Arrays, Args> tbbmap(in, out, this->args); tbb::task_scheduler_init init(numThreads); tbb::parallel_for(tbb::blocked_range<int>(0, in.getHeight()), tbbmap); } #endif //******************************************************************************************* // Map 2D //******************************************************************************************* template<class Arrays, class Args> Map2D<Arrays,Args>::Map2D(){} template<class Arrays, class Args> Map2D<Arrays,Args>::Map2D(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } #ifdef PSKEL_CUDA template<class Arrays, class Args> void Map2D<Arrays,Args>::runCUDA(Arrays in, Arrays out, size_t blockSize){ dim3 DimBlock(blockSize, blockSize, 1); dim3 DimGrid((in.getWidth() - 1)/blockSize + 1, (in.getHeight() - 1)/blockSize + 1, 1); mapCU2D<<<DimGrid, DimBlock>>>(in, out, this->args); gpuErrchk( cudaPeekAtLastError() ); gpuErrchk( cudaDeviceSynchronize() ); //gpuErrchk( cudaGetLastError() ); } #endif template<class Arrays, class Args> void Map2D<Arrays,Args>::runSeq(Arrays in, Arrays out){ for (int h = 0; h < in.getHeight(); h++){ for (int w = 0; w < in.getWidth(); w++){ mapKernel(in, out, this->args,h,w); }} } template<class Arrays, class Args> void Map2D<Arrays,Args>::runOpenMP(Arrays in, Arrays out, size_t numThreads){ omp_set_num_threads(numThreads); #pragma omp parallel for for (int h = 0; h < in.getHeight(); h++){ for (int w = 0; w < in.getWidth(); w++){ mapKernel(in, out, this->args,h,w); }} } #ifdef PSKEL_TBB template<class Arrays, class Args> struct TBBMap2D{ Arrays input; Arrays output; Args args; TBBMap2D(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } void operator()(tbb::blocked_range<int> r)const{ for (int h = r.begin(); h != r.end(); h++){ for (int w = 0; w < this->input.getWidth(); w++){ mapKernel(this->input, this->output, this->args,h,w); }} } }; template<class Arrays, class Args> void Map2D<Arrays, Args>::runTBB(Arrays in, Arrays out, size_t numThreads){ TBBMap2D<Arrays, Args> tbbmap(in, out, this->args); tbb::task_scheduler_init init(numThreads); tbb::parallel_for(tbb::blocked_range<int>(0, in.getHeight()), tbbmap); } #endif //******************************************************************************************* // Stencil 1D //******************************************************************************************* template<class Arrays, class Args> Map<Arrays,Args>::Map(){} template<class Arrays, class Args> Map<Arrays,Args>::Map(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } #ifdef PSKEL_CUDA template<class Arrays, class Args> void Map<Arrays,Args>::runCUDA(Arrays in, Arrays out, size_t blockSize){ dim3 DimBlock(blockSize, 1, 1); dim3 DimGrid((in.getWidth() - 1)/blockSize + 1,1,1); mapCU<<<DimGrid, DimBlock>>>(in, out, this->args); gpuErrchk( cudaPeekAtLastError() ); gpuErrchk( cudaDeviceSynchronize() ); } #endif template<class Arrays, class Args> void Map<Arrays,Args>::runSeq(Arrays in, Arrays out){ for (int i = 0; i < in.getWidth(); i++){ mapKernel(in, out, this->args, i); } } template<class Arrays, class Args> void Map<Arrays,Args>::runOpenMP(Arrays in, Arrays out, size_t numThreads){ omp_set_num_threads(numThreads); #pragma omp parallel for for (int i = 0; i < in.getWidth(); i++){ mapKernel(in, out, this->args, i); } } #ifdef PSKEL_TBB template<class Arrays, class Args> struct TBBMap{ Arrays input; Arrays output; Args args; TBBMap(Arrays input, Arrays output, Args args){ this->input = input; this->output = output; this->args = args; } void operator()(tbb::blocked_range<int> r)const{ for (int i = r.begin(); i != r.end(); i++){ mapKernel(this->input, this->output, this->args, i); } } }; template<class Arrays, class Args> void Map<Arrays, Args>::runTBB(Arrays in, Arrays out, size_t numThreads){ TBBMap<Arrays, Args> tbbmap(in, out, this->args); tbb::task_scheduler_init init(numThreads); tbb::parallel_for(tbb::blocked_range<int>(0, in.getWidth()), tbbmap); } #endif }//end namespace #endif
33.349716
145
0.659846
[ "3d" ]
b310d2a537e02e3b3650a5f28d3bb6d3c252921b
440
cpp
C++
cpp/alg_accumulate.cpp
PhilipDaniels/learn
cbacb52fd472b5c90b6c3890bb912cd3020905fc
[ "MIT" ]
null
null
null
cpp/alg_accumulate.cpp
PhilipDaniels/learn
cbacb52fd472b5c90b6c3890bb912cd3020905fc
[ "MIT" ]
null
null
null
cpp/alg_accumulate.cpp
PhilipDaniels/learn
cbacb52fd472b5c90b6c3890bb912cd3020905fc
[ "MIT" ]
null
null
null
#include <functional> #include <iostream> #include <numeric> #include <vector> using namespace std; int main(int argc, char *argv[]) { vector<int> src { 1, 2, 100, 200, 300 }; int sum = accumulate(src.begin(), src.end(), 0); cout << "sum = " << sum << "\n"; int product = accumulate(src.begin(), src.end(), 1, multiplies<int>()); cout << "product = " << product << "\n"; return 0; }
22
52
0.538636
[ "vector" ]
b311c46521558e2d14c951a9542f5475f98ad361
945
cpp
C++
LeetCode/C++/1008.cpp
maalolankannan1/HacktoberFest2021-1
c23136d5aaabd198f5af60ad1b990a4788a40d51
[ "Apache-2.0" ]
11
2021-10-01T06:53:31.000Z
2022-02-05T20:36:20.000Z
LeetCode/C++/1008.cpp
maalolankannan1/HacktoberFest2021-1
c23136d5aaabd198f5af60ad1b990a4788a40d51
[ "Apache-2.0" ]
37
2021-10-01T06:54:01.000Z
2021-10-20T18:02:31.000Z
LeetCode/C++/1008.cpp
maalolankannan1/HacktoberFest2021-1
c23136d5aaabd198f5af60ad1b990a4788a40d51
[ "Apache-2.0" ]
110
2021-10-01T06:51:28.000Z
2021-10-31T18:00:55.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode *bst(TreeNode *&root, int value) { if (root == NULL) { return root = new TreeNode(value); cout << "yes "; } if (root->val > value) { root->left = bst(root->left, value); } else { root->right = bst(root->right, value); } return root; } TreeNode *bstFromPreorder(vector<int> &preorder) { TreeNode *root = NULL; int n = preorder.size(); for (auto x : preorder) { bst(root, x); } return root; } };
21.477273
93
0.511111
[ "vector" ]
b31213562c97ce2974cc450e33ba0af715fd4e12
2,542
cpp
C++
solutions/LeetCode/C++/676.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/676.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/676.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission class MagicDictionary { public: /** Initialize your data structure here. */ MagicDictionary() { } /** Build a dictionary through a list of words */ void buildDict(vector<string> dict) { for (const string& word : dict) { words_.insert(word); for (int i = 0; i < word.size(); i++) { string w = word; w[i] = '*'; count_[w]++; } } } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { for (int i = 0; i < word.size(); i++) { char c = word[i]; string w = word; w[i] = '*'; if ((count_[w] > 1) || (count_[w] == 1 && !words_.count(word))) { return true; } } return false; } private: set<string> words_; map<string, int> count_; }; __________________________________________________________________________________________________ sample 9048 kb submission set<string> Set; class MagicDictionary { public: /** Initialize your data structure here. */ MagicDictionary() { Set.clear(); } /** Build a dictionary through a list of words */ void buildDict(vector<string> dict) { for(int i=0;i<dict.size();i++) Set.insert(dict[i]); } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { string str; set<string>::iterator it ; for(it=Set.begin();it !=Set.end();it++) { int mismatch = 0; str = *it; if(str.length() == word.length()) { for(int j=0;j<word.length();j++) { if(str[j] != word[j]) { mismatch++; } } if(mismatch == 1) return true; } } return false; } }; /** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * bool param_2 = obj.search(word); */ __________________________________________________________________________________________________
28.244444
119
0.543666
[ "object", "vector" ]
b3267ffddda58e08d4d794c33dba51d6efe12a5e
696
cpp
C++
Aizu/SumOfIntegers2.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Aizu/SumOfIntegers2.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Aizu/SumOfIntegers2.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> #include <vector> #include <stdio.h> #include <string.h> using namespace std; int N, S, ans, dp[100][100][100]; void rec(int base, int x, int used) { if(x == S && used == N) { if(!dp[base][x][used]) { dp[base][x][used] = 1; ans += 1; } return; } dp[base][x][used] = 1; if(x > S) return; for(int i = base; i <= 9; i++) { rec(i + 1, x + i, used + 1); } } int main(void) { while(1) { scanf("%d%d", &N, &S); if(N == 0 && S == 0) break; ans = 0; memset(dp, 0, sizeof(dp)); rec(0, 0, 0); printf("%d\n", ans); } return 0; }
19.333333
37
0.416667
[ "vector" ]
b32bd044bc2d8afa67365debfe2e620c224bae5c
16,222
cxx
C++
Widgets/vtkKWEPaintbrushShapeBox.cxx
wuzhuobin/vtkEdge
ed13af68a72cec79e3645f7e842d6074592abfa2
[ "BSD-3-Clause" ]
1
2021-01-09T16:06:14.000Z
2021-01-09T16:06:14.000Z
Widgets/vtkKWEPaintbrushShapeBox.cxx
wuzhuobin/vtkEdge
ed13af68a72cec79e3645f7e842d6074592abfa2
[ "BSD-3-Clause" ]
null
null
null
Widgets/vtkKWEPaintbrushShapeBox.cxx
wuzhuobin/vtkEdge
ed13af68a72cec79e3645f7e842d6074592abfa2
[ "BSD-3-Clause" ]
null
null
null
//============================================================================= // This file is part of VTKEdge. See vtkedge.org for more information. // // Copyright (c) 2010 Kitware, Inc. // // VTKEdge may be used under the terms of the BSD License // Please see the file Copyright.txt in the root directory of // VTKEdge for further information. // // Alternatively, you may see: // // http://www.vtkedge.org/vtkedge/project/license.html // // // For custom extensions, consulting services, or training for // this or any other Kitware supported open source project, please // contact Kitware at sales@kitware.com. // // //============================================================================= #include "vtkKWEPaintbrushShapeBox.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkImageStencilData.h" #include "vtkImageData.h" #include "vtkCubeSource.h" #include "vtkPlane.h" #include "vtkMath.h" #define sign(x) ((x<0) ? (-1) : (1)) vtkCxxRevisionMacro(vtkKWEPaintbrushShapeBox, "$Revision: 3282 $"); vtkStandardNewMacro(vtkKWEPaintbrushShapeBox); //---------------------------------------------------------------------- vtkKWEPaintbrushShapeBox::vtkKWEPaintbrushShapeBox() { this->Width[0] = 2.0; this->Width[1] = 2.0; this->Width[2] = 2.0; } //---------------------------------------------------------------------- vtkKWEPaintbrushShapeBox::~vtkKWEPaintbrushShapeBox() { } //---------------------------------------------------------------------- vtkSmartPointer< vtkPolyData > vtkKWEPaintbrushShapeBox::GetShapePolyData( double *center, vtkPlane *plane) { if (plane == NULL) { // No Orientation specified. Return the whole Polydata. This is what will // be rendered on the volume widget vtkCubeSource * templateOutline = vtkCubeSource::New(); templateOutline->SetCenter( center ); templateOutline->SetXLength(this->Width[0]); templateOutline->SetYLength(this->Width[1]); templateOutline->SetZLength(this->Width[2]); templateOutline->Update(); vtkSmartPointer< vtkPolyData > pd = templateOutline->GetOutput(); templateOutline->Delete(); return pd; } else { double normal[3], origin[3]; plane->GetNormal(normal); plane->GetOrigin(origin); // Fast handlers for axis aligned planes. const double tolerance = 0.01; if ((fabs(normal[0])-1.0) < tolerance && fabs(normal[1]) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[0] - center[0]) > this->Width[0]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0], center[1] - this->Width[1]/2.0, center[2] - this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] - this->Width[1]/2.0, center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] + this->Width[1]/2.0, center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0], center[1] + this->Width[1]/2.0, center[2] - this->Width[2]/2.0); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && (fabs(normal[1])-1.0) < tolerance && fabs(normal[2]) < tolerance) { if (fabs(origin[1] - center[1]) > this->Width[1]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1], center[2] - this->Width[2]/2.0); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1], center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1], center[2] + this->Width[2]/2.0); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1], center[2] - this->Width[2]/2.0); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else if (fabs(normal[0]) < tolerance && fabs(normal[1]) < tolerance && (fabs(normal[2])-1.0) < tolerance) { if (fabs(origin[2] - center[2]) > this->Width[2]/2.0) { return NULL; } vtkSmartPointer< vtkPolyData > templateOutline = vtkSmartPointer< vtkPolyData >::New(); templateOutline->Allocate(1, 1); vtkPoints * points = vtkPoints::New(); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1] - this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] - this->Width[0]/2.0, center[1] + this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1] + this->Width[1]/2.0, center[2]); points->InsertNextPoint( center[0] + this->Width[0]/2.0, center[1] - this->Width[1]/2.0, center[2]); templateOutline->SetPoints(points); vtkIdType ptIds[4]; ptIds[0] = 0; ptIds[1] = 1; ptIds[2] = 2; ptIds[3] = 3; templateOutline->InsertNextCell(VTK_QUAD, 4, ptIds); points->Delete(); return templateOutline; } else { // TODO intersect cube with arbitrarily oriented plane and return polydata vtkErrorMacro( << "Not yet supported" ); return NULL; } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetStencil( vtkImageStencilData *stencilData, double p[3]) { int extent[6]; this->GetExtent( extent, p ); stencilData->SetExtent(extent); stencilData->SetSpacing(this->Spacing); stencilData->SetOrigin(this->Origin); stencilData->AllocateExtents(); for (int idz=extent[4]; idz<=extent[5]; idz++) { for (int idy = extent[2]; idy <= extent[3]; idy++) { stencilData->InsertNextExtent( extent[0], extent[1], idy, idz ); } } } //---------------------------------------------------------------------- // This really returns the distance map from an ellipsoid of similar size // as the cuboid.. Who the hell will use a box shaped rectangular image // data anyway.. Its got singularities.. noone doing image processing // for sure.. !! template < class T > int vtkKWEPaintbrushShapeBoxFillBuffer( vtkKWEPaintbrushShapeBox * self, vtkImageData *imageData, T, int extent[6], double p[3] ) { // Polarity of the shape bool state = false; if (self->GetPolarity() == vtkKWEPaintbrushEnums::Draw) { state = true; } const double r1square = 0.25 * self->GetWidth()[0]*self->GetWidth()[0]; const double r2square = 0.25 * self->GetWidth()[1]*self->GetWidth()[1]; const double r3square = 0.25 * self->GetWidth()[2]*self->GetWidth()[2]; double value; for (int k= extent[4]; k<=extent[5]; k++) { for (int j= extent[2]; j<=extent[3]; j++) { for (int i= extent[0]; i<=extent[1]; i++) { T * np = static_cast< T* >(imageData->GetScalarPointer(i,j,k)); double px = (i * self->GetSpacing()[0] + self->GetOrigin()[0]) - p[0]; double py = (j * self->GetSpacing()[1] + self->GetOrigin()[1]) - p[1]; double pz = (k * self->GetSpacing()[2] + self->GetOrigin()[2]) - p[2]; if ( (px*px/r1square + py*py/r2square + pz*pz/r3square) > 2.0 ) { // Outside the ellipse *np = static_cast< T >(0.0); continue; } // Normalized distance of the point from the surface of the ellipse. // This is 1.0 at the surface, 0.0 at the center, 2.0 at twice the // distance from the surface... double distance = sqrt(px*px/r1square + py*py/r2square + pz*pz/r3square); if (state) { value = 255.0 - 127.5 * distance; } else { value = 127.5 * distance; } // clamp value if( value < 1.0 ) { value = 1.0; } else if( value > 254.0 ) { value = 254.0; } *np = static_cast< T >(value); } } } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetGrayscaleData( vtkImageData *imageData, double p[3]) { // Compute the extents of the an image centered about p. int extent[6]; this->GetExtent( extent, p ); imageData->SetSpacing(this->Spacing); imageData->SetOrigin(this->Origin); imageData->SetExtent(extent); imageData->SetScalarType(this->GetScalarType()); imageData->AllocateScalars(); switch (imageData->GetScalarType()) { vtkTemplateMacro( vtkKWEPaintbrushShapeBoxFillBuffer( this, imageData, static_cast< VTK_TT >(0), extent, p )); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::SetWidth( double newWidthX, double newWidthY, double newWidthZ ) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting Width to (" << newWidthX << "," << newWidthY << "," << newWidthZ << ")"); if ((this->Width[0] != newWidthX)||(this->Width[1] != newWidthY)||(this->Width[2] != newWidthZ)) { this->Width[0] = (this->MaxWidth[0] < 0. || this->MaxWidth[0] > newWidthX)? newWidthX :this->MaxWidth[0]; this->Width[1] = (this->MaxWidth[1] < 0. || this->MaxWidth[1] > newWidthY)? newWidthY :this->MaxWidth[1]; this->Width[2] = (this->MaxWidth[2] < 0. || this->MaxWidth[2] > newWidthZ)? newWidthZ :this->MaxWidth[2]; this->Modified(); } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::SetWidth( double newWidth[3] ) { this->SetWidth( newWidth[0], newWidth[1], newWidth[2] ); } //---------------------------------------------------------------------- int vtkKWEPaintbrushShapeBox::Resize(double d[3], int ResizeType) { // If the user specified a constraint on the resize type, use that, // otherwise default to whatever the widget told us in the functions' // argument. const int resizeType = (this->ResizeConstraint == PaintbrushResizeUnConstrained) ? ResizeType : this->ResizeConstraint; // Define a minimum size that the shape will take. The shape will not // get smaller than this. const double minSize = 0.5; double newWidth[3] = { this->Width[0], this->Width[1], this->Width[2] }; if (resizeType == vtkKWEPaintbrushShape::PaintbrushResizeAnisotropic) { // non-isotropic resize. This will resize each axis according to the // factor specified along each axis. for (unsigned int i=0; i<3; i++) { if (d[i] > 0.0 || this->Width[i] > 0.5) { newWidth[i] *= (1+d[i]/10.0); } } } else { // Not an AnIsotropic resize.. This will resize each axis by the same // factor. This factor will be the norm of the factor vector specified // as the functions' argument // Calculate the sign.. (grow or shrink) unsigned int idx = 0; double max = fabs(d[0]); int signVal; for (unsigned int i=1; i<3; i++) { if (fabs(d[i]) > max) { idx = i; max = fabs(d[i]); } } signVal = sign(d[idx]); // The new size is .... const double norm = vtkMath::Norm(d); for (unsigned int i=0; i<3; i++) { newWidth[i] *= (1+(norm * signVal)/10.0); } } // Handle special cases. switch (resizeType) { case PaintbrushResize_XY: newWidth[2] = this->Width[2]; break; case PaintbrushResize_YZ: newWidth[0] = this->Width[0]; break; case PaintbrushResize_XZ: newWidth[1] = this->Width[1]; break; } // Make sure we aren't smaller than the minimum if (newWidth[0] < minSize || newWidth[1] < minSize || newWidth[2] < minSize) { return 0; } // Now change our size to the new size. this->SetWidth( newWidth ); return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::DeepCopy(vtkKWEPaintbrushShape *s) { if (s == this) { return; } vtkKWEPaintbrushShapeBox *sb = vtkKWEPaintbrushShapeBox::SafeDownCast(s); if (sb) { for (unsigned int i=0; i<3; i++) { this->Width[i] = sb->Width[i]; } } this->Superclass::DeepCopy(s); this->Modified(); } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetAnnotation(char *s) { sprintf(s, "(%0.3g,%0.3g,%0.3g)", this->Width[0], this->Width[1], this->Width[2]); } //---------------------------------------------------------------------- int vtkKWEPaintbrushShapeBox::IsInside(double currPos[3], double worldPos[3]) { for (unsigned int i=0; i<3; i++) { if (fabs(worldPos[i] - currPos[i]) > this->Width[i]/2.0) { return 0; } } return 1; } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::GetExtent( int extent[6], double p[3] ) { if (this->Representation == vtkKWEPaintbrushEnums::Grayscale) { for (int i=0; i< 3; i++) { // transition region based extension of width. extent[2*i] = static_cast<int>((p[i] - this->Width[i]* (0.5+1.0/2.0) - this->Origin[i])/ this->Spacing[i] + 0.5); extent[2*i+1] = static_cast<int>((p[i] + this->Width[i]* (0.5+1.0/2.0) - this->Origin[i])/ this->Spacing[i] - 0.4999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } else { for (int i=0; i< 3; i++) { extent[2*i] = static_cast<int>((p[i] - this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] + 0.5); extent[2*i+1] = static_cast<int>((p[i] + this->Width[i]/2.0 - this->Origin[i]) /this->Spacing[i] - 0.49999999); extent[2*i] = extent[2*i] < 0 ? 0 : extent[2*i]; if (extent[2*i] > extent[2*i+1]) { extent[2*i+1] = extent[2*i]; } } } // Clip the extents with the ClipExtent for (int i=0; i< 3; i++) { if (extent[2*i] < this->ClipExtent[2*i]) { extent[2*i] = this->ClipExtent[2*i]; } if (extent[2*i+1] > this->ClipExtent[2*i+1]) { extent[2*i+1] = this->ClipExtent[2*i+1]; } } } //---------------------------------------------------------------------- void vtkKWEPaintbrushShapeBox::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Width: (" << this->Width[0] << ", " << this->Width[1] << ", " << this->Width[2] << ")\n"; }
31.136276
144
0.515904
[ "shape", "vector" ]
b32e835b745f527d49f339234116579f146a51db
1,921
cpp
C++
Slicer/Slicing/BoundaryDetection.cpp
twang15/BarrierFinder
c20ff99ffeeeabc1508682bc99ffb4c7659e7e9f
[ "MIT" ]
null
null
null
Slicer/Slicing/BoundaryDetection.cpp
twang15/BarrierFinder
c20ff99ffeeeabc1508682bc99ffb4c7659e7e9f
[ "MIT" ]
null
null
null
Slicer/Slicing/BoundaryDetection.cpp
twang15/BarrierFinder
c20ff99ffeeeabc1508682bc99ffb4c7659e7e9f
[ "MIT" ]
null
null
null
#include "BoundaryDetection.h" void initializeSCCAuxInfo(const std::vector<BasicBlock*>& scc, AuxiliaryMap& auxiliaryMap) { for (std::vector<BasicBlock*>::const_iterator I = scc.begin(), E = scc.end(); I != E; ++I) { BasicBlock *bb = *I; //Create bb to auxInfo mapping entry. AuxiliaryInfo auxInfo; auxInfo.inLocal.clear(); auxInfo.outLocal.clear(); auxInfo.inGlobal.clear(); auxInfo.outGlobal.clear(); //Insert into <bb, auxInfo> map. auxiliaryMap.insert(itemPair(bb, auxInfo)); } } void computeAuxInfoOut(BasicBlock *bb, AuxiliaryInfo& auxInfo, const vector<BasicBlock*>& nextSCC, AuxiliaryMap& auxiliaryMap, BasicBlock * readCriteriaBB) { for (succ_iterator I = succ_begin(bb), E = succ_end(bb); I != E; I++) { BasicBlock *succ = *I; //test whether the successor is in current SCC. //The BB containing read-side criteria should be handled differently: skip it. if(readCriteriaBB == succ) { continue; } AuxiliaryInfo succAuxInfo = auxiliaryMap[succ]; set_union(auxInfo.inLocal, succAuxInfo.outLocal); //set_union(auxInfo.inGlobal, succAuxInfo.outGlobal); //because DRC's equality is not based on its address, set_union cannot be used. for(SetOfDRC::iterator iSucc=succAuxInfo.outGlobal.begin(), eSucc=succAuxInfo.outGlobal.end(); iSucc != eSucc; ++iSucc) { DRC *drcSucc = *iSucc; bool bInGlobal = false; for(SetOfDRC::iterator i=auxInfo.inGlobal.begin(), e=auxInfo.inGlobal.end(); i != e; ++i) { DRC *tmp = *i; if(*drcSucc == *tmp) { bInGlobal = true; break; } } if(!bInGlobal) { auxInfo.inGlobal.insert(drcSucc); } } } //propagate in to out. auxInfo.outLocal = auxInfo.inLocal; auxInfo.outGlobal = auxInfo.inGlobal; }
27.84058
98
0.622592
[ "vector" ]
b330d6d6d1e3b724a0db55bcf9fc1a8b2078252d
867
hpp
C++
src/json_operations/json_operations.hpp
Wolfiwolf/blockchain_node
b1108f11a155fdd766f7fb6f10ed8dd0a1428fce
[ "MIT" ]
null
null
null
src/json_operations/json_operations.hpp
Wolfiwolf/blockchain_node
b1108f11a155fdd766f7fb6f10ed8dd0a1428fce
[ "MIT" ]
null
null
null
src/json_operations/json_operations.hpp
Wolfiwolf/blockchain_node
b1108f11a155fdd766f7fb6f10ed8dd0a1428fce
[ "MIT" ]
null
null
null
#ifndef JSON_OPERATIONS_H #define JSON_OPERATIONS_H #include <string> #include "../models/models.h" namespace BlockchainNode { class JsonOperations { public: static int get_int_value(const std::string& json_str, const std::string& key); static unsigned long int get_unsigned_long_int_value(const std::string &json_str, const std::string &key); static std::string get_str_value(const std::string& json_str, const std::string& key); static Transaction get_transaction(const std::string &json_str); static std::vector<TxInWithAmount> get_array_of_tx_ins_with_amount(const std::string &json_str); static std::string transaction_to_json(const Transaction& transaction); static std::string tx_in_to_json(const TxIn& tx_in); static std::string tx_out_to_json(const TxOut& tx_out); }; } #endif
34.68
114
0.727797
[ "vector" ]
b33969ff852ddc528c66b31d1edaf5cc1fa3462d
2,235
hpp
C++
include/grafos/io.hpp
KROSF/EDNL
601fcd765e9acd2974ca73e4c63ac381f36bbe51
[ "MIT" ]
null
null
null
include/grafos/io.hpp
KROSF/EDNL
601fcd765e9acd2974ca73e4c63ac381f36bbe51
[ "MIT" ]
14
2019-03-16T17:47:16.000Z
2019-06-12T14:48:14.000Z
include/grafos/io.hpp
KROSF/EDNL
601fcd765e9acd2974ca73e4c63ac381f36bbe51
[ "MIT" ]
1
2019-03-16T17:45:08.000Z
2019-03-16T17:45:08.000Z
#ifndef GRAFOS_IO_HPP #define GRAFOS_IO_HPP #include <ostream> #include <vector> #include "grafos/lista.hpp" #include "grafos/matriz.hpp" #include "grafos/pmc.hpp" namespace grafos { namespace pmc { template <typename T> std::ostream& operator<<(std::ostream& os, const vector<T>& v) { for (size_t i = 0; i < v.size(); ++i) { os << std::setw(4); if (v[i] != GrafoP<T>::INFINITO) os << v[i]; else os << "-"; } return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const matriz<T>& m) { const std::size_t n = m.dimension(); std::size_t digits{0}; for (std::size_t i = 0; i < n; ++i) { for (std::size_t j = 0; j < n; ++j) { if ((m[i][j] != GrafoP<T>::INFINITO && m[i][j] != GrafoP<T>::INFINITO * -1) && static_cast<std::size_t>(m[i][j]) > digits) { digits = m[i][j]; } } } digits = std::to_string(digits).size() + 1; os << "\033[1m\033[32m" << std::string(digits, ' '); for (std::size_t j = 0; j < n; ++j) { os << std::setw(digits) << j; } os << "\033[00m\n"; for (std::size_t i = 0; i < n; ++i) { os << "\033[1m\033[32m" << std::setw(digits) << i << "\033[00m" << std::setw(digits); for (std::size_t j = 0; j < n; ++j) { if (m[i][j] == GrafoP<T>::INFINITO || m[i][j] == GrafoP<T>::INFINITO * -1) { os << std::setw(digits + 16) << "\033[1m\033[34m\u221E\033[00m"; } else { os << std::setw(digits) << m[i][j]; } } os << std::endl; } return os; } } // namespace pmc std::ostream& operator<<(std::ostream& os, const matriz<bool>& m) { const size_t n = m.dimension(); os << " "; for (size_t j = 0; j < n; ++j) os << std::setw(3) << j; os << std::endl; for (size_t i = 0; i < n; ++i) { os << std::setw(3) << i; for (size_t j = 0; j < n; ++j) os << std::setw(3) << m[i][j]; os << std::endl; } return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const Lista<T>& L) { auto au = L.anterior(L.fin()); for (auto i = L.primera(); i != au; i = L.siguiente(i)) os << L.elemento(i) << " \033[1m\033[34m\u2192\033[00m "; os << L.elemento(au); return os; } } // namespace grafos #endif
27.592593
72
0.517226
[ "vector" ]
b33ddde97a9f2e0f6497eae376eec581493c3ceb
1,039
cpp
C++
Hackerrank/10 Days of Statistics/Day 0 - Mean Median Mode .cpp
JanaSabuj/cpmaster
d943780c7ca4badbefbce2d300848343c4032650
[ "MIT" ]
1
2020-11-29T08:36:38.000Z
2020-11-29T08:36:38.000Z
Hackerrank/10 Days of Statistics/Day 0 - Mean Median Mode .cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
Hackerrank/10 Days of Statistics/Day 0 - Mean Median Mode .cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <map> #include <iomanip> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; cin>>n; vector<int> vec(n); int total = 0; for(int i = 0; i < n; i++){ cin>>vec[i]; total += vec[i]; } sort(vec.begin(), vec.end()); float avg = (float)total / n; cout << fixed << showpoint << setprecision(1) <<avg <<endl; float median ; if(n & 1) median = vec[(n)/ 2]; else { median = (float)(vec[(n-1)/2] + vec[(n-1)/2 + 1])/2; } cout << fixed << showpoint << setprecision(1) << median <<endl; int ans = 0; int val ; map<int,int> mp; for(auto x: vec) mp[x]++; for(auto x: mp){ if(x.second > ans){ ans = x.second; val = x.first; } } cout << fixed << showpoint << setprecision(1) << val <<endl; return 0; }
18.553571
77
0.503369
[ "vector" ]
b34252b9fe70b7a108f2523bf2d7fe3b4cc5ff66
7,946
cc
C++
DetectorDescription/Core/src/DDPartSelection.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DetectorDescription/Core/src/DDPartSelection.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DetectorDescription/Core/src/DDPartSelection.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DetectorDescription/Core/interface/Singleton.h" #include "DetectorDescription/Core/interface/DDLogicalPart.h" #include "DetectorDescription/Core/interface/DDName.h" #include "DetectorDescription/Core/interface/DDPartSelection.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "boost/spirit/include/classic.hpp" namespace boost { namespace spirit { namespace classic { } } } using namespace boost::spirit::classic; struct DDSelLevelCollector { std::string namespace_; std::string name_; int copyNo_; bool isCopyNoValid_; bool isChild_; std::vector<DDPartSelRegExpLevel>* p_; std::vector<DDPartSelRegExpLevel>* path(std::vector<DDPartSelRegExpLevel>* p=nullptr) { if (p) { p_=p; namespace_=""; name_=""; copyNo_=0; isCopyNoValid_=false; isChild_=false; } return p_; } }; void noNameSpace(char const * /*first*/, char const* /*last*/) { DDI::Singleton<DDSelLevelCollector>::instance().namespace_=""; } /* Functor for the parser; it does not consume memory - pointers are only used to store references to memory managed elsewhere */ struct DDSelLevelFtor { DDSelLevelFtor() : c_(DDI::Singleton<DDSelLevelCollector>::instance()) { } // parser calls this whenever a selection has been parsed ( //ns:nm[cn], /nm, //ns:nm, .... ) void operator() (char const* /*first*/, char const* /*last*/) const { if(c_.path()){ if (c_.isCopyNoValid_ && c_.isChild_) { c_.path()->emplace_back(DDPartSelRegExpLevel(c_.namespace_,c_.name_,c_.copyNo_,ddchildposp)); //edm::LogInfo("DDPartSelection") << namespace_ << name_ << copyNo_ << ' ' << ddchildposp << std::endl; } else if (c_.isCopyNoValid_ && !c_.isChild_) { c_.path()->emplace_back(DDPartSelRegExpLevel(c_.namespace_,c_.name_,c_.copyNo_,ddanyposp)); // edm::LogInfo("DDPartSelection") << namespace_ << name_ << copyNo_ << ' ' << ddanyposp << std::endl; } else if (!c_.isCopyNoValid_ && c_.isChild_) { c_.path()->emplace_back(DDPartSelRegExpLevel(c_.namespace_,c_.name_,c_.copyNo_,ddchildlogp)); // edm::LogInfo("DDPartSelection") << namespace_ << name_ << copyNo_ << ' ' << ddchildlogp << std::endl; } else if (!c_.isCopyNoValid_ && !c_.isChild_) { c_.path()->emplace_back(DDPartSelRegExpLevel(c_.namespace_,c_.name_,c_.copyNo_,ddanylogp)); // edm::LogInfo("DDPartSelection") << namespace_ << name_ << copyNo_ << ' ' << ddanylogp << std::endl; } c_.namespace_=""; c_.name_=""; c_.isCopyNoValid_=false; } } DDSelLevelCollector & c_; }; struct DDIsChildFtor { void operator()(char const* first, char const* last) const { DDSelLevelCollector & sl = DDI::Singleton<DDSelLevelCollector>::instance(); if ( (last-first) > 1) sl.isChild_=false; if ( (last-first) ==1 ) sl.isChild_=true; //edm::LogInfo("DDPartSelection") << "DDIsChildFtor isChild=" << (last-first) << std::endl; } }; struct DDNameSpaceFtor { void operator()(char const* first, char const* last) const { DDSelLevelCollector & sl = DDI::Singleton<DDSelLevelCollector>::instance(); sl.namespace_.assign(first,last); // edm::LogInfo("DDPartSelection") << "DDNameSpaceFtor singletonname=" << DDI::Singleton<DDSelLevelCollector>::instance().namespace_ << std::endl; } DDSelLevelFtor* selLevelFtor_; }; struct DDNameFtor { void operator()(char const* first, char const* last) const { DDSelLevelCollector & sl = DDI::Singleton<DDSelLevelCollector>::instance(); sl.name_.assign(first,last); // edm::LogInfo("DDPartSelection") << "DDNameFtor singletonname=" << Singleton<DDSelLevelCollector>::instance().name_ << std::endl; } }; struct DDCopyNoFtor { void operator()(int i) const { DDSelLevelCollector & sl = DDI::Singleton<DDSelLevelCollector>::instance(); sl.copyNo_ = i; sl.isCopyNoValid_ = true; // edm::LogInfo("DDPartSelection") << "DDCopyNoFtor ns=" << i; } }; /** A boost::spirit parser for the <SpecPar path="xxx"> syntax */ struct SpecParParser : public grammar<SpecParParser> { template <typename ScannerT> struct definition { definition(SpecParParser const& /*self*/) { Selection //= FirstStep[selLevelFtor()] //>> *SelectionStep[selLevelFtor()] = +SelectionStep[selLevelFtor()] ; FirstStep = Descendant >> Part ; Part = PartNameCopyNumber | PartName ; PartNameCopyNumber = PartName >> CopyNumber ; SelectionStep = NavigationalElement[isChildFtor()] >> Part ; NavigationalElement = Descendant | Child ; CopyNumber = ch_p('[') >> int_p[copyNoFtor()] >> ch_p(']') ; PartName = NameSpaceName | SimpleName[nameFtor()][&noNameSpace] ; SimpleName = +( alnum_p | ch_p('_') | ch_p('.') | ch_p('*') ) ; NameSpaceName = SimpleName[nameSpaceFtor()] >> ':' >> SimpleName[nameFtor()] ; Descendant = ch_p('/') >> ch_p('/') ; Child = ch_p('/') ; } rule<ScannerT> Selection, FirstStep, Part, SelectionStep, NavigationalElement, CopyNumber, PartName, PartNameCopyNumber, NameSpaceName, SimpleName, Descendant, Child; rule<ScannerT> const& start() const { return Selection; } DDSelLevelFtor & selLevelFtor() { return DDI::Singleton<DDSelLevelFtor>::instance(); } DDNameFtor & nameFtor() { static DDNameFtor f_; return f_; } DDNameSpaceFtor & nameSpaceFtor() { static DDNameSpaceFtor f_; return f_; } DDIsChildFtor & isChildFtor() { static DDIsChildFtor f_; return f_; } DDCopyNoFtor & copyNoFtor() { static DDCopyNoFtor f_; return f_; } }; }; DDPartSelectionLevel::DDPartSelectionLevel(const DDLogicalPart & lp, int c, ddselection_type t) : lp_(lp), copyno_(c), selectionType_(t) {} void DDTokenize2(const std::string & sel, std::vector<DDPartSelRegExpLevel> & path) { static SpecParParser parser; DDI::Singleton<DDSelLevelCollector>::instance().path(&path); bool result = parse(sel.c_str(), parser).full; if (!result) { edm::LogError("DDPartSelection") << "DDTokenize2() error in parsing of " << sel << std::endl; } } std::ostream & operator<<(std::ostream & o, const DDPartSelection & p) { DDPartSelection::const_iterator it(p.begin()), ed(p.end()); for (; it != ed; ++it) { const DDPartSelectionLevel lv =*it; switch (lv.selectionType_) { case ddanylogp: o << "//" << lv.lp_.ddname(); break; case ddanyposp: o << "//" << lv.lp_.ddname() << '[' << lv.copyno_ << ']'; break; case ddchildlogp: o << "/" << lv.lp_.ddname(); break; case ddchildposp: o << "/" << lv.lp_.ddname() << '[' << lv.copyno_ << ']'; break; default: o << "{Syntax ERROR}"; } } return o; } std::ostream & operator<<(std::ostream & os, const std::vector<DDPartSelection> & v) { std::vector<DDPartSelection>::const_iterator it(v.begin()), ed(v.end()); for (; it != (ed-1); ++it) { os << *it << std::endl; } if ( it != ed ) { ++it; os << *it; } return os; } // explicit template instantiation. template class DDI::Singleton<DDSelLevelFtor>; //template class DDI::Singleton<DDI::Store<DDName, DDSelLevelCollector> >; template class DDI::Singleton<DDSelLevelCollector>; #include <DetectorDescription/Core/interface/Singleton.icc>
28.789855
151
0.602819
[ "vector" ]
b34961681fe678903263f2ad0dfd4d4cd10ed4ec
2,260
cpp
C++
src/deserialization.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
234
2020-04-24T22:09:49.000Z
2022-03-30T10:40:04.000Z
src/deserialization.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
199
2020-04-29T08:43:21.000Z
2022-03-29T09:05:52.000Z
src/deserialization.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
80
2020-04-29T14:54:41.000Z
2022-03-30T14:50:29.000Z
//***************************************************************************** // Copyright 2021 Intel Corporation // // 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 "deserialization.hpp" namespace ovms { template <> Status InputSink<InferenceEngine::InferRequest&>::give(const std::string& name, InferenceEngine::Blob::Ptr blob) { Status status; try { requester.SetBlob(name, blob); // OV implementation the InferenceEngine::Exception is not // a base class for all other exceptions thrown from OV. // OV can throw exceptions derived from std::logic_error. } catch (const InferenceEngine::Exception& e) { status = StatusCode::OV_INTERNAL_DESERIALIZATION_ERROR; SPDLOG_DEBUG("{}: {}", status.string(), e.what()); return status; } catch (std::logic_error& e) { status = StatusCode::OV_INTERNAL_DESERIALIZATION_ERROR; SPDLOG_DEBUG("{}: {}", status.string(), e.what()); return status; } return status; } InferenceEngine::TensorDesc getFinalTensorDesc(const ovms::TensorInfo& servableInfo, const tensorflow::TensorProto& requestInput, bool isPipeline) { InferenceEngine::Precision precision = servableInfo.getPrecision(); if (!isPipeline) { return InferenceEngine::TensorDesc(precision, servableInfo.getShape(), servableInfo.getLayout()); } InferenceEngine::SizeVector shape; for (size_t i = 0; i < requestInput.tensor_shape().dim_size(); i++) { shape.push_back(requestInput.tensor_shape().dim(i).size()); } return InferenceEngine::TensorDesc(precision, shape, InferenceEngine::Layout::ANY); } } // namespace ovms
42.641509
148
0.655752
[ "shape" ]
b35047d52c263b08bc3233d1728e832d29b0bb26
6,940
cc
C++
src/evaluator.cc
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
6
2020-03-19T04:16:02.000Z
2022-03-30T15:41:39.000Z
src/evaluator.cc
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
1
2020-05-20T12:05:49.000Z
2021-11-14T13:39:23.000Z
src/evaluator.cc
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
null
null
null
#include <fcntl.h> #include "configrange.hh" #include "evaluator.hh" #include "network.cc" #include "rat-templates.cc" #include "fish-templates.cc" template <typename T> Evaluator< T >::Evaluator( const ConfigRange & range ) : _prng_seed( global_PRNG()() ), /* freeze the PRNG seed for the life of this Evaluator */ _tick_count( range.simulation_ticks ), _configs() { // add configs from every point in the cube of configs for (double link_ppt = range.link_ppt.low; link_ppt <= range.link_ppt.high; link_ppt += range.link_ppt.incr) { for (double rtt = range.rtt.low; rtt <= range.rtt.high; rtt += range.rtt.incr) { for (unsigned int senders = range.num_senders.low; senders <= range.num_senders.high; senders += range.num_senders.incr) { for (double on = range.mean_on_duration.low; on <= range.mean_on_duration.high; on += range.mean_on_duration.incr) { for (double off = range.mean_off_duration.low; off <= range.mean_off_duration.high; off += range.mean_off_duration.incr) { for ( double buffer_size = range.buffer_size.low; buffer_size <= range.buffer_size.high; buffer_size += range.buffer_size.incr) { for ( double loss_rate = range.stochastic_loss_rate.low; loss_rate <= range.stochastic_loss_rate.high; loss_rate += range.stochastic_loss_rate.incr) { _configs.push_back( NetConfig().set_link_ppt( link_ppt ).set_delay( rtt ).set_num_senders( senders ).set_on_duration( on ).set_off_duration(off).set_buffer_size( buffer_size ).set_stochastic_loss_rate( loss_rate ) ); if ( range.stochastic_loss_rate.isOne() ) { break; } } if ( range.buffer_size.isOne() ) { break; } } if ( range.mean_off_duration.isOne() ) { break; } } if ( range.mean_on_duration.isOne() ) { break; } } if ( range.num_senders.isOne() ) { break; } } if ( range.rtt.isOne() ) { break; } } if ( range.link_ppt.isOne() ) { break; } } } template <typename T> ProblemBuffers::Problem Evaluator< T >::_ProblemSettings_DNA( void ) const { ProblemBuffers::Problem ret; ProblemBuffers::ProblemSettings settings; settings.set_prng_seed( _prng_seed ); settings.set_tick_count( _tick_count ); ret.mutable_settings()->CopyFrom( settings ); for ( auto &x : _configs ) { RemyBuffers::NetConfig *config = ret.add_configs(); *config = x.DNA(); } return ret; } template <> ProblemBuffers::Problem Evaluator< WhiskerTree >::DNA( const WhiskerTree & whiskers ) const { ProblemBuffers::Problem ret = _ProblemSettings_DNA(); ret.mutable_whiskers()->CopyFrom( whiskers.DNA() ); return ret; } template <> ProblemBuffers::Problem Evaluator< FinTree >::DNA( const FinTree & fins ) const { ProblemBuffers::Problem ret = _ProblemSettings_DNA(); ret.mutable_fins()->CopyFrom( fins.DNA() ); return ret; } template <> Evaluator< WhiskerTree >::Outcome Evaluator< WhiskerTree >::score( WhiskerTree & run_whiskers, const unsigned int prng_seed, const vector<NetConfig> & configs, const bool trace, const unsigned int ticks_to_run ) { PRNG run_prng( prng_seed ); run_whiskers.reset_counts(); /* run tests */ Evaluator::Outcome the_outcome; for ( auto &x : configs ) { /* run once */ Network<SenderGang<Rat, TimeSwitchedSender<Rat>>, SenderGang<Rat, TimeSwitchedSender<Rat>>> network1( Rat( run_whiskers, trace ), run_prng, x ); network1.run_simulation( ticks_to_run ); the_outcome.score += network1.senders().utility(); the_outcome.throughputs_delays.emplace_back( x, network1.senders().throughputs_delays() ); } the_outcome.used_actions = run_whiskers; return the_outcome; } template <> Evaluator< FinTree >::Outcome Evaluator< FinTree >::score( FinTree & run_fins, const unsigned int prng_seed, const vector<NetConfig> & configs, const bool trace, const unsigned int ticks_to_run ) { PRNG run_prng( prng_seed ); unsigned int fish_prng_seed( run_prng() ); run_fins.reset_counts(); /* run tests */ Evaluator::Outcome the_outcome; for ( auto &x : configs ) { /* run once */ Network<SenderGang<Fish, TimeSwitchedSender<Fish>>, SenderGang<Fish, TimeSwitchedSender<Fish>>> network1( Fish( run_fins, fish_prng_seed, trace ), run_prng, x ); network1.run_simulation( ticks_to_run ); the_outcome.score += network1.senders().utility(); the_outcome.throughputs_delays.emplace_back( x, network1.senders().throughputs_delays() ); } the_outcome.used_actions = run_fins; return the_outcome; } template <> typename Evaluator< WhiskerTree >::Outcome Evaluator< WhiskerTree >::parse_problem_and_evaluate( const ProblemBuffers::Problem & problem ) { vector<NetConfig> configs; for ( const auto &x : problem.configs() ) { configs.emplace_back( x ); } WhiskerTree run_whiskers = WhiskerTree( problem.whiskers() ); return Evaluator< WhiskerTree >::score( run_whiskers, problem.settings().prng_seed(), configs, false, problem.settings().tick_count() ); } template <> typename Evaluator< FinTree >::Outcome Evaluator< FinTree >::parse_problem_and_evaluate( const ProblemBuffers::Problem & problem ) { vector<NetConfig> configs; for ( const auto &x : problem.configs() ) { configs.emplace_back( x ); } FinTree run_fins = FinTree( problem.fins() ); return Evaluator< FinTree >::score( run_fins, problem.settings().prng_seed(), configs, false, problem.settings().tick_count() ); } template <typename T> AnswerBuffers::Outcome Evaluator< T >::Outcome::DNA( void ) const { AnswerBuffers::Outcome ret; for ( const auto & run : throughputs_delays ) { AnswerBuffers::ThroughputsDelays *tp_del = ret.add_throughputs_delays(); tp_del->mutable_config()->CopyFrom( run.first.DNA() ); for ( const auto & x : run.second ) { AnswerBuffers::SenderResults *results = tp_del->add_results(); results->set_throughput( x.first ); results->set_delay( x.second ); } } ret.set_score( score ); return ret; } template <typename T> Evaluator< T >::Outcome::Outcome( const AnswerBuffers::Outcome & dna ) : score( dna.score() ), throughputs_delays(), used_actions() { for ( const auto &x : dna.throughputs_delays() ) { vector< pair< double, double > > tp_del; for ( const auto &result : x.results() ) { tp_del.emplace_back( result.throughput(), result.delay() ); } throughputs_delays.emplace_back( NetConfig( x.config() ), tp_del ); } } template <typename T> typename Evaluator< T >::Outcome Evaluator< T >::score( T & run_actions, const bool trace, const double carefulness ) const { return score( run_actions, _prng_seed, _configs, trace, _tick_count * carefulness ); } template class Evaluator< WhiskerTree>; template class Evaluator< FinTree >;
33.68932
232
0.6817
[ "vector" ]
b356fa1af39fe0280607d80fad6ac30e17724134
438
cpp
C++
solutions/c++/problems/[1833_Medium] Maximum Ice Cream Bars.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
6
2021-02-20T14:00:22.000Z
2022-03-31T15:26:44.000Z
solutions/c++/problems/[1833_Medium] Maximum Ice Cream Bars.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
solutions/c++/problems/[1833_Medium] Maximum Ice Cream Bars.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
class Solution { public: int maxIceCream(vector<int> &costs, int coins) { int n = costs.size(); sort(costs.begin(), costs.end()); int count = 0; for (int i = 0; i < n; i++) { int curr = costs[i]; if (coins >= curr) { coins -= curr; count++; } else { return count; } } return count; } };
24.333333
52
0.39726
[ "vector" ]
b3599a09716c38f104f45523c58cadd96fca5dd8
1,647
cpp
C++
platforms/codeforces/all/codeforces_1323_A.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/codeforces/all/codeforces_1323_A.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/codeforces/all/codeforces_1323_A.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <limits> #include <cmath> #include <algorithm> #include <vector> #include <unordered_map> #include <unordered_set> #include <string> #include <array> #include <map> #include <set> #include <deque> #include <list> #include <sstream> #include <iomanip> #include <numeric> #include <climits> #include <cstring> #include <bitset> #include <stack> #include <queue> #define MOD (1e9 + 7); #define PI (3.14159265358979323846) using ll = int64_t; using ull = uint64_t; using namespace std; [[maybe_unused]] static auto __x = [](){ios_base::sync_with_stdio(0); cin.tie(0);}; int main() { int tests_total; cin >> tests_total; for (int test_count = 0; test_count < tests_total; ++test_count) { int n; cin >> n; bool i_need_odd = false; int prev_odd_idx = -1; bool ok = false; for (int i = 0; i < n; ++i) { int number; cin >> number; if (ok) { continue; } if (number % 2 != 0) { if (i_need_odd) { cout << 2 << '\n'; cout << prev_odd_idx << ' ' << i + 1 << '\n'; ok = true; } else { i_need_odd = true; prev_odd_idx = i + 1; } } else { cout << 1 << '\n'; cout << i + 1 << '\n'; ok = true; } } if (not ok) { cout << -1 << '\n'; } ok = false; i_need_odd = false; prev_odd_idx = -1; } }
23.197183
83
0.471767
[ "vector" ]
b3636bf7e7eb82ea7a5600352e5cf5a35a4b6bfd
853
cpp
C++
source/459.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
2
2017-02-28T11:39:13.000Z
2019-12-07T17:23:20.000Z
source/459.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
source/459.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
// // 459.cpp // LeetCode // // Created by Narikbi on 10.03.17. // Copyright © 2017 app.leetcode.kz. All rights reserved. // #include <stdio.h> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <deque> #include <queue> #include <set> #include <map> #include <stack> #include <cmath> #include <numeric> #include <unordered_map> using namespace std; bool repeatedSubstringPattern(string s) { int n = s.length(); if (s.length() < 2) return true; for (int len = 1; len <= n/2; len++) { if (n % len == 0) { string str = s.substr(0, len); string res = ""; while (res.length() < n) { res += str; } // cout << res << endl; if (res == s) return true; } } return false; }
18.543478
58
0.526377
[ "vector" ]
b364d6634a78570e5d2ff1e05472924312b8245e
4,167
cpp
C++
mapnikvt/src/mapnikvt/GeneratorUtils.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
6
2018-06-27T17:43:35.000Z
2021-06-29T18:50:49.000Z
mapnikvt/src/mapnikvt/GeneratorUtils.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
22
2019-04-10T06:38:09.000Z
2022-01-20T08:12:02.000Z
mapnikvt/src/mapnikvt/GeneratorUtils.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
5
2019-03-12T10:25:20.000Z
2021-12-28T10:18:56.000Z
#include "GeneratorUtils.h" #include "ValueGenerator.h" #include "ExpressionGenerator.h" #include "TransformGenerator.h" #include "ParseTables.h" #include "ColorGenerator.h" #include <iomanip> #include <sstream> #include <utility> #include <boost/algorithm/string.hpp> namespace carto { namespace mvt { std::string generateLineCapModeString(vt::LineCapMode lineCapMode) { auto it = std::find_if(getLineCapModeTable().begin(), getLineCapModeTable().end(), [lineCapMode](const auto& keyVal) { return keyVal.second == lineCapMode; }); if (it == getLineCapModeTable().end()) { throw GeneratorException("Could not generate LineCapMode string"); } return it->first; } std::string generateLineJoinModeString(vt::LineJoinMode lineJoinMode) { auto it = std::find_if(getLineJoinModeTable().begin(), getLineJoinModeTable().end(), [lineJoinMode](const auto& keyVal) { return keyVal.second == lineJoinMode; }); if (it == getLineJoinModeTable().end()) { throw GeneratorException("Could not generate LineJoinMode string"); } return it->first; } std::string generateCompOpString(vt::CompOp compOp) { auto it = std::find_if(getCompOpTable().begin(), getCompOpTable().end(), [compOp](const auto& keyVal) { return keyVal.second == compOp; }); if (it == getCompOpTable().end()) { throw GeneratorException("Could not generate CompOp string"); } return it->first; } std::string generateLabelOrientationString(vt::LabelOrientation labelOrientation) { auto it = std::find_if(getLabelOrientationTable().begin(), getLabelOrientationTable().end(), [labelOrientation](const auto& keyVal) { return keyVal.second == labelOrientation; }); if (it == getLabelOrientationTable().end()) { throw GeneratorException("Could not generate LabelOrientation string"); } return it->first; } std::string generateColorString(vt::Color color) { std::string str; std::back_insert_iterator<std::string> it(str); colorgenimpl::Delimiter delimiter; bool result = boost::spirit::karma::generate_delimited(it, ColorGeneratorGrammar<std::back_insert_iterator<std::string>>(), delimiter, color.value()); if (!result) { throw GeneratorException("Could not generate color string"); } return boost::trim_copy(str); } std::string generateValueString(const Value& val) { std::string str; std::back_insert_iterator<std::string> it(str); bool result = boost::spirit::karma::generate(it, ValueGeneratorGrammar<std::back_insert_iterator<std::string>>(), val); if (!result) { throw GeneratorException("Could not generate value string"); } return boost::trim_copy(str); } std::string generateTransformListString(const std::vector<Transform>& transforms) { std::string str; std::back_insert_iterator<std::string> it(str); transgenimpl::Delimiter delimiter; bool result = boost::spirit::karma::generate_delimited(it, TransformGeneratorGrammar<std::back_insert_iterator<std::string>>() % ',', delimiter, transforms); if (!result) { throw GeneratorException("Could not generate transform string"); } return boost::trim_copy(str); } std::string generateExpressionString(const Expression& expr, bool stringExpr) { std::string str; std::back_insert_iterator<std::string> it(str); bool result = false; if (stringExpr) { result = boost::spirit::karma::generate(it, StringExpressionGeneratorGrammar<std::back_insert_iterator<std::string>>(), expr); } else { result = boost::spirit::karma::generate(it, ExpressionGeneratorGrammar<std::back_insert_iterator<std::string>>(), expr); } if (!result) { throw GeneratorException("Could not generate expression string"); } return boost::trim_copy(str); } } }
40.456311
165
0.644828
[ "vector", "transform" ]
b365d3dc5e93b91273e30d34c05041c65bb91596
6,125
cc
C++
src/MainWindow.cc
gajus123/Genetic-Cars
f399ebcf0952465e91d8711e08f0c38e6c18bb92
[ "MIT" ]
null
null
null
src/MainWindow.cc
gajus123/Genetic-Cars
f399ebcf0952465e91d8711e08f0c38e6c18bb92
[ "MIT" ]
1
2018-10-25T21:04:03.000Z
2018-10-25T21:06:35.000Z
src/MainWindow.cc
gajus123/Genetic-Cars
f399ebcf0952465e91d8711e08f0c38e6c18bb92
[ "MIT" ]
1
2018-11-28T13:39:05.000Z
2018-11-28T13:39:05.000Z
/*! * @authors Jakub Gajownik, Rafał Galczak * @date 14.12.17 * */ #include <MainWindow.h> #include <physics/objects/GroundGenerator.h> #include <ui/ui_MainWindow.h> MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags), simulation_(), simulation_view_(simulation_), ui_(new Ui::MainWindow), pause_action_(QKeySequence(Qt::CTRL + Qt::Key_P), this) { ui_->setupUi(this); ui_->gridLayout_5->addWidget(&simulation_view_); ui_->gridLayout_8->addWidget(&statistic_view_); connect(&pause_action_, SIGNAL(activated()), ui_->pause_button, SLOT(click())); connect(ui_->elite_specimen_number_edit, SIGNAL(editingFinished()), this, SLOT(eliteSpecimenNumberChanged())); connect(ui_->mutation_size_edit, SIGNAL(editingFinished()), this, SLOT(mutationSizeChanged())); connect(ui_->load_button, SIGNAL(clicked()), this, SLOT(loadFromFile())); connect(ui_->save_button, SIGNAL(clicked()), this, SLOT(saveToFile())); connect(ui_->reset_button, SIGNAL(clicked()), this, SLOT(resetSimulation())); connect(ui_->pause_button, SIGNAL(toggled(bool)), this, SLOT(pauseSimulation(bool))); connect(ui_->cars_count_edit, SIGNAL(editingFinished()), this, SLOT(carsNumberChanged())); connect(ui_->simulation_speed_chooser, SIGNAL(currentIndexChanged(int)), this, SLOT(speedChanged())); connect(&simulation_, SIGNAL(roundEnd(std::vector<float>)), &statistics_, SLOT(calculateStatistics(std::vector<float>))); connect(&statistics_, SIGNAL(newValues(float, float, float, float)), &statistic_view_, SLOT(addData(float, float, float, float))); connect(&simulation_, SIGNAL(roundEnd(std::vector<float>)), &population_, SLOT(nextPopulation(std::vector<float>))); connect(&population_, SIGNAL(newVehiclesGenerated(std::vector<Objects::Vehicle>)), &simulation_, SLOT(newRound(std::vector<Objects::Vehicle>))); connect(&loop_, SIGNAL(step(unsigned int)), &simulation_, SLOT(step(unsigned int))); Physics::ObjectsFactory::init(simulation_.getWorld().getWorld()); simulation_.newGround(); population_.generateVehicles(); initializeSpeedWidget(); ui_->cars_count_edit->setText(QString::number(population_.nextGenerationSize())); ui_->mutation_size_edit->setText(QString::number(population_.mutationRate())); ui_->elite_specimen_number_edit->setText(QString::number(population_.eliteSpecimen())); } void MainWindow::initializeSpeedWidget() { ui_->simulation_speed_chooser->addItem("25%", QVariant(0.25f)); ui_->simulation_speed_chooser->addItem("50%", QVariant(0.5f)); ui_->simulation_speed_chooser->addItem("75%", QVariant(0.75f)); ui_->simulation_speed_chooser->addItem("100%", QVariant(1.0f)); ui_->simulation_speed_chooser->addItem("150%", QVariant(1.5f)); ui_->simulation_speed_chooser->addItem("200%", QVariant(2.0f)); ui_->simulation_speed_chooser->addItem("300%", QVariant(3.0f)); ui_->simulation_speed_chooser->addItem("400%", QVariant(4.0f)); ui_->simulation_speed_chooser->addItem("500%", QVariant(5.0f)); ui_->simulation_speed_chooser->setCurrentIndex(3); } void MainWindow::eliteSpecimenNumberChanged() { QString new_text = ui_->elite_specimen_number_edit->text(); bool is_int; std::size_t elite_specimen = new_text.toInt(&is_int); if (is_int) population_.setEliteSpecimen(elite_specimen); ui_->elite_specimen_number_edit->setText(QString::number(population_.eliteSpecimen())); } void MainWindow::mutationSizeChanged() { bool is_float; float mutation_size = ui_->mutation_size_edit->text().toFloat(&is_float); if (is_float) population_.setMutationRate(mutation_size); ui_->mutation_size_edit->setText(QString().setNum(population_.mutationRate())); } void MainWindow::saveToFile() { if (!ui_->pause_button->isChecked()) pauseSimulation(); QFileDialog file_dialog{this, "Load Population", "", "Text Files (*.txt);;AllFiles (*)"}; file_dialog.setAcceptMode(QFileDialog::AcceptSave); file_dialog.setFileMode(QFileDialog::AnyFile); file_dialog.setOption(QFileDialog::DontUseNativeDialog, true); if(QDialog::Accepted != file_dialog.exec()) { if (!ui_->pause_button->isChecked()) resumeSimulation(); return; } QString filename = file_dialog.selectedFiles().at(0); if (!filename.isEmpty()) population_.saveToFile(filename.toStdString()); if (!ui_->pause_button->isChecked()) resumeSimulation(); } void MainWindow::loadFromFile() { if (!ui_->pause_button->isChecked()) pauseSimulation(); QFileDialog file_dialog{this, "Load Population", "", "Text Files (*.txt);;AllFiles (*)"}; file_dialog.setAcceptMode(QFileDialog::AcceptOpen); file_dialog.setFileMode(QFileDialog::ExistingFile); file_dialog.setOption(QFileDialog::DontUseNativeDialog, true); if(QDialog::Accepted != file_dialog.exec()) { if (!ui_->pause_button->isChecked()) resumeSimulation(); return; } QString filename = file_dialog.selectedFiles().at(0); if (!filename.isEmpty()) population_.loadFromFile(filename.toStdString()); if (!ui_->pause_button->isChecked()) resumeSimulation(); } void MainWindow::pauseSimulation(bool paused) { if (paused) pauseSimulation(); else resumeSimulation(); } void MainWindow::carsNumberChanged() { QString new_text = ui_->cars_count_edit->text(); bool is_int; std::size_t cars_number = new_text.toInt(&is_int); if (is_int) population_.setNextGenerationSize(cars_number); ui_->cars_count_edit->setText(QString::number(population_.nextGenerationSize())); ui_->elite_specimen_number_edit->setText(QString::number(population_.eliteSpecimen())); } void MainWindow::resetSimulation() { statistic_view_.reset(); simulation_.reset(); population_.reset(); } void MainWindow::speedChanged() { float time_speed = ui_->simulation_speed_chooser->currentData().toFloat(); loop_.setTimeSpeed(time_speed); } void MainWindow::pauseSimulation() { loop_.stop(); } void MainWindow::resumeSimulation() { loop_.start(); }
40.562914
149
0.718857
[ "vector" ]
b37a36771ae72af98ab051fcd9fa65b7dc444f62
1,169
cpp
C++
CleaningShift/CleaningShift.cpp
biyue111/POJ
7b45d737015b22c6b3a5eaa539bcc157a78010fc
[ "MIT" ]
null
null
null
CleaningShift/CleaningShift.cpp
biyue111/POJ
7b45d737015b22c6b3a5eaa539bcc157a78010fc
[ "MIT" ]
null
null
null
CleaningShift/CleaningShift.cpp
biyue111/POJ
7b45d737015b22c6b3a5eaa539bcc157a78010fc
[ "MIT" ]
null
null
null
//Date : 2016-1-19 // #include <cstdio> #include <algorithm> #include <vector> using namespace std; bool compare(const pair<int,int> a,const pair<int,int> b) { return a.first < b.first; } int main() { vector< pair<int,int> > teams; int N,T,tmpb,tmpe,endtime,num,begintime,flag; scanf("%d%d",&N,&T); for(int i=0;i<N;i++){ scanf("%d%d",&tmpb,&tmpe); teams.push_back(make_pair(tmpb,tmpe)); } sort(teams.begin(),teams.end(),compare); endtime = 0; begintime = 0; num = 1; flag = 1; for(int i=0;i<N;i++){ if(teams[i].first<=begintime+1){ if(teams[i].second>endtime) endtime = teams[i].second; if(endtime == T) break; } else if(teams[i].first<=endtime+1){ //teams[i].frist > begintime+1 begintime = endtime; num++; if(teams[i].second>endtime) endtime = teams[i].second; if(endtime == T) break; } else if(teams[i].first>endtime+1){ flag = 0; break; } } if(endtime < T) flag = 0; if(flag) printf("%d\n",num); else printf("-1\n"); return 0; }
21.648148
74
0.523524
[ "vector" ]
b38148d6229dd1eb3becef8a23429aafec15fcab
1,761
hpp
C++
1.48/tuning/object.hpp
spirick/tuninglib
c390d7abc74847be0ebd9d08905151d72347ab82
[ "MIT" ]
3
2021-12-01T18:31:31.000Z
2021-12-06T02:15:00.000Z
1.48/tuning/object.hpp
spirick/tuninglib
c390d7abc74847be0ebd9d08905151d72347ab82
[ "MIT" ]
null
null
null
1.48/tuning/object.hpp
spirick/tuninglib
c390d7abc74847be0ebd9d08905151d72347ab82
[ "MIT" ]
null
null
null
// Spirick Tuning // // A C++ class and template library // for performance critical applications. // Copyright (C) 1996-2021 Dietmar Deimling. // All rights reserved. // Internet www.spirick.com // E-Mail info@spirick.com // // Version 1.48 // File tuning/object.hpp #ifndef TUNING_OBJECT_HPP #define TUNING_OBJECT_HPP #include "tuning/defs.hpp" //--------------------------------------------------------------------------- #define TL_CLASSID(t_class) \ static t_ClassId ClassId () { return (t_ClassId) t_class::ClassId; } \ virtual t_ClassId GetClassId () const { return (t_ClassId) t_class::ClassId; } \ virtual const char * GetClassName () const { return # t_class; } \ virtual bool IsKindOf (t_ClassId o_id) const; #define TL_ISKINDOF(t_class, t_base) \ bool t_class::IsKindOf (t_ClassId o_id) const \ { \ if (ClassId () == o_id) \ return true; \ else \ return t_base::IsKindOf (o_id); \ } //--------------------------------------------------------------------------- class TL_EXPORT ct_Object { public: virtual ~ct_Object () { } typedef void (* t_ClassId) (); TL_CLASSID (ct_Object) virtual bool operator < (const ct_Object & co_comp) const; virtual t_UInt GetHash () const; inline void Swap (ct_Object &) { } }; //--------------------------------------------------------------------------- class TL_EXPORT ct_Empty { public: inline void Swap (ct_Empty &) { } }; #endif
29.35
87
0.467916
[ "object" ]
b383084d8af799200cdbf005c069333f707a0db0
6,536
hpp
C++
src/axom/primal/operators/closest_point.hpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/primal/operators/closest_point.hpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/primal/operators/closest_point.hpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2020, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) /*! * \file * * \brief Consists of a set of methods that compute the closest point on a * geometric primitive B from another geometric primitive A. * */ #ifndef CLOSEST_POINT_HPP_ #define CLOSEST_POINT_HPP_ #include "axom/primal/geometry/Point.hpp" #include "axom/primal/geometry/Triangle.hpp" #include "axom/primal/geometry/OrientedBoundingBox.hpp" namespace axom { namespace primal { /*! * \brief Computes the closest point from a point, P, to a given triangle. * * \param [in] P the query point * \param [in] tri user-supplied triangle. * \param [out] loc int pointer to store location of closest point (optional). * \return cp the closest point from a point P and a triangle. * * \note If the optional int pointer is supplied for `loc`, the method returns * the location of the closest point, which is illustrated in the schematic * diagram below and encoded as follows: * <ul> * <li> loc \f$ \in [0,2] \f$, loc corresponds to the triangle node index </li> * <li> loc \f$ \in [-3,-1] \f$, abs(loc) corresponds to an edge </li> * <li> loc >= 3, loc is on a triangle face </li> * </ul> * * \verbatim * * 2 * /\ * (-3)--/ \--(-2) * / \ * /_ _ _ \ * 0 | 1 * | * (-1) * * \endverbatim * * \pre NDIMS==2 || NDIMS==3 * * \note Implementation is based on "Real Time Collision Detection, * Chapter 5.1.5 Closest Point on Triangle to Point". */ template < typename T, int NDIMS > inline Point< T,NDIMS > closest_point( const Point< T,NDIMS >& P, const Triangle< T,NDIMS >& tri, int* loc=nullptr ) { // convenience macros to access triangle vertices #define A(t) t[0] #define B(t) t[1] #define C(t) t[2] // Check if P in vertex region outside A Vector< T, NDIMS > ab( A(tri), B(tri) ); Vector< T, NDIMS > ac( A(tri), C(tri) ); Vector< T, NDIMS > ap( A(tri),P ); T d1 = Vector< T,NDIMS >::dot_product( ab, ap ); T d2 = Vector< T,NDIMS >::dot_product( ac, ap ); if ( d1 <= 0.0f && d2 <= 0.0f ) { // A is the closest point if ( loc != nullptr) { *loc = 0; } return ( A(tri) ); } // END if //---------------------------------------------------------------------------- // Check if P in vertex region outside B Vector< T,NDIMS > bp( B(tri), P ); T d3 = Vector< T,NDIMS >::dot_product( ab, bp ); T d4 = Vector< T,NDIMS >::dot_product( ac, bp ); if ( d3 >= 0.0f && d4 <= d3 ) { // B is the closest point if ( loc != nullptr) { *loc = 1; } return ( B(tri) ); } // END if //---------------------------------------------------------------------------- // Check if P in edge region of AB T vc = d1*d4 - d3*d2; if ( vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f ) { T v = d1 / ( d1-d3 ); Vector< T,NDIMS > v_ab = ab*v; double x = A(tri)[0] + v_ab[0]; double y = A(tri)[1] + v_ab[1]; double z = (NDIMS==3) ? A(tri)[2] + v_ab[2] : 0.0; if ( loc != nullptr ) { *loc = -1; } return ( Point< T,NDIMS >::make_point( x,y,z ) ); } // END if //---------------------------------------------------------------------------- // Check if P in vertex region outside C Vector< T,NDIMS > cp( C(tri), P ); T d5 = Vector< T,NDIMS >::dot_product(ab,cp); T d6 = Vector< T,NDIMS >::dot_product(ac,cp); if ( d6 >= 0.0f && d5 <= d6 ) { // C is the closest point if ( loc != nullptr ) { *loc = 2; } return ( C(tri) ); } //---------------------------------------------------------------------------- // Check if P in edge region of AC T vb = d5*d2 - d1*d6; if ( vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f ) { T w = d2 / (d2-d6); Vector< T, NDIMS > w_ac = ac*w; double x = A(tri)[0] + w_ac[0]; double y = A(tri)[1] + w_ac[1]; double z = (NDIMS==3) ? A(tri)[2] + w_ac[2] : 0.0; if ( loc != nullptr) { *loc = -3; } return ( Point< T,NDIMS >::make_point( x,y,z ) ); } // END if //---------------------------------------------------------------------------- // Check if P in edge region of BC T va = d3*d6 - d5*d4; if ( va <= 0.0f && (d4-d3) >= 0.0f && (d5-d6) >= 0.0f ) { T w = (d4-d3)/( (d4-d3)+(d5-d6) ); Vector< T,NDIMS > bc( B(tri), C(tri) ); Vector< T,NDIMS > w_bc = bc*w; double x = B(tri)[0] + w_bc[0]; double y = B(tri)[1] + w_bc[1]; double z = (NDIMS==3) ? B(tri)[2] + w_bc[2] : 0.0; if ( loc != nullptr ) { *loc = -2; } return ( Point< T,NDIMS >::make_point( x,y,z ) ); } // END if //---------------------------------------------------------------------------- // P is inside face region T denom = 1.0f / (va + vb + vc ); T v = vb * denom; T w = vc * denom; Vector< T,NDIMS > N = (ab*v) + (ac*w); double x = A(tri)[0] + N[0]; double y = A(tri)[1] + N[1]; double z = (NDIMS==3) ? A(tri)[2] + N[2] : 0.0; if ( loc != nullptr ) { *loc = Triangle< T,NDIMS >::NUM_TRI_VERTS; } return ( Point< T,NDIMS >::make_point( x,y,z ) ); #undef A #undef B #undef C } /*! * \brief Computes the closest point from a point to a given OBB. * * \param [in] pt the query pt. * \param [in] obb user-supplied oriented bounding box. * \return cp the closest point from a point pt and an OBB. */ template < typename T, int NDIMS > inline Point< T, NDIMS > closest_point(const Point< T, NDIMS >& pt, const OrientedBoundingBox< T, NDIMS >& obb) { Vector< T, NDIMS > e = obb.getExtents(); const Vector< T, NDIMS >* u = obb.getAxes(); Vector< T, NDIMS > pt_l = obb.toLocal(pt); Vector< T, NDIMS > res(obb.getCentroid()); for (int i = 0 ; i < NDIMS ; i++) { // since the local coordinates are individually constrained, we can simply // choose the "best" local coordinate in each axis direction if (pt_l[i] <= e[i] && pt_l[i] >= -e[i]) { res += pt_l[i]*u[i]; } else if (pt_l[i] > e[i]) { res += e[i]*u[i]; } else { res -= e[i]*u[i]; } } return Point< T, NDIMS >(res.array()); } } /* namespace primal */ } /* namespace axom */ #endif /* CLOSEST_POINT_HPP_ */
25.631373
80
0.493727
[ "geometry", "vector" ]
b39166c7d90fd981c39d4bdef09588ce5071b759
766
hpp
C++
lib/native/stopword.hpp
nurcahyaari/Vector-Space-Model-using-Cosine-Similarity
7841347cacf9466b6f9173c82dde97d71cffb82d
[ "MIT" ]
2
2020-04-22T06:00:28.000Z
2020-04-22T19:17:56.000Z
lib/native/stopword.hpp
nurcahyaari/Vector-Space-Model-using-Cosine-Similarity
7841347cacf9466b6f9173c82dde97d71cffb82d
[ "MIT" ]
1
2021-05-11T11:22:18.000Z
2021-05-11T11:22:18.000Z
lib/native/stopword.hpp
nurcahyaari/Vector-Space-Model-using-Cosine-Similarity
7841347cacf9466b6f9173c82dde97d71cffb82d
[ "MIT" ]
null
null
null
#include<iostream> #include<iterator> #include<vector> #include<fstream> #include<string.h> using namespace std; class Stopword { private: vector<string> text; void readFileFromDb(); public: Stopword(vector<string> text); string SearchText(); }; Stopword::Stopword(vector<string> text){ for(int i = 0; i < text.size(); i++){ this.text.push_back(text); } } string Stopword::SearchText(){ ifstream stopwordFile; string line; bool found; stopwordFile.open("./db/stopword.db.txt"); if (stopwordFile.is_open()){ while ( getline (stopwordFile,line) ){ if(line == "mau"){ found = false; } } stopwordFile.close(); } }
20.157895
46
0.571802
[ "vector" ]
b3964a3e053806e4a318d17a407363882ff3f338
2,121
cpp
C++
cod_solucaoInicial.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
cod_solucaoInicial.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
cod_solucaoInicial.cpp
BrunoBertozzi/tcc-2021
d1a1837d28f7507598e96818ade50671a1050efc
[ "MIT" ]
null
null
null
/*************************************************************** * Nome: Bruno Oswaldo Bertozzi Oliveira * File name: main.cpp * Data 17/02/2021 * ***************************************************************/ #include <iostream> #include <vector> #include <iostream> #include<fstream> #include <algorithm> #include <bits/stdc++.h> using namespace std; #include "head_struct.h" #include "head_solucaoInicial.h" void firstFit_ordenado (vector<Tbin> &bins, const vector<Titem> itens, const TinfoBins infoBins, const int **matriz_adj){ vector<Titem> itens_ordenados = itens; int contador_bins = 0, aux = -1; int j; sort(itens_ordenados.begin(), itens_ordenados.end(), sort_peso); for(unsigned int i = 0; i < itens_ordenados.size(); i++){ for(j = 0; j < contador_bins; j++){ aux = -1; aux = confere_conflito(itens_ordenados[i].idItem, bins, j, matriz_adj); if(bins[j].pesoLivre >= itens_ordenados[i].peso && aux == 0){ bins[j].pesoUsado += itens_ordenados[i].peso; bins[j].pesoLivre -= itens_ordenados[i].peso; bins[j].items.push_back(itens_ordenados[i].idItem); break; } } if(j == contador_bins){ bins[contador_bins].pesoUsado += itens_ordenados[i].peso; bins[contador_bins].pesoLivre -= itens_ordenados[i].peso; bins[contador_bins].items.push_back(itens_ordenados[i].idItem); contador_bins++; } } bins.resize(contador_bins); } bool sort_peso (const Titem &a, const Titem &b){ return a.peso > b.peso; } int confere_conflito(int id_obj, const vector<Tbin> bins, int j , const int **matriz_adj){ int quant_itens = bins[j].items.size(); if(quant_itens == 0){ return 0; } int i = 0; while(i < quant_itens){ if(matriz_adj[bins[j].items[i]-1][(id_obj-1)] == 1 || matriz_adj [id_obj-1][bins[j].items[i]-1] == 1){ return 1; } i++; } return 0; }
29.873239
122
0.542197
[ "vector" ]
b39bcbec05d02e4d9c9b8c293aea840eb5f4c54b
3,697
cpp
C++
src/mapnik_js_datasource.cpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
src/mapnik_js_datasource.cpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
src/mapnik_js_datasource.cpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
/* #include <mapnik/datasource_cache.hpp> #include "mapnik_js_datasource.hpp" #include "utils.hpp" #include "mem_datasource.hpp" Persistent<FunctionTemplate> JSDatasource::constructor; void JSDatasource::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(JSDatasource::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("JSDatasource")); // methods NODE_SET_PROTOTYPE_METHOD(constructor, "next", next); target->Set(String::NewSymbol("JSDatasource"),constructor->GetFunction()); } JSDatasource::JSDatasource() : ObjectWrap(), ds_ptr_() {} JSDatasource::~JSDatasource() { } Handle<Value> JSDatasource::New(const Arguments& args) { if (!args.IsConstructCall()) return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); if (args[0]->IsExternal()) { //std::clog << "external!\n"; Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); JSDatasource* d = static_cast<JSDatasource*>(ptr); d->Wrap(args.This()); return args.This(); } if (!args.Length() == 2){ return ThrowException(Exception::TypeError( String::New("two argument required: an object of key:value datasource options and a callback function for features"))); } if (!args[0]->IsObject()) return ThrowException(Exception::TypeError( String::New("Must provide an object, eg {extent: '-180,-90,180,90'}"))); Local<Object> options = args[0]->ToObject(); // function callback if (!args[args.Length()-1]->IsFunction()) return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); // TODO - maybe validate in js? bool bind=true; if (options->Has(String::New("bind"))) { Local<Value> bind_opt = options->Get(String::New("bind")); if (!bind_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'bind' must be a Boolean"))); bind = bind_opt->BooleanValue(); } mapnik::parameters params; params["type"] = "js"; Local<Array> names = options->GetPropertyNames(); unsigned int i = 0; unsigned int a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); Local<Value> value = options->Get(name); params[TOSTR(name)] = TOSTR(value); i++; } mapnik::datasource_ptr ds; try { ds = mapnik::datasource_ptr(new js_datasource(params,bind,args[args.Length()-1])); } catch (std::exception const& ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("unknown exception happened, please file bug"))); } if (ds) { JSDatasource* d = new JSDatasource(); d->Wrap(args.This()); d->ds_ptr_ = ds; return args.This(); } return Undefined(); } Handle<Value> JSDatasource::next(const Arguments& args) { HandleScope scope; JSDatasource* d = node::ObjectWrap::Unwrap<JSDatasource>(args.This()); js_datasource *js = dynamic_cast<js_datasource *>(d->ds_ptr_.get()); return scope.Close((*js->cb_)->Call(Context::GetCurrent()->Global(), 0, NULL)); } */
29.576
153
0.60211
[ "object" ]
b39e7bd94200ee5d4b66faa8c5ad784df0bad79e
1,795
cpp
C++
UVA/Map/417_WordIndex.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/Map/417_WordIndex.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/Map/417_WordIndex.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> #include <queue> #include <stack> #include <deque> #include <sstream> #include <set> #include <climits> #include <cstdio> #include <string> #include <map> #include <unordered_map> using namespace std; int alpha[26]; char str[7]; int i, len; bool flag = false; map<string, int> mp[5]; string letters[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; string temp = ""; map<string, int> result; void compute() { for (i = 0; i < 26; i++) mp[0][letters[i]] = i + 1; int idx = 27; for (i = 1; i <= 4; i++) { for (map<string, int>::iterator it = mp[i - 1].begin(); it != mp[i - 1].end(); it++) { temp = it->first; len = temp.length(); for (char j = temp[len - 1] + 1; j <= 'z'; j++) { mp[i][(temp + j)] = idx++; } } } for (i = 0; i <= 4; i++) { for (map<string, int>::iterator it = mp[i].begin(); it != mp[i].end(); it++) { result[it->first] = it->second; } } // for (map<string, int>::iterator it = result.begin(); it != result.end(); it++) { // cout << it->first << " " << it->second << '\n'; // } } void efficient() { queue<string> q; for (i = 0; i < 26; i++) q.push(letters[i]); int count = 1; string s; while (!q.empty()) { s = q.front(); q.pop(); result[s] = count++; if (s.size() == 5) continue; for (char j = s[s.size() - 1] + 1; j <= 'z'; j++) q.push(s + j); } } int main() { #ifndef ONLINE_JUDGE freopen("1.txt", "r", stdin); freopen("2.txt", "w", stdout); #endif efficient(); while (scanf("%s", &str) != EOF) { printf("%d\n", result[string(str)]); } }
22.4375
151
0.491365
[ "vector" ]
b39ff81e79a5728fac616bc21e1c31c7e9ef088d
5,867
cpp
C++
X4ConverterTools/src/model/Part.cpp
dsedivec/X4Converter
1713f2efa266bba29bc395567e58b933060bb923
[ "MIT" ]
5
2019-08-03T19:59:39.000Z
2022-01-29T23:50:55.000Z
X4ConverterTools/src/model/Part.cpp
dsedivec/X4Converter
1713f2efa266bba29bc395567e58b933060bb923
[ "MIT" ]
2
2019-12-06T20:19:29.000Z
2021-05-05T07:07:05.000Z
X4ConverterTools/src/model/Part.cpp
dsedivec/X4Converter
1713f2efa266bba29bc395567e58b933060bb923
[ "MIT" ]
2
2021-12-11T12:27:07.000Z
2021-12-14T04:14:19.000Z
#include "X4ConverterTools/model/Part.h" #include <string> #include <iostream> #include <X4ConverterTools/model/CollisionLod.h> #include <X4ConverterTools/model/VisualLod.h> #include <regex> namespace model { Part::Part(std::shared_ptr<ConversionContext> ctx) : AbstractElement(ctx) { hasRef = false; collisionLod = nullptr; } Part::Part(pugi::xml_node node, std::shared_ptr<ConversionContext> ctx) : AbstractElement(ctx) { if (std::string(node.name()) != "part") { throw std::runtime_error("XML element must be a <part> element!"); } if (node.attribute("name").empty()) { throw std::runtime_error("Part must have a name attribute!"); } hasRef = false; for (auto attr: node.attributes()) { auto attrName = std::string(attr.name()); if (attrName == "ref") { hasRef = true; attrs["DO_NOT_EDIT.ref"] = attr.value(); } else if (attrName == "name") { setName(attr.value()); } else { std::cerr << "Warning, unhandled attribute on part: " << getName() << " attribute: " << attrName << ". This may work fine, just a heads up ;)" << std::endl; attrs[attrName] = attr.value(); } } auto lodsNode = node.child("lods"); if (hasRef && !lodsNode.empty()) { throw std::runtime_error("ref should not contain lods"); } // TODO common with Layer auto lightsNode = node.child("lights"); if (!lightsNode.empty()) { for (auto lightNode: lightsNode.children()) { lights.emplace_back(lightNode, ctx, getName()); } } // TODO figure out a better way if (!hasRef) { collisionLod = std::make_unique<CollisionLod>(getName(), ctx); for (auto lodNode : lodsNode.children()) { auto lod = VisualLod(lodNode, getName(), ctx); lods.insert(std::pair<int, VisualLod>(lod.getIndex(), lod)); } } } aiNode *Part::ConvertToAiNode() { auto *result = new aiNode(getName()); std::vector<aiNode *> children = attrToAiNode(); if (!hasRef) { children.push_back(collisionLod->ConvertToAiNode()); for (auto lod: lods) { children.push_back(lod.second.ConvertToAiNode()); } auto lightResult = new aiNode(); lightResult->mName = getName() + "-lights"; // TODO should really add a Lights object or something std::vector<aiNode *> lightChildren; for (auto light: lights) { lightChildren.push_back(light.ConvertToAiNode()); } populateAiNodeChildren(lightResult, lightChildren); children.push_back(lightResult); } populateAiNodeChildren(result, children); return result; } static std::regex lodRegex("[^-]+\\-lod\\d"); static std::regex collisionRegex("[^-]+\\-collision"); void Part::ConvertFromAiNode(aiNode *node) { std::string name = node->mName.C_Str(); setName(name); for (int i = 0; i < node->mNumChildren; i++) { auto child = node->mChildren[i]; std::string childName = child->mName.C_Str(); // TODO check part names? if (childName == name + "-lights") { handleAiLights(child); } else if (regex_match(childName, lodRegex)) { auto lod = VisualLod(ctx); lod.ConvertFromAiNode(child); lods.insert(std::pair<int, VisualLod>(lod.getIndex(), lod)); } else if (regex_match(childName, collisionRegex)) { collisionLod = std::make_unique<CollisionLod>(ctx); collisionLod->ConvertFromAiNode(child); } else if (childName.find('*') != std::string::npos) { // Ignore connection, handled elsewhere } else { readAiNodeChild(node, child); } } // TODO more } void Part::handleAiLights(aiNode *node) { for (int i = 0; i < node->mNumChildren; i++) { auto child = node->mChildren[i]; lights.emplace_back(child, ctx); } } void Part::ConvertToGameFormat(pugi::xml_node out) { if (std::string(out.name()) != "parts") { throw std::runtime_error("part must be appended to a parts xml element"); } auto partNode = AddChildByAttr(out, "part", "name", getName()); // Note the return statement! referenced parts don't get LODS!!! // TODO remove if lods exist or at least error out if (attrs.count("DO_NOT_EDIT.ref")) { hasRef = true; auto value = attrs["DO_NOT_EDIT.ref"]; if (partNode.attribute("ref")) { partNode.attribute("ref").set_value(value.c_str()); } else { partNode.prepend_attribute("ref").set_value(value.c_str()); } return; } for (const auto &attr : attrs) { WriteAttr(partNode, attr.first, attr.second); } if (!lods.empty()) { auto lodsNode = AddChild(partNode, "lods"); collisionLod->ConvertToGameFormat(partNode); for (auto lod : lods) { lod.second.ConvertToGameFormat(lodsNode); } } else { partNode.remove_child("lods"); } if (!lights.empty()) { auto lightsNode = AddChild(partNode, "lights"); for (auto light : lights) { light.ConvertToGameFormat(lightsNode); } } // TODO out more } }
35.77439
112
0.534686
[ "object", "vector", "model" ]
b3a22e8fc392e22afed418657cda23b5a482e195
139
hpp
C++
addons/ammunition/ammo/762x39.hpp
Theseus-Aegis/GTArmory
771c33044c87625b1b19896fab9aad0fa5a7f21c
[ "MIT" ]
2
2020-02-11T08:08:00.000Z
2020-11-06T13:51:29.000Z
addons/ammunition/ammo/762x39.hpp
Theseus-Aegis/GTArmory
771c33044c87625b1b19896fab9aad0fa5a7f21c
[ "MIT" ]
13
2020-02-10T19:04:32.000Z
2021-05-25T14:38:30.000Z
addons/ammunition/ammo/762x39.hpp
Theseus-Aegis/GTArmory
771c33044c87625b1b19896fab9aad0fa5a7f21c
[ "MIT" ]
1
2021-04-24T20:40:31.000Z
2021-04-24T20:40:31.000Z
class CLASS(762x39_BP): B_762x39_Ball_F { hit = 14; caliber = 2.1; model = "\A3\Weapons_f\Data\bullettracer\tracer_yellow"; };
23.166667
60
0.669065
[ "model" ]