blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca6c7492048501678e1ba6e5a79991e370279e6a | 3ead41a4c3d7f5e9dea45c8409341ac53dceecb1 | /uart_frame.h | f1a742538301e87cf7e32c916a6ea5792c9c1f18 | [] | no_license | acx0/beehive | 03a5e15e2c2b6c0a57d4028374988eda98b2082a | d60b13aac05967267dc3cf81948be9f8c35c18ce | refs/heads/master | 2020-03-19T04:51:15.782788 | 2017-12-11T00:07:34 | 2017-12-11T00:07:34 | 135,874,801 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | h | #ifndef UART_FRAME_H
#define UART_FRAME_H
#include <cstdint>
#include <iterator>
#include <memory>
#include <numeric>
#include <vector>
#include "at_command_response_frame.h"
#include "frame_data.h"
#include "logger.h"
#include "rx_packet_64_frame.h"
#include "tx_request_64_frame.h"
#include "tx_status_frame.h"
#include "util.h"
class uart_frame
{
public:
static const uint8_t FRAME_DELIMITER;
static const uint8_t ESCAPE;
static const uint8_t XON;
static const uint8_t XOFF;
static const uint8_t XOR_CONST;
static const uint8_t CHECKSUM_TARGET;
static const size_t FRAME_DELIMITER_OFFSET;
static const size_t LENGTH_MSB_OFFSET;
static const size_t LENGTH_LSB_OFFSET;
static const size_t API_IDENTIFIER_OFFSET;
static const size_t IDENTIFIER_DATA_OFFSET;
static const size_t HEADER_LENGTH;
static const size_t MIN_FRAME_SIZE;
static const size_t MAX_FRAME_SIZE;
static std::shared_ptr<uart_frame> parse_frame(
std::vector<uint8_t>::const_iterator begin, std::vector<uint8_t>::const_iterator end);
uart_frame(std::shared_ptr<frame_data> data);
uart_frame(
uint8_t length_msb, uint8_t length_lsb, std::shared_ptr<frame_data> data, uint8_t checksum);
uint8_t get_api_identifier() const;
std::shared_ptr<frame_data> get_data();
static uint8_t compute_checksum(
std::vector<uint8_t>::const_iterator begin, std::vector<uint8_t>::const_iterator end);
operator std::vector<uint8_t>() const;
private:
// note: length and checksum fields only populated when reading response frames
uint8_t length_msb;
uint8_t length_lsb;
std::shared_ptr<frame_data> data;
uint8_t checksum;
};
#endif
| [
"sam.lidder@gmail.com"
] | sam.lidder@gmail.com |
ee77ad583c4763f8c836d9da9700fb26c6918a30 | 5ddd0ec20099a9c3ffe865c835dcceb5b7fd0332 | /of_v0.8.0_vs_release-gesture-recognizer/libs/openFrameworks/types/ofColor.cpp | c651d631dd9ebe97256b195dfd67459d67870172 | [
"MIT"
] | permissive | MarkusKonk/Geographic-Interaction | af81f9f4c7c201dd55843d4dd0d369f2f407d480 | b74f6f04656611df8dc4ebdea43f263cea67b366 | refs/heads/master | 2020-12-30T10:36:34.414880 | 2014-02-03T12:37:45 | 2014-02-03T12:37:45 | 13,868,029 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 32,637 | cpp | #include "ofColor.h"
#include "ofConstants.h"
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gray(limit() / 2, limit() / 2, limit() / 2);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::white(limit(), limit(), limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::red(limit(), 0, 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::green(0, limit(), 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blue(0, 0, limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cyan(0, limit(), limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::magenta(limit(), 0, limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::yellow(limit(), limit(), 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::black(0, 0, 0);
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aliceBlue(0.941176*limit(),0.972549*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::antiqueWhite(0.980392*limit(),0.921569*limit(),0.843137*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aqua(0*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::aquamarine(0.498039*limit(),1*limit(),0.831373*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::azure(0.941176*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::beige(0.960784*limit(),0.960784*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::bisque(1*limit(),0.894118*limit(),0.768627*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blanchedAlmond(1*limit(),0.921569*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blueViolet(0.541176*limit(),0.168627*limit(),0.886275*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::brown(0.647059*limit(),0.164706*limit(),0.164706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::burlyWood(0.870588*limit(),0.721569*limit(),0.529412*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cadetBlue(0.372549*limit(),0.619608*limit(),0.627451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::chartreuse(0.498039*limit(),1*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::chocolate(0.823529*limit(),0.411765*limit(),0.117647*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::coral(1*limit(),0.498039*limit(),0.313726*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cornflowerBlue(0.392157*limit(),0.584314*limit(),0.929412*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::cornsilk(1*limit(),0.972549*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::crimson(0.862745*limit(),0.0784314*limit(),0.235294*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkBlue(0*limit(),0*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkCyan(0*limit(),0.545098*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGoldenRod(0.721569*limit(),0.52549*limit(),0.0431373*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGray(0.662745*limit(),0.662745*limit(),0.662745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGrey(0.662745*limit(),0.662745*limit(),0.662745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkGreen(0*limit(),0.392157*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkKhaki(0.741176*limit(),0.717647*limit(),0.419608*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkMagenta(0.545098*limit(),0*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkOliveGreen(0.333333*limit(),0.419608*limit(),0.184314*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkorange(1*limit(),0.54902*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkOrchid(0.6*limit(),0.196078*limit(),0.8*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkRed(0.545098*limit(),0*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSalmon(0.913725*limit(),0.588235*limit(),0.478431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSeaGreen(0.560784*limit(),0.737255*limit(),0.560784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateBlue(0.282353*limit(),0.239216*limit(),0.545098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateGray(0.184314*limit(),0.309804*limit(),0.309804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkSlateGrey(0.184314*limit(),0.309804*limit(),0.309804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkTurquoise(0*limit(),0.807843*limit(),0.819608*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::darkViolet(0.580392*limit(),0*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::deepPink(1*limit(),0.0784314*limit(),0.576471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::deepSkyBlue(0*limit(),0.74902*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dimGray(0.411765*limit(),0.411765*limit(),0.411765*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dimGrey(0.411765*limit(),0.411765*limit(),0.411765*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::dodgerBlue(0.117647*limit(),0.564706*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::fireBrick(0.698039*limit(),0.133333*limit(),0.133333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::floralWhite(1*limit(),0.980392*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::forestGreen(0.133333*limit(),0.545098*limit(),0.133333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::fuchsia(1*limit(),0*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gainsboro(0.862745*limit(),0.862745*limit(),0.862745*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::ghostWhite(0.972549*limit(),0.972549*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::gold(1*limit(),0.843137*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::goldenRod(0.854902*limit(),0.647059*limit(),0.12549*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::grey(0.501961*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::greenYellow(0.678431*limit(),1*limit(),0.184314*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::honeyDew(0.941176*limit(),1*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::hotPink(1*limit(),0.411765*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::indianRed (0.803922*limit(),0.360784*limit(),0.360784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::indigo (0.294118*limit(),0*limit(),0.509804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::ivory(1*limit(),1*limit(),0.941176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::khaki(0.941176*limit(),0.901961*limit(),0.54902*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lavender(0.901961*limit(),0.901961*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lavenderBlush(1*limit(),0.941176*limit(),0.960784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lawnGreen(0.486275*limit(),0.988235*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lemonChiffon(1*limit(),0.980392*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightBlue(0.678431*limit(),0.847059*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightCoral(0.941176*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightCyan(0.878431*limit(),1*limit(),1*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGoldenRodYellow(0.980392*limit(),0.980392*limit(),0.823529*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGray(0.827451*limit(),0.827451*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGrey(0.827451*limit(),0.827451*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightGreen(0.564706*limit(),0.933333*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightPink(1*limit(),0.713726*limit(),0.756863*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSalmon(1*limit(),0.627451*limit(),0.478431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSeaGreen(0.12549*limit(),0.698039*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSkyBlue(0.529412*limit(),0.807843*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSlateGray(0.466667*limit(),0.533333*limit(),0.6*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSlateGrey(0.466667*limit(),0.533333*limit(),0.6*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightSteelBlue(0.690196*limit(),0.768627*limit(),0.870588*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lightYellow(1*limit(),1*limit(),0.878431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::lime(0*limit(),1*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::limeGreen(0.196078*limit(),0.803922*limit(),0.196078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::linen(0.980392*limit(),0.941176*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::maroon(0.501961*limit(),0*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumAquaMarine(0.4*limit(),0.803922*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumBlue(0*limit(),0*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumOrchid(0.729412*limit(),0.333333*limit(),0.827451*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumPurple(0.576471*limit(),0.439216*limit(),0.858824*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSeaGreen(0.235294*limit(),0.701961*limit(),0.443137*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSlateBlue(0.482353*limit(),0.407843*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumSpringGreen(0*limit(),0.980392*limit(),0.603922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumTurquoise(0.282353*limit(),0.819608*limit(),0.8*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mediumVioletRed(0.780392*limit(),0.0823529*limit(),0.521569*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::midnightBlue(0.0980392*limit(),0.0980392*limit(),0.439216*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mintCream(0.960784*limit(),1*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::mistyRose(1*limit(),0.894118*limit(),0.882353*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::moccasin(1*limit(),0.894118*limit(),0.709804*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::navajoWhite(1*limit(),0.870588*limit(),0.678431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::navy(0*limit(),0*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::oldLace(0.992157*limit(),0.960784*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::olive(0.501961*limit(),0.501961*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::oliveDrab(0.419608*limit(),0.556863*limit(),0.137255*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orange(1*limit(),0.647059*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orangeRed(1*limit(),0.270588*limit(),0*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::orchid(0.854902*limit(),0.439216*limit(),0.839216*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleGoldenRod(0.933333*limit(),0.909804*limit(),0.666667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleGreen(0.596078*limit(),0.984314*limit(),0.596078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleTurquoise(0.686275*limit(),0.933333*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::paleVioletRed(0.858824*limit(),0.439216*limit(),0.576471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::papayaWhip(1*limit(),0.937255*limit(),0.835294*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::peachPuff(1*limit(),0.854902*limit(),0.72549*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::peru(0.803922*limit(),0.521569*limit(),0.247059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::pink(1*limit(),0.752941*limit(),0.796078*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::plum(0.866667*limit(),0.627451*limit(),0.866667*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::powderBlue(0.690196*limit(),0.878431*limit(),0.901961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::purple(0.501961*limit(),0*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::rosyBrown(0.737255*limit(),0.560784*limit(),0.560784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::royalBlue(0.254902*limit(),0.411765*limit(),0.882353*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::saddleBrown(0.545098*limit(),0.270588*limit(),0.0745098*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::salmon(0.980392*limit(),0.501961*limit(),0.447059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::sandyBrown(0.956863*limit(),0.643137*limit(),0.376471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::seaGreen(0.180392*limit(),0.545098*limit(),0.341176*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::seaShell(1*limit(),0.960784*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::sienna(0.627451*limit(),0.321569*limit(),0.176471*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::silver(0.752941*limit(),0.752941*limit(),0.752941*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::skyBlue(0.529412*limit(),0.807843*limit(),0.921569*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateBlue(0.415686*limit(),0.352941*limit(),0.803922*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateGray(0.439216*limit(),0.501961*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::slateGrey(0.439216*limit(),0.501961*limit(),0.564706*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::snow(1*limit(),0.980392*limit(),0.980392*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::springGreen(0*limit(),1*limit(),0.498039*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::steelBlue(0.27451*limit(),0.509804*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::blueSteel(0.27451*limit(),0.509804*limit(),0.705882*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::tan(0.823529*limit(),0.705882*limit(),0.54902*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::teal(0*limit(),0.501961*limit(),0.501961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::thistle(0.847059*limit(),0.74902*limit(),0.847059*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::tomato(1*limit(),0.388235*limit(),0.278431*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::turquoise(0.25098*limit(),0.878431*limit(),0.815686*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::violet(0.933333*limit(),0.509804*limit(),0.933333*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::wheat(0.960784*limit(),0.870588*limit(),0.701961*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::whiteSmoke(0.960784*limit(),0.960784*limit(),0.960784*limit());
template<typename PixelType> const ofColor_<PixelType> ofColor_<PixelType>::yellowGreen(0.603922*limit(),0.803922*limit(),0.196078*limit());
template<typename A, typename B>
A clampedSubtract(const A& a, const B& b) {
return CLAMP((float) a - (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedAdd(const A& a, const B& b) {
return CLAMP((float) a + (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedDivide(const A& a, const B& b) {
return CLAMP((float) a / (float) b, 0, ofColor_<A>::limit());
}
template<typename A, typename B>
A clampedMultiply(const A& a, const B& b) {
return CLAMP((float) a * (float) b, 0, ofColor_<A>::limit());
}
template<typename PixelType>
float ofColor_<PixelType>::limit() {
return numeric_limits<PixelType>::max();
}
template<>
float ofColor_<float>::limit() {
return 1.f;
}
template<typename PixelType>
ofColor_<PixelType>::ofColor_ (){
r = limit();
g = limit();
b = limit();
a = limit();
}
template<typename PixelType>
ofColor_<PixelType>::~ofColor_ (){}
template<typename PixelType>
ofColor_<PixelType>::ofColor_ (float _r, float _g, float _b, float _a){
r = _r;
g = _g;
b = _b;
a = _a;
}
template<typename PixelType>
ofColor_<PixelType>::ofColor_ (const ofColor_<PixelType> & color){
r = color.r;
g = color.g;
b = color.b;
a = color.a;
}
template<typename PixelType>
ofColor_<PixelType>::ofColor_ (const ofColor_<PixelType> & color, float _a){
r = color.r;
g = color.g;
b = color.b;
a = _a;
}
template<typename PixelType>
ofColor_<PixelType>::ofColor_ (float gray, float _a){
r = g = b = gray;
a = _a;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::fromHsb (float hue, float saturation, float brightness, float alpha) {
ofColor_<PixelType> cur;
cur.setHsb(hue, saturation, brightness, alpha);
return cur;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::fromHex(int hexColor, float alpha) {
ofColor_<PixelType> cur;
cur.setHex(hexColor, alpha);
return cur;
}
template<typename PixelType>
void ofColor_<PixelType>::set (float _r, float _g, float _b, float _a){
r = _r;
g = _g;
b = _b;
a = _a;
}
template<typename PixelType>
void ofColor_<PixelType>::set (float _gray, float _a){
r = g = b = _gray;
a = _a;
}
template<typename PixelType>
void ofColor_<PixelType>::set (ofColor_<PixelType> const & color){
r = color.r;
g = color.g;
b = color.b;
a = color.a;
}
template<>
void ofColor_<unsigned char>::setHex (int hexColor, float alpha){
r = (hexColor >> 16) & 0xff;
g = (hexColor >> 8) & 0xff;
b = (hexColor >> 0) & 0xff;
a = alpha;
}
template<typename PixelType>
void ofColor_<PixelType>::setHex (int hexColor, float alpha){
ofColor c = ofColor::fromHex(hexColor);
*this = c;
a = alpha;
}
template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::clamp (){
r = CLAMP(r, 0.0f, limit());
g = CLAMP(g, 0.0f, limit());
b = CLAMP(b, 0.0f, limit());
a = CLAMP(a, 0.0f, limit());
return *this;
}
template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::invert() {
r = limit() - r;
g = limit() - g;
b = limit() - b;
return *this;
}
template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::normalize() {
float scaleFactor = getBrightness() / limit();
*this /= scaleFactor;
return *this;
}
template<typename PixelType>
ofColor_<PixelType>& ofColor_<PixelType>::lerp(const ofColor_<PixelType>& target, float amount) {
float invAmount = 1.f - amount;
r = invAmount * r + amount * target.r;
g = invAmount * g + amount * target.g;
b = invAmount * b + amount * target.b;
a = invAmount * a + amount * target.a;
return *this;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getClamped () const {
ofColor_<PixelType> cur(*this);
cur.clamp();
return cur;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getInverted () const {
ofColor_<PixelType> cur(*this);
cur.invert();
return cur;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getNormalized () const {
ofColor_<PixelType> cur(*this);
cur.normalize();
return cur;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::getLerped(const ofColor_<PixelType>& target, float amount) const {
ofColor_<PixelType> cur(*this);
cur.lerp(target, amount);
return cur;
}
template<typename PixelType>
float ofColor_<PixelType>::getHue() const {
float hue, saturation, brightness;
getHsb(hue, saturation, brightness);
return hue;
}
template<typename PixelType>
float ofColor_<PixelType>::getSaturation() const {
float hue, saturation, brightness;
getHsb(hue, saturation, brightness);
return saturation;
}
/*
Brightness is simply the maximum of the three color components.
This is used by Photoshop (HSB) and Processing (HSB).
Brightness is also called "value".
*/
template<typename PixelType>
float ofColor_<PixelType>::getBrightness() const {
float max = r;
if(g > max) {
max = g;
}
if(b > max) {
max = b;
}
return max;
}
/*
Lightness is the average of the three color components.
This is used by the Lab and HSL color spaces.
*/
template<typename PixelType>
float ofColor_<PixelType>::getLightness() const {
return (r + g + b) / 3.f;
}
template<typename PixelType>
void ofColor_<PixelType>::getHsb(float& hue, float& saturation, float& brightness) const {
float max = getBrightness();
float min = r;
if(g < min) {
min = g;
}
if(b < min) {
min = b;
}
if(max == min) { // grays
hue = 0.f;
saturation = 0.f;
brightness = max;
return;
}
float hueSixth;
if(r == max) {
hueSixth = (g - b) / (max - min);
if(hueSixth < 0.f)
hueSixth += 6.f;
} else if (g == max) {
hueSixth = 2.f + (b - r) / (max - min);
} else {
hueSixth = 4.f + (r - g) / (max - min);
}
hue = limit() * hueSixth / 6.f;
saturation = limit() * (max - min) / max;
brightness = max;
}
template<typename PixelType>
void ofColor_<PixelType>::setHue (float hue) {
float oldHue, saturation, brightness;
getHsb(oldHue, saturation, brightness);
setHsb(hue, saturation, brightness, a );
}
template<typename PixelType>
void ofColor_<PixelType>::setSaturation (float saturation) {
float hue, oldSaturation, brightness;
getHsb(hue, oldSaturation, brightness);
setHsb(hue, saturation, brightness, a );
}
template<typename PixelType>
void ofColor_<PixelType>::setBrightness (float brightness) {
float hue, saturation, oldBrightness;
getHsb(hue, saturation, oldBrightness);
setHsb(hue, saturation, brightness, a );
}
template<typename PixelType>
void ofColor_<PixelType>::setHsb(float hue, float saturation, float brightness, float alpha ) {
saturation = ofClamp(saturation, 0, limit());
brightness = ofClamp(brightness, 0, limit());
if(brightness == 0) { // black
set(0);
} else if(saturation == 0) { // grays
set(brightness);
} else {
float hueSix = hue * 6. / limit();
float saturationNorm = saturation / limit();
int hueSixCategory = (int) floorf(hueSix);
float hueSixRemainder = hueSix - hueSixCategory;
PixelType pv = (PixelType) ((1.f - saturationNorm) * brightness);
PixelType qv = (PixelType) ((1.f - saturationNorm * hueSixRemainder) * brightness);
PixelType tv = (PixelType) ((1.f - saturationNorm * (1.f - hueSixRemainder)) * brightness);
switch(hueSixCategory) {
case 0: case 6: // r
r = brightness;
g = tv;
b = pv;
break;
case 1: // g
r = qv;
g = brightness;
b = pv;
break;
case 2:
r = pv;
g = brightness;
b = tv;
break;
case 3: // b
r = pv;
g = qv;
b = brightness;
break;
case 4:
r = tv;
g = pv;
b = brightness;
break;
case 5: // back to r
r = brightness;
g = pv;
b = qv;
break;
}
}
// finally assign the alpha
a = alpha;
}
template<>
int ofColor_<unsigned char>::getHex () const {
return
((0xff & (unsigned char) r) << 16) |
((0xff & (unsigned char) g) << 8) |
((0xff & (unsigned char) b));
}
template<typename PixelType>
int ofColor_<PixelType>::getHex () const {
return ((ofColor) *this).getHex();
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator = (ofColor_<PixelType> const & color){
r = color.r;
g = color.g;
b = color.b;
a = color.a;
return *this;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator = (float const & val){
r = val;
g = val;
b = val;
a = limit();
return *this;
}
template<typename PixelType>
bool ofColor_<PixelType>::operator == (ofColor_<PixelType> const & color){
return (r == color.r) && (g == color.g) && (b == color.b);
}
template<typename PixelType>
bool ofColor_<PixelType>::operator != (ofColor_<PixelType> const & color){
return (r != color.r) || (g != color.g) || (b != color.b);
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator + (ofColor_<PixelType> const & color) const{
ofColor_<PixelType> result(*this);
result += color;
return result;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator + (float const & val) const{
ofColor_<PixelType> result(*this);
result += val;
return result;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator += (ofColor_<PixelType> const & color){
r = clampedAdd(r, color.r);
g = clampedAdd(g, color.g);
b = clampedAdd(b, color.b);
return *this;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator += (float const & val){
r = clampedAdd(r, val);
g = clampedAdd(g, val);
b = clampedAdd(b, val);
return *this;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator - (ofColor_<PixelType> const & color) const{
ofColor_<PixelType> result(*this);
result -= color;
return result;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator - (float const & val) const{
ofColor_<PixelType> result(*this);
result -= val;
return result;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator -= (ofColor_<PixelType> const & color){
r = clampedSubtract(r, color.r);
g = clampedSubtract(g, color.g);
b = clampedSubtract(b, color.b);
return *this;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator -= (float const & val){
r = clampedSubtract(r, val);
g = clampedSubtract(g, val);
b = clampedSubtract(b, val);
return *this;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator * (ofColor_<PixelType> const & color) const{
ofColor_<PixelType> result(*this);
result *= color;
return result;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator * (float const & val) const{
ofColor_<PixelType> result(*this);
result *= val;
return result;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator *= (ofColor_<PixelType> const & color){
r = clampedMultiply(r, (float) color.r / limit());
g = clampedMultiply(g, (float) color.g / limit());
b = clampedMultiply(b, (float) color.b / limit());
return *this;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator *= (float const & val){
r = clampedMultiply(r, val);
g = clampedMultiply(g, val);
b = clampedMultiply(b, val);
return *this;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator / (ofColor_<PixelType> const & color) const{
ofColor_<PixelType> result(*this);
result /= color;
return result;
}
template<typename PixelType>
ofColor_<PixelType> ofColor_<PixelType>::operator / (float const & val) const{
ofColor_<PixelType> result(*this);
result /= val;
return result;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator /= (ofColor_<PixelType> const & color){
r = clampedDivide(r, (float) color.r / limit());
g = clampedDivide(g, (float) color.g / limit());
b = clampedDivide(b, (float) color.b / limit());
return *this;
}
template<typename PixelType>
ofColor_<PixelType> & ofColor_<PixelType>::operator /= (float const & val){
r = clampedDivide(r, val);
g = clampedDivide(g, val);
b = clampedDivide(b, val);
return *this;
}
template<typename PixelType>
const PixelType & ofColor_<PixelType>::operator [] (int n) const{
switch( n ){
case 0:
return r;
case 1:
return g;
case 2:
return b;
case 3:
return a;
default:
return r;
break;
}
}
template<typename PixelType>
PixelType & ofColor_<PixelType>::operator [] (int n){
switch( n ){
case 0:
return r;
case 1:
return g;
case 2:
return b;
case 3:
return a;
default:
return r;
break;
}
}
template class ofColor_<char>;
template class ofColor_<unsigned char>;
template class ofColor_<short>;
template class ofColor_<unsigned short>;
template class ofColor_<int>;
template class ofColor_<unsigned int>;
template class ofColor_<long>;
template class ofColor_<unsigned long>;
template class ofColor_<float>;
template class ofColor_<double>;
| [
"matthias.m.hinz@googlemail.com"
] | matthias.m.hinz@googlemail.com |
c3ac7b699d75b5a5fd256fbb7bd125f079e65ced | ab1c643f224197ca8c44ebd562953f0984df321e | /wmi/wbem/providers/win32provider/cimwin32a/win32_controllerhashub.cpp | e6ccdba949a52b3fce98fdb7c65fab2cbbf5c7f4 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_admin | e162e0452fb2067f0675745f2273d5c569798709 | d36e522f16bd866384bec440517f954a1a5c4a4d | refs/heads/master | 2023-04-12T13:25:45.807158 | 2021-04-13T16:33:59 | 2021-04-13T16:33:59 | 357,613,696 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | cpp | //=================================================================
//
// Win32_ControllerHasHub.cpp -- Controller to usb hub assoc
//
// Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved
//
//=================================================================
#include "precomp.h"
#include <Binding.h>
#include <ConfgMgr.h>
#include "Win32_ControllerHasHub.h"
CContHasHub::CContHasHub(
LPCWSTR pwszClassName,
LPCWSTR pwszNamespaceName,
LPCWSTR pwszLeftClassName,
LPCWSTR pwszRightClassName,
LPCWSTR pwszLeftPropertyName,
LPCWSTR pwszRightPropertyName,
LPCWSTR pwszLeftBindingPropertyName,
LPCWSTR pwszRightBindingPropertyName
) : CBinding (
pwszClassName,
pwszNamespaceName,
pwszLeftClassName,
pwszRightClassName,
pwszLeftPropertyName,
pwszRightPropertyName,
pwszLeftBindingPropertyName,
pwszRightBindingPropertyName
)
{
}
CContHasHub UserToDomain(
L"Win32_ControllerHasHub",
IDS_CimWin32Namespace,
L"Win32_USBController",
L"Win32_USBHub",
IDS_Antecedent,
IDS_Dependent,
IDS_DeviceID,
IDS_DeviceID
);
bool CContHasHub::AreRelated(
const CInstance *pLeft,
const CInstance *pRight
)
{
// Ok, at this point, we know pLeft is a usb controller and pRight
// is a usb hub. The only question left is whether the usb controller
// is controlling this specific hub.
bool bRet = false;
CHString sHub;
pRight->GetCHString(IDS_DeviceID, sHub);
CConfigManager cfgmgr;
CConfigMgrDevicePtr pDevice, pParentDevice;
if ( cfgmgr.LocateDevice ( sHub , pDevice ) )
{
CHString sController, sDeviceID;
pLeft->GetCHString(IDS_DeviceID, sController);
while (pDevice->GetParent(pParentDevice))
{
pParentDevice->GetDeviceID(sDeviceID);
if (sDeviceID.CompareNoCase(sController) == 0)
{
bRet = true;
break;
}
else
{
pDevice = pParentDevice;
}
}
}
return bRet;
} | [
"polarisdp@gmail.com"
] | polarisdp@gmail.com |
7b20d17896b84814f3ee2ab170f65cfc2c6a17cb | 90047daeb462598a924d76ddf4288e832e86417c | /third_party/WebKit/Source/platform/loader/fetch/ResourceRequestTest.cpp | d769c49386158941afe21b2451a0018d290dd117 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 7,103 | cpp | // Copyright 2014 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 "platform/loader/fetch/ResourceRequest.h"
#include <memory>
#include "platform/network/EncodedFormData.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/Referrer.h"
#include "platform/wtf/text/AtomicString.h"
#include "public/platform/WebCachePolicy.h"
#include "public/platform/WebURLRequest.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
TEST(ResourceRequestTest, RequestorOriginNonNull) {
ResourceRequest req;
EXPECT_NE(nullptr, req.RequestorOrigin().Get());
EXPECT_TRUE(req.RequestorOrigin()->IsUnique());
}
TEST(ResourceRequestTest, CrossThreadResourceRequestData) {
ResourceRequest original;
original.SetURL(KURL(kParsedURLString, "http://www.example.com/test.htm"));
original.SetCachePolicy(WebCachePolicy::kUseProtocolCachePolicy);
original.SetTimeoutInterval(10);
original.SetFirstPartyForCookies(
KURL(kParsedURLString, "http://www.example.com/first_party.htm"));
original.SetRequestorOrigin(SecurityOrigin::Create(
KURL(kParsedURLString, "http://www.example.com/first_party.htm")));
original.SetHTTPMethod(HTTPNames::GET);
original.SetHTTPHeaderField(AtomicString("Foo"), AtomicString("Bar"));
original.SetHTTPHeaderField(AtomicString("Piyo"), AtomicString("Fuga"));
original.SetPriority(kResourceLoadPriorityLow, 20);
RefPtr<EncodedFormData> original_body(EncodedFormData::Create("Test Body"));
original.SetHTTPBody(original_body);
original.SetAllowStoredCredentials(false);
original.SetReportUploadProgress(false);
original.SetHasUserGesture(false);
original.SetDownloadToFile(false);
original.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kAll);
original.SetFetchRequestMode(WebURLRequest::kFetchRequestModeCORS);
original.SetFetchCredentialsMode(
WebURLRequest::kFetchCredentialsModeSameOrigin);
original.SetRequestorID(30);
original.SetRequestorProcessID(40);
original.SetAppCacheHostID(50);
original.SetRequestContext(WebURLRequest::kRequestContextAudio);
original.SetFrameType(WebURLRequest::kFrameTypeNested);
original.SetHTTPReferrer(
Referrer("http://www.example.com/referrer.htm", kReferrerPolicyDefault));
EXPECT_STREQ("http://www.example.com/test.htm",
original.Url().GetString().Utf8().data());
EXPECT_EQ(WebCachePolicy::kUseProtocolCachePolicy, original.GetCachePolicy());
EXPECT_EQ(10, original.TimeoutInterval());
EXPECT_STREQ("http://www.example.com/first_party.htm",
original.FirstPartyForCookies().GetString().Utf8().data());
EXPECT_STREQ("www.example.com",
original.RequestorOrigin()->Host().Utf8().data());
EXPECT_STREQ("GET", original.HttpMethod().Utf8().data());
EXPECT_STREQ("Bar", original.HttpHeaderFields().Get("Foo").Utf8().data());
EXPECT_STREQ("Fuga", original.HttpHeaderFields().Get("Piyo").Utf8().data());
EXPECT_EQ(kResourceLoadPriorityLow, original.Priority());
EXPECT_STREQ("Test Body",
original.HttpBody()->FlattenToString().Utf8().data());
EXPECT_FALSE(original.AllowStoredCredentials());
EXPECT_FALSE(original.ReportUploadProgress());
EXPECT_FALSE(original.HasUserGesture());
EXPECT_FALSE(original.DownloadToFile());
EXPECT_EQ(WebURLRequest::ServiceWorkerMode::kAll,
original.GetServiceWorkerMode());
EXPECT_EQ(WebURLRequest::kFetchRequestModeCORS,
original.GetFetchRequestMode());
EXPECT_EQ(WebURLRequest::kFetchCredentialsModeSameOrigin,
original.GetFetchCredentialsMode());
EXPECT_EQ(30, original.RequestorID());
EXPECT_EQ(40, original.RequestorProcessID());
EXPECT_EQ(50, original.AppCacheHostID());
EXPECT_EQ(WebURLRequest::kRequestContextAudio, original.GetRequestContext());
EXPECT_EQ(WebURLRequest::kFrameTypeNested, original.GetFrameType());
EXPECT_STREQ("http://www.example.com/referrer.htm",
original.HttpReferrer().Utf8().data());
EXPECT_EQ(kReferrerPolicyDefault, original.GetReferrerPolicy());
std::unique_ptr<CrossThreadResourceRequestData> data1(original.CopyData());
ResourceRequest copy1(data1.get());
EXPECT_STREQ("http://www.example.com/test.htm",
copy1.Url().GetString().Utf8().data());
EXPECT_EQ(WebCachePolicy::kUseProtocolCachePolicy, copy1.GetCachePolicy());
EXPECT_EQ(10, copy1.TimeoutInterval());
EXPECT_STREQ("http://www.example.com/first_party.htm",
copy1.FirstPartyForCookies().GetString().Utf8().data());
EXPECT_STREQ("www.example.com",
copy1.RequestorOrigin()->Host().Utf8().data());
EXPECT_STREQ("GET", copy1.HttpMethod().Utf8().data());
EXPECT_STREQ("Bar", copy1.HttpHeaderFields().Get("Foo").Utf8().data());
EXPECT_EQ(kResourceLoadPriorityLow, copy1.Priority());
EXPECT_STREQ("Test Body", copy1.HttpBody()->FlattenToString().Utf8().data());
EXPECT_FALSE(copy1.AllowStoredCredentials());
EXPECT_FALSE(copy1.ReportUploadProgress());
EXPECT_FALSE(copy1.HasUserGesture());
EXPECT_FALSE(copy1.DownloadToFile());
EXPECT_EQ(WebURLRequest::ServiceWorkerMode::kAll,
copy1.GetServiceWorkerMode());
EXPECT_EQ(WebURLRequest::kFetchRequestModeCORS, copy1.GetFetchRequestMode());
EXPECT_EQ(WebURLRequest::kFetchCredentialsModeSameOrigin,
copy1.GetFetchCredentialsMode());
EXPECT_EQ(30, copy1.RequestorID());
EXPECT_EQ(40, copy1.RequestorProcessID());
EXPECT_EQ(50, copy1.AppCacheHostID());
EXPECT_EQ(WebURLRequest::kRequestContextAudio, copy1.GetRequestContext());
EXPECT_EQ(WebURLRequest::kFrameTypeNested, copy1.GetFrameType());
EXPECT_STREQ("http://www.example.com/referrer.htm",
copy1.HttpReferrer().Utf8().data());
EXPECT_EQ(kReferrerPolicyDefault, copy1.GetReferrerPolicy());
copy1.SetAllowStoredCredentials(true);
copy1.SetReportUploadProgress(true);
copy1.SetHasUserGesture(true);
copy1.SetDownloadToFile(true);
copy1.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone);
copy1.SetFetchRequestMode(WebURLRequest::kFetchRequestModeNoCORS);
copy1.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeInclude);
std::unique_ptr<CrossThreadResourceRequestData> data2(copy1.CopyData());
ResourceRequest copy2(data2.get());
EXPECT_TRUE(copy2.AllowStoredCredentials());
EXPECT_TRUE(copy2.ReportUploadProgress());
EXPECT_TRUE(copy2.HasUserGesture());
EXPECT_TRUE(copy2.DownloadToFile());
EXPECT_EQ(WebURLRequest::ServiceWorkerMode::kNone,
copy2.GetServiceWorkerMode());
EXPECT_EQ(WebURLRequest::kFetchRequestModeNoCORS,
copy1.GetFetchRequestMode());
EXPECT_EQ(WebURLRequest::kFetchCredentialsModeInclude,
copy1.GetFetchCredentialsMode());
}
TEST(ResourceRequestTest, SetHasUserGesture) {
ResourceRequest original;
EXPECT_FALSE(original.HasUserGesture());
original.SetHasUserGesture(true);
EXPECT_TRUE(original.HasUserGesture());
original.SetHasUserGesture(false);
EXPECT_TRUE(original.HasUserGesture());
}
} // namespace blink
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
66b03ee6eec72ce6cfacc16b81a55cc6ad1d0a1d | 157ee4d0f6d8834bc06baf15d4c9b0ed43bad0fe | /cat/applicative/optional.hpp | f6df26ef90574e4648cf5c13d8fadd0491425ebf | [] | no_license | antmd/cat | f75ba86bce82c639b6999c7595a755a836ffe526 | e4f37e7a8c28b177765106745724129a4e5f869e | refs/heads/master | 2021-01-21T16:31:33.468526 | 2015-04-30T07:53:29 | 2015-04-30T07:53:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,873 | hpp | /******************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2014-15 Nicola Bonelli <nicola@pfq.io>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
******************************************************************************/
#pragma once
#include <cat/optional.hpp>
#include <cat/applicative/applicative.hpp>
namespace cat
{
// optional is an applicative instance:
//
template <> struct is_applicative<optional> : std::true_type { };
// optional instance:
//
template <typename F, typename A, typename Ff_, typename Fa_, typename A_>
struct ApplicativeInstance<optional<F>, optional<A>, Ff_, Fa_, A_> final : Applicative<optional>::
template _<F, A, Ff_, Fa_, A_>
{
using B = std::result_of_t<F(A_)>;
optional<A>
pure(A_ &&elem) override
{
return make_optional(std::forward<A_>(elem));
}
optional<B>
apply(Ff_ && f, Fa_ &&x) override
{
if (f && x)
return make_optional<B>(forward_as<Ff_>(*f)(forward_as<Fa_>(*x)));
return {};
}
};
// optional is an alternative instance:
//
template <> struct is_alternative<optional> : std::true_type { };
// optional instance:
//
template <typename A, typename Fl_, typename Fr_>
struct AlternativeInstance<optional<A>, Fl_, Fr_> final : Alternative<optional>::
template _<optional<A>, Fl_, Fr_>
{
optional<A>
empty() override
{
return optional<A>{};
}
optional<A>
or_(Fl_ && lhs, Fr_ && rhs) override
{
if (lhs)
return std::forward<Fl_>(lhs);
return std::forward<Fr_>(rhs);
}
};
} // namespace cat
| [
"nicola.bonelli@gmail.com"
] | nicola.bonelli@gmail.com |
0a4af763a4a67f2021cbd9b1e8f321610d7d8878 | 5647bc026240464efd3e3a0a6ab88744d3fa3618 | /src/iucore/convert.cpp | a6a71be0427102e6c463c909eba371b9e40d97c9 | [] | no_license | nemobtx/imageutilities | 94f2605a970bed5988481fd14ec93bc7247dce0e | 96901c94045890e97ea859dc9bb8cd6dfcaee088 | refs/heads/master | 2020-12-02T19:22:29.090868 | 2016-03-06T19:59:10 | 2016-03-06T19:59:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,793 | cpp | /*
* Copyright (c) ICG. All rights reserved.
*
* Institute for Computer Graphics and Vision
* Graz University of Technology / Austria
*
*
* This software is distributed WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notices for more information.
*
*
* Project : ImageUtilities
* Module : Core
* Class : none
* Language : C
* Description : Implementation of convert operations on host and device memory
*
* Author : Manuel Werlberger
* EMail : werlberger@icg.tugraz.at
*
*/
#include <cstring>
#include "convert.h"
namespace iuprivate {
/* ***************************************************************************
* Declaration of CUDA WRAPPERS
* ***************************************************************************/
extern IuStatus cuConvert(const iu::ImageGpu_32f_C3* src, const IuRect& src_roi,
iu::ImageGpu_32f_C4* dst, const IuRect& dst_roi);
extern IuStatus cuConvert(const iu::ImageGpu_32f_C4* src, const IuRect& src_roi,
iu::ImageGpu_32f_C3* dst, const IuRect& dst_roi);
extern IuStatus cuConvert_8u_32f(const iu::ImageGpu_8u_C1* src, const IuRect& src_roi,
iu::ImageGpu_32f_C1* dst, const IuRect& dst_roi,
float mul_constant, float add_constant);
extern IuStatus cuConvert_32f_8u(const iu::ImageGpu_32f_C1* src, const IuRect& src_roi,
iu::ImageGpu_8u_C1* dst, const IuRect& dst_roi,
float mul_constant, unsigned char add_constant);
extern IuStatus cuConvert_32f_8u(const iu::ImageGpu_32f_C4* src, const IuRect& src_roi,
iu::ImageGpu_8u_C4* dst, const IuRect& dst_roi,
float mul_constant, unsigned char add_constant);
extern IuStatus cuConvert_rgb_to_hsv(const iu::ImageGpu_32f_C4* src, iu::ImageGpu_32f_C4* dst, bool normalize);
extern IuStatus cuConvert_hsv_to_rgb(const iu::ImageGpu_32f_C4* src, iu::ImageGpu_32f_C4* dst, bool denormalize);
/* ***************************************************************************/
/* ***************************************************************************
* FUNCTION IMPLEMENTATIONS
* ***************************************************************************/
//-----------------------------------------------------------------------------
// [host] 2D bit depth conversion; 32f_C1 -> 8u_C1;
void convert_32f8u_C1(const iu::ImageCpu_32f_C1* src, iu::ImageCpu_8u_C1 *dst,
float mul_constant, float add_constant)
{
for (unsigned int x=0; x<dst->width(); x++)
{
for (unsigned int y=0; y<dst->height(); y++)
{
float val = *src->data(x,y);
*dst->data(x,y) = mul_constant*val + add_constant;
}
}
}
//-----------------------------------------------------------------------------
// [host] 2D bit depth conversion; 16u_C1 -> 32f_C1;
void convert_16u32f_C1(const iu::ImageCpu_16u_C1* src, iu::ImageCpu_32f_C1 *dst,
float mul_constant, float add_constant)
{
for (unsigned int x=0; x<dst->width(); x++)
{
for (unsigned int y=0; y<dst->height(); y++)
{
unsigned short val = *src->data(x,y); //((*src->data(x,y) & 0x00ffU) << 8) | ((*src->data(x,y) & 0xff00U) >> 8);
*dst->data(x,y) = mul_constant*(float)val + add_constant;
}
}
}
//-----------------------------------------------------------------------------
// [device] conversion 32f_C1 -> 8u_C1
void convert_32f8u_C1(const iu::ImageGpu_32f_C1* src, const IuRect& src_roi, iu::ImageGpu_8u_C1 *dst, const IuRect& dst_roi,
float mul_constant, unsigned char add_constant)
{
IuStatus status;
status = cuConvert_32f_8u(src, src_roi, dst, dst_roi, mul_constant, add_constant);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion 32f_C4 -> 8u_C4
void convert_32f8u_C4(const iu::ImageGpu_32f_C4* src, const IuRect& src_roi, iu::ImageGpu_8u_C4 *dst, const IuRect& dst_roi,
float mul_constant, unsigned char add_constant)
{
IuStatus status;
status = cuConvert_32f_8u(src, src_roi, dst, dst_roi, mul_constant, add_constant);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion 8u_C1 -> 32f_C1
void convert_8u32f_C1(const iu::ImageGpu_8u_C1* src, const IuRect& src_roi, iu::ImageGpu_32f_C1 *dst, const IuRect& dst_roi,
float mul_constant, float add_constant)
{
IuStatus status;
status = cuConvert_8u_32f(src, src_roi, dst, dst_roi, mul_constant, add_constant);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion 32f_C3 -> 32f_C4
void convert(const iu::ImageGpu_32f_C3* src, const IuRect& src_roi, iu::ImageGpu_32f_C4* dst, const IuRect& dst_roi)
{
IuStatus status;
status = cuConvert(src, src_roi, dst, dst_roi);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion 32f_C4 -> 32f_C3
void convert(const iu::ImageGpu_32f_C4* src, const IuRect& src_roi, iu::ImageGpu_32f_C3* dst, const IuRect& dst_roi)
{
IuStatus status;
status = cuConvert(src, src_roi, dst, dst_roi);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion RGB -> HSV
void convertRgbHsv(const iu::ImageGpu_32f_C4* src, iu::ImageGpu_32f_C4* dst, bool normalize)
{
IuStatus status;
status = cuConvert_rgb_to_hsv(src, dst, normalize);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
//-----------------------------------------------------------------------------
// [device] conversion HSV -> RGB
void convertHsvRgb(const iu::ImageGpu_32f_C4* src, iu::ImageGpu_32f_C4* dst, bool denormalize)
{
IuStatus status;
status = cuConvert_hsv_to_rgb(src, dst, denormalize);
if (status != IU_SUCCESS) throw IuException("function returned with an error", __FILE__, __FUNCTION__, __LINE__);
}
} // namespace iuprivate
| [
"handa.ankur@gmail.com"
] | handa.ankur@gmail.com |
3684903d2cb295cc5b75d90c70f9672c837927a4 | ae089b04d461f964fb1c63f0d3ad6c5dba4ddeb7 | /src/arrow/util.h | 132c282e3c4e82238aeaabea09a6a53979c5d48c | [
"Apache-2.0"
] | permissive | grundprinzip/arrow | 63c10c442933a30ac498d3d91576c753dbf59e45 | bab4dbf5151fb4c036b331fb314652e975da5822 | refs/heads/master | 2020-07-10T17:35:17.688702 | 2015-12-23T21:35:39 | 2015-12-23T22:22:00 | 48,502,960 | 0 | 0 | null | 2015-12-23T17:33:49 | 2015-12-23T17:33:49 | null | UTF-8 | C++ | false | false | 1,855 | h | // Copyright 2015 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ARROW_UTIL_H
#define ARROW_UTIL_H
#include <cstdlib>
namespace arrow {
namespace util {
inline size_t ceil_byte(size_t size) {
return (size + 7) & ~7;
}
inline size_t ceil_2bytes(size_t size) {
return (size + 15) & ~15;
}
inline bool get_bit(const uint8_t* bits, size_t i) {
return bits[i / 8] & (1 << (i % 8));
}
inline void set_bit(uint8_t* bits, size_t i, bool is_set) {
bits[i / 8] |= (1 << (i % 8)) * is_set;
}
size_t next_power2(size_t n) {
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
if (sizeof(size_t) == 8) {
n |= n >> 32;
}
n++;
return n;
}
void bytes_to_bits(uint8_t* bytes, size_t length, uint8_t* bits) {
for (size_t i = 0; i < length; ++i) {
set_bit(bits, i, static_cast<bool>(bytes[i]));
}
}
uint8_t* bytes_to_bits(uint8_t* bytes, size_t length, size_t* out_length) {
if (!length) {
return nullptr;
}
size_t bit_length = *out_length = ceil_byte(length) / 8;
uint8_t* result = reinterpret_cast<uint8_t*>(malloc(bit_length));
if (result == nullptr) {
// malloc failed
return result;
}
memset(result, 0, bit_length);
bytes_to_bits(bytes, length, result);
return result;
}
} // namespace util
} // namespace arrow
#endif // ARROW_UTIL_H
| [
"wes@cloudera.com"
] | wes@cloudera.com |
718ae6118150e3cff7898d8f4fbb577d550c6d30 | 48de99b1f76dc847fd0366e68095103184c870ce | /torch_ipex/csrc/jit/accelerated_ops.h | 3d4b6944b5d3148822e017272a5e04a785a8b2e6 | [
"Apache-2.0"
] | permissive | jiayisunx/intel-extension-for-pytorch | d18310d74035fc3bbdf580790829059a8aca7251 | ed82813091b8a49bd2db2d87280e7be5e7821335 | refs/heads/master | 2022-11-16T05:09:32.667007 | 2020-07-03T07:36:46 | 2020-07-06T02:16:01 | 262,252,437 | 0 | 0 | Apache-2.0 | 2020-05-08T07:09:24 | 2020-05-08T07:09:24 | null | UTF-8 | C++ | false | false | 2,141 | h | #pragma once
#include <ideep.hpp>
#include <torch/csrc/jit/runtime/custom_operator.h>
namespace torch { namespace jit {
// XXX: PyTorch does not support nesting namespace
// And the alias analysis is not working for namespace other than aten ...
// So we fake some op namespaces to workaround that.
namespace dnnl {
static auto reorder = Symbol::fromQualString("dnnl::reorder");
static auto conv2d = Symbol::fromQualString("dnnl::conv2d");
static auto relu = Symbol::fromQualString("dnnl::relu");
static auto relu_ = Symbol::fromQualString("dnnl::relu_");
static auto batch_norm = Symbol::fromQualString("dnnl::batch_norm");
static auto conv2d_relu = Symbol::fromQualString("dnnl::conv2d_relu");
static auto pooling_max_2d = Symbol::fromQualString("dnnl::pooling_max_2d");
static auto pooling_avg_2d = Symbol::fromQualString("dnnl::pooling_avg_2d");
static auto sum = Symbol::fromQualString("dnnl::sum");
static auto sum_ = Symbol::fromQualString("dnnl::sum_");
static auto conv2d_sum = Symbol::fromQualString("dnnl::conv2d_sum");
static auto conv2d_relu_sum = Symbol::fromQualString("dnnl::conv2d_relu_sum");
static auto conv2d_sum_relu = Symbol::fromQualString("dnnl::conv2d_sum_relu");
// Fold weights of batch_norm with conv2d's
static auto fold_weight =
Symbol::fromQualString("dnnl::fold_weight");
static auto fold_bias =
Symbol::fromQualString("dnnl::fold_bias");
}
Operation createDNNL_reorder(const Node *node);
Operation createDNNL_relu(const Node *node);
Operation createDNNL_relu_(const Node *node);
Operation createDNNL_conv2d(const Node *node);
Operation createDNNL_conv2d_relu(const Node *node);
Operation createDNNL_batch_norm(const Node *node);
Operation createDNNL_fold_weight(const Node *node);
Operation createDNNL_fold_bias(const Node *node);
Operation createDNNL_pooling_max_2d(const Node *node);
Operation createDNNL_pooling_avg_2d(const Node *node);
Operation createDNNL_sum(const Node* node);
Operation createDNNL_sum_(const Node *node);
Operation createDNNL_conv2d_sum(const Node *node);
Operation createDNNL_conv2d_sum_relu(const Node* node);
}} // namespace torch::jit
| [
"eikan.wang@intel.com"
] | eikan.wang@intel.com |
bd9c3f65b0e4f07432db91edc7575a78c23931a8 | ead07f20ab683e03ec84f6dc59640a38ff3dde15 | /GameEngine2D/ParticleBatch2D.cpp | 49c410edd8abd3f1f9189d7ff85bc563ed01f19c | [] | no_license | dmauk/2DGameEngine | 62ecb8c95b05c9632022abc5c0bf9e6f7fdd84c2 | a89439dcf9e5b996819805a93db20f6c23e086b2 | refs/heads/master | 2021-01-15T15:31:19.441516 | 2016-07-05T19:19:34 | 2016-07-05T19:19:34 | 52,846,900 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,080 | cpp | #include "ParticleBatch2D.h"
namespace GameEngine2D {
ParticleBatch2D::ParticleBatch2D()
{
//Empty
}
ParticleBatch2D::~ParticleBatch2D()
{
delete[] m_particles;
}
void ParticleBatch2D::init(int maxParticles, float decayRate, GLTexture texture, function<void(Particle2D&, float)> updateFunction /* = defaultParticleUpdate */)
{
m_maxParticles = maxParticles;
m_particles = new Particle2D[maxParticles];
m_decayRate = decayRate;
m_texture = texture;
m_updateFunction = updateFunction;
}
void ParticleBatch2D::addParticle(const glm::vec2& position, const glm::vec2& velocity, const ColorRGBA8& color, float width)
{
int particleIndex = findFreeParticle();
auto& p = m_particles[particleIndex];
p.life = 1.0f;
p.position = position;
p.velocity = velocity;
p.color = color;
p.width = width;
}
void ParticleBatch2D::update(float deltaTime)
{
for (int i = 0; i < m_maxParticles; i++)
{
if (m_particles[i].life > 0.0f) //check if active
{
m_updateFunction(m_particles[i], deltaTime); //Using the function pointer boi
m_particles[i].life -= m_decayRate;
}
}
}
void ParticleBatch2D::draw(SpriteBatch* spriteBatch)
{
glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
for (int i = 0; i < m_maxParticles; i++)
{
if (m_particles[i].life > 0.0f)//still active?
{
auto& p = m_particles[i]; //So we don't have to keep typing m_particles[i] we just use a reference to it
glm::vec4 destRect(p.position.x, p.position.y, p.width, p.width);
spriteBatch->draw(destRect, uvRect, m_texture.id, 0.0f, p.color);
}
}
}
int ParticleBatch2D::findFreeParticle()
{
for (int i = m_lastFreeParticle; i < m_maxParticles; i++)
{
if (m_particles[i].life <= 0.0f)
{
m_lastFreeParticle = i;
return i; //Return index of free particle
}
}
for (int i = 0; i < m_lastFreeParticle; i++)
{
if (m_particles[i].life <= 0.0f)
{
m_lastFreeParticle = i;
return i; //Return index of free particle
}
}
//No particles are free so overwrite first particle for now
return 0;
}
} | [
"dmauk@fau.edu"
] | dmauk@fau.edu |
47adedb6c0ae818c7d24ce985ca78334869260f3 | ab95572e01fce409bc413d8d0f5320dd61b62c85 | /software/modules/cv_utils/FindCameraMatrices.cpp | dd2a1d26aadc3cc7059c37087621b168acbcbab3 | [] | no_license | spillai/articulation_learning | 8615413ab8c70c367bd3d1e2dc5675db2f59e068 | 4bae0b55813fb9e3683cee363268c51b9b195002 | refs/heads/master | 2021-05-19T22:53:35.725923 | 2015-10-17T21:42:21 | 2015-10-17T21:42:21 | 38,456,267 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,412 | cpp | /*****************************************************************************
* ExploringSfMWithOpenCV
******************************************************************************
* by Roy Shilkrot, 5th Dec 2012
* http://www.morethantechnical.com/
******************************************************************************
* Ch4 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
#include "FindCameraMatrices.h"
#include "Triangulation.h"
#include <vector>
#include <iostream>
#include <opencv2/calib3d/calib3d.hpp>
using namespace cv;
using namespace std;
#ifdef USE_EIGEN
#include <Eigen/Eigen>
#endif
#define DECOMPOSE_SVD
#ifndef CV_PCA_DATA_AS_ROW
#define CV_PCA_DATA_AS_ROW 0
#endif
void DecomposeEssentialUsingHorn90(double _E[9], double _R1[9], double _R2[9], double _t1[3], double _t2[3]) {
//from : http://people.csail.mit.edu/bkph/articles/Essential.pdf
#ifdef USE_EIGEN
using namespace Eigen;
Matrix3d E = Map<Matrix<double,3,3,RowMajor> >(_E);
Matrix3d EEt = E * E.transpose();
Vector3d e0e1 = E.col(0).cross(E.col(1)),e1e2 = E.col(1).cross(E.col(2)),e2e0 = E.col(2).cross(E.col(2));
Vector3d b1,b2;
#if 1
//Method 1
Matrix3d bbt = 0.5 * EEt.trace() * Matrix3d::Identity() - EEt; //Horn90 (12)
Vector3d bbt_diag = bbt.diagonal();
if (bbt_diag(0) > bbt_diag(1) && bbt_diag(0) > bbt_diag(2)) {
b1 = bbt.row(0) / sqrt(bbt_diag(0));
b2 = -b1;
} else if (bbt_diag(1) > bbt_diag(0) && bbt_diag(1) > bbt_diag(2)) {
b1 = bbt.row(1) / sqrt(bbt_diag(1));
b2 = -b1;
} else {
b1 = bbt.row(2) / sqrt(bbt_diag(2));
b2 = -b1;
}
#else
//Method 2
if (e0e1.norm() > e1e2.norm() && e0e1.norm() > e2e0.norm()) {
b1 = e0e1.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)
b2 = -b1;
} else if (e1e2.norm() > e0e1.norm() && e1e2.norm() > e2e0.norm()) {
b1 = e1e2.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)
b2 = -b1;
} else {
b1 = e2e0.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)
b2 = -b1;
}
#endif
//Horn90 (19)
Matrix3d cofactors; cofactors.col(0) = e1e2; cofactors.col(1) = e2e0; cofactors.col(2) = e0e1;
cofactors.transposeInPlace();
//B = [b]_x , see Horn90 (6) and http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication
Matrix3d B1; B1 << 0,-b1(2),b1(1),
b1(2),0,-b1(0),
-b1(1),b1(0),0;
Matrix3d B2; B2 << 0,-b2(2),b2(1),
b2(2),0,-b2(0),
-b2(1),b2(0),0;
Map<Matrix<double,3,3,RowMajor> > R1(_R1),R2(_R2);
//Horn90 (24)
R1 = (cofactors.transpose() - B1*E) / b1.dot(b1);
R2 = (cofactors.transpose() - B2*E) / b2.dot(b2);
Map<Vector3d> t1(_t1),t2(_t2);
t1 = b1; t2 = b2;
cout << "Horn90 provided " << endl << R1 << endl << "and" << endl << R2 << endl;
#endif
}
bool CheckCoherentRotation(cv::Mat_<double>& R) {
if(fabsf(determinant(R))-1.0 > 1e-07) {
cerr << "det(R) != +-1.0, this is not a rotation matrix" << endl;
return false;
}
return true;
}
Mat GetFundamentalMat(const vector<KeyPoint>& imgpts1,
const vector<KeyPoint>& imgpts2,
vector<KeyPoint>& imgpts1_good,
vector<KeyPoint>& imgpts2_good,
vector<DMatch>& matches
#ifdef __SFM__DEBUG__
,const Mat& img_1,
const Mat& img_2
#endif
)
{
//Try to eliminate keypoints based on the fundamental matrix
//(although this is not the proper way to do this)
vector<uchar> status(imgpts1.size());
#ifdef __SFM__DEBUG__
std::vector< DMatch > good_matches_;
std::vector<KeyPoint> keypoints_1, keypoints_2;
#endif
// undistortPoints(imgpts1, imgpts1, cam_matrix, distortion_coeff);
// undistortPoints(imgpts2, imgpts2, cam_matrix, distortion_coeff);
//
imgpts1_good.clear(); imgpts2_good.clear();
vector<KeyPoint> imgpts1_tmp;
vector<KeyPoint> imgpts2_tmp;
if (matches.size() <= 0) {
//points already aligned...
imgpts1_tmp = imgpts1;
imgpts2_tmp = imgpts2;
} else {
GetAlignedPointsFromMatch(imgpts1, imgpts2, matches, imgpts1_tmp, imgpts2_tmp);
}
Mat F;
{
vector<Point2f> pts1,pts2;
KeyPointsToPoints(imgpts1_tmp, pts1);
KeyPointsToPoints(imgpts2_tmp, pts2);
#ifdef __SFM__DEBUG__
cout << "pts1 " << pts1.size() << " (orig pts " << imgpts1_tmp.size() << ")" << endl;
cout << "pts2 " << pts2.size() << " (orig pts " << imgpts2_tmp.size() << ")" << endl;
#endif
double minVal,maxVal;
cv::minMaxIdx(pts1,&minVal,&maxVal);
F = findFundamentalMat(pts1, pts2, FM_RANSAC, 0.006 * maxVal, 0.99, status); //threshold from [Snavely07 4.1]
// F = findFundamentalMat(pts1, pts2, FM_RANSAC, 2.0, 0.99, status); //threshold from [Snavely07 4.1]
}
vector<DMatch> new_matches;
cout << "F keeping " << countNonZero(status) << " / " << status.size() << endl;
for (unsigned int i=0; i<status.size(); i++) {
if (status[i])
{
imgpts1_good.push_back(imgpts1_tmp[i]);
imgpts2_good.push_back(imgpts2_tmp[i]);
if (matches.size() <= 0) { //points already aligned...
new_matches.push_back(DMatch(matches[i].queryIdx,matches[i].trainIdx,matches[i].distance));
} else {
new_matches.push_back(matches[i]);
}
#ifdef __SFM__DEBUG__
good_matches_.push_back(DMatch(imgpts1_good.size()-1,imgpts1_good.size()-1,1.0));
keypoints_1.push_back(imgpts1_tmp[i]);
keypoints_2.push_back(imgpts2_tmp[i]);
#endif
}
}
cout << matches.size() << " matches before, " << new_matches.size() << " new matches after Fundamental Matrix\n";
matches = new_matches; //keep only those points who survived the fundamental matrix
#if 0
//-- Draw only "good" matches
#ifdef __SFM__DEBUG__
if(!img_1.empty() && !img_2.empty()) {
vector<Point2f> i_pts,j_pts;
Mat img_orig_matches;
{ //draw original features in red
vector<uchar> vstatus(imgpts1_tmp.size(),1);
vector<float> verror(imgpts1_tmp.size(),1.0);
img_1.copyTo(img_orig_matches);
KeyPointsToPoints(imgpts1_tmp, i_pts);
KeyPointsToPoints(imgpts2_tmp, j_pts);
drawArrows(img_orig_matches, i_pts, j_pts, vstatus, verror, Scalar(0,0,255));
}
{ //superimpose filtered features in green
vector<uchar> vstatus(imgpts1_good.size(),1);
vector<float> verror(imgpts1_good.size(),1.0);
i_pts.resize(imgpts1_good.size());
j_pts.resize(imgpts2_good.size());
KeyPointsToPoints(imgpts1_good, i_pts);
KeyPointsToPoints(imgpts2_good, j_pts);
drawArrows(img_orig_matches, i_pts, j_pts, vstatus, verror, Scalar(0,255,0));
imshow( "Filtered Matches", img_orig_matches );
}
int c = waitKey(0);
if (c=='s') {
imwrite("fundamental_mat_matches.png", img_orig_matches);
}
destroyWindow("Filtered Matches");
}
#endif
#endif
return F;
}
void TakeSVDOfE(Mat_<double>& E, Mat& svd_u, Mat& svd_vt, Mat& svd_w) {
#if 1
//Using OpenCV's SVD
SVD svd(E,SVD::MODIFY_A);
svd_u = svd.u;
svd_vt = svd.vt;
svd_w = svd.w;
#else
//Using Eigen's SVD
cout << "Eigen3 SVD..\n";
Eigen::Matrix3f e = Eigen::Map<Eigen::Matrix<double,3,3,Eigen::RowMajor> >((double*)E.data).cast<float>();
Eigen::JacobiSVD<Eigen::MatrixXf> svd(e, Eigen::ComputeThinU | Eigen::ComputeThinV);
Eigen::MatrixXf Esvd_u = svd.matrixU();
Eigen::MatrixXf Esvd_v = svd.matrixV();
svd_u = (Mat_<double>(3,3) << Esvd_u(0,0), Esvd_u(0,1), Esvd_u(0,2),
Esvd_u(1,0), Esvd_u(1,1), Esvd_u(1,2),
Esvd_u(2,0), Esvd_u(2,1), Esvd_u(2,2));
Mat_<double> svd_v = (Mat_<double>(3,3) << Esvd_v(0,0), Esvd_v(0,1), Esvd_v(0,2),
Esvd_v(1,0), Esvd_v(1,1), Esvd_v(1,2),
Esvd_v(2,0), Esvd_v(2,1), Esvd_v(2,2));
svd_vt = svd_v.t();
svd_w = (Mat_<double>(1,3) << svd.singularValues()[0] , svd.singularValues()[1] , svd.singularValues()[2]);
#endif
cout << "----------------------- SVD ------------------------\n";
cout << "U:\n"<<svd_u<<"\nW:\n"<<svd_w<<"\nVt:\n"<<svd_vt<<endl;
cout << "----------------------------------------------------\n";
}
bool TestTriangulation(const vector<CloudPoint>& pcloud, const Matx34d& P, vector<uchar>& status) {
vector<Point3d> pcloud_pt3d = CloudPointsToPoints(pcloud);
vector<Point3d> pcloud_pt3d_projected(pcloud_pt3d.size());
Matx44d P4x4 = Matx44d::eye();
for(int i=0;i<12;i++) P4x4.val[i] = P.val[i];
perspectiveTransform(pcloud_pt3d, pcloud_pt3d_projected, P4x4);
status.resize(pcloud.size(),0);
for (int i=0; i<pcloud.size(); i++) {
status[i] = (pcloud_pt3d_projected[i].z > 0) ? 1 : 0;
}
int count = countNonZero(status);
double percentage = ((double)count / (double)pcloud.size());
cout << count << "/" << pcloud.size() << " = " << percentage*100.0 << "% are in front of camera" << endl;
if(percentage < 0.75)
return false; //less than 75% of the points are in front of the camera
//check for coplanarity of points
if(false) //not
{
cv::Mat_<double> cldm(pcloud.size(),3);
for(unsigned int i=0;i<pcloud.size();i++) {
cldm.row(i)(0) = pcloud[i].pt.x;
cldm.row(i)(1) = pcloud[i].pt.y;
cldm.row(i)(2) = pcloud[i].pt.z;
}
cv::Mat_<double> mean;
cv::PCA pca(cldm,mean,CV_PCA_DATA_AS_ROW);
int num_inliers = 0;
cv::Vec3d nrm = pca.eigenvectors.row(2); nrm = nrm / norm(nrm);
cv::Vec3d x0 = pca.mean;
double p_to_plane_thresh = sqrt(pca.eigenvalues.at<double>(2));
for (int i=0; i<pcloud.size(); i++) {
Vec3d w = Vec3d(pcloud[i].pt) - x0;
double D = fabs(nrm.dot(w));
if(D < p_to_plane_thresh) num_inliers++;
}
cout << num_inliers << "/" << pcloud.size() << " are coplanar" << endl;
if((double)num_inliers / (double)(pcloud.size()) > 0.85)
return false;
}
return true;
}
bool DecomposeEtoRandT(
Mat_<double>& E,
Mat_<double>& R1,
Mat_<double>& R2,
Mat_<double>& t1,
Mat_<double>& t2)
{
#ifdef DECOMPOSE_SVD
//Using HZ E decomposition
Mat svd_u, svd_vt, svd_w;
TakeSVDOfE(E,svd_u,svd_vt,svd_w);
//check if first and second singular values are the same (as they should be)
double singular_values_ratio = fabsf(svd_w.at<double>(0) / svd_w.at<double>(1));
if(singular_values_ratio>1.0) singular_values_ratio = 1.0/singular_values_ratio; // flip ratio to keep it [0,1]
if (singular_values_ratio < 0.7) {
cout << "singular values are too far apart\n";
return false;
}
Matx33d W(0,-1,0, //HZ 9.13
1,0,0,
0,0,1);
Matx33d Wt(0,1,0,
-1,0,0,
0,0,1);
R1 = svd_u * Mat(W) * svd_vt; //HZ 9.19
R2 = svd_u * Mat(Wt) * svd_vt; //HZ 9.19
t1 = svd_u.col(2); //u3
t2 = -svd_u.col(2); //u3
#else
//Using Horn E decomposition
DecomposeEssentialUsingHorn90(E[0],R1[0],R2[0],t1[0],t2[0]);
#endif
return true;
}
bool FindCameraMatrices(const Mat& K,
const Mat& Kinv,
const Mat& distcoeff,
const vector<KeyPoint>& imgpts1,
const vector<KeyPoint>& imgpts2,
vector<KeyPoint>& imgpts1_good,
vector<KeyPoint>& imgpts2_good,
Matx34d& P,
Matx34d& P1,
vector<DMatch>& matches,
vector<CloudPoint>& outCloud
#ifdef __SFM__DEBUG__
,const Mat& img_1,
const Mat& img_2
#endif
)
{
//Find camera matrices
{
cout << "Find camera matrices...";
// double t =cv::getTickCount();
Mat F = GetFundamentalMat(imgpts1,imgpts2,imgpts1_good,imgpts2_good,matches
#ifdef __SFM__DEBUG__
,img_1,img_2
#endif
);
if(matches.size() < 100) { // || ((double)imgpts1_good.size() / (double)imgpts1.size()) < 0.25
cerr << "not enough inliers after F matrix" << endl;
return false;
}
//Essential matrix: compute then extract cameras [R|t]
Mat_<double> E = K.t() * F * K; //according to HZ (9.12)
//according to http://en.wikipedia.org/wiki/Essential_matrix#Properties_of_the_essential_matrix
if(fabsf(determinant(E)) > 1e-07) {
cout << "det(E) != 0 : " << determinant(E) << "\n";
P1 = 0;
return false;
}
Mat_<double> R1(3,3);
Mat_<double> R2(3,3);
Mat_<double> t1(1,3);
Mat_<double> t2(1,3);
//decompose E to P' , HZ (9.19)
{
if (!DecomposeEtoRandT(E,R1,R2,t1,t2)) return false;
if(determinant(R1)+1.0 < 1e-09) {
//according to http://en.wikipedia.org/wiki/Essential_matrix#Showing_that_it_is_valid
cout << "det(R) == -1 ["<<determinant(R1)<<"]: flip E's sign" << endl;
E = -E;
DecomposeEtoRandT(E,R1,R2,t1,t2);
}
if (!CheckCoherentRotation(R1)) {
cout << "resulting rotation is not coherent\n";
P1 = 0;
return false;
}
P1 = Matx34d(R1(0,0), R1(0,1), R1(0,2), t1(0),
R1(1,0), R1(1,1), R1(1,2), t1(1),
R1(2,0), R1(2,1), R1(2,2), t1(2));
cout << "Testing P1 " << endl << Mat(P1) << endl;
vector<CloudPoint> pcloud,pcloud1; vector<KeyPoint> corresp;
double reproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);
double reproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);
vector<uchar> tmp_status;
//check if pointa are triangulated --in front-- of cameras for all 4 ambiguations
if (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {
P1 = Matx34d(R1(0,0), R1(0,1), R1(0,2), t2(0),
R1(1,0), R1(1,1), R1(1,2), t2(1),
R1(2,0), R1(2,1), R1(2,2), t2(2));
cout << "Testing P1 "<< endl << Mat(P1) << endl;
pcloud.clear(); pcloud1.clear(); corresp.clear();
reproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);
reproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);
if (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {
if (!CheckCoherentRotation(R2)) {
cout << "resulting rotation is not coherent\n";
P1 = 0;
return false;
}
P1 = Matx34d(R2(0,0), R2(0,1), R2(0,2), t1(0),
R2(1,0), R2(1,1), R2(1,2), t1(1),
R2(2,0), R2(2,1), R2(2,2), t1(2));
cout << "Testing P1 "<< endl << Mat(P1) << endl;
pcloud.clear(); pcloud1.clear(); corresp.clear();
reproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);
reproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);
if (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {
P1 = Matx34d(R2(0,0), R2(0,1), R2(0,2), t2(0),
R2(1,0), R2(1,1), R2(1,2), t2(1),
R2(2,0), R2(2,1), R2(2,2), t2(2));
cout << "Testing P1 "<< endl << Mat(P1) << endl;
pcloud.clear(); pcloud1.clear(); corresp.clear();
reproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);
reproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);
if (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {
cout << "Shit." << endl;
return false;
}
}
}
}
for (unsigned int i=0; i<pcloud.size(); i++) {
outCloud.push_back(pcloud[i]);
}
}
// t = ((double)getTickCount() - t)/getTickFrequency();
// cout << "Done. (" << t <<"s)"<< endl;
}
return true;
}
| [
"spillai@csail.mit.edu"
] | spillai@csail.mit.edu |
ad9654ff488506cbb37d862f39e6d5e8ce72a4df | 1b4d6be8363951e1ce7516d3e1d9b1ac6038af8c | /source/XmlTileDeclaration.cpp | 78c2c66c973c9cfd71a127b0c1e973a06fcc3734 | [] | no_license | adamjjablonski/cse335-tower-defense | dde028a9a3d9b2719a30e8ecde3b5c514521d74a | b6a5bd9673cb84afd2e9e1d359b560978e57001c | refs/heads/main | 2023-06-09T18:18:18.199958 | 2021-06-21T23:09:14 | 2021-06-21T23:09:14 | 379,081,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | /**
* \file XmlTileDeclaration.cpp
*
* \author Adam Jablonski
*/
#include "pch.h"
#include "XmlTileDeclaration.h"
/**
* Custom constructor
* \param node The XML node used to create this declaration
*/
CXmlTileDeclaration::CXmlTileDeclaration(shared_ptr<CXmlNode> node)
{
mId = node->GetAttributeValue(L"id", L"");
mImage = node->GetAttributeValue(L"image", L"");
mType = node->GetAttributeValue(L"type", L"");
}
/**
* Destructor
*/
CXmlTileDeclaration::~CXmlTileDeclaration()
{
} | [
"noreply@github.com"
] | adamjjablonski.noreply@github.com |
9f6a02f334aa407f5c10789113bd6dd4cbb60431 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /tcss/src/v20201101/model/DescribeValueAddedSrvInfoRequest.cpp | d121cabdfff72dd228dab00111f23f9f0642f5c9 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 1,390 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tcss/v20201101/model/DescribeValueAddedSrvInfoRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tcss::V20201101::Model;
using namespace std;
DescribeValueAddedSrvInfoRequest::DescribeValueAddedSrvInfoRequest()
{
}
string DescribeValueAddedSrvInfoRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
4e99686c8f5efc6dd28f4e9a1844b3e0738069d2 | 71dfa11149953a0d6724a0ba5a945b952df6f01e | /src/icp/icp.cpp | 651ebe3ddee2e9fb0b353ac358589e7b789e40ed | [
"BSD-3-Clause"
] | permissive | erickulcyk/strawberrypeaches | db892b985e9d020e2b1a4ad966ad988a19664b5d | 9e78a354da855460e4f6005c7da7d3fb809252f4 | refs/heads/master | 2020-05-29T23:19:24.003719 | 2014-02-02T04:19:22 | 2014-02-02T04:19:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,641 | cpp | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include <pcl/visualization/cloud_viewer.h>
void ShowCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, int index)
{
stringstream title;
title << "Cloud "<<index;
pcl::visualization::CloudViewer viewer (title.str());
viewer.showCloud (cloud);
while (!viewer.wasStopped ())
{
}
}
int
main (int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZRGBA>);
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_out (new pcl::PointCloud<pcl::PointXYZRGBA>);
// Fill in the CloudIn data
cloud_in->width = 10;
cloud_in->height = 1;
cloud_in->is_dense = false;
cloud_in->points.resize (cloud_in->width * cloud_in->height);
for (size_t i = 0; i < cloud_in->points.size (); ++i)
{
cloud_in->points[i].x = 3 * rand () / (RAND_MAX + 1.0f);
cloud_in->points[i].y = 3 * rand () / (RAND_MAX + 1.0f);
cloud_in->points[i].z = 3 * rand () / (RAND_MAX + 1.0f);
cloud_in->points[i].r = 255;
cloud_in->points[i].g = 0;
cloud_in->points[i].b = 0;
}
std::cout << "Saved " << cloud_in->points.size () << " data points to input:"
<< std::endl;
ShowCloud(cloud_in,0);
// for (size_t i = 0; i < cloud_in->points.size (); ++i) std::cout << " " <<
// cloud_in->points[i].x << " " << cloud_in->points[i].y << " " <<
// cloud_in->points[i].z << std::endl;
*cloud_out = *cloud_in;
std::cout << "size:" << cloud_out->points.size() << std::endl;
for (size_t i = 0; i < cloud_in->points.size (); ++i)
{
cloud_out->points[i].x = cloud_in->points[i].x + 10.0f;
cloud_out->points[i].g = 255;
cloud_out->points[i].r = 0;
}
std::cout << "Transformed " << cloud_in->points.size () << " data points:"
<< std::endl;
ShowCloud(cloud_out,0);
// for (size_t i = 0; i < cloud_out->points.size (); ++i)
// std::cout << " " << cloud_out->points[i].x << " " <<
// cloud_out->points[i].y << " " << cloud_out->points[i].z << std::endl;
pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;
icp.setMaxCorrespondenceDistance (115);
icp.setInputCloud(cloud_in);
icp.setInputTarget(cloud_out);
// pcl::PointCloud<pcl::PointXYZRGBA> Final;
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr Final(new pcl::PointCloud<pcl::PointXYZRGBA>);
icp.align(*Final);
*Final +=*cloud_out;
ShowCloud(Final,0);
std::cout << "has converged:" << icp.hasConverged() << " score: " <<
icp.getFitnessScore() << std::endl;
std::cout << icp.getFinalTransformation() << std::endl;
return (0);
}
| [
"erickulcyk@gmail.com"
] | erickulcyk@gmail.com |
0899b932d60ddee3eae6c8e04a2b6aa7217845ce | 74cd4e6098029ee5d168f45ba73e0479ac8ae09f | /src1.3/Tree.h | 2a6866d167ca3160d0e00d1e9c7b600f695c609c | [] | no_license | gilles-didier/TDALP | e19130f5ff7499741a9c77fd9960147b6f215b3b | 280937ca31a50b7481c90d498359ada2f4eeced8 | refs/heads/master | 2020-06-26T16:41:56.129091 | 2016-11-27T15:29:42 | 2016-11-27T15:29:42 | 74,549,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,919 | h | /*
'tdalp' computes the time-dependent-asymmetric-linear-parsimony parametric reconstruction of a phylogenetic tree.
Copyright (C) 2016 Gilles DIDIER
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TreeF
#define TreeF
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "Utils.h"
#define INC_SIZE 100
#define INC_SIZE_TREE 100
//#define MAX_CURRENT INT_MAX
#define MAX_CURRENT 10000
//#define MAX(x,y) ((x)>(y)?(x):(y))
//#define MIN(x,y) ((x)<(y)?(x):(y))
#define UNKNOWN DBL_MAX
#define NOSUCH -1
#define NO_TIME -DBL_MAX
#define CO_TIME DBL_MAX
typedef enum DISPLAY_NAME {
display_none=0,
display_name,
display_index,
display_both,
display_time_none,
display_time_name,
display_time_index,
display_time_both
} TypeDisplayName;
typedef struct TIME_INTERVAL {
double inf, sup;
} TypeTimeInterval;
typedef struct NODE {
int child, sibling;
} TypeNode;
typedef struct TIME_TAB {
char **name1, **name2;
double *time;
int size;
} TypeTimeTab;
typedef void* (*TypeGetFeature)(int, void*);
typedef void (*TypeSetFeature)(int, void*, void*);
typedef void* (*TypeAllocFeature)(int);
typedef void (*TypeReallocFeature)(int, void*);
typedef void (*TypeFreeFeature)(int, void*);
typedef struct FEATURE_FUNCT {
TypeReallocFeature realloc;
TypeFreeFeature free;
TypeSetFeature set;
} TypeFeatureFunc;
typedef struct TREE_FEATURE {
void *data;
TypeAllocFeature alloc;
TypeSetFeature set;
TypeGetFeature get;
TypeFreeFeature free;
} TypeTreeFrature;
/*
typedef struct STANDARD_FEATURE {
char **name, **comment;
int size, sizeBuf;
void *info;
} TypeStandardFeature;
*/
typedef struct TREE {
TypeNode *node;
int root, size, sizeBuf, *parent;
double *time, maxTime, minTime;
char **name, **comment;
void *info;
TypeTimeInterval minTimeInt, maxTimeInt;
} TypeTree;
#ifdef __cplusplus
extern "C" {
namespace Tree {
#endif
double getMaximumLeafTime(TypeTree *tree);
/*prune "tree" to keep only leaves in dict*/
TypeTree *pruneLeavesFromDict(TypeTree *tree, TypeLexiTree *dict);
/*remove the subtree pending from n*/
int *removeSubtreeReturnIndex(int n, TypeTree *tree);
/*set the table of parents*/
void setParent(TypeTree *tree);
TypeTree *readTreeFromName(char *filename);
/*remove the subtree pending from n*/
void removeSubtree(int n, TypeTree *tree);
/*add a new leaf from branch/node n with name n*/
int addLeaf(int n, char *name, TypeTree *tree);
/*extend the tree buffer*/
void reallocTreeFeature(TypeTree *tree);
/*make tree to be binary*/
void toBinary(TypeTree *tree);
/*make node m be child of n*/
void transfer(int m, int n, TypeTree *tree);
/*return the root of tree*/
int getRoot(TypeTree *tree);
/*return the numbre of childre of node n*/
int getNumberChildren(int n, TypeTree *tree);
/*returns the number of leaves of the n subtree of "tree"*/
int countSubLeaves(int n, TypeTree *tree);
/*name (numerote) leaves of tree*/
char **nameBoth(char *prefixIntern, char *prefixLeaf, TypeTree *tree);
/*name (numerote) leaves of tree*/
char **nameLeaves(char *prefix, TypeTree *tree);
/*return a standard feature*/
//TypeStandardFeature *getBasicStandardFeature(TypeTree *tree);
/*turn branch lengthes to absolute time*/
void bltoabsTime(TypeTree *tree);
/*turn branch lengthes to absolute time*/
void abstoblTime(TypeTree *tree);
/*get the smallest time of the tree - makes sense only with absolute times*/
double getMinTime(TypeTree *tree);
/*get the greatest time of the tree - makes sense only with absolute times*/
double getMaxTime(TypeTree *tree);
/*shift all the times/branch from beg*/
void offsetTime(double beg, TypeTree *tree);
/*return the least common ancestor of n and m*/
int getLCA(int n, int m, TypeTree *tree);
/*return 1 if m descends from n*/
int isDescendant(int m, int n, TypeTree *tree);
/*return the table of parents*/
int *getParent(TypeTree *tree);
/*get the status from comments*/
char *getSpecy(char *str);
/*return name tab containing species found in comments*/
char **getNamestoSpecies(char **comment, TypeTree *tree);
/*return name tab containing species found in comments for leaves only*/
char **getNamestoSpeciesLeaves(char **comment, TypeTree *tree);
/*returns the number of contemporary lineages (i.e. living at maxTime) of "tree"*/
int countContemp(TypeTree *tree);
/*returns the number of leaves of "tree"*/
int countLeaves(TypeTree *tree);
/*fully duplicate "tree"*/
TypeTree *cpyTree(TypeTree *tree);
/*create and allocate a standard feature of sizeBuf*/
void *newStandardFeature(int sizeBuf);
/*reallocate a standard feature of sizeBuf*/
void reallocStandardFeature(int sizeBuf, void *std);
/*allocate and initialize a new_feat tree*/
TypeTree *newTree(int sizeBuf);
/*desallocate standard features*/
void freeStandardFeature(int size, void *std);
void setStandardFeature(int n, void *dest, int m, void *src);
/*desallocate tree*/
void freeTree(TypeTree *tree);
/*initialize fields of node to standard values*/
void initNode(TypeNode *node);
/*read tree in newick format*/
TypeTree *readTree(FILE *f);
/*read a node in newick format*/
int readNode(FILE *f, TypeTree *tree);
/*read a leaf in newick format*/
int readLeaf(FILE *f, TypeTree *tree);
/*read the name*/
char *readName(FILE *f);
/*read the comment*/
char *readComment(FILE *f);
/*read the time or branch length*/
double readTime(FILE *f);
/*reorder all children in a canonical (provided at least leaves are named)*/
void reorderTree(char **name, TypeTree *tree);
/*reorder all children in a canonical (provided at least leaves are named)*/
TypeTree *reorderTreeCpy(char **name, TypeTree *tree);
/*rename internal nodes*/
void nameInternalNodes(char **name, TypeTree *tree);
TypeTimeTab *readTimeTab(FILE *f);
/*read a table <leaf1>\t<leaf2>\t<time> and set the time of the lca of <leaf1> and <leaf2> to <time>*/
void setTime(FILE *fi, char **name, TypeTree *tree);
/*prune "tree" to that can be observed from contemporary lineages only*/
TypeTree *pruneContemp(TypeTree *tree);
TypeTree *fixBinary(TypeTree *tree);
extern TypeFeatureFunc stdFeatureFunc;
/*reallocate tree*/
void reallocTree(int sizeBuf, TypeTree *tree);
/*allocate a string tab and set its entries to NULL*/
char **newStringTab(int size);
/*print tree in debug mode*/
void fprintTreeX(FILE *f, TypeTree *tree);
/*print tree in PsTricks format*/
void fprintTreePst(FILE *f, TypeTree *tree, TypeDisplayName display);
/*print node in PsTricks format*/
void fprintNodePst(FILE *f, int n, TypeTree *tree, TypeDisplayName display);
/*replace ' ' by underscores*/
void fixNameUnderscore(char **name, int size);
/*print tree in text format*/
void printTreeDebug(FILE *f, int n, TypeTree *tree, char **name);
/*print ident, time and comment of node n*/
void fprintIdentTimeComment(FILE *f, int n, TypeTree *tree, TypeDisplayName display);
/*print tree in newick format*/
void fprintSubtreeNewick(FILE *f, int n, TypeTree *tree);
/*print tree in newick format*/
void fprintTreeNewick(FILE *f, TypeTree *tree);
/*print node in newick format*/
void fprintNodeNewick(FILE *f, int n, TypeTree *tree);
/*print tree in newick format*/
void fprintTree(FILE *f, TypeTree *tree, TypeDisplayName display);
void fprintNode(FILE *f, int n, TypeTree *tree, TypeDisplayName display);
#ifdef __cplusplus
}
}
#endif
#endif
| [
"gilles.didier@free.fr"
] | gilles.didier@free.fr |
0ef96d4163b2c8c9439f161629bc610ee5e3c754 | f7587c0be83c5b9b9cc2dc4c9bf3bacc275dd3a3 | /chromecast/browser/display_configurator_observer.cc | caabcd3006d4ae47a4f2f5f0c707c3c4eedf9608 | [
"BSD-3-Clause"
] | permissive | bramus/chromium | 64e7cf1e8e4a8ddb28964bd0ff54c8b1082faa76 | 43139ddcc7e184a66bdaf1b6b8f23561675be819 | refs/heads/main | 2023-04-13T15:27:32.890558 | 2021-04-18T10:14:28 | 2021-04-18T10:14:28 | 359,112,142 | 1 | 0 | BSD-3-Clause | 2021-04-18T10:30:23 | 2021-04-18T10:30:22 | null | UTF-8 | C++ | false | false | 840 | cc | // Copyright 2021 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 "display_configurator_observer.h"
namespace chromecast {
DisplayConfiguratorObserver::DisplayConfiguratorObserver(
chromecast::shell::CastDisplayConfigurator* display_configurator,
chromecast::CastWindowManagerAura* manager)
: display_configurator_(display_configurator), window_manager_(manager) {
display_configurator_->AddObserver(this);
}
DisplayConfiguratorObserver::~DisplayConfiguratorObserver() {
display_configurator_->RemoveObserver(this);
}
void DisplayConfiguratorObserver::OnDisplayStateChanged() {
window_manager_->GetRootWindow()
->GetHost()
->compositor()
->ScheduleFullRedraw();
}
} // namespace chromecast | [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
c81cfef22c1e8cad1210546e18e7c2409457e672 | 31e6e1b72ebc27339b4e65b71c62f5f392e897b9 | /IODEVICES.h | 8868a80e3623d88ccd8270c778c83616a03f8b65 | [] | no_license | ramitix/OS-Simulator | b088a34660ae01bf1480110bd854ccd363547aad | b3333c906c0d5a35f37f36cf18b5ba1b42be2443 | refs/heads/master | 2021-01-11T22:30:40.866480 | 2017-01-15T00:13:06 | 2017-01-15T00:13:09 | 78,977,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,068 | h | //Ramy Atalla
#ifndef IODEVICES_H
#define IODEVICES_H
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <vector>
#include <string>
#include <list>
#include <queue>
#include <algorithm>
#include "PCB.h"
#include "Memory.h"
#include "CPU.h"
using namespace std;
class PCB;
class CPU;
class Printer
{
public:
Printer();
int GetPrinterNumber() const;
void SetPrinterNumber(int pNumber);
void AddProcessToPrinterQueue(PCB* pcbBlock);
void PrintingCompelete(CPU& cpu);
friend ostream& operator<<(ostream& out, Printer& printer);
private:
int printerNumber;
queue<PCB*> printerQueue;
};
class Disk {
public:
Disk();
int GetDiskNumber() const;
void SetDiskNumber(int dNumber);
void AddProcessToDiskQueue(PCB* pcbBlock);
void TaskCompelete(CPU& cpu);
friend ostream& operator<<(ostream& out, Disk& disk);
private:
int diskNumber;
queue<PCB*> diskQueue;
};
#endif // IODEVICES_H
| [
"ramitix@ramys-Air.home"
] | ramitix@ramys-Air.home |
428f49d711cccdb73ceb1d0297e8e06bbf973841 | d73eb9e6b9450f5456d92c710c457fb36bbe8d59 | /cdcAnim/AnimNodes/AnimSmartMovementNode.h | fcc4c551c21a877a9b9ffbca403b9c812ea5f5b0 | [] | no_license | rrika/cdcEngineDXHR | 110cb9314f242e0cfe07c51d439da1045aec78a0 | ff312d19663ca1f68881b46089c4a856c2ced0f5 | refs/heads/main | 2023-08-31T05:09:34.118694 | 2023-08-30T23:49:39 | 2023-08-30T23:49:39 | 474,729,623 | 192 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 135 | h | #pragma once
#include "../AnimPipelineNode.h"
namespace cdc {
class AnimSmartMovementNode : public AnimPipelineNode {
// TODO
};
}
| [
"adam.jensen@si.det.usa"
] | adam.jensen@si.det.usa |
65fc964b1b30b6365060858ea48baa62a57d08dc | b17b253b5f12903ce0d2531541fd390247379394 | /04/main2.cpp | ae0619e60b4debb5ab3ffb93f894f672d5151bd5 | [] | no_license | Worthy-Wang/Sword2Offer | 5fa73636448c0dbdb8f82a769e1792d28f3c32de | 6e69bca7318784c3debb569ea24c72e70fb7effb | refs/heads/master | 2022-11-27T14:29:40.106119 | 2020-08-05T06:23:05 | 2020-08-05T06:23:05 | 283,200,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | #include <iostream>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <vector>
#include <fstream>
#include <sstream>
#include <string.h>
#include <memory>
#include <limits>
#include <list>
using namespace std;
/*
begin: 15:06
end: 15:22
Time Complexity: O(M+N)
Space Complexity: O(1)
Method:采用该矩阵的特点,从右上角入手进行查找
*/
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if (matrix.empty())
return false;
int M = matrix.size() - 1, N = matrix[0].size() - 1;
int i = 0, j = N;
while (i <= M && j >= 0)
{
if (target == matrix[i][j]) return true;
else if (target < matrix[i][j]) j--;
else i++;
}
return false;
}
};
int main()
{
return 0;
}
| [
"you@example.com"
] | you@example.com |
a348d08e081ee69cc9b14de138c6eed22c052574 | f715f25577cfe5cf9fa5281cf7ff109487ebf363 | /L2_CustomWidgets/Lesson5/build-PromoteWidget-Desktop_Qt_5_12_8_MSVC2017_64bit-Debug/debug/moc_indicator.cpp | 2a02c20248e5eec2efcdffe2b44601593c888680 | [] | no_license | sid1980/CppQtProjects | b01a05e3760680e009d2e08884f3453329e3e035 | 8b397d2b39dc38080f6f17dc9cbeb7280ffc6ec8 | refs/heads/master | 2023-04-01T01:56:01.661748 | 2021-03-27T19:07:27 | 2021-03-27T19:07:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,737 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'indicator.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../PromoteWidget/indicator.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'indicator.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.8. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Indicator_t {
QByteArrayData data[5];
char stringdata0[57];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Indicator_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Indicator_t qt_meta_stringdata_Indicator = {
{
QT_MOC_LITERAL(0, 0, 9), // "Indicator"
QT_MOC_LITERAL(1, 10, 14), // "activateNormal"
QT_MOC_LITERAL(2, 25, 0), // ""
QT_MOC_LITERAL(3, 26, 15), // "activateWarning"
QT_MOC_LITERAL(4, 42, 14) // "activateDanger"
},
"Indicator\0activateNormal\0\0activateWarning\0"
"activateDanger"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Indicator[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x0a /* Public */,
3, 0, 30, 2, 0x0a /* Public */,
4, 0, 31, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void Indicator::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<Indicator *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->activateNormal(); break;
case 1: _t->activateWarning(); break;
case 2: _t->activateDanger(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject Indicator::staticMetaObject = { {
&QWidget::staticMetaObject,
qt_meta_stringdata_Indicator.data,
qt_meta_data_Indicator,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *Indicator::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Indicator::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Indicator.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int Indicator::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"akashkumarsinha007@gmail.com"
] | akashkumarsinha007@gmail.com |
6e6eab19244ef589c2b709e56378c7f6ca3f87e0 | d94aeeb531ca5866f91ef4ee7bd696e2b09be061 | /infoarena/fallingb/fallingb.cpp | 09f5c64574c10edb9bb7ba53a2f890065549b96d | [] | no_license | alexvelea/competitive | ffbe56d05a41941f39d8fa8e3fc366e97c73c2e0 | f1582ba49174ca956359de6f68e26f6b30306a4d | refs/heads/master | 2022-10-20T17:04:25.483158 | 2020-06-18T23:33:25 | 2020-06-18T23:33:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | cpp | #include <fstream>
#include <iostream>
using namespace std;
const int MOD = 9901;
ifstream in("fallingb.in");
ofstream out("fallingb.out");
int nr[125][1000];
int rez[125];
int l, add;
void bt(int p, int lst, int nxt) {
if (p == 8) {
nr[l + 1][nxt] += add;
nr[l + 1][nxt] %= MOD;
return ;
}
if (lst & (1 << p)) {
bt(p + 1, lst, nxt);
return ;
}
bt(p + 1, lst, nxt);
if ((nxt & (1 << p)) == 0)
bt(p + 1, lst, nxt | (1 << p));
if ((nxt & (1 << p)) == 0 and (nxt & (1 << (p+1))) == 0 and p + 1 < 8)
bt(p + 1, lst, nxt | (1 << p) | (1 << (p + 1)));
if (p and (nxt & (1 << p)) == 0 and (nxt & (1 << (p-1))) == 0)
bt(p + 1, lst, nxt | (1 << p) | (1 << (p - 1)));
if ((lst & (1 << (p + 1))) or (p == 7))
return ;
bt(p + 2, lst, nxt);
if ((nxt & (1 << p)) == 0)
bt(p + 2, lst, nxt | (1 << p));
if ((nxt & (1 << (p + 1))) == 0)
bt(p + 2, lst, nxt | (1 << (p + 1)));
}
int bt_final(int p, int st) {
if (p == 8)
return 1;
if (st & (1 << p))
return bt_final(p + 1, st);
if (p == 7)
return 1;
if (st & (1 << (p + 1)))
return bt_final(p + 2, st);
return bt_final(p + 1, st) + bt_final(p + 2, st);
}
int main() {
nr[1][0] = 1;
for (int i = 1; i <= 120; ++i) {
// calculam rez[i]
for (int j = 0; j < (1 << 8); ++j) {
int f = bt_final(0, j);
rez[i] += f * nr[i][j];
rez[i] %= MOD;
}
for (int j = 0; j < (1 << 8); ++j) {
add = nr[i][j];
l = i;
bt(0, j, 0);
}
}
int t;
in >> t;
while (t--) {
int n, m;
in >> n >> m;
out << rez[m] << '\n';
}
return 0;
}
| [
"veleandu@yahoo.com"
] | veleandu@yahoo.com |
d92b3346654b762f02ea268efc49df5fd8b56d9a | ef9876a305a6c5b4f93f68e0fed0ba01761df5c2 | /AcCoRD2/src/mesoscopic_region.cpp | 0c13c41e21bcc72a78d670f41dff8cc7be1bb11f | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"MIT"
] | permissive | Jackrekirby/AcCoRD2 | 4b2fd4f3847e7d2338b42f13d75988a998bcd5c9 | d712b3f7e73f32dc1894fcb79bec4510a13a9dce | refs/heads/master | 2023-03-23T10:59:13.544882 | 2021-03-16T15:49:25 | 2021-03-16T15:49:25 | 311,968,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,237 | cpp | // The AcCoRD 2 Simulator (Actor - based Communication via Reaction - Diffusion)
// Copyright 2021 Jack Kirby. All rights reserved.
// For license details, read LICENSE.txt in the root AcCoRD2 directory
#include "pch.h"
#include "mesoscopic_region.h"
#include "vec3d.h"
#include "vec3i.h"
#include "vec3b.h"
#include "microscopic_grid.h"
namespace accord::mesoscopic
{
Region::Region(const Vec3d& origin, double subvolume_length, const Vec3i& n_subvolumes,
const std::vector<double>& diffusion_coefficients, const std::vector<Vec3i>& removedSubvolumes, int priority, const MesoscopicRegionID& id)
: box(origin, subvolume_length * Vec3d(n_subvolumes)), Event(0, priority), id(id),
n_subvolumes(n_subvolumes), subvolume_length(subvolume_length), surface_direction(microscopic::HighPriorityRelative::SurfaceDirection::External)
{
//LOG_INFO("n subs = {}", n_subvolumes);
std::vector<int> removed_indices;
removed_indices.reserve(removedSubvolumes.size());
for (const Vec3i& subvolume_index : removedSubvolumes)
{
removed_indices.emplace_back(GetIndex(subvolume_index));
}
CreateSubvolumes(n_subvolumes, diffusion_coefficients, subvolume_length, removed_indices);
}
void Region::AddMolecule(const MoleculeID& id, const Vec3d& position)
{
//LOG_INFO("molecule id = {}", id);
Vec3i index = Vec3d(n_subvolumes) * ((position - box.GetOrigin()) / box.GetLength());
GetSubvolume(index).AddMolecule(id);
RefreshEventTime();
}
void Region::AddSubvolumesToQueue()
{
// now subvolumes are confirmed delete subvolumes marked for deletion (because other regions have replaced the subvolumes)
//LOG_INFO("num_subvolume = {}", subvolumes.size());
subvolume_queue.Reserve(subvolumes.size());
for (auto& subvolume : subvolumes)
{
subvolume_queue.Add(&subvolume);
subvolume.UpdateReactionTime();
//LOG_INFO("subvolume propensity = {}, time = {}", subvolume.GetPropensity(), subvolume.GetTime());
}
SetEventTime(subvolume_queue.Front().GetTime());
}
void Region::LinkSiblingSubvolumes()
{
for (auto& s1 : subvolumes)
{
auto& b1 = s1.GetBoundingBox();
for (auto& s2 : subvolumes)
{
if (&s1 != &s2)
{
//LOG_INFO("link1");
if ((s1.GetRelativePosition() - s2.GetRelativePosition()).Abs().Sum() == 1)
{
//LOG_INFO("link2 {} {}", s1.GetRelativePosition(), s2.GetRelativePosition());
s1.AddNeighbour(s2);
}
}
}
}
}
// will always return a valid subvolume even if index is for a position outside of subvolume
Subvolume& Region::GetSubvolume(Vec3i index)
{
// if index is below or above index range limit it to within range
index *= (index > Vec3i(0, 0, 0));
index.EqualIf((index >= n_subvolumes), n_subvolumes - 1);
return subvolumes.at(index.x + index.y * n_subvolumes.x + index.z * n_subvolumes.x * n_subvolumes.y);
}
int Region::GetIndex(Vec3i index)
{
// if index is below or above index range limit it to within range
index *= (index > Vec3i(0, 0, 0));
index.EqualIf((index >= n_subvolumes), n_subvolumes - 1);
return (index.x + index.y * n_subvolumes.x + index.z * n_subvolumes.x * n_subvolumes.y);
}
// could be private?
// if index is not valid null will be returned
Subvolume* Region::GetSubvolumeIfExists(const Vec3i& index)
{
if ((index < Vec3i(0, 0, 0)).Any()) return nullptr;
if ((index >= n_subvolumes).Any()) return nullptr;
return &subvolumes.at(index.x + index.y * n_subvolumes.x + index.z * n_subvolumes.x * n_subvolumes.y);
}
void Region::CreateSubvolumes(const Vec3i& n_subvolumes,
std::vector<double> diffusion_coefficients, double subvolume_length, const std::vector<int>& removed_indices)
{
subvolumes.reserve(n_subvolumes.Volume());
Vec3i i;
int j = 0;
for (i.z = 0; i.z < n_subvolumes.z; i.z++)
{
for (i.y = 0; i.y < n_subvolumes.y; i.y++)
{
for (i.x = 0; i.x < n_subvolumes.x; i.x++)
{
// if remove index not found then include subvolume
if (std::find(removed_indices.begin(), removed_indices.end(), GetIndex(i)) == removed_indices.end())
{
//LOG_INFO("include subvolume = {}", i);
subvolumes.emplace_back(box.GetOrigin() + Vec3d(i) * subvolume_length,
subvolume_length, diffusion_coefficients, i, j);
j++;
}
else
{
//LOG_INFO("dont include subvolume = {}", i);
}
}
}
}
}
std::vector<Subvolume>& Region::GetSubvolumes()
{
return subvolumes;
}
void Region::AddZerothOrderReaction(const std::vector<int>& products, double reaction_rate)
{
for (auto& subvolume : subvolumes)
{
subvolume.AddZerothOrderReaction(products, reaction_rate);
}
}
void Region::AddFirstOrderReaction(const MoleculeID& reactant, const std::vector<int>& products, double reaction_rate)
{
for (auto& subvolume : subvolumes)
{
subvolume.AddFirstOrderReaction(reactant, products, reaction_rate);
}
}
void Region::AddSecondOrderReaction(const MoleculeID& reactant_a, const MoleculeID& reactant_b, const std::vector<int>& products, double reaction_rate)
{
for (auto& subvolume : subvolumes)
{
subvolume.AddSecondOrderReaction(reactant_a, reactant_b, products, reaction_rate);
}
}
void Region::RefreshEventTime()
{
//LOG_INFO("NEXT REGION TIME = {}", subvolume_queue.Front().GetTime());
//double mintime = 1e10;
//for (auto& subvolume : subvolume_queue.GetSubvolumes())
//{
// if (subvolume->GetTime() < mintime) mintime = subvolume->GetTime();
//}
//LOG_INFO("NEXT MIN TIME = {}", mintime);
//
//if (subvolume_queue.Front().GetTime() > 100)
//{
// for (auto& subvolume : subvolume_queue.GetSubvolumes())
// {
// LOG_INFO("TIMES: {}", subvolume->GetTime());
// }
// throw std::exception();
//}
SetEventTime(subvolume_queue.Front().GetTime());
}
// will delete subvolumes from the region in preparation for another mesoscopic or microscopic region to be placed inside
void Region::AddChild()
{
// for both meso and microscopic regions
// check for intersection with each subvolume and delete those which intersect
// for those which neighbour add as neighbour (just send across to the add neighbour function
}
void Region::AddNeighbour(Region& other)
{
// for those which neighbour add as neighbour
// each subvolume is checked against every other subvolume.
// Inefficient but as only done once not a high priority performace improvement unless a region contains 1000's of subvolumes
//LOG_INFO("add region, b1 = {}, b2 = {}", box, other.box);
// could optimise by adding both at same time.
if (box.IsPartiallyNeighbouring(other.box))
{
//LOG_INFO("regions are neighbouring");
for (auto& s1 : subvolumes)
{
auto& b1 = s1.GetBoundingBox();
for (auto& s2 : other.subvolumes)
{
//LOG_INFO("subvolume id = {}, {}", s1.GetID(), s2.GetID());
auto& b2 = s2.GetBoundingBox();
//LOG_INFO("subvolumes 1:{}, 2:{}", b1, b2);
if (b1.IsPartiallyNeighbouring(b2))
{
/*if (((b1.GetOrigin() == b2.GetEnd()) || (b1.GetEnd() == b2.GetOrigin())).Sum() == 1)
{*/
s1.AddNeighbour(s2, &other);
//LOG_INFO("subvolumes {} and {} are neighbours", s1.GetID(), s2.GetID());
//}
}
}
}
}
else
{
LOG_WARN("Attempted to add mesoscopic region as neighbour but the regions do not neighbour");
}
}
// returns the required dimensions of the replacement region to ensure correct neighbouring (avoid floating point error)
shape::basic::Box Region::RemoveInterior(const Vec3i& origin_subvolume, const Vec3i& n_subvolumes)
{
Vec3i i = origin_subvolume;
Vec3i end_subvolume = origin_subvolume + n_subvolumes;
//LOG_INFO("HERE {} {} {}", origin_subvolume, n_subvolumes, end_subvolume);
for (i.x = origin_subvolume.x; i.x < end_subvolume.x; i.x++)
{
for (i.y = origin_subvolume.y; i.y < end_subvolume.y; i.y++)
{
for (i.z = origin_subvolume.z; i.z < end_subvolume.z; i.z++)
{
//LOG_INFO("removing i = {}, {}", i, i.x + i.y * this->n_subvolumes.x + i.z * this->n_subvolumes.x * this->n_subvolumes.y);
Subvolume* s = GetSubvolumeIfExists(i);
if (s != nullptr)
{
s->MarkForDeletion();
}
else
{
LOG_INFO("subvolume cannot be deleted as it does not exist");
}
}
}
}
return { box.GetOrigin() + Vec3d(origin_subvolume) * subvolume_length, subvolume_length * Vec3d(n_subvolumes) };
}
std::string Region::LogEvent() const
{
return fmt::format("Microscopic Region. ID:{}, Priority:{}, Time:{}", id, priority, time);
}
void Region::Run()
{
subvolume_queue.Front().Run();
SetEventTime(subvolume_queue.Front().GetTime());
//LOG_INFO("RUN: Event time = {}", GetEventTime());
//for (auto& subvolume : subvolumes)
//{
// for (auto& layer : subvolume.GetLayers())
// {
// if (layer.GetCount() > 0)
// {
// LOG_INFO("RUN: Layer molecule {}", layer.GetCount());
// }
// }
//}
}
void Region::Print()
{
for (auto& subvolume : subvolumes)
{
LOG_INFO("id = {}, time = {}", subvolume.GetID(), subvolume.GetTime());
}
}
const shape::relation::Box& Region::GetBoundingBox() const
{
return box;
}
void Region::NextRealisation()
{
for (auto& subvolume : subvolumes)
{
subvolume.NextRealisation();
}
RefreshEventTime();
}
MesoscopicRegionID Region::GetID() const
{
return id;
}
void Region::ToJson(Json& j) const
{
j["type"] = "gridBox";
j["origin"] = box.GetOrigin();
j["length"] = box.GetLength();
j["end"] = box.GetEnd();
j["nPartitions"] = n_subvolumes;
}
const RegionShape& Region::GetShape() const
{
return box;
}
const microscopic::HighPriorityRelative::SurfaceDirection& Region::GetSurfaceDirection() const
{
return surface_direction;
}
bool Region::IsRegion() const
{
// is not microscopic region
return false;
}
std::optional<microscopic::MoleculeDestination> Region::PassMolecule(const Vec3d& end,
const shape::collision::Collision3D& collision, microscopic::Grid* owner,
microscopic::SurfaceType surface_type, int cycles, bool allowObstructions)
{
AddMolecule(owner->GetMoleculeID(), collision.intersection);
return std::nullopt;
}
void to_json(Json& j, const Region& region)
{
region.ToJson(j);
}
} | [
"jackrekirby@gmail.com"
] | jackrekirby@gmail.com |
7c95b203a58d9ab5cdb9e67ed9df75be04c19a69 | c003995232de360da7332fc05b9df117e47b48fb | /Glitter/Headers/SimpleModel.hpp | 77bc40cef28ace5f778d8d1624ea2b92daf81265 | [
"MIT"
] | permissive | LegendaryZReborn/Glitter | 93fea30b9d0a689b50383b1fa33207816ccb1289 | 3bdca116eebf7886b03056afe81d38b68c387c36 | refs/heads/master | 2021-04-28T20:17:01.966987 | 2018-03-20T19:17:51 | 2018-03-20T19:17:51 | 121,920,372 | 0 | 0 | null | 2018-02-18T05:10:48 | 2018-02-18T05:10:48 | null | UTF-8 | C++ | false | false | 1,012 | hpp | #ifndef SIMPLEMODEL_H
#define SIMPLEMODEL_H
#include <glitter.hpp>
#include <vector>
#include "Material.hpp"
#include "Shader.hpp"
#include <sstream>
class SimpleModel {
friend class Loader;
friend class Renderer;
public:
SimpleModel();
SimpleModel(std::vector<glm::vec4> vertices, std::vector<glm::vec4> normals,
std::vector<glm::vec2> uVs, std::vector<GLuint> indicies, std::vector<GLuint> textures, Material mat);
~SimpleModel();
GLuint getVAO() const;
void setVAO(const int val);
GLuint getVBO() const;
void setVBO(const int val);
int getNumVertices() const;
void setNumVertices(const int val);
void addTexture(const GLuint val);
void setTextureUnits(Shader& shader) const;
void draw(Shader& shader) const;
private:
std::vector<glm::vec4> vertices, normals;
std::vector<glm::vec2> uVs;
std::vector<GLuint> textures, indicies;
GLuint vao, vbo;
int numVertices;
Material material;
};
#endif // SIMPLEMODEL_H
| [
"cbrolegendz@gmail.com"
] | cbrolegendz@gmail.com |
da88d1d60fdbd14acb9d508542ae597bc21bcf87 | 161bb0e9067b46268acea4485cf94be11be676cc | /libraries/NDEF/MifareUltralight.cpp | 87d405053e22f3d11b3fb396fb0d2743c82d0d52 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | lnxz/BOTHackathon2017-Ditto | 9b9cb14760e1cb244200763419529f20a9bec8fc | 008712495c0f50cd0c7895864c3e158559d7d015 | refs/heads/master | 2020-12-30T13:28:45.654764 | 2017-05-14T15:22:01 | 2017-05-14T15:22:01 | 91,222,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,533 | cpp | #include <MifareUltralight.h>
#define ULTRALIGHT_PAGE_SIZE 4
#define ULTRALIGHT_READ_SIZE 4 // we should be able to read 16 bytes at a time
#define ULTRALIGHT_DATA_START_PAGE 4
#define ULTRALIGHT_MESSAGE_LENGTH_INDEX 1
#define ULTRALIGHT_DATA_START_INDEX 2
#define ULTRALIGHT_MAX_PAGE 63
#define NFC_FORUM_TAG_TYPE_2 ("NFC Forum Type 2")
MifareUltralight::MifareUltralight(PN532& nfcShield)
{
nfc = &nfcShield;
ndefStartIndex = 0;
messageLength = 0;
}
MifareUltralight::~MifareUltralight()
{
}
NfcTag MifareUltralight::read(byte * uid, unsigned int uidLength)
{
if (isUnformatted())
{
// Serial.println(F("WARNING: Tag is not formatted."));
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2);
}
readCapabilityContainer(); // meta info for tag
findNdefMessage();
calculateBufferSize();
if (messageLength == 0) { // data is 0x44 0x03 0x00 0xFE
NdefMessage message = NdefMessage();
message.addEmptyRecord();
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, message);
}
boolean success;
uint8_t page;
uint8_t index = 0;
byte buffer[bufferSize];
for (page = ULTRALIGHT_DATA_START_PAGE; page < ULTRALIGHT_MAX_PAGE; page++)
{
// read the data
success = nfc->mifareultralight_ReadPage(page, &buffer[index]);
if (success)
{
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Page "));Serial.print(page);Serial.print(" ");
nfc->PrintHexChar(&buffer[index], ULTRALIGHT_PAGE_SIZE);
#endif
}
else
{
Serial.print(F("Read failed "));Serial.println(page);
// TODO error handling
messageLength = 0;
break;
}
if (index >= (messageLength + ndefStartIndex))
{
break;
}
index += ULTRALIGHT_PAGE_SIZE;
}
NdefMessage ndefMessage = NdefMessage(&buffer[ndefStartIndex], messageLength);
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, ndefMessage);
}
boolean MifareUltralight::isUnformatted()
{
uint8_t page = 4;
byte data[ULTRALIGHT_READ_SIZE];
boolean success = nfc->mifareultralight_ReadPage (page, data);
if (success)
{
return (data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[3] == 0xFF);
}
else
{
Serial.print(F("Error. Failed read page "));Serial.println(page);
return false;
}
}
// page 3 has tag capabilities
void MifareUltralight::readCapabilityContainer()
{
byte data[ULTRALIGHT_PAGE_SIZE];
int success = nfc->mifareultralight_ReadPage (3, data);
if (success)
{
// See AN1303 - different rules for Mifare Family byte2 = (additional data + 48)/8
tagCapacity = data[2] * 8;
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Tag capacity "));Serial.print(tagCapacity);Serial.println(F(" bytes"));
#endif
// TODO future versions should get lock information
}
}
// read enough of the message to find the ndef message length
void MifareUltralight::findNdefMessage()
{
int page;
byte data[12]; // 3 pages
byte* data_ptr = &data[0];
// the nxp read command reads 4 pages, unfortunately adafruit give me one page at a time
boolean success = true;
for (page = 4; page < 6; page++)
{
success = success && nfc->mifareultralight_ReadPage(page, data_ptr);
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Page "));Serial.print(page);Serial.print(F(" - "));
nfc->PrintHexChar(data_ptr, 4);
#endif
data_ptr += ULTRALIGHT_PAGE_SIZE;
}
if (success)
{
if (data[0] == 0x03)
{
messageLength = data[1];
ndefStartIndex = 2;
}
else if (data[5] == 0x3) // page 5 byte 1
{
// TODO should really read the lock control TLV to ensure byte[5] is correct
messageLength = data[6];
ndefStartIndex = 7;
}
}
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("messageLength "));Serial.println(messageLength);
Serial.print(F("ndefStartIndex "));Serial.println(ndefStartIndex);
#endif
}
// buffer is larger than the message, need to handle some data before and after
// message and need to ensure we read full pages
void MifareUltralight::calculateBufferSize()
{
// TLV terminator 0xFE is 1 byte
bufferSize = messageLength + ndefStartIndex + 1;
if (bufferSize % ULTRALIGHT_READ_SIZE != 0)
{
// buffer must be an increment of page size
bufferSize = ((bufferSize / ULTRALIGHT_READ_SIZE) + 1) * ULTRALIGHT_READ_SIZE;
}
}
boolean MifareUltralight::write(NdefMessage& m, byte * uid, unsigned int uidLength)
{
if (isUnformatted())
{
Serial.println(F("WARNING: Tag is not formatted."));
return false;
}
readCapabilityContainer(); // meta info for tag
messageLength = m.getEncodedSize();
ndefStartIndex = messageLength < 0xFF ? 2 : 4;
calculateBufferSize();
if(bufferSize>tagCapacity) {
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Encoded Message length exceeded tag Capacity "));Serial.println(tagCapacity);
#endif
return false;
}
uint8_t encoded[bufferSize];
uint8_t * src = encoded;
unsigned int position = 0;
uint8_t page = ULTRALIGHT_DATA_START_PAGE;
// Set message size. With ultralight should always be less than 0xFF but who knows?
encoded[0] = 0x3;
if (messageLength < 0xFF)
{
encoded[1] = messageLength;
}
else
{
encoded[1] = 0xFF;
encoded[2] = ((messageLength >> 8) & 0xFF);
encoded[3] = (messageLength & 0xFF);
}
m.encode(encoded+ndefStartIndex);
// this is always at least 1 byte copy because of terminator.
memset(encoded+ndefStartIndex+messageLength,0,bufferSize-ndefStartIndex-messageLength);
encoded[ndefStartIndex+messageLength] = 0xFE; // terminator
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("messageLength "));Serial.println(messageLength);
Serial.print(F("Tag Capacity "));Serial.println(tagCapacity);
nfc->PrintHex(encoded,bufferSize);
#endif
while (position < bufferSize){ //bufferSize is always times pagesize so no "last chunk" check
// write page
if (!nfc->mifareultralight_WritePage(page, src))
return false;
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Wrote page "));Serial.print(page);Serial.print(F(" - "));
nfc->PrintHex(src,ULTRALIGHT_PAGE_SIZE);
#endif
page++;
src+=ULTRALIGHT_PAGE_SIZE;
position+=ULTRALIGHT_PAGE_SIZE;
}
return true;
}
// Mifare Ultralight can't be reset to factory state
// zero out tag data like the NXP Tag Write Android application
boolean MifareUltralight::clean()
{
readCapabilityContainer(); // meta info for tag
uint8_t pages = (tagCapacity / ULTRALIGHT_PAGE_SIZE) + ULTRALIGHT_DATA_START_PAGE;
// factory tags have 0xFF, but OTP-CC blocks have already been set so we use 0x00
uint8_t data[4] = { 0x00, 0x00, 0x00, 0x00 };
for (int i = ULTRALIGHT_DATA_START_PAGE; i < pages; i++) {
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Wrote page "));Serial.print(i);Serial.print(F(" - "));
nfc->PrintHex(data, ULTRALIGHT_PAGE_SIZE);
#endif
if (!nfc->mifareultralight_WritePage(i, data)) {
return false;
}
}
return true;
}
| [
"lnx@live.com.sg"
] | lnx@live.com.sg |
01651835b157211250a9b03715c6145d49f34940 | c952a9dfde3ee42f919db607e05b06166ac5e0b9 | /codeforces/1338/A.cpp | f30664bd82137fcf9ae06c4456bb3e850fccc6f2 | [] | no_license | ntloi95/Codeforces | 1afaa753e3c84752907fb2e8bb79b0d1fc4e1a1b | 3fab8d5a0d00cafc74e392f1db6ee20b9e68d1d1 | refs/heads/master | 2023-05-23T17:51:47.532503 | 2021-06-26T07:59:47 | 2021-06-26T07:59:47 | 335,175,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | cpp | #include <bits/stdc++.h>
#define ll long long
#define ii pair<int, int>
#define fi first
#define se second
using namespace std;
const int N = 50;
int main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int mx;
cin >> mx;
int ans = 0;
for (int i = 0; i < n - 1; i++)
{
int x;
cin >> x;
if (x < mx)
{
int k = mx - x;
int c = 0;
while (k)
{
k /= 2;
c++;
}
ans = max(ans, c);
}
else
{
mx = x;
}
}
cout << ans << endl;
}
return 0;
} | [
"ntloi95@gmail.com"
] | ntloi95@gmail.com |
3fcf2fdc7a2eb661e83726297657e3aa80e470b2 | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/video/Dune2Image.h | 459b78b084ecbcc51af8afe2c361150deaddb6f5 | [] | no_license | crutchwalkfactory/motocakerteam | 1cce9f850d2c84faebfc87d0adbfdd23472d9f08 | 0747624a575fb41db53506379692973e5998f8fe | refs/heads/master | 2021-01-10T12:41:59.321840 | 2010-12-13T18:19:27 | 2010-12-13T18:19:27 | 46,494,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,172 | h | // Dune2Image.h
// 1.0
// This file is part of OpenRedAlert.
//
// OpenRedAlert is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2 of the License.
//
// OpenRedAlert is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OpenRedAlert. If not, see <http://www.gnu.org/licenses/>.
#ifndef DUNE2IMAGE_H
#define DUNE2IMAGE_H
#include "SDL/SDL_types.h"
#include "SDL/SDL_video.h"
#include "Dune2Header.h"
#include "SHPBase.h"
class Dune2Image : SHPBase
{
public:
Dune2Image(const char *fname, Sint8 scaleq);
~Dune2Image();
SDL_Surface* getImage(Uint16 imgnum);
private:
Uint32 getD2Header(Uint16 imgnum);
Uint8* shpdata;
/** @link aggregationByValue*/
Dune2Header lnkHeader;
};
#endif
| [
"cepiperez@gmail.com"
] | cepiperez@gmail.com |
17cd18a9b62ef9b0e1bbb95ae64b2e0707ca8a38 | 730455062efc93c01ce6a074339e86e1c7282ef4 | /gpuemutest/tests.cpp | 0e30dfcc06e227c4724ef7694838efed15302583 | [
"Apache-2.0"
] | permissive | veeYceeY/alice5 | 6a222658f002f3957147df2629a8f53bc0814563 | 6001088d432faf1b9e4b0498f6f3af32d7f8e294 | refs/heads/master | 2023-05-08T15:00:44.286299 | 2021-05-26T18:02:22 | 2021-05-26T18:02:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,162 | cpp | #include <vector>
#include <iostream>
#include <iomanip>
#include <cassert>
#include "gpuemu.h"
#include "riscv-disas.h"
void print_inst(uint64_t pc, uint32_t inst)
{
char buf[80] = { 0 };
disasm_inst(buf, sizeof(buf), rv64, pc, inst);
printf("%016" PRIx64 ": %s\n", pc, buf);
}
void dumpGPUCore(const GPUCore& core)
{
std::cout << std::setfill('0');
for(int i = 0; i < 32; i++) {
std::cout << "x" << std::setw(2) << i << ":" << std::hex << std::setw(8) << core.x[i] << std::dec;
std::cout << (((i + 1) % 4 == 0) ? "\n" : " ");
}
std::cout << "pc :" << std::hex << std::setw(8) << core.pc << '\n' << std::dec;
std::cout << std::setfill(' ');
}
struct Memory
{
std::vector<uint8_t> memorybytes;
bool verbose;
Memory(const std::vector<uint8_t>& memorybytes_, bool verbose_ = false) :
memorybytes(memorybytes_),
verbose(verbose_)
{}
uint8_t read8(uint32_t addr)
{
if(verbose) printf("read 8 from %08X\n", addr);
assert(addr < memorybytes.size());
return memorybytes[addr];
}
uint16_t read16(uint32_t addr)
{
if(verbose) printf("read 16 from %08X\n", addr);
assert(addr + 1 < memorybytes.size());
return *reinterpret_cast<uint16_t*>(memorybytes.data() + addr);
}
uint32_t read32(uint32_t addr)
{
if(verbose) printf("read 32 from %08X\n", addr);
assert(addr + 3 < memorybytes.size());
return *reinterpret_cast<uint32_t*>(memorybytes.data() + addr);
}
void write8(uint32_t addr, uint32_t v)
{
if(verbose) printf("write 8 bits of %08X to %08X\n", v, addr);
assert(addr < memorybytes.size());
memorybytes[addr] = static_cast<uint8_t>(v);
}
void write16(uint32_t addr, uint32_t v)
{
if(verbose) printf("write 16 bits of %08X to %08X\n", v, addr);
assert(addr + 1 < memorybytes.size());
*reinterpret_cast<uint16_t*>(memorybytes.data() + addr) = static_cast<uint16_t>(v);
}
void write32(uint32_t addr, uint32_t v)
{
if(verbose) printf("write 32 bits of %08X to %08X\n", v, addr);
assert(addr + 3 < memorybytes.size());
*reinterpret_cast<uint32_t*>(memorybytes.data() + addr) = v;
}
};
int main(int argc, char **argv)
{
{
GPUCore core;
Memory m({0x13, 0x05, 0x55, 0x03}); /* i = i + 53 */
core.step(m);
assert(core.x[10] == 53);
if(false) dumpGPUCore(core);
}
{
GPUCore core;
Memory m({0x13, 0x05, 0x55, 0x03, 0x73, 0x00, 0x10, 0x00}); /* i = i + 53; ebreak; */
GPUCore::Status status = core.stepUntilException(m);
assert(status == GPUCore::BREAK);
if(false) dumpGPUCore(core);
}
{
GPUCore core;
// unsigned int* ptr = (unsigned int *)0x1000;
// ptr[0] = 0xBADACCE5;
std::vector<uint8_t> bytes = { 0x37, 0x17, 0x00, 0x00, 0xb7, 0xd7, 0xda, 0xba, 0x93, 0x87, 0x57, 0xce, 0x23, 0x20, 0xf7, 0x00 };
bytes.resize(0x2000);
Memory m(bytes);
core.step(m);
core.step(m);
core.step(m); core.step(m);
assert(m.read32(0x1000) == 0xBADACCE5);
if(false) dumpGPUCore(core);
}
{
GPUCore core;
// int j = 9;
// for(int i = 0; i < 1000000; i++)
// j = j * 3;
// riscv32-none-elf-gcc -mabi=ilp32 -march=rv32im -S q.c
std::vector<uint8_t> bytes = { 0x13, 0x01, 0x01, 0xfd, 0x23, 0x26, 0x81, 0x02, 0x13, 0x04, 0x01, 0x03, 0x23, 0x2e, 0xa4, 0xfc, 0x93, 0x07, 0x90, 0x00, 0x23, 0x26, 0xf4, 0xfe, 0x23, 0x24, 0x04, 0xfe, 0x6f, 0x00, 0x40, 0x02, 0x03, 0x27, 0xc4, 0xfe, 0x93, 0x07, 0x07, 0x00, 0x93, 0x97, 0x17, 0x00, 0xb3, 0x87, 0xe7, 0x00, 0x23, 0x26, 0xf4, 0xfe, 0x83, 0x27, 0x84, 0xfe, 0x93, 0x87, 0x17, 0x00, 0x23, 0x24, 0xf4, 0xfe, 0x03, 0x27, 0x84, 0xfe, 0xb7, 0x47, 0x0f, 0x00, 0x93, 0x87, 0xf7, 0x23, 0xe3, 0xda, 0xe7, 0xfc, 0x13, 0x00, 0x00, 0x00, 0x13, 0x85, 0x07, 0x00, 0x03, 0x24, 0xc1, 0x02, 0x13, 0x01, 0x01, 0x03, 0x73, 0x00, 0x10, 0x00 };
bytes.resize(0x2000);
Memory m(bytes);
core.x[2] = 0x2000; // Set SP to highest memory
GPUCore::Status status;
do{
// print_inst(core.pc, m.read32(core.pc));
status = core.step(m);
} while(status == GPUCore::RUNNING);
assert(m.read32(0x00001FEC) == 0x184ECD09);
}
{
GPUCore core;
// unsigned char *pi = (unsigned char *)0x1000;
// int i = *pi;
// int j = 9;
// unsigned char *pb = (unsigned char *)0x1004;
// for(int k = 0; k < 1000; k++) {
// j = j * 3;
// if(j > i)
// break;
// }
// *pb = j & 0xff;
std::vector<uint8_t> bytes = {
0x13, 0x01, 0x01, 0xfd, 0x23, 0x26, 0x81, 0x02, 0x13, 0x04, 0x01, 0x03, 0xb7, 0x17, 0x00, 0x00, 0x23, 0x22, 0xf4, 0xfe, 0x83, 0x27, 0x44, 0xfe, 0x83, 0xc7, 0x07, 0x00, 0x23, 0x20, 0xf4, 0xfe, 0x93, 0x07, 0x90, 0x00, 0x23, 0x26, 0xf4, 0xfe, 0xb7, 0x17, 0x00, 0x00, 0x93, 0x87, 0x47, 0x00, 0x23, 0x2e, 0xf4, 0xfc, 0x23, 0x24, 0x04, 0xfe, 0x6f, 0x00, 0x00, 0x03, 0x03, 0x27, 0xc4, 0xfe, 0x93, 0x07, 0x07, 0x00, 0x93, 0x97, 0x17, 0x00, 0xb3, 0x87, 0xe7, 0x00, 0x23, 0x26, 0xf4, 0xfe, 0x03, 0x27, 0xc4, 0xfe, 0x83, 0x27, 0x04, 0xfe, 0x63, 0xc0, 0xe7, 0x02, 0x83, 0x27, 0x84, 0xfe, 0x93, 0x87, 0x17, 0x00, 0x23, 0x24, 0xf4, 0xfe, 0x03, 0x27, 0x84, 0xfe, 0x93, 0x07, 0x70, 0x3e, 0xe3, 0xd6, 0xe7, 0xfc, 0x6f, 0x00, 0x80, 0x00, 0x13, 0x00, 0x00, 0x00, 0x83, 0x27, 0xc4, 0xfe, 0x13, 0xf7, 0xf7, 0x0f, 0x83, 0x27, 0xc4, 0xfd, 0x23, 0x80, 0xe7, 0x00, 0x13, 0x00, 0x00, 0x00, 0x13, 0x85, 0x07, 0x00, 0x03, 0x24, 0xc1, 0x02, 0x13, 0x01, 0x01, 0x03,
0x73, 0x00, 0x10, 0x00,
};
bytes.resize(0x2000);
Memory m(bytes, false);
m.write32(0x1000, 43);
core.x[2] = 0x2000; // Set SP to highest memory
GPUCore::Status status;
do{
// print_inst(core.pc, m.read32(core.pc));
status = core.step(m);
} while(status == GPUCore::RUNNING);
assert(m.read8(0x00001004) == 0x51);
// dumpGPUCore(core);
}
}
| [
"grantham@plunk.org"
] | grantham@plunk.org |
45452ca12079b8c95c73c13dcfb9f860525bfe36 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/ash/system_web_apps/apps/camera_app/camera_app_untrusted_ui_config.h | 2ff78cf3b0d20f408cad984440276276b6cb46fe | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 969 | h | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_SYSTEM_WEB_APPS_APPS_CAMERA_APP_CAMERA_APP_UNTRUSTED_UI_CONFIG_H_
#define CHROME_BROWSER_ASH_SYSTEM_WEB_APPS_APPS_CAMERA_APP_CAMERA_APP_UNTRUSTED_UI_CONFIG_H_
#include "content/public/browser/webui_config.h"
namespace ash {
class CameraAppUntrustedUIConfig : public content::WebUIConfig {
public:
CameraAppUntrustedUIConfig();
CameraAppUntrustedUIConfig(const CameraAppUntrustedUIConfig& other) = delete;
CameraAppUntrustedUIConfig& operator=(const CameraAppUntrustedUIConfig&) =
delete;
~CameraAppUntrustedUIConfig() override;
std::unique_ptr<content::WebUIController> CreateWebUIController(
content::WebUI* web_ui,
const GURL& url) override;
};
} // namespace ash
#endif // CHROME_BROWSER_ASH_SYSTEM_WEB_APPS_APPS_CAMERA_APP_CAMERA_APP_UNTRUSTED_UI_CONFIG_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
a608f00ea8ca130c09265df7e48a79b54e554fd0 | 9cfa1b8858a11e347bf8b0e611b1d68e06780717 | /stasm/shapefile.cpp | fec04b47ac1ea55e6fb04944930608eeaa3315c2 | [] | no_license | tbian/aov | aaa1a20308afef7858ab34a309a7e867317abc53 | 3fd188d3c4d9d4355a58bedc6f87ab2a5c267a22 | refs/heads/master | 2021-01-22T23:53:36.038775 | 2012-07-12T05:35:48 | 2012-07-12T05:35:48 | 4,985,242 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,140 | cpp | // $shapefile.cpp 3.0 milbo$ routines for shape files
//-----------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// A copy of the GNU General Public License is available at
// http://www.r-project.org/Licenses/
//-----------------------------------------------------------------------------
#include "stasm.hpp"
//#include "tasm.hpp"
// The following is used only if nMaxShapes != 0.
//
// If CONF_nSeed_SelectShapes == 0 then we select the first nMaxShapes
//
// If CONF_nSeed_SelectShapes != 0 then we select a random selection of
// shapes as follows: randomly shuffle the shapes with the given random
// seed, and then select the first nMaxShapes from the shuffled shapes.
int CONF_nSeed_SelectShapes = 99;
//-----------------------------------------------------------------------------
// Note: the "magic number" of any file is the first few chars in the file
// that identify the file type
static void CheckShapeFileMagicNumber (FILE *pFile, const char sFile[])
{
char s[SLEN];
if (NULL == fgets(s, SLEN-1, pFile))
Err("can't read %s", sFile);
if (s[0] != 's' || s[1] != 's')
Err("%s is not a shape file (first two chars aren't \"ss\")", sFile);
}
//-----------------------------------------------------------------------------
// On return sImageDirs will be a string holding the image
// directories in sShapeFile, something like "/dir1;/dir2".
//
// On entry, we assume pShapeFile points to the string (or to comments
// preceding it which will be ignored). We also assume sImageDirs is big enough.
static void
GetImageDirsFromShapeFile (char sImageDirs[], // out
const char sShapeFile[], // in
FILE *pShapeFile) // in
{
char s[SLEN];
Fgets(s, SLEN-1, pShapeFile); // this skips blank lines and comments, if any
const char *sWhiteSpace = " \t\n\r";
char *sToken = strtok(s, sWhiteSpace);
if (!sToken || 0 != strcmp(sToken, "Directories"))
Err("expected \"Directories\" in line %d of %s",
nGetLineNbr(pShapeFile), sShapeFile);
sToken = strtok(NULL, sWhiteSpace);
if (!sToken)
Err("can't read image directories in line %d of %s",
nGetLineNbr(pShapeFile), sShapeFile);
strcpy(sImageDirs, sToken);
}
//-----------------------------------------------------------------------------
static void PrintMatchParams (const char sTagRegex[], // in
unsigned Mask0, unsigned Mask1) // in
{
if ((sTagRegex && sTagRegex[0]) || Mask0 || Mask1)
lprintf("Matching ");
if (sTagRegex && sTagRegex[0])
lprintf("\"%s\" ", sTagRegex);
if (Mask0 || Mask1)
{
lprintf("Mask0 %x [%s]", Mask0, sGetAtFaceString(Mask0));
lprintf(" Mask1 %x [%s]", Mask1, sGetAtFaceString(Mask1, true));
}
if ((sTagRegex && sTagRegex[0]) || Mask0 || Mask1)
lprintf("\n");
}
//-----------------------------------------------------------------------------
void ReadShapeFile (
vec_Mat &Mats, // out
vec_string &Tags, // out: strings preceding each mat i.e. tags
char sImageDirs[], // out: string following "Directories" in shape file
// can be NULL
const char sTagRegex[], // in: only read matrices whose tag
// matches this regular expression
unsigned Mask0, // in:
unsigned Mask1, // in: only read matrices where
// (Attr & Mask0) == Mask1
// (Attr is hex part of tag string)
const char sShapeFile[]) // in:
{
clock_t StartTime = clock();
PrintMatchParams(sTagRegex, Mask0, Mask1); // print informational msg
if (VERBOSE_ASM_SEARCH)
lprintf("Reading %s ", sShapeFile);
FILE *pShapeFile = Fopen(sShapeFile, "r"); // will issue Err if can't open
CheckShapeFileMagicNumber(pShapeFile, sShapeFile);
char sImageDirsDummy[SLEN];
if (!sImageDirs)
sImageDirs = sImageDirsDummy;
GetImageDirsFromShapeFile(sImageDirs, sShapeFile, pShapeFile);
ReadMatVec(Mats, &Tags, sShapeFile, pShapeFile, sTagRegex, Mask0, Mask1);
fclose(pShapeFile);
lprintf("%d mat%s [%.1f secs]\n",
Mats.size(), (Mats.size()==1? "": "s"), double(clock() - StartTime) / CLOCKS_PER_SEC);
}
//-----------------------------------------------------------------------------
const char *sGetBasenameFromTag (const char *sTag)
{
if (sTag[4] == ' ')
return sTag + 5;
if (sTag[8] == ' ') // extended tags
return sTag + 9;
Err("malformed tag \"%s\" in sGetBasenameFromTag", sTag);
return sTag;
}
const char *sGetBasenameFromTag (const string &sTag)
{
return sGetBasenameFromTag(sTag.c_str());
}
//-----------------------------------------------------------------------------
void DecomposeTag (const char sTag[], // in
unsigned *pAttr, char sImage[]) // out, can be null
{
// Tag string should be of the form: "1234 filename" or "12345678 filename".
// (Actually, the 8 character version of the tag is not used in the released
// version of stasm).
if (sTag[4] != ' ' && sTag[8] != ' ')
Err("malformed tag \"%s\"", sTag);
unsigned Attr1 = unsigned(-1);
char sImage1[SLEN]; sImage1[0] = 0;
if (2 != sscanf(sTag, "%x %s", &Attr1, sImage1) || Attr1 == unsigned(-1) || !sImage1[0])
Err("Cannot parse tag \"%s\"", sTag);
if (pAttr)
*pAttr = Attr1;
if (sImage)
strcpy(sImage, sImage1);
}
void DecomposeTag (const string &sTag, // in
unsigned *pAttr, char sImage[]) // out, can be null
{
DecomposeTag(sTag.c_str(), pAttr, sImage);
}
//-----------------------------------------------------------------------------
// Remove shapes in pShapes whose attribute tag begins with "1" or "2".
// Also update Tags to match the new *pShapes.
// This will also discard shapes whose names begins with an
// underscore if fDiscardUnderscores true.
void
DiscardFaceDetectorShapes (vec_SHAPE &Shapes, // io: updated
vec_string &Tags, // io: updated
bool fDiscardUnderscores)
{
unsigned iShape1 = 0;
unsigned nShapes = Tags.size();
ASSERT(Shapes.size() == nShapes);
for (unsigned iShape = 0; iShape < nShapes; iShape++)
{
const char *sTag = Tags[iShape].c_str();
// tag string should be of the form: "1234 filename" or "12345678 filename"
if (sTag[4] != ' ' && sTag[8] != ' ')
Err("malformed tag \"%s\"", sTag);
unsigned Attr;
if (1 == sscanf(sTag, "%x", &Attr) &&
!((Attr & FA_ViolaJones) || (Attr & FA_Rowley)) && // not a face detector shape
(!fDiscardUnderscores || sGetBasenameFromTag(sTag)[0] != '_'))
{
Shapes[iShape1].assign(Shapes[iShape]);
Tags[iShape1] = Tags[iShape];
iShape1++;
}
}
if (nShapes - iShape1)
lprintf("Ignored %d face detector%s shape%s\n",
nShapes - iShape1,
(fDiscardUnderscores? " and underscore": ""),
(nShapes - iShape1 == 1? "": "s"));
Shapes.resize(iShape1);
Tags.resize(iShape1);
}
//-----------------------------------------------------------------------------
// chuck out entries in Shapes that don't have nWantedPoints
void
DiscardShapesWithDifferentNbrOfPoints (vec_SHAPE &Shapes, // io: updated
vec_string &Tags, // io: updated
int nWantedPoints)
{
unsigned iShape1 = 0;
unsigned nShapes = Tags.size();
ASSERT(Shapes.size() == nShapes);
for (unsigned iShape = 0; iShape < nShapes; iShape++)
if (Shapes[iShape].nrows() == (unsigned)nWantedPoints)
{
Shapes[iShape1].assign(Shapes[iShape]);
Tags[iShape1] = Tags[iShape];
iShape1++;
}
if (nShapes - iShape1)
lprintf("Ignored %d shape%s "
"not matching the reference number of points %d\n",
nShapes - iShape1,
(nShapes - iShape1 == 1? "": "s"),
nWantedPoints);
Shapes.resize(iShape1);
Tags.resize(iShape1);
}
//-----------------------------------------------------------------------------
// Return a sample of Shapes (without replacement) with sample size nWantedShapes
//
// If nSeed==0 then simply return the first nWantedShapes in Shapes
//
// If nSeed!=0 is true then return a random sample of Shapes, with nSeed as
// the seed for the rand number generator. Do it like this: randomly shuffle
// the shapes then use the first n shapes (where n is nWantedShapes).
static void SelectNShapes (
vec_SHAPE &Shapes, // io
vec_string &Tags, // io: also shuffled, in step with Shapes
int nWantedShapes, // in: 0 means return all shapes
int nSeed=0) // in: 0 means no random selection; if any other
// val select randomly with rand seed=nSeed
{
unsigned nShapes = Tags.size();
if (nWantedShapes == 0)
nWantedShapes = nShapes;
nWantedShapes = MIN((unsigned)nWantedShapes, nShapes);
if (nSeed)
{
// generate a shuffled set of indices in iShuffledShapes
vec_int iShuffledShapes(nShapes);
unsigned iShape;
for (iShape = 0; iShape < nShapes; iShape++)
iShuffledShapes[iShape] = iShape;
SeedRand(nSeed);
// We use our own random shuffle here because different compilers
// give different results which messes up regression testing.
// (I think only Visual C 6.0 is incompatible with everyone else?)
//
// Following code is equivalent to
// random_shuffle(iShuffledShapes.begin(), iShuffledShapes.end(),
// pointer_to_unary_function<int,int>(Rand));
vec_int::iterator pNext = iShuffledShapes.begin();
for (int i = 2; ++pNext != iShuffledShapes.end(); ++i)
iter_swap(pNext, iShuffledShapes.begin() + Rand(i));
iShuffledShapes.resize(nWantedShapes);
// sort the selected indices so we can do an in-place replacement in Shapes
sort(iShuffledShapes.begin(), iShuffledShapes.end());
// keep the first nWantedShapes in iShuffledShapes
for (iShape = 0; iShape < unsigned(nWantedShapes); iShape++)
{
unsigned iOldShape = iShuffledShapes[iShape];
if (iShape > 0 && Shapes[0].nrows() != Shapes[iOldShape].nrows())
{
static bool fIssuedWarning;
if (!fIssuedWarning)
{
fIssuedWarning = true;
WarnWithNewLine("different sized shapes (%s has %d rows, %s has %d rows)\n",
sGetBasenameFromTag(Tags[0].c_str()), Shapes[0].nrows(),
sGetBasenameFromTag(Tags[iOldShape].c_str()), Shapes[iOldShape].nrows());
}
}
Shapes[iShape].assign(Shapes[iOldShape]);
Tags[iShape] = Tags[iOldShape];
}
}
Shapes.resize(nWantedShapes);
Tags.resize(nWantedShapes);
}
//-----------------------------------------------------------------------------
static void ShowFirstFewShapes (const vec_string &Tags) // in
{
if (Tags.size() == 0)
lprintf("No shapes");
else
{
lprintf("First few shapes are ");
unsigned iShape;
for (iShape = 0; iShape < MIN(5, Tags.size()); iShape++)
lprintf("%s ", sGetBase(sGetBasenameFromTag(Tags[iShape])));
if (iShape < Tags.size())
lprintf("...");
lprintf("\n");
}
}
//-----------------------------------------------------------------------------
void ReadSelectedShapes (
vec_SHAPE &Shapes, // out:
vec_string &Tags, // out:
char sImageDirs[], // out:
const char sShapeFile[], // in:
int nMaxShapes, // in: nbr of wanted shapes, 0 for all
const char sTagRegex[], // in: only read matrices whose tag
// matches this regular expression
unsigned Mask0, unsigned Mask1) // in: only read matrices where
// Attr&Mask0 == Mask1
// (Attr is hex part of tag string)
{
ReadShapeFile(Shapes, Tags, sImageDirs, sTagRegex, Mask0, Mask1, sShapeFile);
DiscardFaceDetectorShapes(Shapes, Tags);
unsigned nShapes = Tags.size();
if (nShapes == 0)
Err("no shapes");
if (unsigned(nMaxShapes) > nShapes)
{
lprintf("\n");
ShowFirstFewShapes(Tags);
Err("want %d shapes but there are only %d shapes", nMaxShapes, nShapes);
}
if (nMaxShapes != 0)
{
SelectNShapes(Shapes, Tags, nMaxShapes, CONF_nSeed_SelectShapes);
if (CONF_nSeed_SelectShapes)
lprintf("Selected a random sample of %d shape%s from %d shape%s (seed=%d)\n",
nMaxShapes, ((nMaxShapes==1)? "":"s"),
nShapes, ((nShapes==1)? "":"s"), CONF_nSeed_SelectShapes);
else
lprintf("Selected the first %d shape%s of %d shape%s\n",
nMaxShapes, ((nMaxShapes==1)? "":"s"),
nShapes, ((nShapes==1)? "":"s"));
}
else
lprintf("Read %d shape%s\n", nShapes, ((nShapes==1)? "":"s"));
ShowFirstFewShapes(Tags);
}
//-----------------------------------------------------------------------------
static int iGetRefShapeIndex1 (const vec_string &Tags,
unsigned Mask0, unsigned Mask1,
const char sFile[]) // in: for error reporting
{
for (unsigned iShape = 0; iShape < Tags.size(); iShape++)
{
const char *sTag = Tags[iShape].c_str();
if (!sTag || sTag[0] == 0)
Err("GetRefShapeIndex: shape index %d in %s does not have a tag",
iShape, sFile);
unsigned Tag;
if (sTag[4] != ' ' && sTag[8] != ' ')
Err("GetRefShapeIndex: tag %s in %s is malformed", sTag, sFile);
if (1 != sscanf(sTag, "%x", &Tag))
Err("GetRefShapeIndex: tag %s in %s is not a hex number", sTag, sFile);
if (fMatchAttr(Tag, Mask0, Mask1))
return iShape; // found it
}
return -1; // not found
}
//-----------------------------------------------------------------------------
// return the index of the first shape in Tags that has tag
// attributes which match Mask0 and Mask1
int iGetRefShapeIndex (const vec_string &Tags, // in:
unsigned Mask0, unsigned Mask1, // in:
const char sFile[]) // in: for error reporting
{
int iRefShape = iGetRefShapeIndex1(Tags, Mask0, Mask1, sFile);
if (iRefShape < 0)
{
char s[SLEN]; strcpy(s, sGetAtFaceString(Mask0));
Err("no shapes in %s match Mask0 %x [%s] Mask1 %x [%s] ",
sFile, Mask0, s, Mask1, sGetAtFaceString(Mask1));
}
return iRefShape;
}
| [
"tbian7@gmail.com"
] | tbian7@gmail.com |
f5cc6efb1b86de8efdee20ac402f9ab50245bfeb | b2fe6fffae49f594e63107f2f7fd14a7987943a1 | /InterviewQuestions/LeetCode/1_LinearList/1_2_9_ReverseNodesInKGroup.cpp | 5269762df928b9335c009e8e542bb6f212cc61b9 | [] | no_license | lawenliu/CodeInterview | 4852b97f61ca705274b6ccc45a16b8f99a247459 | 60b457971d064c6f72303a78798b279263392342 | refs/heads/master | 2021-05-02T18:33:03.722897 | 2017-12-20T23:42:48 | 2017-12-20T23:42:48 | 61,231,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,363 | cpp | /*********************************************************
* Given a lined list, reverse the nodes of a linked list k at a time
* and return its modified list.
* If the number of nodes is not a multiple of k then left-out nodes
* in the end should remain as it is.
* You may not alter the values in the nodes, only nodes itself may be changed.
* Only constant memory is allowed.
* For example, Given this linked list: 1->2->3->4->5
* For k = 2, you should return: 2->1->4->3->5
* For k = 3, you should return: 3->2->1->4->5
*********************************************************/
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int v) : val(v), next(nullptr) {}
};
class Solution {
public:
/* Time: O(n), Space: O(1) */
ListNode* reverseKGroup(ListNode *head, int k) {
if (head == nullptr || head->next == nullptr || k < 2) {
return head;
}
ListNode *nextGroup = head;
for (int i = 0; i < k; i++) {
if (nextGroup != nullptr) {
nextGroup = nextGroup->next;
} else {
return head;
}
}
ListNode *newNextGroup = reverseKGroup(nextGroup, k);
ListNode *prev = nullptr;
ListNode *cur = head;
while (cur != nextGroup) {
ListNode *next = cur->next;
if (prev == nullptr) {
cur->next = newNextGroup;
} else {
cur->next = prev;
}
prev = cur;
cur = next;
}
return prev;
}
ListNode* generateList(vector<int> array) {
ListNode dummy(-1);
ListNode* cur = &dummy;
for (int i = 0; i < array.size(); i++) {
cur->next = new ListNode(array[i]);
cur = cur->next;
}
return dummy.next;
}
void outputList(ListNode* head) {
while (head != nullptr) {
cout << head->val << " ";
head = head->next;
}
}
void deleteList(ListNode* head) {
while (head != nullptr) {
ListNode* tmp = head->next;
delete head;
head = tmp;
}
}
};
int main(void) {
Solution* s = new Solution();
vector<int> array = { 1, 2, 3, 4, 5 };
ListNode* head1 = s->generateList(array);
ListNode *head2 = s->generateList(array);
cout << "K = 2:" << endl;
ListNode* result1 = s->reverseKGroup(head1, 2);
s->outputList(result1);
cout << endl << "K = 3:" << endl;
ListNode* result2 = s->reverseKGroup(head2, 3);
s->outputList(result2);
s->deleteList(result1);
s->deleteList(result2);
delete s;
return 0;
} | [
"lwc541117@gmail.com"
] | lwc541117@gmail.com |
172714875d05008af8fe8a4d9abb84fdeb412d3b | e6c9adcd71fb805e09c91d9e1e07f6e7cf0a321a | /headers/mist-v1.6.0/test/singleton_test.cpp | 318e165c1aef2a72d71716b47180ced7aafbea06 | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | simizlab/atlas-guided-em-algorithm | a1c0f522c2daa0a7e53d0eb02eb7f7a8d73e19b0 | 54dd2df19f65724b1ac6957c06faca39d5b40215 | refs/heads/master | 2020-05-24T08:25:14.742300 | 2019-05-24T06:37:03 | 2019-05-24T06:37:03 | 187,184,512 | 4 | 0 | null | 2019-05-18T09:10:21 | 2019-05-17T09:07:52 | C++ | UTF-8 | C++ | false | false | 2,060 | cpp | //
// Copyright (c) 2003-2010, MIST Project, Nagoya University
// 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 Nagoya University 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 <mist/singleton.h>
#include <iostream>
void foo( )
{
int &s = mist::singleton< int >::get_instance( );
s++;
std::cout << s << std::endl;
}
void bar( )
{
int &s = mist::singleton< int, 1 >::get_instance( );
s++;
std::cout << s << std::endl;
}
int main( int argc, char *argv[] )
{
mist::singleton< int >::get_instance( ) = 0;
mist::singleton< int, 1 >::get_instance( ) = 20;
for( int i = 0 ; i < 10 ; i++ )
{
foo( );
bar( );
}
return( 0 );
}
| [
"38281934+zEttOn86@users.noreply.github.com"
] | 38281934+zEttOn86@users.noreply.github.com |
cffbddf98aef2d1e860b7cda0c9619d1d605c434 | 8d937ba1412c30a08ffd2a1196d65d836486534c | /30 Day Leet Code Challenge/Find the Duplicate Number.cpp | 01c5ae7a6dc47326c025d78252bd2c34d0925b2e | [] | no_license | ArpitSingla/LeetCode | 5988f0a9f43c216ad2d61a847aca8b25ca2330be | 4bfe51209e66ce3cee233841de9d4baa97454415 | refs/heads/master | 2021-03-20T22:14:01.234679 | 2020-07-30T04:09:04 | 2020-07-30T04:09:04 | 247,238,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | class Solution {
public:
// Using Fast and Slow Pointer
int findDuplicate(vector<int>& nums) {
int fast=nums[0];
int slow=nums[0];
do{
fast=nums[nums[fast]];
slow=nums[slow];
}while(fast!=slow);
slow=nums[0];
while(fast!=slow){
fast=nums[fast];
slow=nums[slow];
}
return slow;
}
//Using Binary Search
int findDuplicate(vector<int>& nums) {
int n=nums.size();
int left=1,right=n;
while(left<=right){
int m=left+(right-left)/2;
int temp=0;
for(int i=0;i<n;i++){
if(nums[i]<=m){
temp++;
}
}
if(temp>m){
right=m-1;
}
else{
left=m+1;
}
}
return left;
}
}; | [
"arpitsingla1999@gmail.com"
] | arpitsingla1999@gmail.com |
4b53f496a2ba145ef17bde0fcd5bd94a03bae60c | 671cdae7f9e5db17692e42a0fee96ddc87ce92ec | /Bus.h | b1fa0f0fcafbe1a3ae52960827e62b31c19b0216 | [] | no_license | Tonypony1496/newproject | 2448062c8544f0018afcb6e1f4dd48478017d47b | f624f9ac5a2cdb4c634c4c85d6de829db09101ee | refs/heads/master | 2020-06-07T22:02:32.076873 | 2019-06-21T13:42:48 | 2019-06-21T13:42:48 | 193,102,460 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 419 | h | #ifndef __Bus__
#define __Bus__
#include "Transport.h"
class Bus : public Transport
{
public:
short int passengerĐapacity;
void InData(ifstream& ifst);
void Out(ofstream& ofst);
Bus() {}
};
class BusFactory : public TransportFactory {
public:
BusFactory() :TransportFactory(2) { }
Transport* Create(int key) {
if (key == mark)
return new Bus;
else
return nullptr;
}
};
#endif
| [
"tony1496@yandex.ru"
] | tony1496@yandex.ru |
31a1a241223c55d76a0b38677128a70713739395 | 770718eaaa68c772c22613b5c745c1eff85f7c1a | /26/b.cpp | 9f0bbd52eb37d797c1a6d6020b216a8805daec95 | [] | no_license | duongptit14/GiaiNganHangCTDLGT | f77a280d753f89f139a581af4c8866b1eaca46e2 | b5461e1a212e7e3bd84d86e15f83ba37ad8ac842 | refs/heads/master | 2021-01-10T12:26:36.944302 | 2017-12-28T07:11:36 | 2017-12-28T07:11:36 | 55,380,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | cpp | #include <iostream>
#include<string.h>
using namespace std;
struct tree{//Moi phan tu cua cay la mot ky tu
char data;
tree *l, *r;
}*root = NULL, *p = NULL, *t = NULL, *y = NULL;
struct node {
struct tree *pt;
struct node *next;
}*top = NULL, *q = NULL, *np = NULL;
void push(tree *ptr){
np = new node;
np->pt = ptr;
np->next = NULL;
if (top == NULL){
top = np;
}
else{
q = top;
top = np;
np->next = q;
}
}
tree *pop(){
if (top == NULL) cout<<"tran bo nho\n";
else{
q = top;
top = top->next;
return(q->pt);
delete(q);
}
}
void oprnd_str(char val){
if (val >= 48 && val <= 57){
t = new tree;
t->data = val;
t->l = NULL;
t->r = NULL;
push(t);
}
else if (val >= 42 && val <= 47){
p = new tree;
p->data = val;
p->l = pop();
p->r = pop();
push(p);
}
}
char postorder(tree *w){
if (w != NULL)
{
pstorder(w->l);
pstorder(w->r);
cout<<w->data;
}
}
int main()
{
char a[15];
int i;
int j = -1;
cout<<"nhap chuoi ki tu\n"; cin>>a;
i = strlen(a);
while (i >= 0)
{
i--;
oprnd_str(a[i]);
}
postorder(pop());
system("pause");
}
| [
"duongpv@PVDptit.net.fpt"
] | duongpv@PVDptit.net.fpt |
dcaaf339c0cebcf37d2b4080e1f20760c645dcd8 | 5521a03064928d63cc199e8034e4ea76264f76da | /fboss/agent/hw/bcm/BcmInterface.h | 8cfa22ab119a9054c189cf787581ff04e793feb6 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | facebook/fboss | df190fd304e0bf5bfe4b00af29f36b55fa00efad | 81e02db57903b4369200eec7ef22d882da93c311 | refs/heads/main | 2023-09-01T18:21:22.565059 | 2023-09-01T15:53:39 | 2023-09-01T15:53:39 | 31,927,407 | 925 | 353 | NOASSERTION | 2023-09-14T05:44:49 | 2015-03-09T23:04:15 | C++ | UTF-8 | C++ | false | false | 20,981 | h | #pragma once
#include "fboss/agent/hw/bcm/BcmSdkVer.h"
extern "C" {
#if (defined(IS_OPENNSA))
#define BCM_WARM_BOOT_SUPPORT
#endif
#include <bcm/cosq.h>
#include <bcm/error.h>
#include <bcm/init.h>
#include <bcm/knet.h>
#include <bcm/l2.h>
#include <bcm/l3.h>
#include <bcm/link.h>
#include <bcm/mpls.h>
#include <bcm/pkt.h>
#include <bcm/port.h>
#include <bcm/rx.h>
#include <bcm/stack.h>
#include <bcm/stat.h>
#include <bcm/stg.h>
#include <bcm/switch.h>
#include <bcm/trunk.h>
#include <bcm/tx.h>
#include <bcm/types.h>
#include <bcm/vlan.h>
#include <bcm/pktio.h>
#include <bcm/pktio_defs.h>
}
namespace facebook::fboss {
class BcmInterface {
public:
virtual ~BcmInterface() = default;
virtual int
bcm_port_gport_get(int unit, bcm_port_t port, bcm_gport_t* gport) = 0;
virtual int
bcm_port_vlan_member_set(int unit, bcm_port_t port, uint32 flags) = 0;
virtual int bcm_l2_age_timer_set(int unit, int age_seconds) = 0;
virtual int bcm_stg_destroy(int unit, bcm_stg_t stg) = 0;
virtual int bcm_l3_intf_find_vlan(int unit, bcm_l3_intf_t* intf) = 0;
virtual int bcm_knet_netif_create(int unit, bcm_knet_netif_t* netif) = 0;
virtual int
bcm_l2_traverse(int unit, bcm_l2_traverse_cb trav_fn, void* user_data) = 0;
virtual int bcm_l3_route_delete_by_interface(
int unit,
bcm_l3_route_t* info) = 0;
virtual int bcm_l3_host_delete_by_interface(
int unit,
bcm_l3_host_t* info) = 0;
virtual int bcm_l3_egress_ecmp_traverse(
int unit,
bcm_l3_egress_ecmp_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_l2_age_timer_get(int unit, int* age_seconds) = 0;
virtual int bcm_vlan_list(int unit, bcm_vlan_data_t** listp, int* countp) = 0;
virtual int bcm_vlan_destroy_all(int unit) = 0;
virtual int bcm_l3_ecmp_member_add(
int unit,
bcm_if_t ecmp_group_id,
bcm_l3_ecmp_member_t* ecmp_member) = 0;
virtual int bcm_l3_egress_ecmp_add(
int unit,
bcm_l3_egress_ecmp_t* ecmp,
bcm_if_t intf) = 0;
virtual int
bcm_rx_unregister(int unit, bcm_rx_cb_f callback, uint8 priority) = 0;
virtual int bcm_switch_control_port_get(
int unit,
bcm_port_t port,
bcm_switch_control_t type,
int* arg) = 0;
virtual int bcm_info_get(int unit, bcm_info_t* info) = 0;
virtual int
bcm_port_untagged_vlan_set(int unit, bcm_port_t port, bcm_vlan_t vid) = 0;
virtual int bcm_rx_control_set(int unit, bcm_rx_control_t type, int arg) = 0;
virtual int bcm_knet_netif_destroy(int unit, int netif_id) = 0;
virtual void bcm_port_config_t_init(bcm_port_config_t* config) = 0;
virtual int bcm_port_config_get(int unit, bcm_port_config_t* config) = 0;
virtual int bcm_vlan_destroy(int unit, bcm_vlan_t vid) = 0;
virtual int bcm_stg_create(int unit, bcm_stg_t* stg_ptr) = 0;
virtual int bcm_l3_ecmp_get(
int unit,
bcm_l3_egress_ecmp_t* ecmp_info,
int ecmp_member_size,
bcm_l3_ecmp_member_t* ecmp_member_array,
int* ecmp_member_count) = 0;
virtual int bcm_l3_egress_ecmp_get(
int unit,
bcm_l3_egress_ecmp_t* ecmp,
int intf_size,
bcm_if_t* intf_array,
int* intf_count) = 0;
virtual int bcm_linkscan_mode_set(int unit, bcm_port_t port, int mode) = 0;
virtual int bcm_l3_host_delete(int unit, bcm_l3_host_t* ip_addr) = 0;
virtual int bcm_l3_intf_create(int unit, bcm_l3_intf_t* intf) = 0;
virtual int bcm_l3_route_delete(int unit, bcm_l3_route_t* info) = 0;
virtual int bcm_cosq_bst_stat_sync(int unit, bcm_bst_stat_id_t bid) = 0;
virtual void bcm_knet_filter_t_init(bcm_knet_filter_t* filter) = 0;
virtual int bcm_l3_host_find(int unit, bcm_l3_host_t* info) = 0;
virtual int bcm_stg_default_set(int unit, bcm_stg_t stg) = 0;
virtual int bcm_port_control_get(
int unit,
bcm_port_t port,
bcm_port_control_t type,
int* value) = 0;
virtual int bcm_l3_egress_multipath_find(
int unit,
int intf_count,
bcm_if_t* intf_array,
bcm_if_t* mpintf) = 0;
virtual int bcm_switch_control_port_set(
int unit,
bcm_port_t port,
bcm_switch_control_t type,
int arg) = 0;
virtual int bcm_l3_egress_ecmp_ethertype_set(
int unit,
uint32 flags,
int ethertype_count,
int* ethertype_array) = 0;
virtual int bcm_l3_egress_ecmp_ethertype_get(
int unit,
uint32* flags,
int ethertype_max,
int* ethertype_array,
int* ethertype_count) = 0;
virtual int
bcm_l3_egress_ecmp_member_status_set(int unit, bcm_if_t intf, int status) = 0;
virtual int bcm_l3_egress_ecmp_member_status_get(
int unit,
bcm_if_t intf,
int* status) = 0;
virtual int
bcm_vlan_list_destroy(int unit, bcm_vlan_data_t* list, int count) = 0;
virtual int
bcm_vlan_port_remove(int unit, bcm_vlan_t vid, bcm_pbmp_t pbmp) = 0;
virtual int bcm_l3_route_traverse(
int unit,
uint32 flags,
uint32 start,
uint32 end,
bcm_l3_route_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_l2_station_delete(int unit, int station_id) = 0;
virtual int bcm_linkscan_mode_get(int unit, bcm_port_t port, int* mode) = 0;
virtual int bcm_switch_pkt_trace_info_get(
int unit,
uint32 options,
uint8 port,
int len,
uint8* data,
bcm_switch_pkt_trace_info_t* pkt_trace_info) = 0;
virtual bcm_ip_t bcm_ip_mask_create(int len) = 0;
virtual int bcm_l3_egress_multipath_get(
int unit,
bcm_if_t mpintf,
int intf_size,
bcm_if_t* intf_array,
int* intf_count) = 0;
virtual int bcm_stg_default_get(int unit, bcm_stg_t* stg_ptr) = 0;
virtual int bcm_linkscan_enable_get(int unit, int* us) = 0;
virtual int
bcm_stg_stp_get(int unit, bcm_stg_t stg, bcm_port_t port, int* stp_state) = 0;
virtual int bcm_attach_max(int* max_units) = 0;
virtual int
bcm_port_local_get(int unit, bcm_gport_t gport, bcm_port_t* local_port) = 0;
virtual void bcm_l3_egress_ecmp_t_init(bcm_l3_egress_ecmp_t* ecmp) = 0;
virtual int bcm_cosq_bst_profile_set(
int unit,
bcm_gport_t gport,
bcm_cos_queue_t cosq,
bcm_bst_stat_id_t bid,
bcm_cosq_bst_profile_t* profile) = 0;
virtual int
bcm_cosq_mapping_get(int unit, bcm_cos_t priority, bcm_cos_queue_t* cosq) = 0;
virtual int bcm_port_control_set(
int unit,
bcm_port_t port,
bcm_port_control_t type,
int value) = 0;
virtual int bcm_tx(int unit, bcm_pkt_t* tx_pkt, void* cookie) = 0;
virtual int bcm_pktio_tx(int unit, bcm_pktio_pkt_t* tx_pkt) = 0;
virtual int
bcm_l3_egress_get(int unit, bcm_if_t intf, bcm_l3_egress_t* egr) = 0;
virtual void bcm_l3_egress_t_init(bcm_l3_egress_t* egr) = 0;
virtual int
bcm_port_stat_enable_set(int unit, bcm_gport_t port, int enable) = 0;
#if (defined(IS_OPENNSA) || defined(BCM_SDK_VERSION_GTE_6_5_21))
virtual int bcm_port_fdr_config_set(
int unit,
bcm_port_t port,
bcm_port_fdr_config_t* fdr_config) = 0;
virtual int bcm_port_fdr_config_get(
int unit,
bcm_port_t port,
bcm_port_fdr_config_t* fdr_config) = 0;
virtual int bcm_port_fdr_stats_get(
int unit,
bcm_port_t port,
bcm_port_fdr_stats_t* fdr_stats) = 0;
#endif
virtual int bcm_vlan_default_get(int unit, bcm_vlan_t* vid_ptr) = 0;
virtual int bcm_l3_init(int unit) = 0;
virtual int
bcm_l2_station_get(int unit, int station_id, bcm_l2_station_t* station) = 0;
virtual int bcm_linkscan_detach(int unit) = 0;
virtual int bcm_rx_stop(int unit, bcm_rx_cfg_t* cfg) = 0;
virtual int bcm_l3_egress_multipath_create(
int unit,
uint32 flags,
int intf_count,
bcm_if_t* intf_array,
bcm_if_t* mpintf) = 0;
virtual int bcm_port_ability_advert_get(
int unit,
bcm_port_t port,
bcm_port_ability_t* ability_mask) = 0;
virtual int bcm_l3_route_multipath_get(
int unit,
bcm_l3_route_t* the_route,
bcm_l3_route_t* path_array,
int max_path,
int* path_count) = 0;
virtual int
bcm_port_queued_count_get(int unit, bcm_port_t port, uint32* count) = 0;
virtual int bcm_l3_info(int unit, bcm_l3_info_t* l3info) = 0;
virtual int bcm_port_learn_get(int unit, bcm_port_t port, uint32* flags) = 0;
virtual int bcm_port_frame_max_set(int unit, bcm_port_t port, int size) = 0;
virtual int bcm_l3_route_delete_all(int unit, bcm_l3_route_t* info) = 0;
virtual int bcm_rx_cfg_get(int unit, bcm_rx_cfg_t* cfg) = 0;
virtual int bcm_port_ability_advert_set(
int unit,
bcm_port_t port,
bcm_port_ability_t* ability_mask) = 0;
virtual int bcm_knet_filter_destroy(int unit, int filter_id) = 0;
virtual int
bcm_l3_egress_find(int unit, bcm_l3_egress_t* egr, bcm_if_t* intf) = 0;
virtual int bcm_l3_route_get(int unit, bcm_l3_route_t* info) = 0;
virtual int bcm_cosq_bst_stat_get(
int unit,
bcm_gport_t gport,
bcm_cos_queue_t cosq,
bcm_bst_stat_id_t bid,
uint32 options,
uint64* value) = 0;
virtual int bcm_cosq_bst_stat_extended_get(
int unit,
bcm_cosq_object_id_t* id,
bcm_bst_stat_id_t bid,
uint32 options,
uint64* value) = 0;
virtual int bcm_udf_hash_config_add(
int unit,
uint32 options,
bcm_udf_hash_config_t* config) = 0;
virtual int bcm_udf_hash_config_delete(
int unit,
bcm_udf_hash_config_t* config) = 0;
virtual int bcm_udf_create(
int unit,
bcm_udf_alloc_hints_t* hints,
bcm_udf_t* udf_info,
bcm_udf_id_t* udf_id) = 0;
virtual int bcm_udf_destroy(int unit, bcm_udf_id_t udf_id) = 0;
virtual int bcm_udf_pkt_format_create(
int unit,
bcm_udf_pkt_format_options_t options,
bcm_udf_pkt_format_info_t* pkt_format,
bcm_udf_pkt_format_id_t* pkt_format_id) = 0;
virtual int bcm_udf_pkt_format_destroy(
int unit,
bcm_udf_pkt_format_id_t pkt_format_id) = 0;
virtual int bcm_udf_pkt_format_add(
int unit,
bcm_udf_id_t udf_id,
bcm_udf_pkt_format_id_t pkt_format_id) = 0;
virtual int
bcm_port_pause_addr_set(int unit, bcm_port_t port, bcm_mac_t mac) = 0;
virtual int bcm_udf_pkt_format_delete(
int unit,
bcm_udf_id_t udf_id,
bcm_udf_pkt_format_id_t pkt_format_id) = 0;
virtual int bcm_udf_pkt_format_get(
int unit,
bcm_udf_pkt_format_id_t pkt_format_id,
int max,
bcm_udf_id_t* udf_id_list,
int* actual) = 0;
virtual int bcm_udf_hash_config_get(
int unit,
bcm_udf_hash_config_t* config) = 0;
virtual int bcm_udf_pkt_format_info_get(
int unit,
bcm_udf_pkt_format_id_t pkt_format_id,
bcm_udf_pkt_format_info_t* pkt_format) = 0;
virtual void bcm_udf_pkt_format_info_t_init(
bcm_udf_pkt_format_info_t* pkt_format) = 0;
virtual void bcm_udf_alloc_hints_t_init(bcm_udf_alloc_hints_t* udf_hints) = 0;
virtual void bcm_udf_t_init(bcm_udf_t* udf_info) = 0;
virtual void bcm_udf_hash_config_t_init(bcm_udf_hash_config_t* config) = 0;
virtual int bcm_udf_init(int unit) = 0;
virtual int
bcm_udf_get(int unit, bcm_udf_id_t udf_id, bcm_udf_t* udf_info) = 0;
virtual int bcm_stat_clear(int unit, bcm_port_t port) = 0;
virtual int bcm_l3_route_max_ecmp_set(int unit, int max) = 0;
virtual int bcm_switch_event_unregister(
int unit,
bcm_switch_event_cb_t cb,
void* userdata) = 0;
virtual int bcm_attach(int unit, char* type, char* subtype, int remunit) = 0;
virtual int bcm_port_speed_set(int unit, bcm_port_t port, int speed) = 0;
virtual int bcm_l3_egress_destroy(int unit, bcm_if_t intf) = 0;
virtual int bcm_port_enable_set(int unit, bcm_port_t port, int enable) = 0;
virtual int bcm_l2_addr_delete(int unit, bcm_mac_t mac, bcm_vlan_t vid) = 0;
virtual int bcm_vlan_port_add(
int unit,
bcm_vlan_t vid,
bcm_pbmp_t pbmp,
bcm_pbmp_t ubmp) = 0;
virtual int
bcm_port_selective_get(int unit, bcm_port_t port, bcm_port_info_t* info) = 0;
virtual int bcm_cosq_bst_profile_get(
int unit,
bcm_gport_t gport,
bcm_cos_queue_t cosq,
bcm_bst_stat_id_t bid,
bcm_cosq_bst_profile_t* profile) = 0;
virtual int bcm_l3_ecmp_member_delete(
int unit,
bcm_if_t ecmp_group_id,
bcm_l3_ecmp_member_t* ecmp_member) = 0;
virtual int bcm_l3_egress_ecmp_delete(
int unit,
bcm_l3_egress_ecmp_t* ecmp,
bcm_if_t intf) = 0;
virtual int
bcm_port_link_status_get(int unit, bcm_port_t port, int* status) = 0;
virtual char* bcm_port_name(int unit, int port) = 0;
virtual int bcm_stg_list_destroy(int unit, bcm_stg_t* list, int count) = 0;
virtual int bcm_linkscan_enable_set(int unit, int us) = 0;
virtual int bcm_port_dtag_mode_set(int unit, bcm_port_t port, int mode) = 0;
virtual int bcm_l3_ecmp_create(
int unit,
uint32 options,
bcm_l3_egress_ecmp_t* ecmp_info,
int ecmp_member_count,
bcm_l3_ecmp_member_t* ecmp_member_array) = 0;
virtual int bcm_l3_egress_ecmp_create(
int unit,
bcm_l3_egress_ecmp_t* ecmp,
int intf_count,
bcm_if_t* intf_array) = 0;
virtual int bcm_stk_my_modid_get(int unit, int* my_modid) = 0;
virtual int bcm_l3_intf_delete(int unit, bcm_l3_intf_t* intf) = 0;
virtual int
bcm_l3_egress_multipath_add(int unit, bcm_if_t mpintf, bcm_if_t intf) = 0;
virtual int bcm_l3_egress_traverse(
int unit,
bcm_l3_egress_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_knet_init(int unit) = 0;
virtual int bcm_l3_route_add(int unit, bcm_l3_route_t* info) = 0;
virtual int bcm_stat_multi_get(
int unit,
bcm_port_t port,
int nstat,
bcm_stat_val_t* stat_arr,
uint64* value_arr) = 0;
virtual int bcm_l3_intf_get(int unit, bcm_l3_intf_t* intf) = 0;
virtual int bcm_detach(int unit) = 0;
virtual int _bcm_shutdown(int unit) = 0;
virtual int soc_shutdown(int unit) = 0;
virtual int bcm_l2_addr_get(
int unit,
bcm_mac_t mac_addr,
bcm_vlan_t vid,
bcm_l2_addr_t* l2addr) = 0;
virtual int bcm_stat_get(
int unit,
bcm_port_t port,
bcm_stat_val_t type,
uint64* value) = 0;
virtual int bcm_stat_sync_multi_get(
int unit,
bcm_port_t port,
int nstat,
bcm_stat_val_t* stat_arr,
uint64* value_arr) = 0;
virtual int
bcm_stg_stp_set(int unit, bcm_stg_t stg, bcm_port_t port, int stp_state) = 0;
virtual int bcm_port_untagged_vlan_get(
int unit,
bcm_port_t port,
bcm_vlan_t* vid_ptr) = 0;
virtual int bcm_vlan_default_set(int unit, bcm_vlan_t vid) = 0;
virtual int bcm_linkscan_unregister(int unit, bcm_linkscan_handler_t f) = 0;
virtual int bcm_l3_ecmp_destroy(int unit, bcm_if_t ecmp_group_id) = 0;
virtual int bcm_l3_egress_ecmp_destroy(
int unit,
bcm_l3_egress_ecmp_t* ecmp) = 0;
virtual int bcm_ip6_mask_create(bcm_ip6_t ip6, int len) = 0;
virtual int bcm_rx_start(int unit, bcm_rx_cfg_t* cfg) = 0;
virtual int bcm_l3_egress_create(
int unit,
uint32 flags,
bcm_l3_egress_t* egr,
bcm_if_t* if_id) = 0;
virtual int bcm_l3_intf_find(int unit, bcm_l3_intf_t* intf) = 0;
virtual int bcm_stg_list(int unit, bcm_stg_t** list, int* count) = 0;
virtual int
bcm_port_vlan_member_get(int unit, bcm_port_t port, uint32* flags) = 0;
virtual int bcm_stg_vlan_add(int unit, bcm_stg_t stg, bcm_vlan_t vid) = 0;
virtual void bcm_knet_netif_t_init(bcm_knet_netif_t* netif) = 0;
virtual int bcm_rx_control_get(int unit, bcm_rx_control_t type, int* arg) = 0;
virtual int
bcm_pkt_flags_init(int unit, bcm_pkt_t* pkt, uint32 init_flags) = 0;
virtual int bcm_l3_egress_multipath_traverse(
int unit,
bcm_l3_egress_multipath_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_l3_host_traverse(
int unit,
uint32 flags,
uint32 start,
uint32 end,
bcm_l3_host_traverse_cb cb,
void* user_data) = 0;
virtual int bcm_l3_host_add(int unit, bcm_l3_host_t* info) = 0;
virtual int bcm_port_learn_set(int unit, bcm_port_t port, uint32 flags) = 0;
virtual int
bcm_l2_station_add(int unit, int* station_id, bcm_l2_station_t* station) = 0;
virtual int bcm_port_phy_modify(
int unit,
bcm_port_t port,
uint32 flags,
uint32 phy_reg_addr,
uint32 phy_data,
uint32 phy_mask) = 0;
virtual int bcm_l3_host_delete_all(int unit, bcm_l3_host_t* info) = 0;
virtual int bcm_l2_addr_add(int unit, bcm_l2_addr_t* l2addr) = 0;
virtual int bcm_cosq_bst_stat_multi_get(
int unit,
bcm_gport_t gport,
bcm_cos_queue_t cosq,
uint32 options,
int max_values,
bcm_bst_stat_id_t* id_list,
uint64* values) = 0;
virtual int bcm_l3_egress_ecmp_find(
int unit,
int intf_count,
bcm_if_t* intf_array,
bcm_l3_egress_ecmp_t* ecmp) = 0;
virtual int bcm_pkt_free(int unit, bcm_pkt_t* pkt) = 0;
virtual int bcm_vlan_control_port_set(
int unit,
int port,
bcm_vlan_control_port_t type,
int arg) = 0;
virtual int bcm_vlan_create(int unit, bcm_vlan_t vid) = 0;
virtual int bcm_attach_check(int unit) = 0;
virtual int bcm_port_dtag_mode_get(int unit, bcm_port_t port, int* mode) = 0;
virtual int
bcm_pkt_alloc(int unit, int size, uint32 flags, bcm_pkt_t** pkt_buf) = 0;
virtual int bcm_knet_filter_traverse(
int unit,
bcm_knet_filter_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_port_speed_max(int unit, bcm_port_t port, int* speed) = 0;
virtual int bcm_linkscan_mode_set_pbm(int unit, bcm_pbmp_t pbm, int mode) = 0;
virtual int bcm_port_ability_local_get(
int unit,
bcm_port_t port,
bcm_port_ability_t* local_ability_mask) = 0;
virtual int bcm_port_enable_get(int unit, bcm_port_t port, int* enable) = 0;
virtual int bcm_port_frame_max_get(int unit, bcm_port_t port, int* size) = 0;
virtual int bcm_cosq_bst_stat_clear(
int unit,
bcm_gport_t gport,
bcm_cos_queue_t cosq,
bcm_bst_stat_id_t bid) = 0;
virtual int
bcm_cosq_mapping_set(int unit, bcm_cos_t priority, bcm_cos_queue_t cosq) = 0;
virtual int
bcm_port_selective_set(int unit, bcm_port_t port, bcm_port_info_t* info) = 0;
virtual int
bcm_port_interface_set(int unit, bcm_port_t port, bcm_port_if_t intf) = 0;
virtual int bcm_l3_route_max_ecmp_get(int unit, int* max) = 0;
virtual int
bcm_port_interface_get(int unit, bcm_port_t port, bcm_port_if_t* intf) = 0;
virtual int bcm_l3_egress_multipath_destroy(int unit, bcm_if_t mpintf) = 0;
virtual int bcm_vlan_gport_delete_all(int unit, bcm_vlan_t vlan) = 0;
virtual int
bcm_l3_egress_multipath_delete(int unit, bcm_if_t mpintf, bcm_if_t intf) = 0;
virtual int bcm_knet_filter_create(int unit, bcm_knet_filter_t* filter) = 0;
virtual int
bcm_switch_control_set(int unit, bcm_switch_control_t type, int arg) = 0;
virtual int bcm_rx_free(int unit, void* pkt_data) = 0;
virtual int bcm_rx_register(
int unit,
const char* name,
bcm_rx_cb_f callback,
uint8 priority,
void* cookie,
uint32 flags) = 0;
virtual int bcm_port_speed_get(int unit, bcm_port_t port, int* speed) = 0;
virtual int bcm_knet_netif_traverse(
int unit,
bcm_knet_netif_traverse_cb trav_fn,
void* user_data) = 0;
virtual int bcm_switch_event_register(
int unit,
bcm_switch_event_cb_t cb,
void* userdata) = 0;
virtual int bcm_linkscan_register(int unit, bcm_linkscan_handler_t f) = 0;
virtual int
bcm_switch_control_get(int unit, bcm_switch_control_t type, int* arg) = 0;
virtual int bcm_trunk_init(int unit) = 0;
virtual int bcm_trunk_get(
int unit,
bcm_trunk_t tid,
bcm_trunk_info_t* t_data,
int member_max,
bcm_trunk_member_t* member_array,
int* member_count) = 0;
virtual int bcm_trunk_find(
int unit,
bcm_module_t modid,
bcm_port_t port,
bcm_trunk_t* trunk) = 0;
virtual int bcm_trunk_destroy(int unit, bcm_trunk_t tid) = 0;
virtual int bcm_trunk_create(int unit, uint32 flags, bcm_trunk_t* tid) = 0;
virtual int bcm_trunk_set(
int unit,
bcm_trunk_t tid,
bcm_trunk_info_t* trunk_info,
int member_count,
bcm_trunk_member_t* member_array) = 0;
virtual int bcm_trunk_member_add(
int unit,
bcm_trunk_t tid,
bcm_trunk_member_t* member) = 0;
virtual int bcm_trunk_member_delete(
int unit,
bcm_trunk_t tid,
bcm_trunk_member_t* member) = 0;
virtual int bcm_port_ifg_get(
int unit,
bcm_port_t port,
int speed,
bcm_port_duplex_t duplex,
int* bit_times) = 0;
virtual int bcm_port_ifg_set(
int unit,
bcm_port_t port,
int speed,
bcm_port_duplex_t duplex,
int bit_times) = 0;
};
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
0461b9eafad8df8f3c5324500509c6d917983ef5 | d73dc790ef5d3968c60be25f1373bd10d3e74038 | /rpgEngine/main.cpp | 3b0dc26c9ed849e7f160c0055f64bcb72bfd6c6a | [] | no_license | rjavier441/PROJECT-indigo | f8906973995cf5f4882169dfdfd3b3025f7c86f1 | e1e15fbea9ea04ab982cdc453357c360e3148e24 | refs/heads/master | 2020-03-16T17:56:21.513945 | 2017-08-02T00:41:41 | 2017-08-02T00:41:41 | 132,853,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include "lib/Game.h"
using namespace std;
/* To compile: g++ -c *.h *.cpp
To link: g++ *.o -o game -lsfml-system -lsfml-window -lsfml-graphics -lsfml-audio
*/
int main(int argc, char* argv[]){
Game game("The Arc Stones");
game.Start();
return EXIT_SUCCESS;
}
| [
"rjavier441@gmail.com"
] | rjavier441@gmail.com |
06029b804538f1279ee5919f963fb225380e2a2c | ea71f6289415dfeb4b158a68a763515d0fb8f325 | /localAddons/ofxLight2D/src/Light2D.cpp | b568588b9700c580f96cd1a3af7bc19579262156 | [] | no_license | ofZach/funkyForms | dc043b9ad7a7cd46bb89887852f6ef192f9635a5 | 3a5b231be5382c1376bffb6890951aada24aded4 | refs/heads/master | 2020-04-06T07:07:21.303408 | 2016-08-28T00:11:45 | 2016-08-28T00:11:45 | 61,383,694 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,515 | cpp | // =============================================================================
//
// Copyright (c) 2014 Christopher Baker <http://christopherbaker.net>
//
// 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 "Light2D.h"
#include "ofGraphics.h"
#include "ofAppRunner.h"
#include "ofEvents.h"
#define STRINGIFY(x) #x
namespace ofx {
const float Light2D::DEFAULT_RADIUS = 500;
const float Light2D::DEFAULT_RANGE = 500;
const std::string Light2D::DEFAULT_LIGHT_SHADER_FRAGMENT_SRC = STRINGIFY(
uniform vec3 lightPos;
uniform vec4 lightColor;
uniform float radius;
uniform float bleed;
uniform float linearizeFactor;
void main()
{
// We have our camera set up such that the fragment is equivalent to
// the pixel at the x / y position.
// Get the distance from this pixel to the light's position.
float dist = length(lightPos - gl_FragCoord.xyz);
float attenuation = (radius - dist) * (bleed / pow(dist, 2.0) + linearizeFactor / radius);
// Optional, clamp it to prevent overcoloring
attenuation = clamp(attenuation, 0.0, 1.0);
// Attenuate the pixels colored by the light.
gl_FragColor = lightColor * attenuation;
}
);
ofShader Light2D::DEFAULT_LIGHT_SHADER;
Light2D::Light2D():
_position(0, 0, 0),
_angle(0),
_viewAngle(TWO_PI),
_radius(DEFAULT_RADIUS),
_color(1.0, 1.0, 1.0, 1.0),
_linearizeFactor(1),
_bleed(0),
_isMeshDirty(true)
{
if (!DEFAULT_LIGHT_SHADER.isLoaded())
{
DEFAULT_LIGHT_SHADER.setupShaderFromSource(GL_FRAGMENT_SHADER,
DEFAULT_LIGHT_SHADER_FRAGMENT_SRC);
if (ofIsGLProgrammableRenderer())
{
DEFAULT_LIGHT_SHADER.bindDefaults();
}
DEFAULT_LIGHT_SHADER.linkProgram();
}
}
Light2D::~Light2D()
{
}
void Light2D::update()
{
if (_isMeshDirty)
{
createMesh();
}
}
void Light2D::draw()
{
DEFAULT_LIGHT_SHADER.begin();
DEFAULT_LIGHT_SHADER.setUniform4f("lightColor", _color.r, _color.g, _color.b, _color.a);
DEFAULT_LIGHT_SHADER.setUniform3f("lightPos", _position.x, _position.y, _position.z);
DEFAULT_LIGHT_SHADER.setUniform1f("radius", _radius);
DEFAULT_LIGHT_SHADER.setUniform1f("bleed", _bleed);
DEFAULT_LIGHT_SHADER.setUniform1f("linearizeFactor", _linearizeFactor);
ofPushMatrix();
ofTranslate(_position);
ofRotateZ(ofRadToDeg(_angle - _viewAngle / 2.0));
_mesh.draw();
ofPopMatrix();
DEFAULT_LIGHT_SHADER.end();
}
void Light2D::setPosition(const ofVec3f& position)
{
_position = position;
_isMeshDirty = true;
}
const ofVec3f& Light2D::getPosition() const
{
return _position;
}
void Light2D::setAngle(float angle)
{
_angle = angle;
_isMeshDirty = true;
}
float Light2D::getAngle() const
{
return _angle;
}
void Light2D::setViewAngle(float viewAngle)
{
_viewAngle = viewAngle;
_isMeshDirty = true;
}
float Light2D::getViewAngle() const
{
return _viewAngle;
}
float Light2D::getRadius() const
{
return _radius;
}
void Light2D::setRadius(float radius)
{
_radius = radius;
}
void Light2D::setColor(const ofFloatColor& color)
{
_color = color;
_isMeshDirty = true;
}
ofFloatColor Light2D::getColor() const
{
return _color;
}
float Light2D::getBleed() const
{
return _bleed;
}
void Light2D::setBleed(float bleed)
{
_bleed = bleed;
}
float Light2D::getLinearizeFactor() const
{
return _linearizeFactor;
}
void Light2D::setLinearizeFactor(float linearizeFactor)
{
_linearizeFactor = linearizeFactor;
}
void Light2D::createMesh() const
{
_mesh.clear();
_mesh.setMode(OF_PRIMITIVE_TRIANGLE_FAN);
ofVec3f position(0, 0, 0);
ofFloatColor color(_color);
_mesh.addVertex(position);
_mesh.addColor(color);
color = ofFloatColor(0, 0, 0, 0);
float fanIncrement = TWO_PI / 32;
for (float angle = 0.0; angle < _viewAngle; angle += fanIncrement)
{
if (angle > _viewAngle)
{
angle = _viewAngle;
}
position.x = cos(angle);
position.y = sin(angle);
position *= (_radius * _radius);
_mesh.addVertex(position);
_mesh.addColor(color);
}
position.x = _radius;
position.y = 0;
_mesh.addVertex(position);
_mesh.addColor(color);
_isMeshDirty = false;
}
} // namespace ofx
| [
"qinzi.tan@newschool.edu"
] | qinzi.tan@newschool.edu |
43f38bf5038b25414264e6ddfdf37003b9c4d1ef | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /android_webview/browser/aw_javascript_dialog_manager.cc | 60ac537fb2942317d95e48b355669450aa3a0f17 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 1,981 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/aw_javascript_dialog_manager.h"
#include "android_webview/browser/aw_contents_client_bridge_base.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/web_contents.h"
namespace android_webview {
AwJavaScriptDialogManager::AwJavaScriptDialogManager() {}
AwJavaScriptDialogManager::~AwJavaScriptDialogManager() {}
void AwJavaScriptDialogManager::RunJavaScriptDialog(
content::WebContents* web_contents,
const GURL& origin_url,
content::JavaScriptMessageType message_type,
const base::string16& message_text,
const base::string16& default_prompt_text,
const DialogClosedCallback& callback,
bool* did_suppress_message) {
AwContentsClientBridgeBase* bridge =
AwContentsClientBridgeBase::FromWebContents(web_contents);
if (!bridge) {
callback.Run(false, base::string16());
return;
}
bridge->RunJavaScriptDialog(message_type,
origin_url,
message_text,
default_prompt_text,
callback);
}
void AwJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
bool is_reload,
const DialogClosedCallback& callback) {
AwContentsClientBridgeBase* bridge =
AwContentsClientBridgeBase::FromWebContents(web_contents);
if (!bridge) {
callback.Run(false, base::string16());
return;
}
bridge->RunBeforeUnloadDialog(web_contents->GetURL(),
callback);
}
void AwJavaScriptDialogManager::CancelActiveAndPendingDialogs(
content::WebContents* web_contents) {
}
void AwJavaScriptDialogManager::ResetDialogState(
content::WebContents* web_contents) {
}
} // namespace android_webview
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
7cdc2fe9d0d85f14bc347e864678ae8c53dea88c | 5e3408fb807bf8514f73503d10e648f1dcaf674c | /src/qt/test/uritests.cpp | 60811d1b37c58e56e08c3bd953d7ee3cf8d0267c | [
"MIT"
] | permissive | DataSaverCoin/DSC | e6536901627a461a6d9098fb6b266d160c357a1f | 20b55e51d324db4201748bb5fa7539aa8c7f38af | refs/heads/master | 2021-05-02T07:46:06.450425 | 2018-07-10T13:16:21 | 2018-07-10T13:16:21 | 120,837,812 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | cpp | #include "uritests.h"
#include "../guiutil.h"
#include "../walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("datasavercoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
// We currently don't implement the message parameter (ok, yea, we break spec...)
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("datasavercoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
| [
"support@datasaver.org"
] | support@datasaver.org |
55c627a6abba53e2493713aee71899bdbcca3527 | ab9d3d4a9af4409906c7e322e59eecaac863115b | /thrift/gen-cpp/block_master_types.cpp | 2ca45698abc46e87f0d1ab0fb4f683ff87eb67c5 | [
"Apache-2.0"
] | permissive | pspringer/AlluxioWorker | 95e8a012e0f7e8076e2053970c8288246b8da957 | df07f554449c91b1e0f70abe2317b76903f97545 | refs/heads/master | 2021-05-14T10:06:48.340243 | 2018-01-30T00:00:44 | 2018-01-30T00:00:44 | 116,343,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 6,191 | cpp | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "block_master_types.h"
#include <algorithm>
#include <ostream>
#include <thrift/TToString.h>
WorkerInfo::~WorkerInfo() throw() {
}
void WorkerInfo::__set_id(const int64_t val) {
this->id = val;
}
void WorkerInfo::__set_address(const ::WorkerNetAddress& val) {
this->address = val;
}
void WorkerInfo::__set_lastContactSec(const int32_t val) {
this->lastContactSec = val;
}
void WorkerInfo::__set_state(const std::string& val) {
this->state = val;
}
void WorkerInfo::__set_capacityBytes(const int64_t val) {
this->capacityBytes = val;
}
void WorkerInfo::__set_usedBytes(const int64_t val) {
this->usedBytes = val;
}
void WorkerInfo::__set_startTimeMs(const int64_t val) {
this->startTimeMs = val;
}
uint32_t WorkerInfo::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->id);
this->__isset.id = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->address.read(iprot);
this->__isset.address = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->lastContactSec);
this->__isset.lastContactSec = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->state);
this->__isset.state = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->capacityBytes);
this->__isset.capacityBytes = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 6:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->usedBytes);
this->__isset.usedBytes = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 7:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->startTimeMs);
this->__isset.startTimeMs = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t WorkerInfo::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("WorkerInfo");
xfer += oprot->writeFieldBegin("id", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64(this->id);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("address", ::apache::thrift::protocol::T_STRUCT, 2);
xfer += this->address.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("lastContactSec", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32(this->lastContactSec);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("state", ::apache::thrift::protocol::T_STRING, 4);
xfer += oprot->writeString(this->state);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("capacityBytes", ::apache::thrift::protocol::T_I64, 5);
xfer += oprot->writeI64(this->capacityBytes);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytes", ::apache::thrift::protocol::T_I64, 6);
xfer += oprot->writeI64(this->usedBytes);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("startTimeMs", ::apache::thrift::protocol::T_I64, 7);
xfer += oprot->writeI64(this->startTimeMs);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(WorkerInfo &a, WorkerInfo &b) {
using ::std::swap;
swap(a.id, b.id);
swap(a.address, b.address);
swap(a.lastContactSec, b.lastContactSec);
swap(a.state, b.state);
swap(a.capacityBytes, b.capacityBytes);
swap(a.usedBytes, b.usedBytes);
swap(a.startTimeMs, b.startTimeMs);
swap(a.__isset, b.__isset);
}
WorkerInfo::WorkerInfo(const WorkerInfo& other0) {
id = other0.id;
address = other0.address;
lastContactSec = other0.lastContactSec;
state = other0.state;
capacityBytes = other0.capacityBytes;
usedBytes = other0.usedBytes;
startTimeMs = other0.startTimeMs;
__isset = other0.__isset;
}
WorkerInfo& WorkerInfo::operator=(const WorkerInfo& other1) {
id = other1.id;
address = other1.address;
lastContactSec = other1.lastContactSec;
state = other1.state;
capacityBytes = other1.capacityBytes;
usedBytes = other1.usedBytes;
startTimeMs = other1.startTimeMs;
__isset = other1.__isset;
return *this;
}
void WorkerInfo::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "WorkerInfo(";
out << "id=" << to_string(id);
out << ", " << "address=" << to_string(address);
out << ", " << "lastContactSec=" << to_string(lastContactSec);
out << ", " << "state=" << to_string(state);
out << ", " << "capacityBytes=" << to_string(capacityBytes);
out << ", " << "usedBytes=" << to_string(usedBytes);
out << ", " << "startTimeMs=" << to_string(startTimeMs);
out << ")";
}
| [
"pspringer@emutechnology.com"
] | pspringer@emutechnology.com |
8008ebc4578c14213d91f6ada736122d508205e9 | 903f92ae4980c2b0ee864df451af586ef7e575e2 | /search/bfs.cpp | c906295abbbcf84accf6742b86d4a25eb44b307c | [] | no_license | anandr86/Search-Assignment | cad620807849b2a3d9f2f8a7d7deb2f7ef3647b6 | 5f4cc71237f6599944312314b27af187fc615cde | refs/heads/master | 2021-01-23T13:48:34.635942 | 2011-10-04T06:17:31 | 2011-10-04T06:17:31 | 2,454,326 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | cpp |
#include <bfs.hpp>
#include <search.hpp>
#include <state.hpp>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
#include <memory>
using namespace std;
BFS::BFS(spState start) : Search(start)
{
}
shared_ptr<vector<spState>> BFS::run()
{
list<spState> open;
vector<spState> closed;
open.push_back(start->clone());
while(!open.empty()) {
spState c = open.front();
open.pop_front();
closed.push_back(c);
//generate children
auto ch = c->generateChildren();
for_each(ch.begin(), ch.end(), [&](spState s)
{
s->setParent(c);
});
//check for goal condition
for(auto i = ch.begin(); i != ch.end(); i++) {
//Found goal. Compute path and return
if((*i)->isGoal()) {
return constructPath(*i); // we are using linked states. No need for closed list
}
}
//check closed list and prune
auto mark = remove_if(ch.begin(), ch.end(), [&](spState s)
{
return find_if(closed.begin(), closed.end(), [&](spState ss) { return ss->equal(s);}) != closed.end();
});
ch.erase(mark, ch.end());
//check open list and prune
mark = remove_if(ch.begin(), ch.end(), [&](spState s)
{
return find_if(open.begin(), open.end(), [&](spState ss) { return ss->equal(s);}) != open.end();
});
ch.erase(mark, ch.end());
//add children to open list
copy(ch.rbegin(), ch.rend(), back_inserter(open));
}
return nullptr;
}
void BFS::reset()
{
}
| [
"anandr86@gmail.com"
] | anandr86@gmail.com |
22a7c6d7bf3cb9f9b7bb9438bad387c0ff40996a | 26507c02aedb3014ee03b4d796f15ce4ad8ee8be | /message.cpp | 4dbaa1ae36c572740401e57ee3efc1cb7ebeb05c | [] | no_license | Frost-fusion/P2P_Chord_DHT | 2ae261c7b5803b5afd9c211edc6141fea831f2b8 | 15ba1fd8ad6bbe3df8dfd28abab938893b624444 | refs/heads/master | 2022-04-16T13:56:33.467160 | 2015-05-03T06:47:55 | 2015-05-03T06:47:55 | 254,827,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | #include <cstring>
#include <chrono>
using namespace std;
class message
{
public:
int command;
int id;
int src;
int dest;
int finger_idx;
message() {};
message(int command, int id, int src, int dest, int finger_idx)
{
this->command = command;
this->id = id;
this->src = src;
this->dest = dest;
this->finger_idx = finger_idx;
};
void setContent(int command, int id, int src, int dest, int finger_idx)
{
this->command = command;
this->id = id;
this->src = src;
this->dest = dest;
this->finger_idx = finger_idx;
};
};
| [
"haojin2@460f2f80-ea7f-4ded-9ede-27a2d1ad010b"
] | haojin2@460f2f80-ea7f-4ded-9ede-27a2d1ad010b |
340ffab6d422d38e969540a652d837444abf9ed3 | 86316b629090c023d74104157dda99ca978c81ea | /src/testing/StaticTest.cpp | 903d2c12c032ee1947aa96e3777b363853100a7d | [
"Apache-2.0"
] | permissive | amb/LeapCxx | 5473731375e1972237e3d35a85fd24734c18efa6 | adee8ab2d277edfade3c385b0e6e3dff1445774e | refs/heads/master | 2022-11-22T09:51:12.531577 | 2020-06-13T04:52:10 | 2020-06-13T04:52:10 | 271,942,389 | 0 | 0 | Apache-2.0 | 2020-06-13T04:50:02 | 2020-06-13T04:50:01 | null | UTF-8 | C++ | false | false | 619 | cpp | #include "LeapC++/LeapC++.h"
#include "PipelineInterface/ScorchReason.h"
#define ASSERT_ENUM_EQ(a, b) static_assert((int)a == (int)b, "Mismatched Enums: " #a " != " #b)
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_UNKNOWN, ScorchReason::UNKNOWN);
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_CALIBRATION, ScorchReason::CALIBRATION);
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_FIRMWARE, ScorchReason::FIRMWARE);
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_TRANSPORT, ScorchReason::TRANSPORT);
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_CONTROL, ScorchReason::CONTROL);
ASSERT_ENUM_EQ(Leap::FailedDevice::FAIL_COUNT, ScorchReason::COUNT);
| [
"wgray@leapmotion.com"
] | wgray@leapmotion.com |
ff63d3bb668c32e9ef0eb84524876d4a98e71469 | c25e6270534473111e2a4c7fbd81ac39cef8021d | /OspedaleP2-master/GUI/header/view_medico.h | 0103a2f328939ce05a492ad78e6377eef1b8bb78 | [] | no_license | wahad88/ProgOgettiQT | 4de7021bf7e2dfd28aa7692b539e84c61b8c3098 | 6cc8a70b3b04bdfd296f0901cf331431c2e56713 | refs/heads/master | 2023-03-22T01:27:24.720938 | 2021-03-20T14:42:53 | 2021-03-20T14:42:53 | 263,770,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | h | #ifndef VIEW_MEDICO_H
#define VIEW_MEDICO_H
#include <QWidget>
#include <QLineEdit>
#include <QComboBox>
#include "../../MODEL/header/persona.h"
#include "../../MODEL/header/medico.h"
#include "../../MODEL/header/queuepersone.h"
#include "view_persona.h"
class view_medico : public view_persona{
public:
view_medico(QueuePersone& lista, Persona* persona,bool ed = false, QWidget* parent = nullptr): view_persona(lista,persona, ed, parent){}
virtual ~view_medico();
protected:
virtual void edit() const;
virtual void build_field();
private:
QLineEdit* specializzazione;
QComboBox* chirurgia;
};
#endif // VIEW_MEDICO_H
| [
"wahad88@gmail.com"
] | wahad88@gmail.com |
ade1c0ba374201aa542071a590d0df681d5745ad | c22d3119bf967a1c0690c3c63fe92289ab57064f | /codeforces/Digit Game.cpp | 5a90cafd268f18a7dc10634c52316b862761e6f3 | [] | no_license | mandalsudipti/competitive_programming | b33b599965f073d7c4654fa53d87ae0b1e3b2df0 | 74e7e0c281450acdb130c7ae4d4dde0fec596315 | refs/heads/master | 2021-12-11T00:31:33.601820 | 2021-10-31T15:19:37 | 2021-10-31T15:19:37 | 236,663,914 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int n ;
string S;
cin>>n>>S;
vector<int>A;
vector<int>B;
for(int i=0;i<S.length();i+=2)
{
A.push_back(S[i]-'0');
if(i+1<S.length())
B.push_back(S[i+1]-'0');
}
if(A.size()>B.size())
{
bool flag = false;
for(int i=0;i<A.size();i++)
{
if(A[i]%2)
{
flag = true;
break;
}
}
if(flag)
cout<<"1"<<endl;
else
cout<<"2"<<endl;
}
else
{
bool flag = false;
for(int i=0;i<B.size();i++)
{
if(B[i]%2==0)
{
flag = true;
break;
}
}
if(flag)
cout<<"2"<<endl;
else
cout<<"1"<<endl;
}
}
return 0;
}
| [
"noreply@github.com"
] | mandalsudipti.noreply@github.com |
3da1108a2353f91435e09ea1f6aedf246c5e10f7 | 72852e07bb30adbee608275d6048b2121a5b9d82 | /algorithms/problem_0908/other2.cpp | a07d8596aed36c85c436ecc256a81735dca93ae5 | [] | no_license | drlongle/leetcode | e172ae29ea63911ccc3afb815f6dbff041609939 | 8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13 | refs/heads/master | 2023-01-08T16:26:12.370098 | 2023-01-03T09:08:24 | 2023-01-03T09:08:24 | 81,335,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
// Determine the min and max of A
int minA = A[0];
int maxA = A[0];
for(int i = 1; i < A.size(); i++)
{
minA = min(A[i], minA);
maxA = max(A[i], maxA);
}
// Calculate the "smallest range" by (max(A) - K) - (min(A) + K)
int range = (maxA - K) - (minA + K);
// 0 is returned if range < 0
return max(0, range);
}
};
| [
"drlongle@gmail.com"
] | drlongle@gmail.com |
01eae55178c390b7ee63b0df38bf3ba422362e47 | 3857cab3b6b98612ebd4b87eb0e36c778bacef53 | /NeutrinoPhysics/nueoscilib/src/nuN_interpxsec.h | 5ebdc86ae3256efcd6843b4ca72ca6aeddcc97c8 | [] | no_license | andres0sorio/GRBsWork | 83b23ef6e579b026c58c0561facb66188f64d9ac | 10c899a110afa81ef3ec195181ed7e0a48360a06 | refs/heads/master | 2021-01-10T14:30:37.130283 | 2015-10-26T04:56:27 | 2015-10-26T04:56:27 | 8,447,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | h | #ifndef NUN_XSEC_H
#define NUN_XSEC_H 1
// Include files
#include "RootCommon.h"
#include "GSLHelpers.h"
#include <Math/Interpolator.h>
#include <iterator>
class Interpolation {
public:
Interpolation();
Interpolation(const char *);
virtual ~Interpolation();
double evaluateCC( double );
double evaluateNC( double );
void setLogY();
std::vector<double > m_xx;
std::vector<double > m_cc;
std::vector<double > m_nc;
void showPoints();
private:
std::ifstream * m_in;
ROOT::Math::Interpolator * m_interpolatorCC;
ROOT::Math::Interpolator * m_interpolatorNC;
bool m_logX;
bool m_logY;
double e_nu;
float cc_xsec;
float nc_xsec ;
float tot_xsec;
unsigned int m_ndata;
};
#endif // NUN_XSEC_H
| [
"osorio.af@gmail.com"
] | osorio.af@gmail.com |
4ba9b2c252a4f6604e0b56582fdbae8528a83843 | 6bdd937425077cba9d4855a81da5ddba3affdf4b | /Projects/Ibrahim/Ibrahim/Source.cpp | 1194884669c38bdca52392024ae603cf7b66ca39 | [] | no_license | faksam/My_FPT_C-Sharp | 927a18fa3f4c1fabc7ccd2649f7ed1b61789e274 | 9de7581d15efbc3a23b5e74b7b3f6fe403983807 | refs/heads/master | 2016-09-08T02:41:59.983101 | 2015-10-22T19:15:51 | 2015-10-22T19:15:51 | 38,954,961 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include <iostream>
#include<cstdlib>
using namespace std;
struct ISE802
{
string name;
int age;
string idnum;
};
int main()
{
ISE802 ibrahim, tung, john;
ibrahim.name = "ibrahim akoji";
john.name = "john love adebiyi";
tung.name = "tung bad boy";
int ibrahim, tung, john;
ibrahim.age = 19;
john.age = 98;
tung.age = 45;
char ibrahim, tung, john;
ibrahim.idnum = "ise03508";
tung.idnum = "ise035099";
john.idnum = "ise0359";
int val;
int a, b;
cout << "***********************" << endl;
cout << "input your number" << endl;
cin >> a;
cin >> b;
val = a + b;
cout << val << "result = " << val <<" jkhgjgj"<<endl<< "johnnnnnny"<< endl << "love food"<<endl;
system ("pause");
}
| [
"fakunlesamuel@gmail.com"
] | fakunlesamuel@gmail.com |
9d48b3372a2b4aed3b1cc893874f68c02f755179 | e0bf5836e4f0d75b28b1f787446e655cdeeb8b03 | /files/test.cpp | 768b8a5b1d3e36276ca2bb7d72452bfe4b6566ef | [] | no_license | arunnsit/allcodes | 3f0b73facdee06e802455c6c3fb5de7baae702c2 | 5e6a8bf3883d0c5f67dfa7cc3dc026dbb4c63a71 | refs/heads/master | 2021-01-10T13:58:24.900593 | 2017-10-03T18:11:34 | 2017-10-03T18:11:34 | 50,598,937 | 0 | 2 | null | 2019-09-30T20:16:32 | 2016-01-28T17:06:03 | C++ | UTF-8 | C++ | false | false | 2,251 | cpp | #include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
vector<int>v[80000];
vector<int>ancestor[80000];
int a[80000],b[80000];
int L[100000];
int ances(int start,int parent,int len)
{
L[start]=len;
for(int i=0;i<v[start].size();i++)
{ if(v[start][i]!=parent)
{
ancestor[v[start][i]].push_back(start);
ances(v[start][i],start,len+1);
}
}
return 1;
}
int T[100000], P[100000][25];
void process(int N)
{
int i, j;
//we initialize every element in P with -1
for (i = 0; i < N; i++)
for (j = 0; 1 << j < N; j++)
P[i][j] = -1;
//the first ancestor of every node i is T[i]
for (i = 0; i < N; i++)
P[i][0] = ancestor[i][0];
//bottom up dynamic programing
for (j = 1; 1 << j < N; j++)
for (i = 0; i < N; i++)
if (P[i][j - 1] != -1)
P[i][j] = P[P[i][j - 1]][j - 1];
}
int lca_query( int N,int p, int q)
{
int tmp, log, i;
//if p is situated on a higher level than q then we swap them
if (L[p] < L[q])
tmp = p, p = q, q = tmp;
//we compute the value of [log(L[p)]
for (log = 1; 1 << log <= L[p]; log++);
log--;
//we find the ancestor of node p situated on the same level
//with q using the values in P
for (i = log; i >= 0; i--)
if (L[p] - (1 << i) >= L[q])
p = P[p][i];
if (p == q)
return p;
//we compute LCA(p, q) using the values in P
for (i = log; i >= 0; i--)
if (P[p][i] != -1 && P[p][i] != P[q][i])
p = P[p][i], q = P[q][i];
return T[p];
}
int main()
{
int n,q;
int sol=0,prev;
cin>>n>>q;
int i,j,x,y;
for(i=0;i<n-1;i++)
{
cin>>x>>y;
x--;
y--;
v[x].push_back(y);
v[y].push_back(x);
}
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
cin>>b[i];
ances(0,-2,0);
ancestor[1].push_back(-2);
process(n);
query()
while(q--)
{
int type,po,op;
cin>>type;
if(type==1)
{ cin>>op>>po;
a[op]=po;
}
else
{
sol=0;
cin>>x;
x--;
prev=x;
while(x!=-2)
{
if(b[prev]>=a[x])
sol++;
x=ancestor[x][0];
}
cout<<sol<<endl;
}
}
}
| [
"arun.yad96@gmail.com"
] | arun.yad96@gmail.com |
c23f8b0c98fd713e15126c9b6be3a42be3c43009 | e782c47af0b5d5759de534e532cbe10f13da2515 | /New/Classes/Controller/UIController.cpp | 57da108f1b8c3365fb47c641a0c49d8b7e11dc83 | [] | no_license | ambroseL/Architecture_Pattern | 44ef9b39ca83a46e6a93958b11fa4f1ebdec8dd7 | 8d30fa2ef0ac0517b10ba2247a4410c42de03d3d | refs/heads/master | 2021-01-18T22:23:13.719029 | 2016-12-07T03:19:48 | 2016-12-07T03:19:48 | 72,494,363 | 1 | 1 | null | 2016-12-06T14:20:41 | 2016-11-01T01:55:15 | C++ | GB18030 | C++ | false | false | 820 | cpp | #include "UIController.h"
#include "deprecated/CCDeprecated.h"
#include "SimpleAudioEngine.h"
#include "GameLayer.h"
UIController::UIController():layer(nullptr)
{
}
UIController::~UIController()
{
}
void UIController::setLayer(GameLayer* layer)
{
this->layer = layer;
}
void UIController::updateLifeSprite(int HP)
{
Sprite* dSp = layer->getLifeSprite();
Texture2D* texture = CCTextureCache::sharedTextureCache()->addImage("Image/HP" + StringUtils::format("%d", HP) + ".png");
dSp->setTexture(texture);
}
void UIController::playYX()
{
//开始播放背景音效,false表示不循环
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Sound/eatprops.wav", false);
//设置音效音量0.0-1.0
CocosDenshion::SimpleAudioEngine::sharedEngine()->setEffectsVolume(1.0f);
}
| [
"ambrose2015@icloud.com"
] | ambrose2015@icloud.com |
c40fd3ec8ad740bbf61d3ec4555ee29a3eb64efd | cb4e40043a362288616fdcf784c284147a06086e | /牛客网吉大/堆栈的使用.cpp | c7820d88adac2f5e1ae7f4273db920f97c9a0bde | [] | no_license | stArl23/onlineJudgeExam | aaab6c47ab0cae3eb52dd940e89c08b3301565d0 | c8b7d1f38b0f6463fbd56be08a212084cd96cdde | refs/heads/master | 2021-10-22T11:12:45.783087 | 2019-03-10T05:24:04 | 2019-03-10T05:24:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 543 | cpp | #include<iostream>
#include<vector>
using namespace std;
int main(){
int n;
while(cin>>n&&n>0){
string operation;
int num;
vector<int> s1;
for(int i=0;i<n;i++){
cin>>operation;
if(operation=="A"){
if(s1.empty()){
cout<<"E"<<endl;
}else{
//使用 stack[stack.size()-1] 可能会数组越
cout<<(int)s1.back()<<endl;
}
}else if(operation=="O"){
if(!s1.empty()){
s1.pop_back();
}
}else{
cin>>num;
cin.ignore();
s1.push_back(num);
}
}
cout<<endl;
}
return 0;
}
| [
"wanghuidi@841417348@qq.com"
] | wanghuidi@841417348@qq.com |
3cbd20a1d9783ccea1e45f58bced9b8f18b97639 | 5d54ae7bfc22d84541d737cee8512569824094a6 | /src/psvrservice/Service/ServiceRequestHandler.h | 57c46f831717f7a82520b49faabf25e4a8794f20 | [
"MIT"
] | permissive | cooperate/WMRTracker | 9086f2cdd4d68311a25418e84f5e1e5b5174d3c2 | ce2937734bf09f435d6af6307cb9fb0f73f57c59 | refs/heads/master | 2020-04-24T07:43:30.399429 | 2018-11-10T08:56:58 | 2018-11-10T08:56:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,740 | h | #ifndef SERVICE_REQUEST_HANDLER_H
#define SERVICE_REQUEST_HANDLER_H
// -- includes -----
#include "PSVRClient_CAPI.h"
#include "PSVRServiceInterface.h"
#include <bitset>
// -- pre-declarations -----
class DeviceManager;
// -- definitions -----
struct ControllerStreamInfo
{
bool include_position_data;
bool include_physics_data;
bool include_raw_sensor_data;
bool include_calibrated_sensor_data;
bool include_raw_tracker_data;
bool led_override_active;
bool disable_roi;
int last_data_input_sequence_number;
int selected_tracker_index;
inline void Clear()
{
include_position_data = false;
include_physics_data = false;
include_raw_sensor_data = false;
include_calibrated_sensor_data= false;
include_raw_tracker_data = false;
led_override_active = false;
disable_roi = false;
last_data_input_sequence_number = -1;
selected_tracker_index = 0;
}
};
struct TrackerStreamInfo
{
bool streaming_video_data;
bool has_temp_settings_override;
inline void Clear()
{
streaming_video_data = false;
has_temp_settings_override = false;
}
};
struct HMDStreamInfo
{
bool include_position_data;
bool include_physics_data;
bool include_raw_sensor_data;
bool include_calibrated_sensor_data;
bool include_raw_tracker_data;
bool disable_roi;
int selected_tracker_index;
inline void Clear()
{
include_position_data = false;
include_physics_data = false;
include_raw_sensor_data = false;
include_calibrated_sensor_data = false;
include_raw_tracker_data = false;
disable_roi = false;
selected_tracker_index = 0;
}
};
struct PersistentRequestConnectionState
{
std::bitset<PSVRSERVICE_MAX_CONTROLLER_COUNT> active_controller_streams;
std::bitset<PSVRSERVICE_MAX_TRACKER_COUNT> active_tracker_streams;
std::bitset<PSVRSERVICE_MAX_HMD_COUNT> active_hmd_streams;
ControllerStreamInfo active_controller_stream_info[PSVRSERVICE_MAX_CONTROLLER_COUNT];
TrackerStreamInfo active_tracker_stream_info[PSVRSERVICE_MAX_TRACKER_COUNT];
HMDStreamInfo active_hmd_stream_info[PSVRSERVICE_MAX_HMD_COUNT];
PersistentRequestConnectionState()
: active_controller_streams()
, active_tracker_streams()
, active_hmd_streams()
{
for (int index = 0; index < PSVRSERVICE_MAX_CONTROLLER_COUNT; ++index)
{
active_controller_stream_info[index].Clear();
}
for (int index = 0; index < PSVRSERVICE_MAX_TRACKER_COUNT; ++index)
{
active_tracker_stream_info[index].Clear();
}
for (int index = 0; index < PSVRSERVICE_MAX_HMD_COUNT; ++index)
{
active_hmd_stream_info[index].Clear();
}
}
};
class ServiceRequestHandler
{
public:
ServiceRequestHandler();
virtual ~ServiceRequestHandler();
static ServiceRequestHandler *get_instance() { return m_instance; }
bool startup(
class DeviceManager *deviceManager,
class IDataFrameListener *data_frame_listener,
class INotificationListener *notification_listener);
void shutdown();
void handle_input_data_frame(DeviceInputDataFrame &data_frame);
/// When publishing controller data to all listening connections
/// we need to provide a callback that will fill out a data frame given:
/// * A \ref ServerControllerView we want to publish to all listening connections
/// * A \ref ControllerStreamInfo that describes what info the connection wants
/// This callback will be called for each listening connection
typedef void(*t_generate_controller_data_frame_for_stream)(
const class ServerControllerView *controller_view,
const ControllerStreamInfo *stream_info,
DeviceOutputDataFrame &data_frame);
void publish_controller_data_frame(
class ServerControllerView *controller_view, t_generate_controller_data_frame_for_stream callback);
/// When publishing tracker data to all listening connections
/// we need to provide a callback that will fill out a data frame given:
/// * A \ref ServerTrackerView we want to publish to all listening connections
/// * A \ref TrackerStreamInfo that describes what info the connection wants
/// This callback will be called for each listening connection
typedef void(*t_generate_tracker_data_frame_for_stream)(
const class ServerTrackerView *tracker_view,
const TrackerStreamInfo *stream_info,
DeviceOutputDataFrame &data_frame);
void publish_tracker_data_frame(
class ServerTrackerView *tracker_view, t_generate_tracker_data_frame_for_stream callback);
/// When publishing hmd data to all listening connections
/// we need to provide a callback that will fill out a data frame given:
/// * A \ref ServerHMDView we want to publish to all listening connections
/// * A \ref HMDStreamInfo that describes what info the connection wants
/// This callback will be called for each listening connection
typedef void(*t_generate_hmd_data_frame_for_stream)(
const class ServerHMDView *hmd_view,
const HMDStreamInfo *stream_info,
DeviceOutputDataFrame &data_frame);
void publish_hmd_data_frame(
class ServerHMDView *hmd_view, t_generate_hmd_data_frame_for_stream callback);
/// Send a event to the client
void publish_notification(const PSVREventMessage &message);
// -- controller requests -----
ServerControllerView *get_controller_view_or_null(PSVRControllerID hmd_id);
PSVRResult get_controller_list(bool inlcude_usb, PSVRControllerList *out_controller_list);
PSVRResult start_controller_data_stream(PSVRControllerID controller_id, unsigned int flags);
PSVRResult stop_controller_data_stream(PSVRControllerID controller_id);
PSVRResult set_led_tracking_color(PSVRControllerID controller_id, PSVRTrackingColorType tracking_color);
PSVRResult reset_orientation(PSVRControllerID controller_id, const PSVRQuatf& q_pose);
PSVRResult set_controller_data_stream_tracker_index(PSVRControllerID controller_id, PSVRTrackerID tracker_id);
PSVRResult set_controller_hand(PSVRControllerID controller_id, PSVRControllerHand controller_hand);
PSVRResult set_controller_accelerometer_calibration(PSVRControllerID controller_id, float noise_radius, float noise_variance);
PSVRResult set_controller_gyroscope_calibration(PSVRControllerID controller_id, float drift, float variance, const char *gain_setting);
PSVRResult set_controller_orientation_filter(PSVRControllerID controller_id, const std::string orientation_filter);
PSVRResult set_controller_position_filter(PSVRControllerID controller_id, const std::string position_filter);
PSVRResult set_controller_prediction_time(PSVRControllerID controller_id, const float prediction_time);
// -- tracker requests -----
PSVRResult get_tracker_list(PSVRTrackerList *out_tracker_list);
PSVRResult start_tracker_data_stream(PSVRTrackerID tracker_id);
PSVRResult stop_tracker_data_stream(PSVRTrackerID tracker_id);
PSVRResult get_shared_video_frame_buffer(PSVRTrackerID tracker_id, SharedVideoFrameBuffer **out_shared_buffer);
PSVRResult get_hmd_tracker_settings(
PSVRTrackerID tracker_id, PSVRHmdID hmd_id,
PSVRClientTrackerSettings *out_settings);
PSVRResult get_controller_tracker_settings(
PSVRTrackerID tracker_id, PSVRControllerID controller_id,
PSVRClientTrackerSettings *out_settings);
PSVRResult get_tracker_mode(const PSVRTrackerID tracker_id, std::string &out_mode);
PSVRResult set_tracker_mode(const PSVRTrackerID tracker_id, const std::string &new_mode);
PSVRResult set_tracker_video_property(
const PSVRTrackerID tracker_id, const PSVRVideoPropertyType property_type, int desired_value, bool save_setting,
int *out_value);
PSVRResult set_tracker_controller_color_preset(
const PSVRTrackerID tracker_id,
const PSVRControllerID hmd_id,
const PSVRTrackingColorType tracking_color_type,
const PSVR_HSVColorRange &desired_color_filter,
PSVR_HSVColorRange &out_color_filter);
PSVRResult set_tracker_hmd_color_preset(
const PSVRTrackerID tracker_id, const PSVRHmdID HmdID,
const PSVRTrackingColorType tracking_color_type,
const PSVR_HSVColorRange &desired_color_filter, PSVR_HSVColorRange &out_color_filter);
PSVRResult set_tracker_pose(const PSVRTrackerID tracker_id, const PSVRPosef *pose);
PSVRResult set_tracker_intrinsics(const PSVRTrackerID tracker_id, const PSVRTrackerIntrinsics *tracker_intrinsics);
PSVRResult get_tracking_space_settings(PSVRTrackingSpace *out_tracking_space);
PSVRResult reload_tracker_settings(const PSVRTrackerID tracker_id);
PSVRResult get_tracker_debug_flags(PSVRTrackerDebugFlags *out_flags) const;
PSVRResult set_tracker_debug_flags(PSVRTrackerDebugFlags flags);
// -- hmd requests -----
ServerHMDView *get_hmd_view_or_null(PSVRHmdID hmd_id);
PSVRResult get_hmd_list(PSVRHmdList *out_hmd_list);
PSVRResult get_hmd_tracking_shape(PSVRHmdID hmd_id, PSVRTrackingShape *out_shape);
PSVRResult start_hmd_data_stream(const PSVRHmdID hmd_id, unsigned int data_stream_flags);
PSVRResult stop_hmd_data_stream(const PSVRHmdID hmd_id);
PSVRResult set_hmd_led_tracking_color(const PSVRHmdID hmd_id, const PSVRTrackingColorType new_color_id);
PSVRResult set_hmd_accelerometer_calibration(
const PSVRHmdID hmd_id, const PSVRVector3f &measured_g, const float raw_variance);
PSVRResult set_hmd_gyroscope_calibration(
const PSVRHmdID hmd_id, const PSVRVector3f &raw_gyro_bias, const float raw_variance, const float raw_drift);
PSVRResult set_hmd_orientation_filter(const PSVRHmdID hmd_id, const std::string orientation_filter);
PSVRResult set_hmd_position_filter(const PSVRHmdID hmd_id, const std::string position_filter);
PSVRResult set_hmd_prediction_time(const PSVRHmdID hmd_id, const float hmd_prediction_time);
PSVRResult set_hmd_data_stream_tracker_index(const PSVRTrackerID tracker_id, const PSVRHmdID hmd_id);
// -- general requests -----
PSVRResult get_service_version(char *out_version_string, size_t max_version_string);
private:
void handle_data_frame__controller_packet(DeviceInputDataFrame &data_frame);
// Keeps track of all active stream state
PersistentRequestConnectionState *m_peristentRequestState;
class DeviceManager *m_deviceManager;
class IDataFrameListener *m_dataFrameListener;
class INotificationListener *m_notificationListener;
// Singleton instance of the class
// Assigned in startup, cleared in teardown
static ServiceRequestHandler *m_instance;
};
#endif // SERVICE_REQUEST_HANDLER_H
| [
"hipstersloth908@gmail.com"
] | hipstersloth908@gmail.com |
724c1c97f159a1b14d002fc8a7c19e87e8e0f16f | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/openexr/IlmBase/ImathTest/testRandom.cpp | 7798c00cabb5bea7d064121acd2feba438f2caa6 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 6,592 | cpp | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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 <testRandom.h>
#include "ImathRandom.h"
#include "ImathVec.h"
#include "ImathFun.h"
#include <iostream>
#include <iomanip>
#include <assert.h>
using namespace std;
using IMATH_INTERNAL_NAMESPACE::abs;
namespace {
void
testErand48 ()
{
//
// Our implementation of erand48(), nrand48(), etc.
// assumes that sizeof (unsigned short) == 2.
//
assert (sizeof (unsigned short) == 2);
//
// starting with a given seed, erand48() and nrand48()
// must generate the same sequence as the standard
// Unix/Linux functions.
//
unsigned short state[3];
state[0] = 0;
state[1] = 1;
state[2] = 2;
assert (abs (IMATH_INTERNAL_NAMESPACE::erand48 (state) - 0.671004) < 0.00001);
assert (abs (IMATH_INTERNAL_NAMESPACE::erand48 (state) - 0.786905) < 0.00001);
assert (abs (IMATH_INTERNAL_NAMESPACE::erand48 (state) - 0.316850) < 0.00001);
assert (abs (IMATH_INTERNAL_NAMESPACE::erand48 (state) - 0.384870) < 0.00001);
assert (abs (IMATH_INTERNAL_NAMESPACE::erand48 (state) - 0.854650) < 0.00001);
assert (IMATH_INTERNAL_NAMESPACE::nrand48 (state) == 0x4f4e8cb0);
assert (IMATH_INTERNAL_NAMESPACE::nrand48 (state) == 0x063e864b);
assert (IMATH_INTERNAL_NAMESPACE::nrand48 (state) == 0x2d10f1dd);
assert (IMATH_INTERNAL_NAMESPACE::nrand48 (state) == 0x1aadc122);
assert (IMATH_INTERNAL_NAMESPACE::nrand48 (state) == 0x1836a71f);
assert (state[0] == 0x2a42);
assert (state[1] == 0x4e3e);
assert (state[2] == 0x306d);
}
template <class Rand>
void
testGenerator ()
{
//
// Test if the values, and the differences between
// successive values, are evenly distributed.
//
const int N = 10;
const int M = 100000;
int values[N + 1];
int diffs[2 * N + 3];
int *v = &values[0];
int *d = &diffs[N + 2];
for (int i = 0; i <= N; ++i)
v[i] = 0;
for (int i = -N; i <= N; ++i)
d[i] = 0;
Rand rand (0);
float previous = 0;
for (int i = 0; i < M * N; ++i)
{
float r = rand.nextf (0.0, 1.0);
float diff = r - previous;
previous = r;
v[int (r * N)] += 1;
d[IMATH_INTERNAL_NAMESPACE::floor (diff * N + 0.5)] += 1;
}
cout << " values" << endl;
for (int i = 0; i < N; ++i)
{
// cout << setw (4) << i << ' ' << setw(6) << v[i] << ' ';
assert (abs (v[i] - M) < 0.01 * M);
// for (int j = 0; j < v[i] * 60 / M; ++j)
// cout << '*';
// cout << endl;
}
assert (v[N] == 0);
cout << " differences between successive values" << endl;
for (int i = -N; i <= N; ++i)
{
// cout << setw (4) << i << ' ' << setw (6) << d[i] << ' ';
assert (abs ((N - abs (i)) * M / N - d[i]) < 0.05 * M);
// for (int j = 0; j < d[i] * 60 / M; ++j)
// cout << '*';
// cout << endl;
}
cout << " range" << endl;
double rMin = 1.0;
double rMax = 0.0;
for (int i = 0; i <= 10000000; ++i)
{
double r = rand.nextf (0.0, 1.0);
if (rMin > r)
rMin = r;
if (rMax < r)
rMax = r;
}
assert (rMin < 0.0001 && rMax > 0.9999);
const double pow_2_60 = double (1073741824) * double (1073741824);
for (int i = 0; i <= 10000000; ++i)
{
double r0 = rand.nextf (-2.0, 3.0);
assert (r0 >= -2.0 && r0 <= 3.0);
double r1 = rand.nextf (-pow_2_60, 1);
assert (r1 >= -pow_2_60 && r1 <= 1);
double r2 = rand.nextf (-1, pow_2_60);
assert (r2 >= -1 && r2 <= pow_2_60);
}
}
template <class Rand>
void
testSolidSphere ()
{
const int N = 10;
const int M = 10000;
int v[N + 1];
for (int i = 0; i <= N; ++i)
v[i] = 0;
Rand rand (0);
for (int i = 0; i < M * N; ++i)
{
IMATH_INTERNAL_NAMESPACE::V3f p = IMATH_INTERNAL_NAMESPACE::solidSphereRand<IMATH_INTERNAL_NAMESPACE::V3f> (rand);
float l = p.length();
v[IMATH_INTERNAL_NAMESPACE::floor (l * N)] += 1;
assert (l < 1.00001);
}
for (int i = 0; i < N; ++i)
assert (v[i] > 0);
}
template <class Rand>
void
testHollowSphere ()
{
const int M = 100000;
Rand rand (0);
for (int i = 0; i < M; ++i)
{
IMATH_INTERNAL_NAMESPACE::V3f p = IMATH_INTERNAL_NAMESPACE::hollowSphereRand<IMATH_INTERNAL_NAMESPACE::V3f> (rand);
float l = p.length();
assert (abs (l - 1) < 0.00001);
}
}
} // namespace
void
testRandom ()
{
cout << "Testing random number generators" << endl;
cout << "erand48(), nrand48()" << endl;
testErand48();
cout << "Rand32" << endl;
testGenerator<IMATH_INTERNAL_NAMESPACE::Rand32>();
cout << "Rand48" << endl;
testGenerator<IMATH_INTERNAL_NAMESPACE::Rand48>();
cout << "solidSphereRand()" << endl;
testSolidSphere<IMATH_INTERNAL_NAMESPACE::Rand32>();
cout << "hollowSphereRand()" << endl;
testHollowSphere<IMATH_INTERNAL_NAMESPACE::Rand32>();
cout << "ok\n" << endl;
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
5c6f887337824618329f5a17ec04c9db37b0a976 | ed649693468835126ae0bc56a9a9745cbbe02750 | /win8_apps/cpp/Basic/Signal_Service/SignalService/App.xaml.cpp | 4e34baa4bdc7b53bd176eaa2adc81dd960294a27 | [] | no_license | tkellogg/alljoyn-core | 982304d78da73f07f888c7cbd56731342585d9a5 | 931ed98b3f5e5dbd40ffb529a78825f28cc59037 | refs/heads/master | 2020-12-25T18:22:32.166135 | 2014-07-17T13:56:18 | 2014-07-17T13:58:56 | 21,984,205 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,068 | cpp | //-----------------------------------------------------------------------
// <copyright file="App.xaml.cpp" company="AllSeen Alliance.">
// Copyright (c) 2012, AllSeen Alliance. All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#include "pch.h"
#include "MainPage.xaml.h"
using namespace SignalService;
using namespace Platform;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
App::App() : uiPage(nullptr)
{
InitializeComponent();
Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="pArgs">Details about the launch request and process.</param>
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs ^ pArgs)
{
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running) {
Window::Current->Activate();
return;
}
if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated) {
//TODO: Load state from previously suspended application
}
// Create a Frame to act navigation context and navigate to the first page
auto rootFrame = ref new Frame();
if (!rootFrame->Navigate(TypeName(MainPage::typeid ))) {
throw ref new FailureException("Failed to create initial page");
}
// Place the frame in the current Window and ensure that it is active
Window::Current->Content = rootFrame;
Window::Current->Activate();
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
void App::OnSuspending(Object ^ sender, SuspendingEventArgs ^ e)
{
(void) sender; // Unused parameter
(void) e; // Unused parameter
//TODO: Save application state and stop any background activity
}
void App::OutputLine(Platform::String ^ msg)
{
uiPage->OutputLine(msg);
}
| [
"gerritadmin@allseenalliance.org"
] | gerritadmin@allseenalliance.org |
d1d84e3d95d31a891d3a090149b8fa1d32696901 | 348600b290ab52f04235688e91d2d4e2baf37e99 | /cbaseclientfsm.h | c7f8fb4fb89fff3d11887678a6f66dcf8ed7b2b3 | [] | no_license | dontearbegmail/ydd-fsm | 05112bb1381f6dbdfcf49e1d2dabe24816aa4654 | 5eea0e41cfe955b7f644c9f769e3a1299e6ad988 | refs/heads/master | 2021-05-31T11:16:48.976010 | 2016-03-22T18:03:35 | 2016-03-22T18:03:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | h | #ifndef CBASECLIENTFSM_H
#define CBASECLIENTFSM_H
#include "csocketfsm.h"
namespace ydd
{
class CBaseClientFsm : public CSocketFsm
{
public:
static const size_t NUM_STATES = 0;
void q_ConnectPending();
void q_Connect();
void q_ConnectCheck();
};
}
#endif /* CBASECLIENTFSM_H */
| [
"dmitry.moukharsky@gmail.com"
] | dmitry.moukharsky@gmail.com |
51573835a0a79f6dba6c1935cb8590d7aa54a2e3 | bbcda48854d6890ad029d5973e011d4784d248d2 | /trunk/win/Source/Includes/QtIncludes/src/3rdparty/webkit/WebCore/dom/ErrorEvent.h | 800767c155f230d267deee415b5b419491aabe02 | [
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only",
"MIT",
"curl",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Zlib",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MS-LPL"
] | permissive | dyzmapl/BumpTop | 9c396f876e6a9ace1099b3b32e45612a388943ff | 1329ea41411c7368516b942d19add694af3d602f | refs/heads/master | 2020-12-20T22:42:55.100473 | 2020-01-25T21:00:08 | 2020-01-25T21:00:08 | 236,229,087 | 0 | 0 | Apache-2.0 | 2020-01-25T20:58:59 | 2020-01-25T20:58:58 | null | UTF-8 | C++ | false | false | 2,849 | h | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 Google Inc. 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.
*/
#ifndef ErrorEvent_h
#define ErrorEvent_h
#if ENABLE(WORKERS)
#include "Event.h"
#include "PlatformString.h"
namespace WebCore {
class ErrorEvent : public Event {
public:
static PassRefPtr<ErrorEvent> create()
{
return adoptRef(new ErrorEvent);
}
static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber)
{
return adoptRef(new ErrorEvent(message, fileName, lineNumber));
}
virtual ~ErrorEvent();
void initErrorEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& message, const String& fileName, unsigned lineNumber);
const String& message() const { return m_message; }
const String& filename() const { return m_fileName; }
unsigned lineno() const { return m_lineNumber; }
virtual bool isErrorEvent() const;
private:
ErrorEvent();
ErrorEvent(const String& message, const String& fileName, unsigned lineNumber);
String m_message;
String m_fileName;
unsigned m_lineNumber;
};
} // namespace WebCore
#endif // ENABLE(WORKERS)
#endif // ErrorEvent_h
| [
"anandx@google.com"
] | anandx@google.com |
4dc10e7de0f8f73d20b3be12a2870e77c6e5e9e7 | 833bf3448d536cc66e99f15febd428cf465c9797 | /Mis2x265.cpp | 6cd0f2d8a2d5ec87198f1dbcaf6bf88da7cdbd16 | [] | no_license | Selur/Mis2x265 | dd4a3e67b426fc71e8fdd73baa2545df86b2b203 | 77639e806d3217aaa39a9513a29ffd7d0d9d5631 | refs/heads/master | 2021-01-01T06:12:08.302675 | 2015-07-30T18:43:47 | 2015-07-30T18:43:47 | 39,966,517 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,541 | cpp | #include "Mis2x265.h"
#include <QString>
#include <QMessageBox>
#include <QFileDialog>
Mis2x265::Mis2x265(QWidget *parent)
: QMainWindow(parent), m_simple(), m_special(), m_mediainfo(), m_process(nullptr),
m_mediainfoOutput()
{
ui.setupUi(this);
this->setWindowTitle("Mis2x265 " + QString::fromLocal8Bit(BUILDVERSION) + " - by Selur");
m_special.insert("interlace", "interlaceMode");
m_simple << "wpp" << "ctu" << "min-cu-size" << "max-tu-size" << "tu-intra-depth"
<< "tu-inter-depth" << "me" << "subme" << "merange" << "rect" << "amp" << "max-merge"
<< "temporal-mvp" << "early-skip" << "rdpenalty" << "tskip" << "tskip-fast"
<< "strong-intra-smoothing" << "lossless" << "cu-lossless" << "constrained-intra"
<< "fast-intra" << "open-gop" << "temporal-layers" << "keyint" << "min-keyint" << "scenecut"
<< "rc-lookahead" << "lookahead-slices" << "bframes" << "bframe-bias" << "b-adapt" << "ref"
<< "limit-refs" << "weightp" << "weightb" << "aq-mode" << "aq-strength" << "cbqpoffs"
<< "crqpoffs" << "rd" << "hrd" << "psy-rd" << "rdoq-level" << "psy-rdoq" << "signhide"
<< "deblock" << "sao" << "sao-non-deblock" << "b-pyramid" << "cutree" << "bitrate" << "qcomp"
<< "qpmin" << "qpmax" << "qpstep" << "ipratio" << "pbratio" << "pme" << "qp";
QString path = qApp->applicationDirPath();
path += QDir::separator();
#ifdef Q_OS_WIN
path += "mediainfo.exe";
#else
path += "mediainfo";
#endif
path = QDir::toNativeSeparators(path);
if (QFile::exists(path)) {
m_mediainfo = path;
ui.textBrowser->append("m_mediaInfo: " + m_mediainfo);
}
ui.selectMediaInfoPushButton->setEnabled(m_mediainfo.isEmpty());
}
Mis2x265::~Mis2x265()
{
}
void removeStartOfLine(QString &line)
{
line = line.remove(0, line.indexOf(":") + 1);
line = line.trimmed();
}
void Mis2x265::analyseMediaInfoOutput()
{
QStringList lines = m_mediainfoOutput.split("\n", QString::SkipEmptyParts);
QString addition, tmp;
bool video = false;
foreach(QString line, lines)
{
if (!video) {
if (line.startsWith("Video #") || (line.startsWith("Video") && line.trimmed().size() == 5)) {
video = true;
}
continue;
}
ui.textBrowser->append(line);
if (line.startsWith("Format profile")) {
removeStartOfLine(line);
QStringList elems = line.split("@");
if (elems.count() == 3) {
addition += " --profile " + elems.at(0).toLower();
tmp = elems.at(1);
tmp = tmp.remove("L");
addition += " --level " + tmp;
tmp = elems.at(2).trimmed();
if (tmp.toLower() == "main") {
addition += " --no-high-tier";
} else {
addition += " --high-tier";
}
}
continue;
}
if (line.startsWith("Frame rate") && line.contains("fps")) {
removeStartOfLine(line);
line = line.remove("fps");
line = line.trimmed();
addition += " --fps " + line;
continue;
}
if (line.startsWith("Color range")) {
removeStartOfLine(line);
if (line.toLower() == "limited") {
addition += " --range limited";
} else {
addition += " --range full";
}
continue;
}
if (line.startsWith("Chroma subsampling")) {
removeStartOfLine(line);
line = line.remove(":");
addition += " --input-csp i" + line;
continue;
}
if (line.startsWith("Bit depth") && !line.contains("bits")) {
removeStartOfLine(line);
addition += " --output-depth " + line;
continue;
}
if (line.startsWith("Encoding settings")) {
removeStartOfLine(line);
ui.x265SettingsLineEdit->setText(line);
tmp = this->buildCall();
if (!addition.isEmpty()) {
tmp = tmp.insert(4, addition);
}
ui.textBrowser->append("x265 call:\n" + tmp);
return;
}
}
QString message = tr("MediaInfo output didn't contain any 'Encoding setting'(2)!");
QMessageBox::critical(this, tr("Error"), message);
ui.textBrowser->append("<b>" + message + "</b>");
ui.textBrowser->append(lines.join("<b/>"));
}
void Mis2x265::on_fileInputRadioButton_toggled(bool checked)
{
if (checked && ui.manualRadioButton->isChecked()) {
ui.manualRadioButton->setChecked(false);
}
ui.x265SettingsLineEdit->setEnabled(!checked);
ui.convertPushButton->setEnabled(!checked);
ui.selectAndImportPushButton->setEnabled(checked);
if (m_mediainfo.isEmpty()) {
ui.selectMediaInfoPushButton->setEnabled(checked);
}
}
void Mis2x265::on_manualRadioButton_toggled(bool checked)
{
if (checked && ui.fileInputRadioButton->isChecked()) {
ui.fileInputRadioButton->setChecked(false);
}
ui.x265SettingsLineEdit->setEnabled(checked);
ui.convertPushButton->setEnabled(checked);
ui.selectAndImportPushButton->setEnabled(!checked);
if (m_mediainfo.isEmpty()) {
ui.selectMediaInfoPushButton->setEnabled(!checked);
}
}
QString Mis2x265::buildCall()
{
ui.textBrowser->clear();
QStringList toConvert = ui.x265SettingsLineEdit->text().split("/");
QStringList call;
QString line, value, tmp;
bool no, hasValue;
int equalIndex;
for (int i = 0, c = toConvert.count(); i < c; ++i) {
line = toConvert.at(i).trimmed();
no = line.startsWith("no-");
if (no) {
line = line.remove(0, 3);
}
equalIndex = line.indexOf("=");
hasValue = equalIndex != -1;
value = QString();
if (hasValue) {
value = line;
value = value.remove(0, equalIndex+1);
line = line.remove(equalIndex, line.size());
}
if (line == "rc") {
if (value == "abr" || value == "cqp" || value == "crf") {
continue;
} else {
ui.textBrowser->append("ignored: " + line + ", which probably indicates 2pass encoding. "+ value);
}
} else if (!m_simple.contains(line)) {
tmp = m_special.value(line);
if (!tmp.isEmpty()) {
line = tmp;
} else {
ui.textBrowser->append("ignored: " + line);
continue;
}
}
if (no) {
line = "no-" + line;
}
line = "--" + line;
if (hasValue) {
line += " "+value;
}
call << line;
}
call.insert(0, "x265");
return call.join(" ");
}
void Mis2x265::on_convertPushButton_clicked()
{
ui.textBrowser->append("x265 call:\n" + this->buildCall());
}
void Mis2x265::on_selectAndImportPushButton_clicked()
{
if (m_mediainfo.isEmpty()) {
m_mediainfo = ui.mediaInfoFileLabel->text();
if (m_mediainfo.isEmpty()) {
ui.textBrowser->clear();
ui.textBrowser->append(
tr("You first need to set MediaInfo before you can import settings from a file!"));
return;
}
}
m_inputFile = QFileDialog::getOpenFileName(this, tr("Select input file"), QString());
if (m_inputFile.isEmpty()) {
ui.textBrowser->append(tr("Nothing to do, input is empty,.."));
return;
}
if (!QFile::exists(m_inputFile)) {
QMessageBox::information(this, tr("Info"), tr("File %1 doesn't exist!").arg(m_inputFile));
return;
}
m_mediainfoOutput.clear();
delete m_process;
m_process = new QProcess(this);
QObject::connect(m_process, SIGNAL(finished( int, QProcess::ExitStatus)), this,
SLOT(processFinished(int, QProcess::ExitStatus)));
QObject::connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(collectOutput()));
QObject::connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(collectOutput()));
QString call = "\"" + m_mediainfo + "\" --full \"" + m_inputFile + "\"";
ui.textBrowser->append(call);
m_process->start(call);
}
void Mis2x265::on_selectMediaInfoPushButton_clicked()
{
QString input = QFileDialog::getOpenFileName(this, tr("Select the MediaInfo binary"), QString());
if (input.isEmpty()) {
return;
}
ui.mediaInfoFileLabel->setText(input);
m_mediainfo = input;
}
void Mis2x265::collectOutput()
{
m_mediainfoOutput += QString::fromUtf8(m_process->readAllStandardOutput().data());
m_mediainfoOutput += QString::fromUtf8(m_process->readAllStandardError().data());
}
void Mis2x265::processFinished(const int exitCode, const QProcess::ExitStatus exitStatus)
{
ui.textBrowser->append(tr("MediaInfo finished,.."));
if (exitCode < 0) {
QMessageBox::critical(this, tr("MediaInfo crash"),
tr("MediaInfo crashed with exitCode: %1 and status: %2 while analysing the input!").arg(
exitCode).arg(exitStatus));
return;
}
m_process->disconnect();
m_process->kill();
delete m_process;
m_process = 0;
this->analyseMediaInfoOutput();
}
| [
"hybrid@selur.de"
] | hybrid@selur.de |
dc70bedd1603da96a9f29c6774e418d24850e955 | 692b41e057fb88fd24ee3591cd182a7cc81c8375 | /寒假多校1/A.cpp | e7de4bce570d60bc4d695cef3d36aeef41d307df | [] | no_license | hhu1506010220/ACM_Repository | 509c3b677cbc741981982fd128037a5163e2edac | 873c64733839db49557230d84e83589650e0c6d8 | refs/heads/master | 2021-07-05T22:16:32.164128 | 2018-11-21T13:38:22 | 2018-11-21T13:38:22 | 109,234,665 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 835 | cpp | #include<bits/stdc++.h>
using namespace std;
struct gunn{
int p;
int k;
int kind[1005];
}gun[1005];
struct peijian{
int q;
double b;
}item[1005];
int main(){
int n,m;
int tem;
double temp;
while(~scanf("%d%d",&n,&m)){
memset(gun,0,sizeof(gun));
memset(item,0,sizeof(item));
for(int i=0;i<n;i++){
scanf("%d%d",&gun[i].p,&gun[i].k);
for(int j=0;j<gun[i].k;j++)
scanf("%d",&gun[i].kind[j]);
}
for(int i=0;i<m;i++){
scanf("%d%lf",&tem,&temp);
if(item[tem].b<temp){
item[tem].b=temp;
}
}
double ans = 0;
double res = 0;
double beishu = 1.0;
for(int i=0;i<n;i++){
res = gun[i].p*1.0;
beishu = 1.0;
for(int j=0;j<gun[i].k;j++){
beishu += item[gun[i].kind[j]].b;
}
res *= beishu;
ans = max(ans , res);
}
printf("%.4lf\n",ans);
}
return 0;
}
| [
"598646152@qq.com"
] | 598646152@qq.com |
3c3e3c406d67d1a5d912ffb385b45070da83966f | 27314393ba3efd6fb8c872687b32ccf8dae11a6f | /Team.cc | 5fe4a6f094c84e1a6bf1ad8d5c98cd9995a27f52 | [] | no_license | Angus-Leung/Del2 | 769884aafd38b0dc03c3b134f23eb4263c21087c | a056f09db420033725c339c27aee98f4db99230b | refs/heads/master | 2021-01-13T00:52:57.413725 | 2015-10-30T04:58:52 | 2015-10-30T04:58:52 | 44,989,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cc | #include "Team.h"
//Default ctor
Team::Team(){ name = "Default Team Name"; }
//team ctor
Team::Team(string n){ name = n ; }
//Function to print students in the team
void Team::printRoster(){
cout << "\nRoster for Team '" << name << "':\n";
for(int i = 0; roster[i] != NULL; i++)
cout << " " << i << ") " << *roster[i] << "\n";
}
//Getters and Setters
string Team::getName(){ return name; }
void Team::setName(string n){ name = n; }
| [
"dule.rozman@gmail.com"
] | dule.rozman@gmail.com |
5f428a391c4d00e7d695059498e0696acea48036 | e5a1b2b423358df3dc6f3f04c116a2e836991a0e | /C++/Complex/Complex.cpp | dc7ddacabe8dea2f5af79dd00ffd4057682d6ae6 | [] | no_license | liuyepku/Code | 9071d8fba6e4751036e6bc5e3e7c041d28cb3901 | f4f4f0d3ef175c4520e17b7ba806dc005708d175 | refs/heads/master | 2023-04-14T16:53:44.069722 | 2013-12-20T11:54:56 | 2013-12-20T11:54:56 | 15,337,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,576 | cpp | #include<iostream>
#include"Complex.h"
using namespace std;
Complex::Complex(const Complex &c)
{
real = c.real;
virt = c.virt;
}
Complex::~Complex()
{
std::cout<<"it is just a joke!!!!!!"<<std::endl;
}
Complex& Complex::operator=(const Complex &c)
{
real = c.real;
virt = c.virt;
return *this;
}
Complex Complex::operator+(const Complex &a)
{
Complex temp;
temp.real = real + a.real;
temp.virt = virt + a.virt;
return temp;
}
Complex Complex::operator-(const Complex &a)
{
Complex temp;
temp.real = real - a.real;
temp.virt = virt - a.virt;
return temp;
}
Complex Complex::operator*(const Complex &b)
{
Complex temp;
temp.real = real*b.real - virt*b.virt;
temp.virt = real*b.virt + virt*b.real;
return temp;
}
Complex Complex::operator/(const Complex &b)
{
Complex tem;
double temp = b.real * b.real + b.virt * b.virt;
tem.real = real * b.real + virt * b.virt;
tem.virt = virt * b.real - real * b.virt;
return tem;
}
void Complex::Set(double realnum, double virtnum)
{
real = realnum;
virt = virtnum;
}
void Complex::Set(const Complex &c)
{
real = c.real;
virt = c.virt;
}
void Complex::Get(double &realnum, double &virtnum)
{
realnum = real;
virtnum = virt;
}
Complex& Complex::Get()
{
Complex *temp = new Complex;
temp->Set(real, virt);
return *temp;
}
void Complex::Print()
{
if(virt>0)
{ std::cout<<"The complex number is "<<real<<"+"<<virt<<"i"<<std::endl;}
else if(virt<0)
{ std::cout<<"The complex number is "<<real<<"-"<<virt<<"i"<<std::endl;}
else
{ std::cout<<"The complex number is "<<real<<std::endl;}
}
| [
"liuye.cis@gmail.com"
] | liuye.cis@gmail.com |
ff1ac09149a5cb71567d4007ad4a6c41fe5c3211 | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/wave/preprocessing_hooks.hpp | 18988b57c780b3867e2f53cfab2a8b1241467f7b | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70 | hpp | #include "thirdparty/boost_1_55_0/boost/wave/preprocessing_hooks.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
aa787e33f117176927a8cd96dc4567f69bbee339 | 76c86c75ff1356495ff9394506d8c6893e4157b0 | /VehicleTemplate/Source/VehicleTemplate/NukePowerup.cpp | 1e38927ff8565f317e237953ebc1c01c7a8c4287 | [] | no_license | Luke-DJ/Unreal-AI-Vehicles-Project | 4b8e0d9f00540ceddbb37b65cc503dfa0093f272 | c11fa3d63b439990819318dc7988f5a5e77ccf13 | refs/heads/master | 2020-04-21T21:53:10.328148 | 2019-02-12T04:16:24 | 2019-02-12T04:16:24 | 169,893,231 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include <NukePowerup.h>
#include <EngineUtils.h>
#include <VehicleTemplatePawn.h>
#include <AIWheeledVehicle.h>
void ANukePowerup::OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, int32 OtherBodyIndex, bool bFromSweep, const FHitResult &SweepResult)
{
Super::OnBeginOverlap(OverlappedComponent, OtherActor, OtherComponent, OtherBodyIndex, bFromSweep, SweepResult);
// Triggering the destruction of all enemies on overlap
if (Cast<AVehicleTemplatePawn>(OtherActor) && OtherComponent)
{
DestroyAllEnemies();
Destroy();
}
}
void ANukePowerup::DestroyAllEnemies()
{
/* The iterator I have used: https://wiki.unrealengine.com/Iterators:_Object_%26_Actor_Iterators,_Optional_Class_Scope_For_Faster_Search#Actor_Iterator
Iterating over all enemies, 'killing' each one */
for (TActorIterator<AAIWheeledVehicle> EnemyItr(GetWorld()); EnemyItr; ++EnemyItr)
{
(*EnemyItr)->Kill();
}
}
| [
"u1752044@unimail.hud.ac.uk"
] | u1752044@unimail.hud.ac.uk |
7eb9b6db405d3045e88e1f588d1a19d63950d36b | 09d4a5e0cdfca682a97071fdff92ad06fe6cf363 | /P155PROD-src.cpp | 1c9142197712f82821e8553159519c73a3b30b51 | [] | no_license | capcoders/SPOJ_PTIT | 026463ac24744b3a8116b0153855b1c4595409bb | 5c65a961132cca252642fd71f71f92eaf35282d9 | refs/heads/master | 2020-04-16T16:58:04.797328 | 2018-05-25T12:21:44 | 2018-05-25T12:21:44 | 165,757,372 | 1 | 0 | null | 2019-01-15T00:32:44 | 2019-01-15T00:32:43 | null | UTF-8 | C++ | false | false | 1,115 | cpp | #include <iostream>
#include <string>
using namespace std;
int m, n, d[500][500];
string s[500];
int res;
void Init()
{
for (int i = 0; i <= m; i++)
for (int j = 0; j <= n; j++) d[i][j] = 0;
res = 0;
}
int type(char x)
{
if (x == '.') return 1;
return 0;
}
void BuildD()
{
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) d[i][j] = d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1] + type(s[i][j]);
}
int tinh(int x, int y)
{
int res = 1;
for (int i = x - 1; i >= 0; i--)
for (int j = y - 1; j >= 0; j--)
{
int k = d[x][y] - d[i][y] - d[x][j] + d[i][j];
if (k != (x - i) * (y - j)) break; // Break nay quan trong cat giam toi da truong hop. Neu khong co se bi TLE
int tmp = x - i + y - j;
tmp *= 2;
if (res < tmp) res = tmp;
}
return --res;
}
void Process()
{
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (s[i][j] == '.') res = max(res, tinh(i, j));
}
main()
{
// freopen("in.txt", "r", stdin);
cin >> m >> n;
for (int i = 1; i <= m; i++)
{
cin >> s[i];
s[i] = "*" + s[i];
}
Init();
BuildD();
Process();
cout << res;
}
| [
"noreply@github.com"
] | capcoders.noreply@github.com |
292e321f5da63a32fd44f66b098ee70b22ca724a | 0e8d57f10639b0bdcab2c89b307029697c909863 | /atcoder/abc106/B/main.cpp | 7a611bfdec872d7ee0bab0f2c17ea9f9e8f11a02 | [
"Apache-2.0"
] | permissive | xirc/cp-algorithm | 07a6faf5228e07037920f5011326c16091a9157d | e83ea891e9f8994fdd6f704819c0c69f5edd699a | refs/heads/main | 2021-12-25T16:19:57.617683 | 2021-12-22T12:06:49 | 2021-12-22T12:06:49 | 226,591,291 | 15 | 1 | Apache-2.0 | 2021-12-22T12:06:50 | 2019-12-07T23:53:18 | C++ | UTF-8 | C++ | false | false | 480 | cpp | #include <bits/stdc++.h>
using namespace std;
int nrf(int N) {
int ans = 0;
for (int i = 1; i <= N; ++i) {
if (N % i == 0) ++ans;
}
return ans;
}
int solve(int N) {
int ans = 0;
for (int i = 1; i <= N; i += 2) {
if (nrf(i) == 8) {
++ans;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int N;
cin >> N;
cout << solve(N) << endl;
return 0;
} | [
"xirckey@gmail.com"
] | xirckey@gmail.com |
d79480cd90fd27dcf25f5f889063aaff8fe7436b | 46f53e9a564192eed2f40dc927af6448f8608d13 | /ui/base/font_helper_chromeos.h | e2013ce2e23bcb4c68f4d38a514807c423556ae9 | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 841 | h | // Copyright 2014 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.
#ifndef UI_BASE_FONT_HELPER_CHROMEOS_H
#define UI_BASE_FONT_HELPER_CHROMEOS_H
#include <string>
namespace ui {
// This is a temporary helper function for the Roboto UI font experiment.
// It'll go away once the experiment is over.
// See http://crbug.com/434400 and http://crbug.com/448948 for more details.
//
// "Noto Sans UI" was the primary UI font (both native and web) in most
// locales and we're replacing it with 'Roboto'. For now 'Roboto' is enabled by
// default and can be disabled by setting 'disable-roboto-font-ui' flag to on.
void ReplaceNotoSansWithRobotoIfEnabled(std::string* font_family);
} // namespace ui
#endif // UI_BASE_FONT_HELPER_CHROMEOS_H
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
4d62a9eff7f4c2bb79b8ef9cfb3f99c2669f2624 | 193d1044c96037179f008df62ae1af106ca9a91d | /prograaming_Practice_1003/vector_ex.cpp | d6bf816ccf7b2f2ab7b3f7003454c8f81254621a | [] | no_license | eunsooLim/BeakJoon_algorithm_problem | eb1f9e05604c94119c22221ec573b1e45c7b2028 | 7d759b32bc85de49c8cd548aab80f23ffbba6fe4 | refs/heads/master | 2021-01-21T06:33:15.034631 | 2017-10-22T01:55:26 | 2017-10-22T01:55:26 | 83,253,599 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 1,280 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
typedef struct node {
int key;
string data;
}happp;
void show(vector<node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
cout << (i + 1) << "번째 노드의 키와 데이터" << nodes[i].key << "," << nodes[i].data << endl;
}
}
int main(void) {
map<string, int> maptest1 = { {"eunsoo",1},{"s",2},{"h",3},{"j",4} };
cout << maptest1["h"] << endl;
vector<node> vector_nodes;
cout << "데이터 삽입" << endl;
happp temp;
temp.key = 3;
temp.data = "hello";
vector_nodes.push_back(temp);
temp.key = 5;
temp.data = "toto";
vector_nodes.push_back(temp);
temp.key = 33333;
temp.data = "hello222";
vector_nodes.push_back(temp);
cout << "삽입 후 " << endl;
show(vector_nodes);
vector_nodes.pop_back();
cout << "맨 뒤 삭제 후 " << endl;
show(vector_nodes);
temp.key = 13;
temp.data = "sdhello";
vector_nodes.push_back(temp);
happp temp2 = vector_nodes.front();
cout << "맨앞의 노드:" << temp2.key << "," << temp2.data << endl;
cout << "Size" << vector_nodes.size() << endl;
cout << endl;
show(vector_nodes);
cout << vector_nodes[0].key << endl;
cout << vector_nodes[1].data << endl;
} | [
"noreply@github.com"
] | eunsooLim.noreply@github.com |
8d4d7244e6fdf552e2b8b02731417dd31171f613 | 6f0a3720f8a34b62215e2c5b8aac8baffc03b1f3 | /premake/src/animationbase.cpp | 6edca236699e66a0ca3f86fce57fa169fad2026e | [] | no_license | Serebriakov/premake | 78a722841fa0b97bf8fb96b0e4481dfbb159798e | 95c7d8b8e81bdbfed37a2a301cfb95dddb1461ce | refs/heads/master | 2021-01-10T18:41:33.933658 | 2013-09-02T01:42:09 | 2013-09-02T01:42:09 | 42,235,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | #include "animationbase.h"
AnimationBase::AnimationBase(Uint32 Lifetime)
{
m_Timer = new Stopwatch(Lifetime);
}
AnimationBase::AnimationBase(const AnimationBase &Other)
{
m_Timer = new Stopwatch(*(Other.m_Timer));
}
AnimationBase::~AnimationBase()
{
delete m_Timer;
}
void AnimationBase::ResetTimer()
{
m_Timer->Reset();
}
bool AnimationBase::Expired() const
{
return (m_Timer->GetCycleState() >= 1.f);
}
| [
"farkasgabor.mail@gmail.com"
] | farkasgabor.mail@gmail.com |
38e0e7888c7907fb99769b7311db7aa574898077 | bda16d3ee4e6e25d2aeb19fd977fe89f728c90e5 | /src/qt/test/paymentservertests.h | 412566849391df1e41e907bf182c34b70a0933bf | [
"MIT"
] | permissive | OndraDvorak/predator | 30f791c9d76e3e59526b30dfe734b5fd0fbbaa83 | 0688290ac472d871e0bb8fa574deaba6a31b0d00 | refs/heads/master | 2022-06-09T00:44:13.524192 | 2018-12-04T18:40:06 | 2018-12-04T18:40:06 | 260,152,184 | 0 | 0 | MIT | 2020-04-30T08:13:50 | 2020-04-30T08:13:49 | null | UTF-8 | C++ | false | false | 820 | h | // Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_TEST_PAYPRDTSERVERTESTS_H
#define BITCOIN_QT_TEST_PAYPRDTSERVERTESTS_H
#include "../paymentserver.h"
#include <QObject>
#include <QTest>
class PaymentServerTests : public QObject
{
Q_OBJECT
private Q_SLOTS:
void paymentServerTests();
};
// Dummy class to receive paymentserver signals.
// If SendCoinsRecipient was a proper QObject, then
// we could use QSignalSpy... but it's not.
class RecipientCatcher : public QObject
{
Q_OBJECT
public Q_SLOTS:
void getRecipient(SendCoinsRecipient r);
public:
SendCoinsRecipient recipient;
};
#endif // BITCOIN_QT_TEST_PAYPRDTSERVERTESTS_H
| [
"ptordev@gmail.com"
] | ptordev@gmail.com |
8096d27b26f1cb9c062d10ec1e1748af3cda553d | 217ce39a71141dc051d9f802706ad6e71fc8b208 | /DareEngine2/MappedValues.h | 2145b143906aa620545f8b221f45ee2767986320 | [] | no_license | Heikki00/DareEngine2 | c52c57b0e14fb9926a4db0399d28c99d5d5f511f | 9464c945ef3bccf6f4ddb55c49a88b404570c353 | refs/heads/master | 2016-08-12T21:45:46.442798 | 2015-10-16T12:09:35 | 2015-10-16T12:09:35 | 43,959,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | h | #pragma once
#include <unordered_map>
#include <string>
#include "FestusMath.h"
#include <memory>
class Texture;
class MappedValues{
public:
~MappedValues();
void setVector(const std::string& name, const Vector3& value);
void setFloat(const std::string& name, float value);
void setTexture(const std::string& name, std::shared_ptr<Texture> value);
void setPointer(const std::string& name, void* value);
Vector3 getVector(const std::string& name);
float getFloat(const std::string& name);
std::shared_ptr<Texture> getTexture(const std::string& name);
void* getPointer(const std::string& name);
private:
std::unordered_map<std::string, Vector3> vectors;
std::unordered_map<std::string, float> floats;
std::unordered_map<std::string, std::shared_ptr<Texture>> textures;
std::unordered_map<std::string, void*> pointers;
};
| [
"heikki.simojoki@gmail.com"
] | heikki.simojoki@gmail.com |
230ebae5c01c44de2201929ca9baa32b16523a04 | 44c1bfa4e8de604356672ba767e972f59c75418a | /game/Animation.cpp | 23002c04be889f17ce05c8c61a645757773d9b91 | [] | no_license | jzsampaio/EmotionalFreneticTyper | 9d9bb1b79da1361dce62f2e0337ffd9dde4daec8 | 86aabe6e6a42e05d7fd55ed56d8a081358f117d5 | refs/heads/master | 2021-06-03T11:08:10.460098 | 2016-07-08T16:37:52 | 2016-07-08T16:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,682 | cpp | //
// Created by jasf on 5/8/16.
//
#include "Animation.h"
#include "Camera.h"
Animation::Animation(float centerX, float centerY, float rotation, string sprite, float timeLimit, bool ends,
int frameCount,
float frameTime)
: timeLimit(timeLimit), oneTimeOnly(ends), sp(sprite, frameCount, frameTime) {
this->rotation = rotation;
endTimer.restart();
centerPos = Vec2(centerX, centerY);
int width = sp.getSpriteFullWidth() / frameCount;
int height = sp.getSpriteFullHeight();
center_LT_displacement = -1 * Vec2(width * 0.5f, height * 0.5f);
}
void Animation::update(float dt) {
endTimer.update(dt);
sp.update(dt);
}
void Animation::render() {
GameObject::render();
Vec2 pos = pos + center_LT_displacement - Camera::getPos(Camera::PLAYER_GROUND_VIEW);
sp.render((int) pos.x, (int) pos.y, rotation, (SDL_FLIP_NONE));
}
bool Animation::isDead() {
return oneTimeOnly && (endTimer.get() > timeLimit);
}
void Animation::notifyCollision(GameObject *other) {
//do not react to collision
}
bool Animation::is(std::string type) {
return type == "Animation";
}
void Animation::notifyCollision(GameObject &other) {
//do not react to collision
}
MatrixAnimation::MatrixAnimation(float centerX, float centerY, float rotation, string sprite, float timeLimit,
bool ends, int qtdRows, int qtdCols, float frameTime)
: Animation(centerX, centerY, rotation, timeLimit, ends), matrixSprite(sprite, qtdRows, qtdCols, frameTime) {
this->rotation = rotation;
endTimer.restart();
centerPos = Vec2(centerX, centerY);
int width = matrixSprite.getFrameWidth();
int height = matrixSprite.getFrameHeight();
center_LT_displacement = -1 * Vec2(width * 0.5f, height * 0.5f);
matrixSprite.setFrame(0);
}
void Animation::restart() {
sp.setFrame(0);
endTimer.restart();
}
void MatrixAnimation::restart() {
matrixSprite.setFrame(0);
endTimer.restart();
}
Animation::Animation(float centerX, float centerY, float rotation, float timeLimit, bool ends)
: timeLimit(timeLimit), oneTimeOnly(ends) {
this->rotation = rotation;
endTimer.restart();
centerPos = Vec2(centerX, centerY);
}
void MatrixAnimation::render() {
GameObject::render();
Vec2 pos = getCenterPos() + center_LT_displacement - Camera::getPos(Camera::PLAYER_GROUND_VIEW);
matrixSprite.render((int) pos.x, (int) pos.y, rotation, (SDL_FLIP_NONE));
}
bool MatrixAnimation::isDead() {
return matrixSprite.isThistLastFrame();
}
void MatrixAnimation::update(float dt) {
matrixSprite.update(dt);
}
| [
"juarez.asf@gmail.com"
] | juarez.asf@gmail.com |
11026cfa77cb141fa668a31f9058d25312c5a806 | ed6dd8af385c41c7237c65f9671e23919d48f7b8 | /cs235/Lab 1 - CS 142 RPG Review/Student_Code/Arena.cpp | 0d692f510bed67d87f36824a32f408ebd50fc8fe | [] | no_license | ty-abbott/byu_cs | 7f781f18130ea474a6afe8fa33b7c86daf36886e | 7e06798ab40b326f03ad087f692b3ba8be0819c5 | refs/heads/master | 2021-06-01T08:33:44.066389 | 2016-01-17T07:35:00 | 2016-01-17T07:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,157 | cpp | //
// Arena.cpp
// CS 142 RPG Review
//
#include "Arena.h"
#include <sstream>
#include <vector>
#include <algorithm>
/*
* addFighter(string)
*
* Adds a new fighter to the collection of fighters in the arena. Do not allow
* duplicate names. Reject any string that does not adhere to the format
* outlined in the lab specs.
*
* Return true if a new fighter was added; false otherwise.
*/
bool Arena::addFighter(string info){
string name, type;
int currenthp, maxhp, strength, speed, magic;
stringstream ss(info);
ss >> name;
ss >> type;
ss >> maxhp;
ss >> strength;
ss >> speed;
ss >> magic;
if (maxhp <= 0){
return false;
}
if (strength <= 0){
return false;
}
if (speed <= 0){
return false;
}
if (magic <= 0){
return false;
}
// do this for other attributes too
for (int i = 0; i < Arena.size(); i++){
string newName = Arena[i]->getName();
if (newName == name){
return false;
}
}
if (ss.fail()){
return false;
}
if (!ss.eof()){
return false;
}
if (type == "A"){
Archer* a = new Archer(name, maxhp, currenthp, strength, speed, magic);
Arena.push_back(a);
return true;
}
else if (type == "R"){
Robot* a = new Robot(name, maxhp, currenthp, strength, speed, magic);
Arena.push_back(a);
return true;
}
else if (type == "C"){
Cleric* a = new Cleric(name, maxhp, currenthp, strength, speed, magic);
Arena.push_back(a);
return true;
}
return false;
};
/*
* removeFighter(string)
*
* Removes the fighter whose name is equal to the given name. Does nothing if
* no fighter is found with the given name.
*
* Return true if a fighter is removed; false otherwise.
*/
bool Arena::removeFighter(string name){
for (int i = 0; i < Arena.size(); i++){
string newName = Arena[i]->getName();
if (newName == name){
Arena.erase(Arena.begin() + (i));
return true;
}
}
return false;
}
/*
* getFighter(string)
*
* Returns the memory address of a fighter whose name is equal to the given
* name. Returns NULL if no fighter is found with the given name.
*
* Return a memory address if a fighter is found; NULL otherwise.
*/
FighterInterface* Arena::getFighter(string name){
//FighterInterface* A = new Fighter();
//return NULL;
/*
if (find(Arena.begin(), Arena.end(), "Fumblemore") != Arena.end())
{
return A;
}
*/
for (int i = 0; i < Arena.size(); i++){
string newName = Arena[i]->getName();
if (newName == name){
return Arena[i];
}
}
/*Arena<it>::const_iterator it = find(vec.begin(), vec.end(), "Fumblemore");
if (it != vec.end())
{
cout << "found" << *it << " in the vector" <<endl;
}
*/
}
/*
* getSize()
*
* Returns the number of fighters in the arena.
*
* Return a non-negative integer.
*/
int Arena::getSize(){
return Arena.size();
}
/* int main(){
Fighter* r = new Fighter("Bob", 1, 2, 3, 4, 5);
addFighter(r);
return true;
} */
//Xephos A 200 13 21 10
| [
"byoung888@gmail.com"
] | byoung888@gmail.com |
84bbbaf2228f7b638bc1276420e04855433634dd | 39921d049a882220193fb45f4023a6831fb79908 | /Pods/gRPC-Core/src/core/lib/gpr/env_linux.cc | 7f8a59e1d49b628ef9dbd364a1d716d6b761042a | [] | no_license | furydeveloper/SearchCoinKaraoke | a48bb7f0a4032735a2fc8895bd6bb02626b392b3 | 98043d3e280814f75c4f6c7957e6c0eee320a9b9 | refs/heads/master | 2023-08-10T23:24:28.780365 | 2021-10-03T02:51:57 | 2021-10-03T02:51:57 | 409,012,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cc | version https://git-lfs.github.com/spec/v1
oid sha256:38d4c365805642e09ddcf3fb4356e597459685b4148fc71e7a92612d2660297c
size 2050
| [
"furysecu@gmail.com"
] | furysecu@gmail.com |
583aa2541abd8ccbb9b13bb72ee262c4b454fffd | cb77dcbbce6c480f68c3dcb8610743f027bee95c | /android/art/runtime/dexopt_test.cc | 5994bed3e95118faac90f3ec2805a4bcfa1333d4 | [
"MIT",
"Apache-2.0",
"NCSA"
] | permissive | fengjixuchui/deoptfuscator | c888b93361d837ef619b9eb95ffd4b01a4bef51a | dec8fbf2b59f8dddf2dbd10868726b255364e1c5 | refs/heads/master | 2023-03-17T11:49:00.988260 | 2023-03-09T02:01:47 | 2023-03-09T02:01:47 | 333,074,914 | 0 | 0 | MIT | 2023-03-09T02:01:48 | 2021-01-26T12:16:31 | null | UTF-8 | C++ | false | false | 10,237 | cc | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <vector>
#include <backtrace/BacktraceMap.h>
#include <gtest/gtest.h>
#include "base/file_utils.h"
#include "common_runtime_test.h"
#include "compiler_callbacks.h"
#include "dex2oat_environment_test.h"
#include "dexopt_test.h"
#include "gc/space/image_space.h"
#include "mem_map.h"
namespace art {
void DexoptTest::SetUp() {
ReserveImageSpace();
Dex2oatEnvironmentTest::SetUp();
}
void DexoptTest::PreRuntimeCreate() {
std::string error_msg;
ASSERT_TRUE(PreRelocateImage(GetImageLocation(), &error_msg)) << error_msg;
ASSERT_TRUE(PreRelocateImage(GetImageLocation2(), &error_msg)) << error_msg;
UnreserveImageSpace();
}
void DexoptTest::PostRuntimeCreate() {
ReserveImageSpace();
}
void DexoptTest::GenerateOatForTest(const std::string& dex_location,
const std::string& oat_location_in,
CompilerFilter::Filter filter,
bool relocate,
bool pic,
bool with_alternate_image,
const char* compilation_reason) {
std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(kRuntimeISA));
std::string dalvik_cache_tmp = dalvik_cache + ".redirected";
std::string oat_location = oat_location_in;
if (!relocate) {
// Temporarily redirect the dalvik cache so dex2oat doesn't find the
// relocated image file.
ASSERT_EQ(0, rename(dalvik_cache.c_str(), dalvik_cache_tmp.c_str())) << strerror(errno);
// If the oat location is in dalvik cache, replace the cache path with the temporary one.
size_t pos = oat_location.find(dalvik_cache);
if (pos != std::string::npos) {
oat_location = oat_location.replace(pos, dalvik_cache.length(), dalvik_cache_tmp);
}
}
std::vector<std::string> args;
args.push_back("--dex-file=" + dex_location);
args.push_back("--oat-file=" + oat_location);
args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
args.push_back("--runtime-arg");
// Use -Xnorelocate regardless of the relocate argument.
// We control relocation by redirecting the dalvik cache when needed
// rather than use this flag.
args.push_back("-Xnorelocate");
ScratchFile profile_file;
if (CompilerFilter::DependsOnProfile(filter)) {
args.push_back("--profile-file=" + profile_file.GetFilename());
}
if (pic) {
args.push_back("--compile-pic");
}
std::string image_location = GetImageLocation();
if (with_alternate_image) {
args.push_back("--boot-image=" + GetImageLocation2());
}
if (compilation_reason != nullptr) {
args.push_back("--compilation-reason=" + std::string(compilation_reason));
}
std::string error_msg;
ASSERT_TRUE(OatFileAssistant::Dex2Oat(args, &error_msg)) << error_msg;
if (!relocate) {
// Restore the dalvik cache if needed.
ASSERT_EQ(0, rename(dalvik_cache_tmp.c_str(), dalvik_cache.c_str())) << strerror(errno);
oat_location = oat_location_in;
}
// Verify the odex file was generated as expected.
std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
oat_location.c_str(),
oat_location.c_str(),
nullptr,
nullptr,
false,
/*low_4gb*/false,
dex_location.c_str(),
&error_msg));
ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
EXPECT_EQ(pic, odex_file->IsPic());
EXPECT_EQ(filter, odex_file->GetCompilerFilter());
std::unique_ptr<ImageHeader> image_header(
gc::space::ImageSpace::ReadImageHeader(image_location.c_str(),
kRuntimeISA,
&error_msg));
ASSERT_TRUE(image_header != nullptr) << error_msg;
const OatHeader& oat_header = odex_file->GetOatHeader();
uint32_t combined_checksum = image_header->GetOatChecksum();
if (CompilerFilter::DependsOnImageChecksum(filter)) {
if (with_alternate_image) {
EXPECT_NE(combined_checksum, oat_header.GetImageFileLocationOatChecksum());
} else {
EXPECT_EQ(combined_checksum, oat_header.GetImageFileLocationOatChecksum());
}
}
if (!with_alternate_image) {
if (CompilerFilter::IsAotCompilationEnabled(filter)) {
if (relocate) {
EXPECT_EQ(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()),
oat_header.GetImageFileLocationOatDataBegin());
EXPECT_EQ(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta());
} else {
EXPECT_NE(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()),
oat_header.GetImageFileLocationOatDataBegin());
EXPECT_NE(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta());
}
}
}
}
void DexoptTest::GenerateOdexForTest(const std::string& dex_location,
const std::string& odex_location,
CompilerFilter::Filter filter) {
GenerateOatForTest(dex_location,
odex_location,
filter,
/*relocate*/false,
/*pic*/false,
/*with_alternate_image*/false);
}
void DexoptTest::GeneratePicOdexForTest(const std::string& dex_location,
const std::string& odex_location,
CompilerFilter::Filter filter,
const char* compilation_reason) {
GenerateOatForTest(dex_location,
odex_location,
filter,
/*relocate*/false,
/*pic*/true,
/*with_alternate_image*/false,
compilation_reason);
}
void DexoptTest::GenerateOatForTest(const char* dex_location,
CompilerFilter::Filter filter,
bool relocate,
bool pic,
bool with_alternate_image) {
std::string oat_location;
std::string error_msg;
ASSERT_TRUE(OatFileAssistant::DexLocationToOatFilename(
dex_location, kRuntimeISA, &oat_location, &error_msg)) << error_msg;
GenerateOatForTest(dex_location,
oat_location,
filter,
relocate,
pic,
with_alternate_image);
}
void DexoptTest::GenerateOatForTest(const char* dex_location, CompilerFilter::Filter filter) {
GenerateOatForTest(dex_location,
filter,
/*relocate*/true,
/*pic*/false,
/*with_alternate_image*/false);
}
bool DexoptTest::PreRelocateImage(const std::string& image_location, std::string* error_msg) {
std::string dalvik_cache;
bool have_android_data;
bool dalvik_cache_exists;
bool is_global_cache;
GetDalvikCache(GetInstructionSetString(kRuntimeISA),
true,
&dalvik_cache,
&have_android_data,
&dalvik_cache_exists,
&is_global_cache);
if (!dalvik_cache_exists) {
*error_msg = "Failed to create dalvik cache";
return false;
}
std::string patchoat = GetAndroidRoot();
patchoat += kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat";
std::vector<std::string> argv;
argv.push_back(patchoat);
argv.push_back("--input-image-location=" + image_location);
argv.push_back("--output-image-directory=" + dalvik_cache);
argv.push_back("--instruction-set=" + std::string(GetInstructionSetString(kRuntimeISA)));
argv.push_back("--base-offset-delta=0x00008000");
return Exec(argv, error_msg);
}
void DexoptTest::ReserveImageSpace() {
MemMap::Init();
// Ensure a chunk of memory is reserved for the image space.
// The reservation_end includes room for the main space that has to come
// right after the image in case of the GSS collector.
uint64_t reservation_start = ART_BASE_ADDRESS;
uint64_t reservation_end = ART_BASE_ADDRESS + 384 * MB;
std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid(), true));
ASSERT_TRUE(map.get() != nullptr) << "Failed to build process map";
for (BacktraceMap::iterator it = map->begin();
reservation_start < reservation_end && it != map->end(); ++it) {
const backtrace_map_t* entry = *it;
ReserveImageSpaceChunk(reservation_start, std::min(entry->start, reservation_end));
reservation_start = std::max(reservation_start, entry->end);
}
ReserveImageSpaceChunk(reservation_start, reservation_end);
}
void DexoptTest::ReserveImageSpaceChunk(uintptr_t start, uintptr_t end) {
if (start < end) {
std::string error_msg;
image_reservation_.push_back(std::unique_ptr<MemMap>(
MemMap::MapAnonymous("image reservation",
reinterpret_cast<uint8_t*>(start), end - start,
PROT_NONE, false, false, &error_msg)));
ASSERT_TRUE(image_reservation_.back().get() != nullptr) << error_msg;
LOG(INFO) << "Reserved space for image " <<
reinterpret_cast<void*>(image_reservation_.back()->Begin()) << "-" <<
reinterpret_cast<void*>(image_reservation_.back()->End());
}
}
void DexoptTest::UnreserveImageSpace() {
image_reservation_.clear();
}
} // namespace art
| [
"gyoonus@gmail.com"
] | gyoonus@gmail.com |
e5999e8fcf7dbb9367942027c8121c8aa9edc375 | 47ab511d1e5f2418745f6319b7584221e578a705 | /CardSol/main.cpp | 6fc91220356fa4fc57c64e5986c061b7c34ac25b | [] | no_license | sdaingade/cpplabs | f460936a6e2e4d68e13a9745b6edaae9aa75ba83 | fa6e644c1f83cbd73d4d6494a1d07f942915b62f | refs/heads/master | 2021-05-29T23:53:37.281887 | 2015-10-04T16:14:06 | 2015-10-04T16:14:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | /**************************************************************
*
* File: main.cpp
*
* Description: Main for Card Test Program
*
* Author: SciSpike
*
* Modification History:
*
***************************************************************/
/* Include Files */
#include <iostream>
#include "card.h"
using namespace std;
/* Constants and defines */
/****************************************************************
*
* Description: main to where Card program is tested.
*
* Returns: none
*
* Pre-Conditions: None
*
* Post Conditions: None
*
* Exceptions: None
*
***************************************************************/
int main()
{
cout << "Test Card Program\n" << endl;
cout << "Making an ACE of Hearts card..." << endl;
Card* ace = new Card;
ace->setValue( 1 );
ace->setSuit( HEARTS );
ace->print();
return 0;
}
| [
"petter.graff@scispike.com"
] | petter.graff@scispike.com |
9da99727690e41979e5829ef026d13788de8d4ff | 04adc20411e1d9eaa19a8c1bf6ff3ce200cf0907 | /src/aqdata/aq_lsgc.h | 22d6fa00b96b59a0340e751a0781e788240948f0 | [
"MIT"
] | permissive | rachelslaybaugh/BART | a0a5c365fe5b6028ae25368597570749824bf8fb | 8145c3a0647423a499674799138066f5dcd1ab78 | refs/heads/master | 2021-08-16T04:43:16.600379 | 2017-08-20T14:28:33 | 2017-08-20T14:28:33 | 96,478,643 | 0 | 0 | null | 2017-07-06T22:59:21 | 2017-07-06T22:59:21 | null | UTF-8 | C++ | false | false | 264 | h | #ifndef __aq_lsgc_h__
#define __aq_lsgc_h__
#include "aq_base.h"
using namespace dealii;
template <int dim>
class AQLSGC : public AQBase<dim>
{
public:
AQLSGC (ParameterHandler &prm);
~AQLSGC ();
void produce_angular_quad ();
};
#endif//__aq_lsgc_h__
| [
"weixiong.zheng@berkeley.edu"
] | weixiong.zheng@berkeley.edu |
aaf0ddeaf6adc6c12de181e8e4d5733b7ccfb87b | d2af2477ac51fca468ea1e311a768dd6eaa30c3a | /test/openssl/openssl_rsa_bak_1/rsa2.cpp | 2a909f065d3f7ea03307d54d4b5bf93e0975fe41 | [
"MIT"
] | permissive | yefy/skp | 35f43fe8312a4418ae19e5eb4df08509753f6c5d | a9fafa09eacd6a0a802ea6550efd30ace79e4a4f | refs/heads/master | 2021-01-10T01:06:11.511514 | 2016-04-07T08:15:06 | 2016-04-07T08:15:06 | 54,396,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,207 | cpp | #include "rsa2.h"
/* filename: tmp.c
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include<openssl/pem.h>
#include<openssl/err.h>
//openssl genrsa -out plainPrv.key 1024
//openssl rsa -in plainPrv.key -pubout -out plainPub.key
//openssl rsa -in plainPrv.key -RSAPublicKey_out -out plainPub2.key
//#define RSAPUBKEY
void hexprint(char *str,int len)
{
int i=0;
for(i=0;i<len;i++){
printf("%s%02x%s",((i%16==0?"|":"")),*((unsigned char*)str+i),(((i+1)%16==0)?"|\n":" "));
}
if(i%16!=0)
printf("|\n");
}
static int do_operation(RSA* rsa_ctx,char *instr,char* path_key,int inlen,char** outstr,int type)
{
if(rsa_ctx == NULL || instr == NULL || path_key == NULL)
{
perror("input elems error,please check them!");
return -1;
}
int rsa_len,num;
rsa_len=RSA_size(rsa_ctx);
*outstr=(char *)malloc(rsa_len+1);
memset(*outstr,0,rsa_len+1);
switch(type){
case 1: //pub enc
if(inlen == 0){
perror("input str len is zero!");
goto err;
}
num = RSA_public_encrypt(inlen,(unsigned char *)instr,(unsigned char*)*outstr,rsa_ctx,RSA_PKCS1_OAEP_PADDING);
break;
case 2: //prv dec
num = RSA_private_decrypt(inlen,(unsigned char *)instr,(unsigned char*)*outstr,rsa_ctx,RSA_PKCS1_OAEP_PADDING);
default:
break;
}
if(num == -1)
{
printf("Got error on enc/dec!\n");
err:
free(*outstr);
*outstr = NULL;
num = -1;
}
return num;
}
int rsa_pub_encrypt(char *str,char *path_key,char** outstr){
RSA *p_rsa;
FILE *file;
int flen,rsa_len,num;
if((file=fopen(path_key,"r"))==NULL){
perror("open key file error");
return -1;
}
#ifdef RSAPUBKEY
if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){
#else
if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){
#endif
ERR_print_errors_fp(stdout);
return -1;
}
num = do_operation(p_rsa,str,path_key,strlen(str),outstr,1);
RSA_free(p_rsa);
fclose(file);
return num;
}
int rsa_prv_decrypt(char *str,char *path_key,int inlen,char** outstr){
RSA *p_rsa;
FILE *file;
int rsa_len,num;
if((file=fopen(path_key,"r"))==NULL){
perror("open key file error");
return -1;
}
if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){
ERR_print_errors_fp(stdout);
return -1;
}
num = do_operation(p_rsa,str,path_key,inlen,outstr,2);
RSA_free(p_rsa);
fclose(file);
return num;
}
int main2(){
char *ptr_en,*ptr_de;
int len;
char *argv1 = "common";
#ifdef RSAPUBKEY
char *argv2 = "plainPub.key";
#else
char *argv2 = "plainPub2.key";
#endif
char *argv3 = "plainPrv.key";
printf("source is :%s\n",argv1);
len=rsa_pub_encrypt(argv1,argv2,&ptr_en);
printf("pubkey encrypt:\n");
hexprint(ptr_en,len);
rsa_prv_decrypt(ptr_en,argv3,len,&ptr_de);
printf("prvkey decrypt:%s\n",ptr_de==NULL?"NULL":ptr_de);
if(ptr_en!=NULL){
free(ptr_en);
}
if(ptr_de!=NULL){
free(ptr_de);
}
return 0;
}
| [
"yefy@localhost.localdomain"
] | yefy@localhost.localdomain |
2879b2e7934f4c003d4ba7ef450bdf69356ee3cb | 6ce22059ff64ecf67d7f4ff29b26d3f1de063f8e | /src/gui/solarsys/CelestialBodyOrbitPanel.cpp | e2d67d2894ba24577086ed9da53eb7ca96efa20e | [
"Apache-2.0"
] | permissive | spacecraft-ai/GMAT-R2016a | dec5e0124369bb3642d29d339fc267f991362b04 | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | refs/heads/master | 2021-01-23T12:47:19.009911 | 2017-06-05T08:24:32 | 2017-06-05T08:24:32 | 93,201,082 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 47,838 | cpp | //$Id$
//------------------------------------------------------------------------------
// CelestialBodyOrbitPanel
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Wendy C. Shoan
// Created: 2009.01.26
//
/**
* This is the panel for the Orbit tab on the notebook on the CelestialBody
* Panel.
*
*/
//------------------------------------------------------------------------------
#include "CelestialBodyOrbitPanel.hpp"
#include "SolarSystem.hpp"
#include "GmatBaseException.hpp"
#include "GmatAppData.hpp"
#include "MessageInterface.hpp"
#include "StringUtil.hpp"
#include "A1Mjd.hpp"
#include "bitmaps/OpenFolder.xpm"
#include <wx/config.h>
#include <fstream>
//#define DEBUG_CB_ORBIT_PANEL
//#define DEBUG_CB_ORBIT_SAVE
//------------------------------------------------------------------------------
// event tables for wxMac/Widgets
//------------------------------------------------------------------------------
BEGIN_EVENT_TABLE(CelestialBodyOrbitPanel, wxPanel)
EVT_COMBOBOX(ID_COMBO_BOX_EPHEM_SOURCE, CelestialBodyOrbitPanel::OnEphemSourceComboBoxChange)
EVT_TEXT(ID_TEXT_CTRL_EPHEM_FILE, CelestialBodyOrbitPanel::OnEphemFileTextCtrlChange)
EVT_BUTTON(ID_BROWSE_BUTTON_EPHEM_FILE, CelestialBodyOrbitPanel::OnEphemFileBrowseButton)
EVT_BUTTON(ID_BROWSE_BUTTON_SPK_FILE, CelestialBodyOrbitPanel::OnSpkFileBrowseButton)
EVT_BUTTON(ID_REMOVE_BUTTON_SPK_FILE, CelestialBodyOrbitPanel::OnSpkFileRemoveButton)
EVT_LISTBOX(ID_LIST_BOX_SPK_FILE, CelestialBodyOrbitPanel::OnSpkFileListBoxChange)
EVT_TEXT(ID_TEXT_CTRL_NAIF_ID, CelestialBodyOrbitPanel::OnNaifIdTextCtrlChange)
EVT_COMBOBOX(ID_COMBO_BOX_CENTRAL_BODY, CelestialBodyOrbitPanel::OnCentralBodyComboBoxChange)
EVT_TEXT(ID_TEXT_CTRL_INITIAL_EPOCH, CelestialBodyOrbitPanel::OnEpochTextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_SMA, CelestialBodyOrbitPanel::OnSMATextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_ECC, CelestialBodyOrbitPanel::OnECCTextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_INC, CelestialBodyOrbitPanel::OnINCTextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_RAAN, CelestialBodyOrbitPanel::OnRAANTextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_AOP, CelestialBodyOrbitPanel::OnAOPTextCtrlChange)
EVT_TEXT(ID_TEXT_CTRL_TA, CelestialBodyOrbitPanel::OnTATextCtrlChange)
END_EVENT_TABLE()
//------------------------------------------------------------------------------
// public methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// CelestialBodyOrbitPanel(GmatPanel *cbPanel, wxWindow *parent,
// CelestialBody *body)
//------------------------------------------------------------------------------
/**
* Creates the panel (default constructor).
*
* @param <cbPanel> pointer to panel on which this one resides
* @param <parent> pointer to the parent window
* @param <body> body whose data the panel should display
*/
//------------------------------------------------------------------------------
CelestialBodyOrbitPanel::CelestialBodyOrbitPanel(GmatPanel *cbPanel,
wxWindow *parent, CelestialBody *body) :
wxPanel (parent),
dataChanged (false),
canClose (true),
theBody (body),
naifID (-99),
initialEpoch (0.0),
SMA (0.0),
ECC (0.0),
INC (0.0),
RAAN (0.0),
AOP (0.0),
TA (0.0),
ephemSrcChanged (false),
ephemFileChanged (false),
spkFileChanged (false),
naifIDChanged (false),
cBodyChanged (false),
epochChanged (false),
SMAChanged (false),
ECCChanged (false),
INCChanged (false),
RAANChanged (false),
AOPChanged (false),
TAChanged (false),
spkFilesDeleted (false),
userDef (false),
allowSpiceForDefaultBodies (false),
isSun (false),
includeTwoBody (false), // ***** modify this to include InitialTwoBody epoch and elements (for non-Sun body)
theCBPanel (cbPanel)
{
guiManager = GuiItemManager::GetInstance();
guiInterpreter = GmatAppData::Instance()->GetGuiInterpreter();
ss = guiInterpreter->GetSolarSystemInUse();
#if 1
#ifdef __USE_SPICE__
spiceAvailable = true;
#else
spiceAvailable = false;
#endif
#else
spiceAvailable = false;
#endif
Create();
}
//------------------------------------------------------------------------------
// ~CelestialBodyOrbitPanel()
//------------------------------------------------------------------------------
/**
* Destroys the panel (destructor).
*
*/
//------------------------------------------------------------------------------
CelestialBodyOrbitPanel::~CelestialBodyOrbitPanel()
{
guiManager->UnregisterComboBox("CelestialBody", centralBodyComboBox);
}
//------------------------------------------------------------------------------
// void SaveData()
//------------------------------------------------------------------------------
/**
* Saves the data from the panel widgets to the body object.
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::SaveData()
{
std::string strval;
Real tmpval;
Integer tmpint;
bool retval;
bool stateChanged = SMAChanged || ECCChanged || INCChanged || RAANChanged ||
AOPChanged || TAChanged;
// don't do anything if no data has been changed.
// note that dataChanged will be true if the user modified any combo box or
// text ctrl, whether or not he/she actually changed the value
canClose = true;
try
{
if (ephemSrcChanged)
{
strval = ephemSourceComboBox->GetValue();
theBody->SetStringParameter(theBody->GetParameterID("PosVelSource"), strval);
}
if (ephemFileChanged)
{
strval = ephemFileTextCtrl->GetValue();
#ifdef DEBUG_CB_ORBIT_PANEL
MessageInterface::ShowMessage("ephemFileChanged is true : %s\n",
strval.c_str());
#endif
std::ifstream filename(strval.c_str());
if (!filename)
{
std::string errmsg = "File \"" + strval;
errmsg += "\" does not exist.\n";
MessageInterface::PopupMessage(Gmat::ERROR_, errmsg);
}
else
{
filename.close();
theBody->SetStringParameter(theBody->GetParameterID("SourceFilename"), strval);
}
}
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable && spkFileChanged)
{
#ifdef DEBUG_CB_ORBIT_PANEL
MessageInterface::ShowMessage("spkFileChanged is true : %s\n",
strval.c_str());
#endif
unsigned int numKernels = spkFileListBox->GetCount();
for (unsigned int ii = 0; ii < numKernels; ii++)
{
strval = spkFileListBox->GetString(ii);
std::ifstream filename(strval.c_str());
if (!filename)
{
std::string errmsg = "File \"" + strval;
errmsg += "\" does not exist.\n";
MessageInterface::PopupMessage(Gmat::ERROR_, errmsg);
canClose = false;
}
else
{
filename.close();
theBody->SetStringParameter(theBody->GetParameterID("OrbitSpiceKernelName"),
strval);
}
}
}
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable && naifIDChanged)
{
strval = naifIDTextCtrl->GetValue();
retval = theCBPanel->CheckInteger(tmpint, strval, "NAIF ID", "Integer Number");
canClose = retval;
if (retval)
{
theBody->SetIntegerParameter(theBody->GetParameterID("NAIFId"), tmpint);
}
}
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable && spkFilesDeleted)
{
for (unsigned int ii = 0; ii < spkFilesToDelete.size(); ii++)
{
theBody->RemoveSpiceKernelName("Orbit", spkFilesToDelete.at(ii));
}
}
if (cBodyChanged)
{
strval = centralBodyComboBox->GetValue();
theBody->SetStringParameter(theBody->GetParameterID("CentralBody"), strval);
}
if (!isSun && includeTwoBody)
{
if (epochChanged)
{
strval = initialEpochTextCtrl->GetValue();
retval = theCBPanel->CheckReal(tmpval, strval, "Initial Two Body Epoch", "Real Number");
canClose = retval;
if (retval)
{
A1Mjd a1Epoch(tmpval);
theBody->SetTwoBodyEpoch(a1Epoch);
}
}
if (stateChanged)
{
#ifdef DEBUG_CB_ORBIT_PANEL
MessageInterface::ShowMessage("state has been changed ...\n",
strval.c_str());
#endif
Rvector6 elements;
bool retval[6];
strval = SMATextCtrl->GetValue();
retval[0] = theCBPanel->CheckReal(tmpval, strval, "Initial SMA", "Real Number");
if (retval[0])
{
elements[0] = tmpval;
}
strval = ECCTextCtrl->GetValue();
retval[1] = theCBPanel->CheckReal(tmpval, strval, "Initial SMA", "Real Number");
if (retval[1])
{
elements[1] = tmpval;
}
strval = INCTextCtrl->GetValue();
retval[2] = theCBPanel->CheckReal(tmpval, strval, "Initial INC", "Real Number");
if (retval[2])
{
elements[2] = tmpval;
}
strval = RAANTextCtrl->GetValue();
retval[3] = theCBPanel->CheckReal(tmpval, strval, "Initial RAAN", "Real Number");
if (retval[3])
{
elements[3] = tmpval;
}
strval = AOPTextCtrl->GetValue();
retval[4] = theCBPanel->CheckReal(tmpval, strval, "Initial AOP", "Real Number");
if (retval[4])
{
elements[4] = tmpval;
}
strval = TATextCtrl->GetValue();
retval[5] = theCBPanel->CheckReal(tmpval, strval, "Initial TA", "Real Number");
if (retval[5])
{
elements[5] = tmpval;
}
#ifdef DEBUG_CB_ORBIT_PANEL
MessageInterface::ShowMessage(
"elements = %12.10f %12.10f %12.10f %12.10f %12.10f %12.10f ...\n",
elements[0],elements[1],elements[2],elements[3],elements[4],elements[5]);
#endif
canClose = retval[0] && retval[1] && retval[2] && retval[3] && retval[4] && retval[5];
if (canClose) theBody->SetTwoBodyElements(elements);
}
}
}
catch (BaseException &ex)
{
canClose = false;
dataChanged = true;
MessageInterface::PopupMessage(Gmat::ERROR_, ex.GetFullMessage());
}
#ifdef DEBUG_CB_ORBIT_SAVE
MessageInterface::ShowMessage("at end of CBOrbitPanel::SaveData, canClose = %s\n",
(canClose? "true" : "false"));
#endif
if (canClose)
{
dataChanged = false;
ResetChangeFlags(true);
}
}
//------------------------------------------------------------------------------
// void LoadData()
//------------------------------------------------------------------------------
/**
* Loads the data from the body object to the panel widgets.
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::LoadData()
{
try
{
ephemSrc = theBody->GetStringParameter(theBody->GetParameterID("PosVelSource"));
ephemSourceComboBox->SetValue(ephemSrc.c_str());
previousEphemSrc = ephemSrc;
ephemFile = theBody->GetSourceFileName();
ephemFileTextCtrl->SetValue(ephemFile.c_str());
centralBody = theBody->GetCentralBody();
centralBodyComboBox->SetValue(centralBody.c_str());
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
naifID = theBody->GetIntegerParameter(theBody->GetParameterID("NAIFId"));
naifIDStringWX = guiManager->ToWxString(naifID);
naifIDTextCtrl->SetValue(naifIDStringWX);
spkFileArray = theBody->GetStringArrayParameter(
theBody->GetParameterID("OrbitSpiceKernelName"));
unsigned int spkListSz = spkFileArray.size();
spkFileArrayWX = new wxString[spkListSz];
spkFiles.clear();
for (unsigned int jj = 0; jj < spkListSz; jj++)
{
spkFiles.push_back(spkFileArray[jj]);
spkFileArrayWX[jj] = wxString(spkFileArray[jj].c_str());
}
spkFileListBox->InsertItems(spkListSz, spkFileArrayWX, 0);
spkFileListBox->SetSelection(spkListSz-1); // Select the last item
}
if (ephemSrc != "DE405")
{
ephemFileStaticText->Hide();
ephemFileTextCtrl->Hide();
ephemFileBrowseButton->Hide();
mainBoxSizer->Layout();
}
else
{
ephemFileStaticText->Show();
ephemFileTextCtrl->Show();
ephemFileBrowseButton->Show();
orbitDataFlexGridSizer->Layout();
}
if (ephemSrc == "TwoBodyPropagation")
{
if (!isSun && includeTwoBody)
{
initialEpochTextCtrl->Enable();
SMATextCtrl->Enable();
ECCTextCtrl->Enable();
INCTextCtrl->Enable();
RAANTextCtrl->Enable();
AOPTextCtrl->Enable();
TATextCtrl->Enable();
mainBoxSizer->Layout();
}
}
else
{
if (!isSun && includeTwoBody)
{
initialEpochTextCtrl->Disable();
SMATextCtrl->Disable();
ECCTextCtrl->Disable();
INCTextCtrl->Disable();
RAANTextCtrl->Disable();
AOPTextCtrl->Disable();
TATextCtrl->Disable();
mainBoxSizer->Layout();
}
}
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
if (ephemSrc != "SPICE")
{
spkFileStaticText->Hide();
spkFileListBox->Hide();
spkFileBrowseButton->Hide();
spkFileRemoveButton->Hide();
naifIDStaticText->Hide();
naifIDTextCtrl->Hide();
naifIDBlankText->Hide();
mainBoxSizer->Layout();
}
else // SPICE
{
spkFileStaticText->Show();
spkFileListBox->Show();
spkFileBrowseButton->Show();
spkFileRemoveButton->Show();
naifIDStaticText->Show();
naifIDTextCtrl->Show();
naifIDBlankText->Show();
mainBoxSizer->Layout();
}
}
if (!isSun && includeTwoBody)
{
initialEpoch = (theBody->GetTwoBodyEpoch()).Get();
initialEpochStringWX = guiManager->ToWxString(initialEpoch);
initialEpochTextCtrl->SetValue(initialEpochStringWX);
Rvector6 elements = theBody->GetTwoBodyElements();
SMA = elements[0];
ECC = elements[1];
INC = elements[2];
RAAN = elements[3];
AOP = elements[4];
TA = elements[5];
SMAStringWX = guiManager->ToWxString(elements[0]);
SMATextCtrl->SetValue(SMAStringWX);
ECCStringWX = guiManager->ToWxString(elements[1]);
ECCTextCtrl->SetValue(ECCStringWX);
INCStringWX = guiManager->ToWxString(elements[2]);
INCTextCtrl->SetValue(INCStringWX);
RAANStringWX = guiManager->ToWxString(elements[3]);
RAANTextCtrl->SetValue(RAANStringWX);
AOPStringWX = guiManager->ToWxString(elements[4]);
AOPTextCtrl->SetValue(AOPStringWX);
TAStringWX = guiManager->ToWxString(elements[5]);
TATextCtrl->SetValue(TAStringWX);
}
ResetChangeFlags();
}
catch (BaseException &e)
{
MessageInterface::PopupMessage(Gmat::ERROR_, e.GetFullMessage());
}
}
//------------------------------------------------------------------------------
// private methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// void Create()
//------------------------------------------------------------------------------
/**
* Creates and arranges the widgets on the panel.
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::Create()
{
int bSize = 2;
#if __WXMAC__
int buttonWidth = 40;
#else
int buttonWidth = 25;
#endif
wxBitmap openBitmap = wxBitmap(OpenFolder_xpm);
// get the config object
wxConfigBase *pConfig = wxConfigBase::Get();
// SetPath() understands ".."
pConfig->SetPath(wxT("/Celestial Body Orbit"));
if (theBody->GetName() == SolarSystem::SUN_NAME) isSun = true;
else isSun = false;
userDef = theBody->IsUserDefined();
allowSpiceForDefaultBodies = ss->IsSpiceAllowedForDefaultBodies();
// empty the temporary value strings
ephemSourceStringWX = "";
ephemFileStringWX = "";
naifIDStringWX = "";
centralBodyStringWX = "";
initialEpochStringWX = "";
SMAStringWX = "";
ECCStringWX = "";
INCStringWX = "";
RAANStringWX = "";
AOPStringWX = "";
TAStringWX = "";
// ephem source combo box
sourceArray = theBody->GetEphemSourceList();
unsigned int ephemListSz = sourceArray.size();
sourceArrayWX = new wxString[ephemListSz];
for (unsigned int jj = 0; jj < ephemListSz; jj++)
sourceArrayWX[jj] = wxString(sourceArray[jj].c_str());
ephemSourceStaticText = new wxStaticText(this, ID_TEXT, wxString("Ephemeris " GUI_ACCEL_KEY "Source"),
wxDefaultPosition, wxSize(-1,-1), 0);
ephemSourceComboBox = new wxComboBox(this, ID_COMBO_BOX_EPHEM_SOURCE, wxString(sourceArrayWX[0]),
wxDefaultPosition, wxDefaultSize, ephemListSz, sourceArrayWX,
wxCB_DROPDOWN|wxCB_READONLY);
ephemSourceComboBox->SetToolTip(pConfig->Read(_T("EphemerisSourceHint")));
// ephem file
ephemFileStaticText = new wxStaticText(this, ID_TEXT, wxString("Ephemeris " GUI_ACCEL_KEY "File"),
wxDefaultPosition, wxSize(-1,-1), 0);
ephemFileTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_EPHEM_FILE, wxT(""),
wxDefaultPosition, wxSize(150,-1), 0);
ephemFileTextCtrl->SetToolTip(pConfig->Read(_T("EphemerisFileHint")));
ephemFileBrowseButton = new wxBitmapButton(this, ID_BROWSE_BUTTON_EPHEM_FILE,
openBitmap, wxDefaultPosition,
wxSize(buttonWidth, -1));
ephemFileBrowseButton->SetToolTip(pConfig->Read(_T("BrowseEphemerisFileHint"), "Browse for file"));
wxBoxSizer *spkButtonSizer = NULL;
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
// naif ID for user-defined bodies
naifIDStaticText = new wxStaticText(this, ID_TEXT,wxString(GUI_ACCEL_KEY"NAIF ID"),
wxDefaultPosition, wxSize(-1,-1), 0);
naifIDTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_NAIF_ID, wxT(""),
wxDefaultPosition, wxSize(80, -1), 0);
naifIDTextCtrl->SetToolTip(pConfig->Read(_T("NAIFIDHint")));
naifIDBlankText = new wxStaticText(this, ID_TEXT,wxT(""),
wxDefaultPosition, wxSize(-1,-1), 0);
// SPK file(s)
wxArrayString emptyList;
spkFileStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"SPK Files"),
wxDefaultPosition, wxSize(-1,-1), 0);
spkFileListBox = new wxListBox(this, ID_LIST_BOX_SPK_FILE, wxDefaultPosition, wxSize(80, 100),
emptyList, wxLB_EXTENDED|wxLB_NEEDED_SB|wxLB_HSCROLL);
spkFileListBox->SetToolTip(pConfig->Read(_T("SPKFileListHint")));
spkFileBrowseButton = new wxButton(this, ID_BROWSE_BUTTON_SPK_FILE, wxString(GUI_ACCEL_KEY"Add"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
spkFileBrowseButton->SetToolTip(pConfig->Read(_T("AddSPKFileHint")));
spkFileRemoveButton = new wxButton(this, ID_REMOVE_BUTTON_SPK_FILE, wxString(GUI_ACCEL_KEY"Remove"),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
spkFileRemoveButton->SetToolTip(pConfig->Read(_T("RemoveSPKFileHint")));
spkButtonSizer = new wxBoxSizer(wxHORIZONTAL);
spkButtonSizer->Add(spkFileBrowseButton,0, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
spkButtonSizer->Add(spkFileRemoveButton,0, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
}
// central body
centralBodyStaticText = new wxStaticText(this, ID_TEXT, wxString("Central " GUI_ACCEL_KEY "Body"),
wxDefaultPosition, wxSize(-1,-1), 0);
centralBodyComboBox = guiManager->GetCelestialBodyComboBox(this, ID_COMBO_BOX_CENTRAL_BODY,
wxSize(150,-1));
centralBodyComboBox->SetToolTip(pConfig->Read(_T("CentralBodyHint")));
if (!isSun && includeTwoBody)
{
// initial epoch
initialEpochStaticText = new wxStaticText(this, ID_TEXT, wxString("Initial A1 " GUI_ACCEL_KEY "Epoch"),
wxDefaultPosition, wxSize(-1,-1), 0);
initialEpochTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_INITIAL_EPOCH, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
initialEpochTextCtrl->SetToolTip(pConfig->Read(_T("InitialA1EpochHint")));
// SMA
SMAStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"SMA"),
wxDefaultPosition, wxSize(-1,-1), 0);
SMATextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_SMA, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
SMATextCtrl->SetToolTip(pConfig->Read(_T("SMAHint")));
SMAUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT("km"),
wxDefaultPosition, wxSize(-1,-1), 0);
// ECC
ECCStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"ECC"),
wxDefaultPosition, wxSize(-1,-1), 0);
ECCTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_ECC, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
ECCTextCtrl->SetToolTip(pConfig->Read(_T("ECCHint")));
ECCUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT(""),
wxDefaultPosition, wxSize(-1,-1), 0);
// INC
INCStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"INC"),
wxDefaultPosition, wxSize(-1,-1), 0);
INCTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_INC, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
INCTextCtrl->SetToolTip(pConfig->Read(_T("INCHint")));
INCUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT("deg"),
wxDefaultPosition, wxSize(-1,-1), 0);
// RAAN
RAANStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"RAAN"),
wxDefaultPosition, wxSize(-1,-1), 0);
RAANTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_RAAN, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
RAANTextCtrl->SetToolTip(pConfig->Read(_T("RAANHint")));
RAANUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT("deg"),
wxDefaultPosition, wxSize(-1,-1), 0);
// AOP
AOPStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"AOP"),
wxDefaultPosition, wxSize(-1,-1), 0);
AOPTextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_AOP, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
AOPTextCtrl->SetToolTip(pConfig->Read(_T("AOPHint")));
AOPUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT("deg"),
wxDefaultPosition, wxSize(-1,-1), 0);
// TA
TAStaticText = new wxStaticText(this, ID_TEXT, wxString(GUI_ACCEL_KEY"TA"),
wxDefaultPosition, wxSize(-1,-1), 0);
TATextCtrl = new wxTextCtrl(this, ID_TEXT_CTRL_TA, wxT(""),
wxDefaultPosition, wxSize(140, -1), 0, wxTextValidator(wxGMAT_FILTER_NUMERIC));
TATextCtrl->SetToolTip(pConfig->Read(_T("TAHint")));
TAUnitsStaticText = new wxStaticText(this, ID_TEXT, wxT("deg"),
wxDefaultPosition, wxSize(-1,-1), 0);
}
// sizers
orbitDataFlexGridSizer = new wxFlexGridSizer(3,0,0);
orbitDataFlexGridSizer->Add(centralBodyStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(centralBodyComboBox,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
//orbitDataFlexGridSizer->Add(30,20,0,wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(0, 0);
orbitDataFlexGridSizer->Add(ephemSourceStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(ephemSourceComboBox,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
//orbitDataFlexGridSizer->Add(30,20,0,wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(0, 0);
orbitDataFlexGridSizer->Add(ephemFileStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(ephemFileTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(ephemFileBrowseButton,0, wxALIGN_CENTRE|wxALL, bSize);
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
orbitDataFlexGridSizer->Add(naifIDStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(naifIDTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(0, 0);
orbitDataFlexGridSizer->Add(spkFileStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(spkFileListBox,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
orbitDataFlexGridSizer->Add(0, 0);
orbitDataFlexGridSizer->Add(0, 0);
orbitDataFlexGridSizer->Add(spkButtonSizer, 0, wxALIGN_CENTRE|wxALL, bSize);
orbitDataFlexGridSizer->Add(0, 0);
}
wxFlexGridSizer *initialStateFlexGridSizer = NULL;
if (!isSun && includeTwoBody)
{
initialStateFlexGridSizer = new wxFlexGridSizer(3,0,0);
initialStateFlexGridSizer->Add(initialEpochStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(initialEpochTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(30,20,0,wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(SMAStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(SMATextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(SMAUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(ECCStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(ECCTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(ECCUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(INCStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(INCTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(INCUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(RAANStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(RAANTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(RAANUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(AOPStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(AOPTextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(AOPUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(TAStaticText,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(TATextCtrl,0, wxGROW|wxALIGN_LEFT|wxALL, bSize);
initialStateFlexGridSizer->Add(TAUnitsStaticText,0, wxALIGN_LEFT|wxALL, bSize);
// Make state edit box growable
initialStateFlexGridSizer->AddGrowableCol( 1 );
}
mainBoxSizer = new wxBoxSizer(wxHORIZONTAL);
GmatStaticBoxSizer *boxSizer1 = new GmatStaticBoxSizer(wxVERTICAL, this, "Ephemeris Data");
boxSizer1->Add(orbitDataFlexGridSizer, 0, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
if (isSun || !includeTwoBody)
{
mainBoxSizer->Add(boxSizer1, 1, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
mainBoxSizer->Add(0,0);
}
else
{
GmatStaticBoxSizer *boxSizer2 = new GmatStaticBoxSizer(wxVERTICAL, this, "Initial Two Body State");
boxSizer2->Add(initialStateFlexGridSizer, 0, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
mainBoxSizer->Add(boxSizer1, 0, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
mainBoxSizer->Add(boxSizer2, 1, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
}
// disable ephem source, ephem file, and central body for default bodies, since
// those need to be set on the SolarSystem panel
if (!userDef)
{
ephemSourceComboBox->Disable();
ephemFileTextCtrl->Disable();
ephemFileBrowseButton->Disable();
}
centralBodyComboBox->Disable(); // do not allow user to change central body (maybe make this
// static text somewhere ...)
// Added #if in case if we want to add another layer of lined box for consistency.
// I like without another layer, too many lines, so set to 0 (LOJ: 2009.11.18)
// Looks bad to have the extra layer on the Mac - it shifts everything over
// to the right too much (WCS: 2013.09.30)
// #if 1
#ifndef __WXMAC__
GmatStaticBoxSizer *mainStaticBoxSizer = new GmatStaticBoxSizer(wxHORIZONTAL, this, "");
mainStaticBoxSizer->Add(mainBoxSizer, 1, wxGROW|wxALIGN_CENTRE|wxALL, bSize);
this->SetAutoLayout(true);
this->SetSizer(mainStaticBoxSizer);
mainStaticBoxSizer->Fit(this);
mainStaticBoxSizer->SetSizeHints(this);
#else
this->SetAutoLayout(true);
this->SetSizer(mainBoxSizer);
mainBoxSizer->Fit(this);
mainBoxSizer->SetSizeHints(this);
#endif
}
//------------------------------------------------------------------------------
// void ResetChangeFlags(bool discardMods)
//------------------------------------------------------------------------------
/**
* Resets the change flags for the panel.
*
* @param <discardMods> flag indicating whether or not to discard the
* modifications on the widgets
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::ResetChangeFlags(bool discardMods)
{
ephemSrcChanged = false;
ephemFileChanged = false;
spkFileChanged = false;
naifIDChanged = false;
cBodyChanged = false;
epochChanged = false;
SMAChanged = false;
ECCChanged = false;
INCChanged = false;
RAANChanged = false;
AOPChanged = false;
TAChanged = false;
spkFilesDeleted = false;
if (discardMods)
{
ephemFileTextCtrl->DiscardEdits();
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
// spkFileListBox->DiscardEdits(); // why doesn't this work??
naifIDTextCtrl->DiscardEdits();
}
if (!isSun && includeTwoBody)
{
initialEpochTextCtrl->DiscardEdits();
SMATextCtrl->DiscardEdits();
ECCTextCtrl->DiscardEdits();
INCTextCtrl->DiscardEdits();
RAANTextCtrl->DiscardEdits();
AOPTextCtrl->DiscardEdits();
TATextCtrl->DiscardEdits();
}
}
}
//------------------------------------------------------------------------------
//Event Handling
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// void OnEphemSourceComboBoxChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the ephem source combo
* box value.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnEphemSourceComboBoxChange(wxCommandEvent &event)
{
std::string newEphemSrc = (ephemSourceComboBox->GetStringSelection()).WX_TO_STD_STRING;
if (newEphemSrc == previousEphemSrc) return;
ephemSrcChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
if (newEphemSrc != "DE405")
{
ephemFileStaticText->Hide();
ephemFileTextCtrl->Hide();
ephemFileBrowseButton->Hide();
orbitDataFlexGridSizer->Layout();
mainBoxSizer->Layout();
}
else
{
// re-insert those items here
ephemFileStaticText->Show();
ephemFileTextCtrl->Show();
ephemFileBrowseButton->Show();
orbitDataFlexGridSizer->Layout();
mainBoxSizer->Layout();
}
if (newEphemSrc == "TwoBodyPropagation")
{
if (!isSun && includeTwoBody)
{
initialEpochTextCtrl->Enable();
SMATextCtrl->Enable();
ECCTextCtrl->Enable();
INCTextCtrl->Enable();
RAANTextCtrl->Enable();
AOPTextCtrl->Enable();
TATextCtrl->Enable();
mainBoxSizer->Layout();
}
}
else
{
if (!isSun && includeTwoBody)
{
initialEpochTextCtrl->Disable();
SMATextCtrl->Disable();
ECCTextCtrl->Disable();
INCTextCtrl->Disable();
RAANTextCtrl->Disable();
AOPTextCtrl->Disable();
TATextCtrl->Disable();
mainBoxSizer->Layout();
}
}
if ((userDef || allowSpiceForDefaultBodies) && spiceAvailable)
{
if (newEphemSrc != "SPICE")
{
spkFileStaticText->Hide();
spkFileListBox->Hide();
spkFileBrowseButton->Hide();
spkFileRemoveButton->Hide();
naifIDStaticText->Hide();
naifIDTextCtrl->Hide();
naifIDBlankText->Hide();
naifIDTextCtrl->Disable();
mainBoxSizer->Layout();
}
else // SPICE
{
spkFileStaticText->Show();
spkFileListBox->Show();
spkFileBrowseButton->Show();
spkFileRemoveButton->Show();
naifIDStaticText->Show();
naifIDTextCtrl->Show();
naifIDBlankText->Show();
naifIDTextCtrl->Enable();
mainBoxSizer->Layout();
}
}
previousEphemSrc = newEphemSrc;
}
//------------------------------------------------------------------------------
// void OnEphemFileTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the ephem file text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnEphemFileTextCtrlChange(wxCommandEvent &event)
{
if (ephemFileTextCtrl->IsModified())
{
ephemFileChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnEphemFileBrowseButton(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user selects the ephem file browse
* button.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnEphemFileBrowseButton(wxCommandEvent &event)
{
wxString oldFile = ephemFileTextCtrl->GetValue();
wxFileDialog dialog(this, _T("Choose a file"), _T(""), _T(""), _T("*.*"));
if (dialog.ShowModal() == wxID_OK)
{
wxString fileName = (dialog.GetPath()).c_str();
if (!fileName.IsSameAs(oldFile))
{
ephemFileTextCtrl->SetValue(fileName);
ephemFileChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
}
//------------------------------------------------------------------------------
// void OnSpkFileBrowseButton(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user selects the SPK browse
* button.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnSpkFileBrowseButton(wxCommandEvent &event)
{
wxArrayString oldFiles = spkFileListBox->GetStrings();
wxFileDialog dialog(this, _T("Choose a file to add"), _T(""), _T(""), _T("*.*"));
Integer foundAt = -99;
if (dialog.ShowModal() == wxID_OK)
{
wxString fileName = (dialog.GetPath()).c_str();
for (Integer ii = 0; ii < (Integer) oldFiles.GetCount(); ii++)
{
if (fileName.IsSameAs(oldFiles[ii]))
{
foundAt = ii;
break;
}
}
if (foundAt == -99) // not found, so it's new
{
// Deselect current selections first
wxArrayInt selections;
int numSelect = spkFileListBox->GetSelections(selections);
for (int i = 0; i < numSelect; i++)
spkFileListBox->Deselect(selections[i]);
spkFileChanged = true;
dataChanged = true;
spkFileListBox->Append(fileName);
spkFileListBox->SetStringSelection(fileName);
theCBPanel->EnableUpdate(true);
}
}
}
//------------------------------------------------------------------------------
// void OnSpkFileRemoveButton(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user selects the SPK remove
* button.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnSpkFileRemoveButton(wxCommandEvent &event)
{
wxArrayInt selections;
int numSelect = spkFileListBox->GetSelections(selections);
// get the string values and delete the selected names from the list
wxString fileSelected;
for (int i = numSelect-1; i >= 0; i--)
{
fileSelected = spkFileListBox->GetString(selections[i]);
spkFilesToDelete.push_back(fileSelected.WX_TO_STD_STRING);
spkFileListBox->Delete(selections[i]);
}
spkFilesDeleted = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
// Select the last item
unsigned int count = spkFileListBox->GetCount();
if (count > 0)
spkFileListBox->SetSelection(count -1);
}
//------------------------------------------------------------------------------
// void OnSpkFileListBoxChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the SPK
* file list box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnSpkFileListBoxChange(wxCommandEvent &event)
{
spkFileChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
//------------------------------------------------------------------------------
// void OnNaifIdTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the NAIF ID
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnNaifIdTextCtrlChange(wxCommandEvent &event)
{
if (naifIDTextCtrl->IsModified())
{
naifIDChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnCentralBodyComboBoxChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the central
* body combo box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnCentralBodyComboBoxChange(wxCommandEvent &event)
{
std::string newCentralBody = (centralBodyComboBox->GetStringSelection()).WX_TO_STD_STRING;
if (newCentralBody == centralBody) return;
cBodyChanged = true;
dataChanged = true;
centralBody = newCentralBody;
theCBPanel->EnableUpdate(true);
}
//------------------------------------------------------------------------------
// void OnEpochTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the epoch
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnEpochTextCtrlChange(wxCommandEvent &event)
{
if (initialEpochTextCtrl->IsModified())
{
epochChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnSMATextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the SMA
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnSMATextCtrlChange(wxCommandEvent &event)
{
if (SMATextCtrl->IsModified())
{
SMAChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnECCTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the ECC
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnECCTextCtrlChange(wxCommandEvent &event)
{
if (ECCTextCtrl->IsModified())
{
ECCChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnINCTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the INC
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnINCTextCtrlChange(wxCommandEvent &event)
{
if (INCTextCtrl->IsModified())
{
INCChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnRAANTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the RAAN
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnRAANTextCtrlChange(wxCommandEvent &event)
{
if (RAANTextCtrl->IsModified())
{
RAANChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnAOPTextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the AOP
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnAOPTextCtrlChange(wxCommandEvent &event)
{
if (AOPTextCtrl->IsModified())
{
AOPChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
//------------------------------------------------------------------------------
// void OnTATextCtrlChange(wxCommandEvent &event)
//------------------------------------------------------------------------------
/**
* Handle the event triggered when the user modifies the value on the TA
* text box.
*
* @param <event> the handled event
*
*/
//------------------------------------------------------------------------------
void CelestialBodyOrbitPanel::OnTATextCtrlChange(wxCommandEvent &event)
{
if (TATextCtrl->IsModified())
{
TAChanged = true;
dataChanged = true;
theCBPanel->EnableUpdate(true);
}
}
| [
"eabesea@rambler.ru"
] | eabesea@rambler.ru |
f8e7ed5ae7bc75713964baf7a44aa76eba662649 | 17ac3acc1f0e89f24e83fba83d7b5ecba9e8917a | /La torre de hanoi.cpp | ff150af135efbe76cb5ea80c0e8081da8ddb4673 | [] | no_license | medranosteven/parcial-2-de-progra | 4c1530d89b2e30d0f00977cc8cb5188cd79bd885 | 86190f572ad15f8d3929dd4869d867796379d2f1 | refs/heads/master | 2020-04-08T18:08:05.847631 | 2018-11-29T02:23:30 | 2018-11-29T02:23:30 | 159,594,796 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,755 | cpp | //Las Torres de Hanoi
// Programa hecho por: JESUS STEVEN MEDRANO CARBALLO
//carnet: MC18055
//segundo parcial de programacion I
//Fecha de entrega 28-nov-2018; hora limite de entrega: 9:00 PM
#include<iostream> //libreria que es utilizado para operaciones de entrada/salida
#include <stdlib.h> //libreria es el archivo de cabecera de la biblioteca estándar
#include <time.h> //libreria para el formato de hora y fecha de cabecera de la biblioteca
using namespace std;
int tem;
int tem2;
int n;
int desde;
int hacia;
int con;
int tam;
int tamdisco;
int espacios;
int k;
int matriz[100][3];
char cr='±',si,fondo=177;
int main(); //Declaracion de la funcion main del programa
void moverdisco(); //Declaracion de la funcion mover disco del programa
int menu(); //Declaracion de la funcion menu del programa
int salir(); //Declaracion de la funcion salir del programa
int torres(); //Declaracion de la funcion torres del programa
void p();//Declaracion de la funcion pause del programa
void cl();//Declaracion de la funcion limpiar del programa
//realizamos el procedimiento del menu
int menu () {// este sera el panel para mostrar y saber que opcion elige el usuario
int select; //funcion para seleccionar
//mostramos un texto de bienvenida
cout<<"\n\t\t BIENVENIDO AL JUEGO DE LAS TORRES DE HANOI"<<endl;
//mostramos en pantalla lo que pedimos que haga el usuario
cout<<"\n\t\t Elige una opcion de las operaciones a realizar"<<endl;
cout<<"\n\t\t\t 1- Jugar 'TORRES DE HANOI'."<<endl;
cout<<"\n\t\t\t 2- Ordenar numeros aleatorios."<<endl;
cout<<"\n\t\t\t 3- Salir."<<endl;
cin>>select;
return select;
}
int salir()//Funcion que se ejecuta para salir del programa
{
system("cls"); //funcion para limpiar pantalla
cout<<cr<<cr<<cr<<cr<<cr<<cr<<cr;
cout<<cr<<cr<<cr<<cr<<cr<<cr<<cr<<cr<<cr<<cr<<cr;
cout<<cr<<" GRACIAS POR JUGAR "<<cr<<endl; //texto de agradecimiento
cout<<cr<<" DESARROLLADOR DEL JUEGO:STEVEN MEDRANO "<<cr<<endl;//mostrar desarrollador del juego
return 0;
}
int torres() //esta es la funcion de creacion de torres de hanoi
{
system("color 5e"); //funcion para el color de fuente y fondo
system("cls"); //funcion para limpiar pantalla
cout<<"Las Torres de Hanoi\n"<<endl<<endl;
cout<<"Digite la cantidad de discos: ";
cin>>n;
while(n>13||n<3) //creamos un while
{
system("cls"); //funcion para limpiar pantalla
cout<<"Tiene que jugar minimo con tres discos y maximo con 13"<<endl<<"Digite la cantidad de discos:";
cin>>n;
}
tam=n+(n-1);
for(int i=1;i<=((tam*3)+3)+1;i++)
cout<<fondo;
cout<<endl<<fondo;
for(int i=0;i<n;i++)
{
for(int j=0;j<3;j++)
{
if(j==0)
matriz[i][j]=i+1;
else
matriz[i][j]=0;
for(k=1;k<=tam;k++)
{
tamdisco=matriz[i][j]+(matriz[i][j]-1);
espacios=(tam-tamdisco)/2;
if(matriz[i][j]==0)
cout<<fondo;
else
{
if(k<=espacios||k>(tam-espacios))
cout<<fondo;
else
cout<<"*";
}
}
cout<<fondo;
}
cout<<endl<<fondo;
}
for(int i=1;i<=((tam*3));i++)
{
if(i==n-1)
cout<<"T1";
else if(i==((n*2)+n)-2)
cout<<"T2";
else if(i==(((n*2)+n)-3)+n*2)
cout<<"T3";
else
cout<<fondo;
}
cout<<endl;
for(int i=1;i<=((tam*3)+4);i++)
cout<<fondo;
moverdisco();
}
void moverdisco()//usamos una funcion de invocacion para mover discos
{
while(matriz[0][1]!=1&&matriz[0][2]!=1) //usamos otro while
{
cout<<"\n\n\t\t\tLleva "<<con++<<" movimientos\n";
do{
cout<<"¿Desde cual torre (T) desea mover el disco?: ";
cin>>desde;
if(matriz[n-1][desde-1]==0){cout<<"No hay disco en esa torre"<<endl;}
}
while(matriz[n-1][desde-1]==0); //creamos otro while
cout<<"¿Hacia cual torre (T) desea mover el disco?: ";
cin>>hacia;
desde--;
hacia--;
for(int i=0;i<n;i++)
{
if(matriz[i][desde]!=0)
{
tem=matriz[i][desde];
tem2=i;
i=n;
}
}
for(int i=n-1;i>=0;i--)
{
if(matriz[i][hacia]==0)
{
if(matriz[i+1][hacia]>tem||i==(n-1))
{
matriz[i][hacia]=tem;
matriz[tem2][desde]=0;
}
else
{
cout<<"\n\nNo puede colocar un disco grande encima de uno pequeno\nni poner un disco en la misma posicion"<<endl
<<"Cambie los parametros"<<endl;
con--;
moverdisco();
}
i=0;
}
}
system("cls");//funcion para limpiar pantalla
for(int i=1;i<=((tam*3)+3)+1;i++)
cout<<fondo;
cout<<endl<<fondo;
for(int i=0;i<n;i++)
{
for(int j=0;j<3;j++)
{
for(k=1;k<=tam;k++)
{
tamdisco=matriz[i][j]+(matriz[i][j]-1);
espacios=(tam-tamdisco)/2;
if(matriz[i][j]==0)
cout<<fondo;
else
{
if(k<=espacios||k>(tam-espacios))
cout<<fondo;
else
cout<<"*";
}
}
cout<<fondo;
}
cout<<endl<<fondo;
}
for(int i=1;i<=((tam*3));i++)
{
if(i==n-1)
cout<<"T1";
else if(i==((n*2)+n)-2)
cout<<"T2";
else if(i==(((n*2)+n)-3)+n*2)
cout<<"T3";
else
cout<<fondo;
}
cout<<endl;
for(int i=1;i<=((tam*3)+4);i++)
cout<<fondo;
}
system("color b3"); //cambiamos el color de consola
cout<<"\n\nFelicitaciones acaba de ganar en "<<con<<" movimientos\n\nDesea volver a jugar S/N: ";
cin>>si;
system("cls");//funcion para limpiar pantalla
con=0;
if(si=='s'||si=='S')
main();
else
main();
getchar();
}
void numeros() //Funcion de crear y ordenar 100 numeros usando random
{
int num[100];
int temp;
srand(time(NULL));
for(int i = 1; i <= 100; i++)
{
num[i] = 1 + rand() % (101 - 1);
cout << num[i]<< " ";
}
cout<<endl<<endl;
for(int i=0; i<100; i++) //usando el Metodo de la burbuja
{
for(int j=i+1; j<=100; j++) //abrimos un for
{
if (num[j]<num[i])
{
temp=num[j];
num[j]=num[i];
num [i]= temp;
}
}
}
cout<<"ORDENANDO NUMEROS"<<endl;
for(int i=0; i<100; i++) //se hace una impresion de numeros ordenados
{
cout<<num[i]<<" ";
}
cout<<endl;
}
void cl(){ // uso de la Funcion para limpiar pantalla
system ("cls");
}
void p(){ //uso de la Funcion para pausar sistema
system ("pause"); //hacemos una pausa
}
int main(){
system ("color 90"); //cambiamos el color de consola
int op;
op=menu();
switch(op){
case 1: cl();
torres();
p();
return main();
break;
case 2: cl();
numeros();
p();
cl();
return main();
break;
case 3: cl();
salir();
break; //se usa para interrumpir la ejecución normal del bucle
}
}
| [
"noreply@github.com"
] | medranosteven.noreply@github.com |
8d2deb39a15171bc7047ceee367fed311bac2875 | 7b8b0ce0d542aafe56f75bed3c2b79cb94f2839f | /Homework1/Map.cpp | 9b7d6d8cd27915dcd32eb98dbae3f734ef6e5d10 | [] | no_license | ZhimingZhuang/CS32 | ee2e4c4c1bb1842391887bdf7d57ae26683e7a88 | 7ee74bd16c5dc1fd3025d8001092802d3ca54724 | refs/heads/master | 2021-01-10T14:46:17.958508 | 2016-04-05T00:19:59 | 2016-04-05T00:19:59 | 55,454,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,096 | cpp | //
// Map.cpp
// hw1
//
// Created by ZhimingZhuang on 1/14/16.
// Copyright (c) 2016 ZhimingZhuang. All rights reserved.
//
#include "Map.h"
Map::Map(){
mapsize = 0;
}
bool Map::empty() const{
if (mapsize == 0)
return true;
else
return false;
}
int Map::size() const{
return mapsize;
}
bool Map::insert(const KeyType& key, const ValueType& value){
if(mapsize >= DEFAULT_MAX_ITEMS)
return false;
else{
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i == mapsize){
mymap[i].mapkey = key;
mymap[i].mapvalue = value;
mapsize++;
return true;
}else{
return false;
}
}
}
bool Map::update(const KeyType& key, const ValueType& value){
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i < mapsize){
mymap[i].mapvalue = value;
return true;
}else{
return false;
}
}
bool Map::insertOrUpdate(const KeyType& key, const ValueType& value){
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i < mapsize){
mymap[i].mapvalue = value;
return true;
}else if(i < DEFAULT_MAX_ITEMS){
mymap[i].mapkey = key;
mymap[i].mapvalue = value;
mapsize++;
return true;
}else{
return false;
}
}
bool Map::erase(const KeyType& key){
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i < mapsize){
for(int j = i+1; j < mapsize; j++){
mymap[j-1].mapkey = mymap[j].mapkey;
mymap[j-1].mapvalue = mymap[j].mapvalue;
}
mapsize--;
return true;
}else{
return false;
}
}
bool Map::contains(const KeyType& key) const{
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i < mapsize)
return true;
else
return false;
}
bool Map::get(const KeyType& key, ValueType& value) const{
int i;
for(i = 0; i < mapsize; i++)
if(mymap[i].mapkey == key) break;
if(i < mapsize){
value = mymap[i].mapvalue;
return true;
}else{
return false;
}
}
bool Map::get(int i, KeyType& key, ValueType& value) const{
if(i >= 0 && i < mapsize){
key = mymap[i].mapkey;
value = mymap[i].mapvalue;
return true;
}else{
return false;
}
}
void Map::swap(Map& other){
int maxcount = std::max(mapsize,other.mapsize);
KeyType tmpkey;
ValueType tmpvalue;
int tmpsize;
for(int i = 0 ; i < maxcount; i++){
tmpkey = mymap[i].mapkey;
mymap[i].mapkey = other.mymap[i].mapkey;
other.mymap[i].mapkey = tmpkey;
tmpvalue = mymap[i].mapvalue;
mymap[i].mapvalue = other.mymap[i].mapvalue;
other.mymap[i].mapvalue = tmpvalue;
}
tmpsize = mapsize;
mapsize = other.mapsize;
other.mapsize = tmpsize;
} | [
"jimmyzhuang0429@gmail.com"
] | jimmyzhuang0429@gmail.com |
1dc6e80faf587663358c1dc68075f300c3c3d80a | 8e889301595dd44d8ff691addd656da45d6c8250 | /Air/case/case4/system/decomposeParDict | b03ab30043c05e92b99780751143cd7b305809ab | [] | no_license | tkk96/study | eb86813bd98f9d6deceeff815e6816692c361ea5 | 641ff0c4b3dca411f909a84788c43095864da972 | refs/heads/master | 2021-02-17T15:36:47.001408 | 2020-04-09T03:42:00 | 2020-04-09T03:42:00 | 245,107,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v3.0+ |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object decomposeParDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
numberOfSubdomains 14;
method scotch;
simpleCoeffs
{
n (14 1 1);
delta 0.001;
}
hierarchicalCoeffs
{
n (1 1 1);
delta 0.001;
order xyz;
}
manualCoeffs
{
dataFile "";
}
distributed no;
roots ( );
// ************************************************************************* //
| [
"noreply@github.com"
] | tkk96.noreply@github.com | |
14f7db0cc019260811221001cb3ae4d471216427 | 2f78e134c5b55c816fa8ee939f54bde4918696a5 | /code_pc/gfx/pictureinpicture_pc.cpp | a11fa5c82752e848dbf582ddc90a15813b25a9a3 | [] | no_license | narayanr7/HeavenlySword | b53afa6a7a6c344e9a139279fbbd74bfbe70350c | a255b26020933e2336f024558fefcdddb48038b2 | refs/heads/master | 2022-08-23T01:32:46.029376 | 2020-05-26T04:45:56 | 2020-05-26T04:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,299 | cpp | //--------------------------------------------------
//!
//! \file pictureinpicture.cpp
//! objects managing final back buffer compositing
//! of multiple viewports.
//!
//--------------------------------------------------
#include "game/capturesystem.h"
#include "gfx/pictureinpicture.h"
#include "gfx/shader.h"
#include "gfx/renderer.h"
#include "gfx/surfacemanager.h"
#include "gfx/sector.h"
#include "gfx/display.h"
#include "gfx/graphicsdevice.h"
#include "gfx/lightingtemplates.h"
#include "gfx/exposure.h"
#include "core/visualdebugger.h"
#include "core/profiling.h"
#include "core/gatso.h"
#include "input/inputhardware.h"
#include "effect/screensprite.h"
//-----------------------------------------------------
//!
//! PIPView::SetupView
//! Allocate VRAM and set as render targets
//!
//-----------------------------------------------------
void PIPView::SetupView(uint32_t iBBWidth, uint32_t iBBHeight)
{
ntAssert_p( !m_bAllocated, ("PIPView already setup.") );
m_bAllocated = true;
uint32_t iWidth = (uint32_t)(m_fWidth * iBBWidth);
uint32_t iHeight = (uint32_t)(m_fHeight * iBBHeight);
// if we're virtually 1, make sure we can use cachable
// render targets
if (fabs((m_fWidth - 1.0f)) < EPSILON)
iWidth = iBBWidth;
if (fabs((m_fHeight - 1.0f)) < EPSILON)
iHeight = iBBHeight;
bool bCacheable = ((iWidth == iBBWidth) && (iHeight == iBBHeight)) ? true : false;
if (CRendererSettings::GetAAMode() == AAM_SUPERSAMPLE_4X)
{
iWidth = iWidth<<1;
iHeight = iHeight<<1;
}
// create back buffer
RenderTarget::CreationStruct createParamsBB( iWidth, iHeight, D3DFMT_A8R8G8B8, false );
createParamsBB.bCacheable = bCacheable;
m_pBackBuffer = SurfaceManager::Get().CreateRenderTarget( createParamsBB );
// create Z buffer
Surface::CreationStruct createParamsZ( iWidth, iHeight, D3DFMT_D24S8 );
createParamsZ.bCacheable = bCacheable;
m_pZBuffer = SurfaceManager::Get().CreateSurface( createParamsZ );
Renderer::Get().m_targetCache.SetColourAndDepthTargets( m_pBackBuffer, m_pZBuffer );
}
//-----------------------------------------------------
//!
//! PIPView::SetActive
//! Do any other persistant allocations or init we require
//!
//-----------------------------------------------------
void PIPView::SetActive( bool bActive )
{
if (m_bActive == bActive)
return;
if (m_bActive)
{
// we're decativating, free stuff
m_bActive = false;
SurfaceManager::Get().ReleaseRenderTarget(m_exposureLastVal);
SurfaceManager::Get().ReleaseRenderTarget(m_exposureLastValTemp);
}
else
{
// we're activating for the first time, alloc stuff
m_bActive = true;
m_fExposureLastVal = 1.0f;
m_exposureLastVal = SurfaceManager::Get().CreateRenderTarget( 1, 1, EXPController::GetInternalFormat() );
m_exposureLastValTemp = SurfaceManager::Get().CreateRenderTarget( 1, 1, EXPController::GetInternalFormat() );
}
}
//-----------------------------------------------------
//!
//! PIPView::FreeView
//! Free VRAM used by view
//!
//-----------------------------------------------------
void PIPView::FreeView()
{
ntAssert_p( m_bAllocated, ("PIPView not setup.") );
m_bAllocated = false;
// we never cache these, as we dont know if theyre going to be fixed
// or variable size.
SurfaceManager::Get().ReleaseRenderTarget( m_pBackBuffer );
SurfaceManager::Get().ReleaseSurface( m_pZBuffer );
}
//--------------------------------------------------
//!
//! PIPView::GetTexture
//! Retrieve our view render target as a texture
//!
//--------------------------------------------------
Texture::Ptr PIPView::GetTexture() const
{
ntAssert_p( m_bAllocated, ("PIPView not setup.") );
return m_pBackBuffer->GetTexture();
}
//-----------------------------------------------------
//!
//! PIPManager::ctor
//! Allocate shaders and VRAM
//!
//-----------------------------------------------------
PIPManager::PIPManager(uint32_t iWidth, uint32_t iHeight)
{
for (int i = 0; i < MAX_VIEWS; i++)
m_views[i].SetDebugID(i);
m_bViewsRendering = false;
m_pCurrentView = 0;
m_iBorderClearCol = NTCOLOUR_ARGB(0xff,0,0,0);
m_iCompositeClearCol = NTCOLOUR_ARGB(0xff,0x10,0x10,0x10);
m_iFadeCol = m_iCompositeClearCol;
m_fFadeFraction = 0.f;
// create our compositing shaders
DebugShader* pNewVS = NT_NEW_CHUNK(Mem::MC_GFX) DebugShader;
pNewVS->SetHLSLFunction(
SHADERTYPE_VERTEX,
"void composite_vs( float4 position : POSITION0, "
" float2 texcoord : TEXCOORD0, "
" out float4 outpos : POSITION, "
" out float2 outtex : TEXCOORD0, "
" uniform float2 global_texeloffset : register(c0) )"
"{ "
" outpos = position; "
" outpos.xy += global_texeloffset*outpos.ww; "
" outtex = texcoord; "
"}",
"composite_vs",
"vs.1.1"
);
m_compositeVS = pNewVS;
DebugShader* pNewPS = NT_NEW_CHUNK(Mem::MC_GFX) DebugShader;
pNewPS->SetHLSLFunction(
SHADERTYPE_PIXEL,
"float4 composite_ps( float2 texcoord : TEXCOORD0, "
" uniform sampler2D source : register(s0), "
" uniform float4 fade_colour : register(c0), "
" uniform float fade_fraction : register(c1) ) : COLOR0 "
"{ "
" return lerp( tex2D( source, texcoord ).xyzw, fade_colour, fade_fraction ); "
"}",
"composite_ps",
"ps.1.1"
);
m_compositePS = pNewPS;
// create our compositing vertex declaration
D3DVERTEXELEMENT9 decl[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 2*sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
D3DDECL_END()
};
m_compositeDecl = CVertexDeclarationManager::Get().GetDeclaration( &decl[0] );
m_iBBWidth = iWidth;
m_iBBHeight = iHeight;
m_views[0].SetActive(true);
}
//-----------------------------------------------------
//!
//! PIPManager::dtor
//! Free shaders and VRAM
//!
//-----------------------------------------------------
PIPManager::~PIPManager()
{
NT_DELETE_CHUNK(Mem::MC_GFX, m_compositeVS );
NT_DELETE_CHUNK(Mem::MC_GFX, m_compositePS );
}
void PIPManager::GetValidViews(SortableList<PIPView>& views)
{
// now sort our views in priority order
for (int i = 0; i < MAX_VIEWS; i++)
{
if (m_views[i].GetActive())
{
ntAssert_p( m_views[i].GetCamera(), ("Active view with no camera") );
views.m_list.push_back( &m_views[i] );
}
}
}
//-----------------------------------------------------
//!
//! PIPManager::RenderBasic
//! Sets up simple back buffers and clears them
//!
//-----------------------------------------------------
void PIPManager::RenderBasic()
{
Renderer::Get().m_Platform.BeginScene();
RenderTarget::CreationStruct createParamsBB( m_iBBWidth, m_iBBHeight, D3DFMT_A8R8G8B8, false );
createParamsBB.bCacheable = true;
m_pSimpleBackBuffer = SurfaceManager::Get().CreateRenderTarget( createParamsBB );
Surface::CreationStruct createParamsZ( m_iBBWidth, m_iBBHeight, D3DFMT_D24S8 );
createParamsZ.bCacheable = true;
m_pSimpleZBuffer = SurfaceManager::Get().CreateSurface( createParamsZ );
Renderer::Get().m_targetCache.SetColourAndDepthTargets( m_pSimpleBackBuffer, m_pSimpleZBuffer );
Renderer::Get().Clear( D3DCLEAR_TARGET, 0, 1.0f, 0 );
}
//-----------------------------------------------------
//!
//! PIPManager::PresentBasic
//! We have finished drawing, so swap buffers
//!
//-----------------------------------------------------
void PIPManager::PresentBasic()
{
// flush any cached debug primitives or text
CGatso::Start( "PIPManager::DebugDraw2D" );
g_VisualDebug->Draw2D();
g_VisualDebug->Reset();
CGatso::Stop( "PIPManager::DebugDraw2D" );
Renderer::Get().m_targetCache.SetColourTarget( Renderer::GetHardwareBackBuffer() );
// need to clear hardwared back buffer if we're bordering
if ( DisplayManager::Get().IsFullScreen() )
Renderer::Get().Clear( D3DCLEAR_TARGET, m_iBorderClearCol, 1.0f, 0 );
DisplayFullscreenTexture( m_pSimpleBackBuffer->GetTexture() );
SurfaceManager::Get().ReleaseRenderTarget( m_pSimpleBackBuffer );
SurfaceManager::Get().ReleaseSurface( m_pSimpleZBuffer );
Renderer::Get().m_Platform.EndScene();
// dump final resolved LDR buffer
if (
(CInputHardware::Exists()) &&
(CInputHardware::Get().GetKeyboard().IsKeyPressed( KEYC_INSERT ))
)
Renderer::Get().m_targetCache.GetPrimaryColourTarget()->SaveToDisk( "X_FinalBuffer" );
// swap the surfaces
// NB, in window mode this is a blocking call, so we pause our profile
// swap the surfaces
Renderer::Get().Present();
}
//-----------------------------------------------------
//!
//! PIPManager::RenderLevel
//! Renders all the views currently required by the level
//!
//-----------------------------------------------------
void PIPManager::RenderLevel()
{
Renderer::Get().m_Platform.BeginScene();
// right, first we're going clear our real back buffer.
RenderTarget::Ptr pCompositingBuffer;
// we have to fake up a back buffer in full screen pc mode
if (DisplayManager::Get().IsFullScreen())
{
m_pFakeBackBuffer = SurfaceManager::Get().CreateRenderTarget(
RenderTarget::CreationStruct( m_iBBWidth, m_iBBHeight, D3DFMT_X8R8G8B8, false ) );
pCompositingBuffer = m_pFakeBackBuffer;
}
else
{
pCompositingBuffer = Renderer::GetHardwareBackBuffer();
}
// now we clear it and loop over our views, rendering them one by one
Renderer::Get().m_targetCache.SetColourTarget( pCompositingBuffer );
Renderer::Get().Clear( D3DCLEAR_TARGET, m_iCompositeClearCol, 1.0f, 0 );
// now sort our views in priority order
SortableList<PIPView> views;
GetValidViews(views);
//for (int i = 0; i < MAX_VIEWS; i++)
//{
// if (m_views[i].GetActive())
// {
// ntAssert_p( m_views[i].GetCamera(), ("Active view with no camera") );
// views.m_list.push_back( &m_views[i] );
// }
//}
ntAssert_p( !views.m_list.empty(), ("Must have atleast one view here") );
views.SortListAscending();
// now render them
m_bViewsRendering = true;
for ( ntstd::List<PIPView*>::iterator it = views.m_list.begin();
it != views.m_list.end(); ++it )
{
m_pCurrentView = (*it);
// allocate views render targets
m_pCurrentView->SetupView( m_iBBWidth, m_iBBHeight );
// render the sector
CSector::Get().Render( m_pCurrentView->GetCamera() );
// swap to compositing buffer and draw view
Renderer::Get().m_targetCache.SetColourTarget( pCompositingBuffer );
// set render states
Renderer::Get().SetBlendMode( GFX_BLENDMODE_LERP );
Renderer::Get().SetCullMode( GFX_CULLMODE_NONE );
// set the shaders
Renderer::Get().SetVertexShader( m_compositeVS );
Renderer::Get().SetPixelShader( m_compositePS );
Renderer::Get().m_Platform.SetVertexDeclaration( m_compositeDecl );
// set PS consts
float r,g,b,a;
NTCOLOUR_EXTRACT_FLOATS( m_pCurrentView->GetFadeColour(), r,g,b,a )
CVector fadeCol( r,g,b,a );
CVector fadeFrac( m_pCurrentView->GetFadeFraction(),0.f,0.f,0.f );
Renderer::Get().SetPixelShaderConstant( 0, &fadeCol, 1 );
Renderer::Get().SetPixelShaderConstant( 1, &fadeFrac, 1 );
// set dimensions
float fLeft, fTop, fWidth, fHeight;
m_pCurrentView->GetViewPos( fLeft, fTop );
m_pCurrentView->GetViewDim( fWidth, fHeight );
Renderer::Get().SetTexture( 0, m_pCurrentView->GetTexture() );
Renderer::Get().SetSamplerAddressMode( 0, TEXTUREADDRESS_CLAMPALL );
Renderer::Get().SetSamplerFilterMode( 0, TEXTUREFILTER_BILINEAR );
ViewVertex verts[6];
CalcViewspaceVerts( fLeft, fTop, fLeft + fWidth, fTop + fHeight, verts );
GetD3DDevice()->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, verts, 4*sizeof(float));
// free the view's render targets
m_pCurrentView->FreeView();
// cleanup
Renderer::Get().SetTexture( 0, Texture::NONE );
Renderer::Get().SetBlendMode( GFX_BLENDMODE_NORMAL );
Renderer::Get().SetCullMode( GFX_CULLMODE_NORMAL );
}
m_bViewsRendering = false;
m_pCurrentView = 0;
}
//-----------------------------------------------------
//!
//! PIPManager::CalcViewspaceVerts
//! Generates two D3D viewspace triangles
//!
//-----------------------------------------------------
void PIPManager::CalcViewspaceVerts( float fLeft, float fTop, float fRight, float fBottom,
ViewVertex* pVerts )
{
pVerts[0] = ViewVertex( 2.0f*fLeft - 1.0f, 1.0f - 2.0f*fTop, 0.0f, 0.0f );
pVerts[1] = ViewVertex( 2.0f*fRight - 1.0f, 1.0f - 2.0f*fTop, 1.0f, 0.0f );
pVerts[2] = ViewVertex( 2.0f*fRight - 1.0f, 1.0f - 2.0f*fBottom, 1.0f, 1.0f );
pVerts[3] = ViewVertex( 2.0f*fRight - 1.0f, 1.0f - 2.0f*fBottom, 1.0f, 1.0f );
pVerts[4] = ViewVertex( 2.0f*fLeft - 1.0f, 1.0f - 2.0f*fBottom, 0.0f, 1.0f );
pVerts[5] = ViewVertex( 2.0f*fLeft - 1.0f, 1.0f - 2.0f*fTop, 0.0f, 0.0f );
}
//-----------------------------------------------------
//!
//! PIPManager::DisplayFullscreenTexture
//! Displays a texture that is assumed to have square pixels
//! (thats important!) in a manner that fits our output
//! display mode. Used for placing internal backbuffer
//! onto the Gc back buffer, or for loading screens
//!
//-----------------------------------------------------
void PIPManager::DisplayFullscreenTexture( Texture::Ptr pTexture )
{
ScreenSprite sprite;
sprite.SetTexture( pTexture );
sprite.SetPosition( CPoint( DisplayManager::Get().GetDeviceWidth() * 0.5f, DisplayManager::Get().GetDeviceHeight() * 0.5f, 0.0f ) );
float fTextureAspect = _R(pTexture->GetWidth()) / _R(pTexture->GetHeight());
if ( fTextureAspect > DisplayManager::Get().GetDeviceAspect() )
{
// our display is 'square-er' than our texture (say a 16:9 texture on a 4:3 display)
// this means we're bordering on top and bottom
sprite.SetWidth( DisplayManager::Get().GetDeviceWidth() );
sprite.SetHeight( (DisplayManager::Get().GetDeviceAspect() / fTextureAspect) * DisplayManager::Get().GetDeviceHeight() );
}
else
{
// our texture is 'square-er' than our display (say a 4:3 texture on a 16:9 display)
// this means we're bordering on left and right
sprite.SetWidth( (fTextureAspect / DisplayManager::Get().GetDeviceAspect()) * DisplayManager::Get().GetDeviceWidth() );
sprite.SetHeight( DisplayManager::Get().GetDeviceHeight() );
}
sprite.Render();
}
//-----------------------------------------------------
//!
//! PIPManager::PresentLevel
//! We have finished drawing, so swap buffers
//!
//-----------------------------------------------------
void PIPManager::PresentLevel()
{
// flush any cached debug primitives or text
CGatso::Start( "PIPManager::DebugDraw2D" );
g_VisualDebug->Draw2D();
g_VisualDebug->Reset();
CGatso::Stop( "PIPManager::DebugDraw2D" );
// Update capture manager
CaptureSystem::Get().Update(0.0f);
// on the pc in fullscreen mode we must draw to the real fullscreen buffer
if ( DisplayManager::Get().IsFullScreen() )
{
// now set the real hardware back buffer up and clear it
Renderer::Get().m_targetCache.SetColourTarget( Renderer::GetHardwareBackBuffer() );
Renderer::Get().Clear( D3DCLEAR_TARGET, m_iBorderClearCol, 1.0f, 0 );
DisplayFullscreenTexture( m_pFakeBackBuffer->GetTexture() );
SurfaceManager::Get().ReleaseRenderTarget( m_pFakeBackBuffer );
}
Renderer::Get().m_Platform.EndScene();
// dump final resolved LDR buffer
if (
(CInputHardware::Exists()) &&
(CInputHardware::Get().GetKeyboard().IsKeyPressed( KEYC_INSERT ))
)
Renderer::Get().m_targetCache.GetPrimaryColourTarget()->SaveToDisk( "X_FinalBuffer" );
// swap the surfaces
Renderer::Get().Present();
}
| [
"hopefullyidontgetbanned735@gmail.com"
] | hopefullyidontgetbanned735@gmail.com |
02e23a75f53b08902f660ba80960ca9f55405da4 | e5cc09797173431e91ce276b01efc4910d3924d1 | /Tutorial_7.cpp/06_pointer_to_derived_class.cpp | 3aee53d0d6f2ee0da56e0b00199e547269ab301e | [] | no_license | abbhowmik/CPP-Total-Course | 11a49a705152a1b7edd38dcb162d9785c1b8839f | d7a331e905903779e70e34d8f5ceddc2fcacd849 | refs/heads/main | 2023-06-10T05:41:45.996067 | 2021-06-29T17:52:47 | 2021-06-29T17:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | #include <iostream>
using namespace std;
class BaseClass
{
public:
int var_base;
void display()
{
cout << "Displaying Base class variable var_base " << var_base << endl;
}
};
class DerivedClass : public BaseClass
{
public:
int var_derived;
void display()
{
cout << "Displaying Base class variable var_base " << var_base << endl;
cout << "Displaying Derived class variable var_derived " << var_derived << endl;
}
};
int main()
{
// BaseClass *base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;
// base_class_pointer = &obj_derived;
// base_class_pointer->var_base = 45;
// base_class_pointer->var_derived = 45;
// this will throws an error as it points to the base class
// base_class_pointer->display();
DerivedClass *derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 456;
derived_class_pointer->var_derived = 676;
derived_class_pointer->display();
return 0;
} | [
"noreply@github.com"
] | abbhowmik.noreply@github.com |
eac9b9584f35564d4fcd232bbfd66ef585064c35 | 036e7d90cd96d2f1e9aa78722fa8f001ba37cf2e | /DM2122 Prac/Source/MeshBuilder.cpp | f387ab90e5d729294e2afae9352b8b38764298ec | [] | no_license | Cawe321/SP2 | c4906b22917816322c59a4ccb14c5e4378019fe0 | 6e343c07ff5df142f7338e004414ea68c2b314f8 | refs/heads/master | 2022-04-13T04:08:52.081565 | 2020-03-01T13:37:10 | 2020-03-01T13:37:10 | 240,672,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,675 | cpp | #include "MeshBuilder.h"
#include <GL\glew.h>
#include <vector>
#include <MyMath.h>
#include "LoadOBJ.h"
/******************************************************************************/
/*!
\brief
Generate the vertices of a reference Axes; Use red for x-axis, green for y-axis, blue for z-axis
Then generate the VBO/IBO and store them in Mesh object
\param meshName - name of mesh
\param lengthX - x-axis should start at -lengthX / 2 and end at lengthX / 2
\param lengthY - y-axis should start at -lengthY / 2 and end at lengthY / 2
\param lengthZ - z-axis should start at -lengthZ / 2 and end at lengthZ / 2
\return Pointer to mesh storing VBO/IBO of reference axes
*/
/******************************************************************************/
Mesh* MeshBuilder::GenerateAxes(const std::string &meshName, float lengthX, float lengthY, float lengthZ)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
// 3 lines using 6 vertices
vertex_buffer_data.reserve(6);
v.pos.Set(0 - lengthX * 0.5, 0, 0);
v.color.Set(1, 0, 0);
vertex_buffer_data.push_back(v);
v.pos.Set(lengthX * 0.5, 0, 0);
v.color.Set(1, 0, 0);
vertex_buffer_data.push_back(v);
v.pos.Set(0, 0 - lengthX * 0.5, 0);
v.color.Set(0, 1, 0);
vertex_buffer_data.push_back(v);
v.pos.Set(0, lengthX * 0.5, 0);
v.color.Set(0, 1, 0);
vertex_buffer_data.push_back(v);
v.pos.Set(0, 0, 0 - lengthX * 0.5);
v.color.Set(0, 0, 1);
vertex_buffer_data.push_back(v);
v.pos.Set(0, 0, lengthX * 0.5);
v.color.Set(0, 0, 1);
vertex_buffer_data.push_back(v);
std::vector<GLuint> index_buffer_data;
index_buffer_data.reserve(6);
index_buffer_data.push_back(0);
index_buffer_data.push_back(1);
index_buffer_data.push_back(2);
index_buffer_data.push_back(3);
index_buffer_data.push_back(4);
index_buffer_data.push_back(5);
Mesh* mesh = new Mesh(meshName);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0],
GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_LINES;
return mesh;
}
/******************************************************************************/
/*!
\brief
Generate the vertices of a quad; Use random color for each vertex
Then generate the VBO/IBO and store them in Mesh object
\param meshName - name of mesh
\param lengthX - width of quad
\param lengthY - height of quad
\return Pointer to mesh storing VBO/IBO of quad
*/
/******************************************************************************/
Mesh* MeshBuilder::GenerateQuad(const std::string& meshName, Color color, float lengthX, float lengthY)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
// a quad has 4 vertices
vertex_buffer_data.reserve(4);
v.color = color;
v.normal.Set(0, 0, 1.0f);
float midvalueX = lengthX * 0.5;
float midvalueY = lengthY * 0.5;
v.pos.Set(-midvalueX, midvalueY, 0);
v.texCoord.Set(0, 1.f);
vertex_buffer_data.push_back(v);
v.pos.Set(-midvalueX, -midvalueY, 0);
v.texCoord.Set(0.f, 0.f);
vertex_buffer_data.push_back(v);
v.pos.Set(midvalueX, midvalueY, 0);
v.texCoord.Set(1.f, 1.f);
vertex_buffer_data.push_back(v);
v.pos.Set(midvalueX, -midvalueY, 0);
v.texCoord.Set(1.f, 0.f);
vertex_buffer_data.push_back(v);
std::vector<GLuint> index_buffer_data;
index_buffer_data.reserve(6);
index_buffer_data.push_back(0);
index_buffer_data.push_back(1);
index_buffer_data.push_back(2);
index_buffer_data.push_back(2);
index_buffer_data.push_back(1);
index_buffer_data.push_back(3);
Mesh* mesh = new Mesh(meshName);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0],
GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLES;
return mesh;
}
/******************************************************************************/
/*!
\brief
Generate the vertices of a cuboid; Use random color for each vertex
Then generate the VBO/IBO and store them in Mesh object
\param meshName - name of mesh
\param lengthX - width of cube
\param lengthY - height of cube
\param lengthZ - depth of cube
\return Pointer to mesh storing VBO/IBO of cube
*/
/******************************************************************************/
Mesh* MeshBuilder::GenerateCuboid(const std::string& meshName, Color color, float lengthX, float lengthY, float lengthZ)
{
// An array of 3 vectors which represents 3 vertices
Vertex v;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
float midvalueX = lengthX * 0.5;
float midvalueY = lengthY * 0.5;
float midvalueZ = lengthZ * 0.5;
v.color = color;
//Top
v.normal = Vector3(0.f, 1.f, 0.f);
v.pos.Set(midvalueX, midvalueY, midvalueZ);
v.texCoord.Set(0, 0);
vertex_buffer_data.push_back(v); //0
v.pos.Set(midvalueX, midvalueY, -midvalueZ);
v.texCoord.Set(1, 0);
vertex_buffer_data.push_back(v); //1
v.pos.Set(-midvalueX, midvalueY, -midvalueZ);
v.texCoord.Set(1, 1);
vertex_buffer_data.push_back(v); //2
v.pos.Set(-midvalueX, midvalueY, midvalueZ);
v.texCoord.Set(0, 1);
vertex_buffer_data.push_back(v); //3
index_buffer_data.push_back(0);
index_buffer_data.push_back(1);
index_buffer_data.push_back(2);
index_buffer_data.push_back(2);
index_buffer_data.push_back(3);
index_buffer_data.push_back(0);
//Rside
v.normal = Vector3(1.f, 0.f, 0.f);
v.pos.Set(midvalueX, -midvalueY, midvalueZ);
v.texCoord.Set(0, 0);
vertex_buffer_data.push_back(v); //4
v.pos.Set(midvalueX, -midvalueY, -midvalueZ);
v.texCoord.Set(1, 0);
vertex_buffer_data.push_back(v); //5
v.pos.Set(midvalueX, midvalueY, -midvalueZ);
v.texCoord.Set(1,1);
vertex_buffer_data.push_back(v); //6
v.pos.Set(midvalueX, midvalueY, midvalueZ);
v.texCoord.Set(0, 1);
vertex_buffer_data.push_back(v); //7
index_buffer_data.push_back(4);
index_buffer_data.push_back(5);
index_buffer_data.push_back(6);
index_buffer_data.push_back(6);
index_buffer_data.push_back(7);
index_buffer_data.push_back(4);
//Front
v.normal = Vector3(0.f, 0.f, 1.f);
v.pos.Set(midvalueX, midvalueY, midvalueZ);
v.texCoord.Set(1, 1);
vertex_buffer_data.push_back(v); //8
v.pos.Set(-midvalueX, midvalueY, midvalueZ);
v.texCoord.Set(0, 1);
vertex_buffer_data.push_back(v); //8
v.pos.Set(-midvalueX, -midvalueY, midvalueZ);
v.texCoord.Set(0, 0);
vertex_buffer_data.push_back(v); //10
v.pos.Set(midvalueX, -midvalueY, midvalueZ);
v.texCoord.Set(1, 0);
vertex_buffer_data.push_back(v); //11
index_buffer_data.push_back(8);
index_buffer_data.push_back(9);
index_buffer_data.push_back(10);
index_buffer_data.push_back(10);
index_buffer_data.push_back(11);
index_buffer_data.push_back(8);
//Back
v.normal = Vector3(0.f, 0.f, -1.f);
v.pos.Set(midvalueX, -midvalueY, -midvalueZ);
v.texCoord.Set(0, 0);
vertex_buffer_data.push_back(v); //12
v.pos.Set(-midvalueX, -midvalueY, -midvalueZ);
v.texCoord.Set(1, 0);
vertex_buffer_data.push_back(v); //13
v.pos.Set(-midvalueX, midvalueY, -midvalueZ);
v.texCoord.Set(0, 1);
vertex_buffer_data.push_back(v); //14
v.pos.Set(midvalueX, midvalueY, -midvalueZ);
v.texCoord.Set(1, 1);
vertex_buffer_data.push_back(v); //15
index_buffer_data.push_back(12);
index_buffer_data.push_back(13);
index_buffer_data.push_back(14);
index_buffer_data.push_back(14);
index_buffer_data.push_back(15);
index_buffer_data.push_back(12);
//Lside
v.normal = Vector3(-1.f, 0.f, 0.f);
v.pos.Set(-midvalueX, -midvalueY, -midvalueZ);
vertex_buffer_data.push_back(v); //16
v.pos.Set(-midvalueX, -midvalueY, midvalueZ);
vertex_buffer_data.push_back(v); //17
v.pos.Set(-midvalueX, midvalueY, midvalueZ);
vertex_buffer_data.push_back(v); //18
v.pos.Set(-midvalueX, midvalueY, -midvalueZ);
vertex_buffer_data.push_back(v); //19
index_buffer_data.push_back(16);
index_buffer_data.push_back(17);
index_buffer_data.push_back(18);
index_buffer_data.push_back(18);
index_buffer_data.push_back(19);
index_buffer_data.push_back(16);
//Bottom
v.normal = Vector3(0.f, -1.f, 0.f);
v.pos.Set(-midvalueX, -midvalueY, -midvalueZ);
vertex_buffer_data.push_back(v); //20
v.pos.Set(midvalueX, -midvalueY, -midvalueZ);
vertex_buffer_data.push_back(v); //21
v.pos.Set(midvalueX, -midvalueY, midvalueZ);
vertex_buffer_data.push_back(v); //22
v.pos.Set(-midvalueX, -midvalueY, midvalueZ);
vertex_buffer_data.push_back(v); //23
index_buffer_data.push_back(20);
index_buffer_data.push_back(21);
index_buffer_data.push_back(22);
index_buffer_data.push_back(22);
index_buffer_data.push_back(23);
index_buffer_data.push_back(20);
Mesh* mesh = new Mesh(meshName);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
mesh->indexSize = 36;
mesh->mode = Mesh::DRAW_TRIANGLES;
return mesh;
}
/******************************************************************************/
/*!
\brief
Generate the vertices of a Sphere or Hemisphere; Use random color for each vertex
Then generate the VBO/IBO and store them in Mesh object
\param meshName - name of mesh
\param numSlice - number of triangle used to draw
\param numStack - number of layers used to draw
\param radius - radius of the circle
\return Pointer to mesh storing VBO/IBO of cube
*/
/******************************************************************************/
float sphereX(float phi, float theta) {
return cos(Math::DegreeToRadian(phi)) * cos(Math::DegreeToRadian(theta));
}
float sphereY(float phi, float theta) {
return sin(Math::DegreeToRadian(phi));
}
float sphereZ(float phi, float theta) {
return cos(Math::DegreeToRadian(phi)) * sin(Math::DegreeToRadian(theta));
}
/******************************************************************************/
Mesh* MeshBuilder::GenerateSphere(const std::string& meshName, Color color, unsigned numStack, unsigned numSlice, float radius)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
float degreePerStack = 180.f / numStack;
float degreePerSlice = 360.f / numSlice;
for (unsigned stack = 0; stack < numStack + 1; ++stack) {
float phi = -90 + stack * degreePerStack;
for (unsigned slice = 0; slice < numSlice + 1; ++slice) {
float theta = slice * degreePerSlice;
v.pos.Set(radius * sphereX(phi, theta), radius * sphereY(phi, theta), radius * sphereZ(phi, theta));
v.color = color;
v.normal.Set(v.pos.x, v.pos.y, v.pos.z);
vertex_buffer_data.push_back(v);
}
}
for (unsigned stack = 0; stack < numStack; ++stack) {
for (unsigned slice = 0; slice < numSlice + 1; ++slice) {
index_buffer_data.push_back(stack * (numSlice + 1) + slice);
index_buffer_data.push_back((stack + 1) * (numSlice + 1) + slice);
}
}
Mesh* mesh = new Mesh(meshName);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLE_STRIP;
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
return mesh;
}
Mesh* MeshBuilder::GenerateRing(const std::string& meshName, Color color, unsigned numSlice, float outerR, float innerR)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
float degreePerSlice = 360.f / numSlice;
for (unsigned slice = 0; slice < numSlice; ++slice) {
float theta = slice * degreePerSlice;
/*v0*/ v.pos.Set(outerR * cos(Math::DegreeToRadian(theta)), 0, outerR * sin(Math::DegreeToRadian(theta)));
v.color = color;
vertex_buffer_data.push_back(v);
/*v1*/ v.pos.Set(innerR * cos(Math::DegreeToRadian(theta)), 0, innerR * sin(Math::DegreeToRadian(theta)));
v.color = color;
vertex_buffer_data.push_back(v);
float theta2 = (slice + 1) * degreePerSlice;
/*v2*/ v.pos.Set(outerR * cos(Math::DegreeToRadian(theta2)), 0, outerR * sin(Math::DegreeToRadian(theta2)));
v.color = color;
vertex_buffer_data.push_back(v);
/*v3*/ v.pos.Set(innerR * cos(Math::DegreeToRadian(theta2)), 0, innerR * sin(Math::DegreeToRadian(theta2)));
v.color = color;
vertex_buffer_data.push_back(v);
}
for (unsigned slice = 0; slice < numSlice; ++slice) {
index_buffer_data.push_back(slice * 4 + 0);
index_buffer_data.push_back(slice * 4 + 1);
index_buffer_data.push_back(slice * 4 + 2);
index_buffer_data.push_back(slice * 4 + 3);
index_buffer_data.push_back(slice * 4 + 2);
index_buffer_data.push_back(slice * 4 + 1);
}
Mesh* mesh = new Mesh(meshName);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLES;
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
return mesh;
}
Mesh* MeshBuilder::GenerateCone(const std::string& meshName, Color color, unsigned numSlice, float radius, float height)
{
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
Vertex v;
float degreePerSlice = 360.f / numSlice;
for (unsigned slice = 0; slice < numSlice + 1; ++slice) //slice
{
float theta = slice * degreePerSlice;
v.pos.Set(radius * cos(Math::DegreeToRadian(theta)), 0, radius * sin(Math::DegreeToRadian(theta)));
v.color = color;
vertex_buffer_data.push_back(v);
v.pos.Set(0, height, 0);
v.color = color;
vertex_buffer_data.push_back(v);
}
for (unsigned slice = 0; slice < numSlice + 1; ++slice)
{
index_buffer_data.push_back(slice * 2 + 0);
index_buffer_data.push_back(slice * 2 + 1);
}
Mesh* mesh = new Mesh(meshName);
mesh->mode = Mesh::DRAW_TRIANGLE_STRIP;
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
return mesh;
}
Mesh* MeshBuilder::GenerateCylinder(const std::string& meshName, Color color, unsigned numStack, unsigned numSlice, float radius, float height)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
float degreePerStack = 180.0f / numStack;
float degreePerSlice = 360.0f / numSlice;
float stackHeight = height / numStack;
for (unsigned stack = 0; stack < numStack + 1; ++stack)
{
for (unsigned slice = 0; slice < numSlice + 1; ++slice)
{
float theta = slice * degreePerSlice;
v.pos.Set(radius * cos(Math::DegreeToRadian(theta)) /*cylinderX(theta)*/,
-height / 2 + stack * stackHeight, radius * sin(Math::DegreeToRadian(theta)) /*cylinderZ(theta)*/);
v.color = color;
vertex_buffer_data.push_back(v);
}
}
for (unsigned stack = 0; stack < numStack; ++stack)
{
for (unsigned slice = 0; slice < numSlice + 1; ++slice)
{
index_buffer_data.push_back(stack * (numSlice + 1) + slice);
index_buffer_data.push_back((stack + 1) * (numSlice + 1) + slice);
}
}
Mesh* mesh = new Mesh(meshName);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLE_STRIP;
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
return mesh;
}
Mesh* MeshBuilder::GenerateTorus(const std::string& meshName, Color color, unsigned numStack, unsigned numSlice, float outerR, float innerR)
{
Vertex v;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
float degreePerStack = 360.f / numStack;
float degreePerSlice = 360.f / numSlice;
float x1, z1;
float x2, y2, z2;
for (unsigned stack = 0; stack < numStack + 1; stack++)
{
for (unsigned slice = 0; slice < numSlice + 1; slice++)
{
z1 = outerR * cos(Math::DegreeToRadian(stack * degreePerStack));
x1 = outerR * sin(Math::DegreeToRadian(stack * degreePerStack));
x2 = (outerR + innerR * cos(Math::DegreeToRadian(slice * degreePerSlice))) * cos(Math::DegreeToRadian(stack * degreePerStack));
y2 = (outerR + innerR * cos(Math::DegreeToRadian(slice * degreePerSlice))) * sin(Math::DegreeToRadian(stack * degreePerStack));
z2 = innerR * sin(Math::DegreeToRadian(slice * degreePerSlice));
v.pos.Set(x2, y2, z2);
v.color = color;
vertex_buffer_data.push_back(v);
}
}
for (unsigned stack = 0; stack < numStack; stack++)
{
for (unsigned slice = 0; slice < numSlice + 1; slice++)
{
index_buffer_data.push_back((numSlice + 1) * stack + slice + 0);
index_buffer_data.push_back((numSlice + 1) * (stack + 1) + slice + 0);
}
}
Mesh* mesh = new Mesh(meshName);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer); // bind index buffer
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLE_STRIP;
return mesh;
}
Mesh* MeshBuilder::GenerateOBJ(const std::string& meshname, const std::string& file_path)
{
std::vector<Position> vertices;
std::vector<TexCoord> uvs;
std::vector<Vector3> normals;
bool success = LoadOBJ(file_path.c_str(), vertices, uvs, normals);
if (!success) return NULL;
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
IndexVBO(vertices, uvs, normals, index_buffer_data, vertex_buffer_data);
Mesh* mesh = new Mesh(meshname);
mesh->mode = Mesh::DRAW_TRIANGLES;
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0], GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
return mesh;
}
Mesh* MeshBuilder::GenerateText(const std::string& meshName, unsigned numRow, unsigned numCol)
{
Vertex v;
v.normal.Set(0, 0, 1.0f);
std::vector<Vertex> vertex_buffer_data;
std::vector<GLuint> index_buffer_data;
// a quad has 4 vertices
// vertex_buffer_data.reserve(numRow* numCol* 4);
// index_buffer_data.reserve(numRow * numCol * 6);
int nCnt = 0;
float width = 1.f / numCol;
float height = 1.f / numRow;
for (unsigned j = 0; j < numRow; ++j)
{
for (unsigned i = 0; i < numCol; ++i)
{
//Task: Add 4 vertices into vertex_buffer_data
v.pos.Set(0, 1, 0);
v.texCoord.Set(width * i, height* (numRow - j));
vertex_buffer_data.push_back(v);
v.pos.Set(0, 0, 0);
v.texCoord.Set(width * i, height * (numRow - j - 1));
vertex_buffer_data.push_back(v);
v.pos.Set(1, 1, 0);
v.texCoord.Set(width * (i + 1), height * (numRow - j));
vertex_buffer_data.push_back(v);
v.pos.Set(1, 0, 0);
v.texCoord.Set(width * (i + 1), height * (numRow - j - 1));
vertex_buffer_data.push_back(v);
//Task: Add 6 indices into index_buffer_data
index_buffer_data.push_back(nCnt);
index_buffer_data.push_back(nCnt+1);
index_buffer_data.push_back(nCnt+2);
index_buffer_data.push_back(nCnt+2);
index_buffer_data.push_back(nCnt+1);
index_buffer_data.push_back(nCnt+3);
nCnt = nCnt + 4;
}
}
Mesh* mesh = new Mesh(meshName);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_buffer_data.size() * sizeof(Vertex), &vertex_buffer_data[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_data.size() * sizeof(GLuint), &index_buffer_data[0],
GL_STATIC_DRAW);
mesh->indexSize = index_buffer_data.size();
mesh->mode = Mesh::DRAW_TRIANGLES;
return mesh;
}
| [
"noreply@github.com"
] | Cawe321.noreply@github.com |
1b7ae7914897563d099e73770de848ee7c45a027 | 55f4ff87aab485953eece1fd0fa019a9c88d3998 | /CountingSort.cpp | b2b439731d96e33555982b3abe2594796f0a0780 | [] | no_license | jsl0149/AlgorithmStudy | 70215a948fbafabbc92ba3229574eccd0d1feccb | a003a2b29533b18f3edca2e8bb1fdb63652ac2b3 | refs/heads/master | 2023-03-19T02:21:00.430662 | 2021-03-01T13:38:43 | 2021-03-01T13:38:43 | 343,424,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main() {
int num = 0; int X2 = 0;;
int count[10001] = { 0, };
scanf("%d", &X2);
for (int i = 0; i < X2; i++) {
scanf("%d", &num);
count[num-1]++;
}
for (int i = 0; i < 10001; i++) {
if (count[i] != 0) {
for (int j = 0; j < count[i]; j++) {
printf("%d ", i+1);
}
}
else;
}
return 0;
}
| [
"noreply@github.com"
] | jsl0149.noreply@github.com |
2c730c90b8cf341840c4ee379371bec55132e9f7 | a796d62943524337fffd2ff594f494390ae84c5e | /src/game/server/vehicle_baseserver.cpp | 00d2683e806c81076fa7aa79e61b088fb902d500 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | blockspacer/source-asw-sdk | 12c4be5e05f76f8b5a1b0e6671d34b66d6385a68 | 88156ac5a4204becb06c6d383e2a947c8b2b27a3 | refs/heads/master | 2021-09-10T09:49:32.508970 | 2018-03-23T23:10:13 | 2018-03-23T23:10:13 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 85,356 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "vcollide_parse.h"
#include "vehicle_base.h"
#include "npc_vehicledriver.h"
#include "in_buttons.h"
#include "engine/IEngineSound.h"
#include "soundenvelope.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "saverestore_utlvector.h"
#include "KeyValues.h"
#include "studio.h"
#include "bone_setup.h"
#include "collisionutils.h"
#include "animation.h"
#include "env_player_surface_trigger.h"
#include "rumble_shared.h"
#ifdef HL2_DLL
#include "hl2_player.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar g_debug_vehiclesound( "g_debug_vehiclesound", "0", FCVAR_CHEAT );
ConVar g_debug_vehicleexit( "g_debug_vehicleexit", "0", FCVAR_CHEAT );
ConVar sv_vehicle_autoaim_scale("sv_vehicle_autoaim_scale", "8");
bool ShouldVehicleIgnoreEntity( CBaseEntity *pVehicle, CBaseEntity *pCollide );
#define HITBOX_SET 2
//-----------------------------------------------------------------------------
// Save/load
//-----------------------------------------------------------------------------
BEGIN_DATADESC_NO_BASE( vehicle_gear_t )
DEFINE_FIELD( flMinSpeed, FIELD_FLOAT ),
DEFINE_FIELD( flMaxSpeed, FIELD_FLOAT ),
DEFINE_FIELD( flSpeedApproachFactor,FIELD_FLOAT ),
END_DATADESC()
BEGIN_DATADESC_NO_BASE( vehicle_crashsound_t )
DEFINE_FIELD( flMinSpeed, FIELD_FLOAT ),
DEFINE_FIELD( flMinDeltaSpeed, FIELD_FLOAT ),
DEFINE_FIELD( iszCrashSound, FIELD_STRING ),
DEFINE_FIELD( gearLimit, FIELD_INTEGER ),
END_DATADESC()
BEGIN_DATADESC_NO_BASE( vehiclesounds_t )
DEFINE_AUTO_ARRAY( iszSound, FIELD_STRING ),
DEFINE_UTLVECTOR( pGears, FIELD_EMBEDDED ),
DEFINE_UTLVECTOR( crashSounds, FIELD_EMBEDDED ),
DEFINE_AUTO_ARRAY( iszStateSounds, FIELD_STRING ),
DEFINE_AUTO_ARRAY( minStateTime, FIELD_FLOAT ),
END_DATADESC()
BEGIN_SIMPLE_DATADESC( CPassengerInfo )
DEFINE_FIELD( m_hPassenger, FIELD_EHANDLE ),
DEFINE_FIELD( m_strRoleName, FIELD_STRING ),
DEFINE_FIELD( m_strSeatName, FIELD_STRING ),
// NOT SAVED
// DEFINE_FIELD( m_nRole, FIELD_INTEGER ),
// DEFINE_FIELD( m_nSeat, FIELD_INTEGER ),
END_DATADESC()
BEGIN_SIMPLE_DATADESC( CBaseServerVehicle )
// These are reset every time by the constructor of the owning class
// DEFINE_FIELD( m_pVehicle, FIELD_CLASSPTR ),
// DEFINE_FIELD( m_pDrivableVehicle; ??? ),
// Controls
DEFINE_FIELD( m_nNPCButtons, FIELD_INTEGER ),
DEFINE_FIELD( m_nPrevNPCButtons, FIELD_INTEGER ),
DEFINE_FIELD( m_flTurnDegrees, FIELD_FLOAT ),
DEFINE_FIELD( m_flVehicleVolume, FIELD_FLOAT ),
// We're going to reparse this data from file in Precache
DEFINE_EMBEDDED( m_vehicleSounds ),
DEFINE_FIELD( m_iSoundGear, FIELD_INTEGER ),
DEFINE_FIELD( m_flSpeedPercentage, FIELD_FLOAT ),
DEFINE_SOUNDPATCH( m_pStateSound ),
DEFINE_SOUNDPATCH( m_pStateSoundFade ),
DEFINE_FIELD( m_soundState, FIELD_INTEGER ),
DEFINE_FIELD( m_soundStateStartTime, FIELD_TIME ),
DEFINE_FIELD( m_lastSpeed, FIELD_FLOAT ),
// NOT SAVED
// DEFINE_FIELD( m_EntryAnimations, CUtlVector ),
// DEFINE_FIELD( m_ExitAnimations, CUtlVector ),
// DEFINE_FIELD( m_bParsedAnimations, FIELD_BOOLEAN ),
// DEFINE_UTLVECTOR( m_PassengerRoles, FIELD_EMBEDDED ),
DEFINE_FIELD( m_iCurrentExitAnim, FIELD_INTEGER ),
DEFINE_FIELD( m_vecCurrentExitEndPoint, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_chPreviousTextureType, FIELD_CHARACTER ),
DEFINE_FIELD( m_savedViewOffset, FIELD_VECTOR ),
DEFINE_FIELD( m_hExitBlocker, FIELD_EHANDLE ),
DEFINE_UTLVECTOR( m_PassengerInfo, FIELD_EMBEDDED ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Base class for drivable vehicle handling. Contain it in your
// drivable vehicle.
//-----------------------------------------------------------------------------
CBaseServerVehicle::CBaseServerVehicle( void )
{
m_pVehicle = NULL;
m_pDrivableVehicle = NULL;
m_nNPCButtons = 0;
m_nPrevNPCButtons = 0;
m_flTurnDegrees = 0;
m_bParsedAnimations = false;
m_iCurrentExitAnim = 0;
m_vecCurrentExitEndPoint = vec3_origin;
m_flVehicleVolume = 0.5;
m_iSoundGear = 0;
m_pStateSound = NULL;
m_pStateSoundFade = NULL;
m_soundState = SS_NONE;
m_flSpeedPercentage = 0;
m_bUseLegacyExitChecks = false;
m_vehicleSounds.Init();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBaseServerVehicle::~CBaseServerVehicle( void )
{
SoundShutdown(0);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Precache( void )
{
int i;
// Precache our other sounds
for ( i = 0; i < VS_NUM_SOUNDS; i++ )
{
if ( m_vehicleSounds.iszSound[i] != NULL_STRING )
{
CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.iszSound[i]) );
}
}
for ( i = 0; i < m_vehicleSounds.crashSounds.Count(); i++ )
{
if ( m_vehicleSounds.crashSounds[i].iszCrashSound != NULL_STRING )
{
CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.crashSounds[i].iszCrashSound) );
}
}
for ( i = 0; i < SS_NUM_STATES; i++ )
{
if ( m_vehicleSounds.iszStateSounds[i] != NULL_STRING )
{
CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.iszStateSounds[i]) );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Parses the vehicle's script for the vehicle sounds
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::Initialize( const char *pScriptName )
{
// Attempt to parse our vehicle script
if ( PhysFindOrAddVehicleScript( pScriptName, NULL, &m_vehicleSounds ) == false )
return false;
Precache();
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetVehicle( CBaseEntity *pVehicle )
{
m_pVehicle = pVehicle;
m_pDrivableVehicle = dynamic_cast<IDrivableVehicle*>(m_pVehicle);
Assert( m_pDrivableVehicle );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
IDrivableVehicle *CBaseServerVehicle::GetDrivableVehicle( void )
{
Assert( m_pDrivableVehicle );
return m_pDrivableVehicle;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the driver. Unlike GetPassenger(VEHICLE_ROLE_DRIVER), it will return
// the NPC driver if it has one.
//-----------------------------------------------------------------------------
CBaseEntity *CBaseServerVehicle::GetDriver( void )
{
return GetPassenger( VEHICLE_ROLE_DRIVER );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBaseCombatCharacter *CBaseServerVehicle::GetPassenger( int nRole )
{
Assert( nRole == VEHICLE_ROLE_DRIVER );
CBaseEntity *pDriver = GetDrivableVehicle()->GetDriver();
if ( pDriver == NULL )
return NULL;
return pDriver->MyCombatCharacterPointer();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetPassengerRole( CBaseCombatCharacter *pPassenger )
{
if ( pPassenger == GetDrivableVehicle()->GetDriver() )
return VEHICLE_ROLE_DRIVER;
return VEHICLE_ROLE_NONE;
}
//-----------------------------------------------------------------------------
// Purpose: Adds a passenger to the vehicle
// Input : nSeat - seat to sit in
// *pPassenger - character to enter
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_AddPassenger( CBaseCombatCharacter *pPassenger, string_t strRoleName, int nSeat )
{
// Players cannot yet use this code! - jdw
Assert( pPassenger != NULL && pPassenger->IsPlayer() == false );
if ( pPassenger == NULL || pPassenger->IsPlayer() )
return false;
// Find our role
int nRole = FindRoleIndexByName( strRoleName );
if ( nRole == -1 )
return false;
// Cannot evict a passenger already in this position
CBaseCombatCharacter *pCurrentPassenger = NPC_GetPassengerInSeat( nRole, nSeat );
if ( pCurrentPassenger == pPassenger )
return true;
// If we weren't the same passenger, we need to be empty
if ( pCurrentPassenger != NULL )
return false;
// Find the seat
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
if ( m_PassengerInfo[i].GetSeat() == nSeat && m_PassengerInfo[i].GetRole() == nRole )
{
m_PassengerInfo[i].m_hPassenger = pPassenger;
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Removes a passenger from the vehicle
// Input : *pPassenger - Passenger to remove
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_RemovePassenger( CBaseCombatCharacter *pPassenger )
{
// Players cannot yet use this code! - jdw
Assert( pPassenger != NULL && pPassenger->IsPlayer() == false );
if ( pPassenger == NULL || pPassenger->IsPlayer() )
return false;
// Find the seat
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
{
m_PassengerInfo[i].m_hPassenger = NULL;
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the attachment point index for the passenger's seat
// Input : *pPassenger - Passenger in the seat
// Output : int - Attachment point index for the vehicle
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetPassengerSeatAttachment( CBaseCombatCharacter *pPassenger )
{
// Get the role and seat the the supplied passenger
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
// If this is the passenger, get the attachment it'll be at
if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
{
// The seat is the attachment point
int nSeat = m_PassengerInfo[i].GetSeat();
int nRole = m_PassengerInfo[i].GetRole();
return m_PassengerRoles[nRole].m_PassengerSeats[nSeat].GetAttachmentID();
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Get the worldspace position and angles of the specified seat
// Input : *pPassenger - Passenger's seat to use
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_GetPassengerSeatPosition( CBaseCombatCharacter *pPassenger, Vector *vecResultPos, QAngle *vecResultAngles )
{
// Get our attachment point
int nSeatAttachment = NPC_GetPassengerSeatAttachment( pPassenger );
if ( nSeatAttachment == -1 )
return false;
// Figure out which entrypoint hitbox the player is in
CBaseAnimating *pAnimating = dynamic_cast< CBaseAnimating * >( m_pVehicle );
if ( pAnimating == NULL )
return false;
Vector vecPos;
QAngle vecAngles;
pAnimating->GetAttachment( nSeatAttachment, vecPos, vecAngles );
if ( vecResultPos != NULL )
{
*vecResultPos = vecPos;
}
if ( vecResultAngles != NULL )
{
*vecResultAngles = vecAngles;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Get the localspace position and angles of the specified seat
// Input : *pPassenger - Passenger's seat to use
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_GetPassengerSeatPositionLocal( CBaseCombatCharacter *pPassenger, Vector *vecResultPos, QAngle *vecResultAngles )
{
// Get our attachment point
int nSeatAttachment = NPC_GetPassengerSeatAttachment( pPassenger );
if ( nSeatAttachment == -1 )
return false;
// Figure out which entrypoint hitbox the player is in
CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
if ( pAnimating == NULL )
return false;
Vector vecPos;
QAngle vecAngles;
pAnimating->InvalidateBoneCache(); // NOTE: We're moving with velocity, so we're almost always out of date
pAnimating->GetAttachmentLocal( nSeatAttachment, vecPos, vecAngles );
if ( vecResultPos != NULL )
{
*vecResultPos = vecPos;
}
if ( vecResultAngles != NULL )
{
*vecResultAngles = vecAngles;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Retrieves a list of animations used to enter/exit the seat occupied by the passenger
// Input : *pPassenger - Passenger who's seat anims to retrieve
// nType - which set of animations to retrieve
//-----------------------------------------------------------------------------
const PassengerSeatAnims_t *CBaseServerVehicle::NPC_GetPassengerSeatAnims( CBaseCombatCharacter *pPassenger, PassengerSeatAnimType_t nType )
{
// Get the role and seat the the supplied passenger
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
{
int nSeat = m_PassengerInfo[i].GetSeat();
int nRole = m_PassengerInfo[i].GetRole();
switch( nType )
{
case PASSENGER_SEAT_ENTRY:
return &m_PassengerRoles[nRole].m_PassengerSeats[nSeat].m_EntryTransitions;
break;
case PASSENGER_SEAT_EXIT:
return &m_PassengerRoles[nRole].m_PassengerSeats[nSeat].m_ExitTransitions;
break;
default:
return NULL;
break;
}
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Get and set the current driver. Use PassengerRole_t enum in shareddefs.h for adding passengers
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetPassenger( int nRole, CBaseCombatCharacter *pPassenger )
{
// Baseclass only handles vehicles with a single passenger
Assert( nRole == VEHICLE_ROLE_DRIVER );
if ( pPassenger != NULL && pPassenger->IsPlayer() == false )
{
// Use NPC_AddPassenger() for NPCs at the moment, these will all be collapsed into one system -- jdw
Assert( 0 );
return;
}
// Getting in? or out?
if ( pPassenger != NULL )
{
CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
if ( pPlayer != NULL )
{
m_savedViewOffset = pPlayer->GetViewOffset();
pPlayer->SetViewOffset( vec3_origin );
pPlayer->ShowCrosshair( false );
GetDrivableVehicle()->EnterVehicle( pPassenger );
#ifdef HL2_DLL
// Stop the player sprint and flashlight.
CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>( pPlayer );
if ( pHL2Player )
{
if ( pHL2Player->IsSprinting() )
{
pHL2Player->StopSprinting();
}
if ( pHL2Player->FlashlightIsOn() )
{
#ifdef REVAMPED_DLL
pHL2Player->FlashlightTurnOff( false );
#else
pHL2Player->FlashlightTurnOff();
#endif
}
}
#endif
}
}
else
{
CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
if ( pPlayer )
{
// Restore the exiting player's view offset
pPlayer->SetViewOffset( m_savedViewOffset );
pPlayer->ShowCrosshair( true );
}
GetDrivableVehicle()->ExitVehicle( nRole );
GetDrivableVehicle()->SetVehicleEntryAnim( false );
UTIL_Remove( m_hExitBlocker );
}
}
//-----------------------------------------------------------------------------
// Purpose: Get a position in *world space* inside the vehicle for the player to start at
//-----------------------------------------------------------------------------
void CBaseServerVehicle::GetPassengerSeatPoint( int nRole, Vector *pPoint, QAngle *pAngles )
{
Assert( nRole == VEHICLE_ROLE_DRIVER );
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( pAnimating )
{
char pAttachmentName[32];
Q_snprintf( pAttachmentName, sizeof( pAttachmentName ), "vehicle_feet_passenger%d", nRole );
int nFeetAttachmentIndex = pAnimating->LookupAttachment(pAttachmentName);
int nIdleSequence = pAnimating->SelectWeightedSequence( ACT_IDLE );
if ( nFeetAttachmentIndex > 0 && nIdleSequence != -1 )
{
// FIXME: This really wants to be a faster query than this implementation!
Vector vecOrigin;
QAngle vecAngles;
if ( GetLocalAttachmentAtTime( nIdleSequence, nFeetAttachmentIndex, 0.0f, &vecOrigin, &vecAngles ) )
{
UTIL_ParentToWorldSpace( pAnimating, vecOrigin, vecAngles );
if ( pPoint )
{
*pPoint = vecOrigin;
}
if ( pAngles )
{
*pAngles = vecAngles;
}
return;
}
}
}
// Couldn't find the attachment point, so just use the origin
if ( pPoint )
{
*pPoint = m_pVehicle->GetAbsOrigin();
}
if ( pAngles )
{
*pAngles = m_pVehicle->GetAbsAngles();
}
}
//---------------------------------------------------------------------------------
// Check Exit Point for leaving vehicle.
//
// Input: yaw/roll from vehicle angle to check for exit
// distance from origin to drop player (allows for different shaped vehicles
// Output: returns true if valid location, pEndPoint
// updated with actual exit point
//---------------------------------------------------------------------------------
bool CBaseServerVehicle::CheckExitPoint( float yaw, int distance, Vector *pEndPoint )
{
QAngle vehicleAngles = m_pVehicle->GetLocalAngles();
Vector vecStart = m_pVehicle->GetAbsOrigin();
Vector vecDir;
vecStart.z += 12; // always 12" from ground
vehicleAngles[YAW] += yaw;
AngleVectors( vehicleAngles, NULL, &vecDir, NULL );
// Vehicles are oriented along the Y axis
vecDir *= -1;
*pEndPoint = vecStart + vecDir * distance;
trace_t tr;
UTIL_TraceHull( vecStart, *pEndPoint, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0 )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Where does this passenger exit the vehicle?
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetPassengerExitPoint( int nRole, Vector *pExitPoint, QAngle *pAngles )
{
Assert( nRole == VEHICLE_ROLE_DRIVER );
// First, see if we've got an attachment point
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( pAnimating )
{
Vector vehicleExitOrigin;
QAngle vehicleExitAngles;
if ( pAnimating->GetAttachment( "vehicle_driver_exit", vehicleExitOrigin, vehicleExitAngles ) )
{
// Make sure it's clear
trace_t tr;
UTIL_TraceHull( vehicleExitOrigin + Vector(0, 0, 12), vehicleExitOrigin, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );
if ( !tr.startsolid )
{
*pAngles = vehicleExitAngles;
*pExitPoint = tr.endpos;
return true;
}
}
}
// left side
if( CheckExitPoint( 90, 90, pExitPoint ) ) // angle from car, distance from origin, actual exit point
return true;
// right side
if( CheckExitPoint( -90, 90, pExitPoint ) )
return true;
// front
if( CheckExitPoint( 0, 100, pExitPoint ) )
return true;
// back
if( CheckExitPoint( 180, 170, pExitPoint ) )
return true;
// All else failed, try popping them out the top.
Vector vecWorldMins, vecWorldMaxs;
m_pVehicle->CollisionProp()->WorldSpaceAABB( &vecWorldMins, &vecWorldMaxs );
pExitPoint->x = (vecWorldMins.x + vecWorldMaxs.x) * 0.5f;
pExitPoint->y = (vecWorldMins.y + vecWorldMaxs.y) * 0.5f;
pExitPoint->z = vecWorldMaxs.z + 50.0f;
// Make sure it's clear
trace_t tr;
UTIL_TraceHull( m_pVehicle->CollisionProp()->WorldSpaceCenter(), *pExitPoint, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );
if ( !tr.startsolid )
{
return true;
}
// No clear exit point available!
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseExitAnim( KeyValues *pkvExitList, bool bEscapeExit )
{
// Look through the entry animations list
KeyValues *pkvExitAnim = pkvExitList->GetFirstSubKey();
while ( pkvExitAnim )
{
// Add 'em to our list
int iIndex = m_ExitAnimations.AddToTail();
Q_strncpy( m_ExitAnimations[iIndex].szAnimName, pkvExitAnim->GetName(), sizeof(m_ExitAnimations[iIndex].szAnimName) );
m_ExitAnimations[iIndex].bEscapeExit = bEscapeExit;
if ( !Q_strncmp( pkvExitAnim->GetString(), "upsidedown", 10 ) )
{
m_ExitAnimations[iIndex].bUpright = false;
}
else
{
m_ExitAnimations[iIndex].bUpright = true;
}
pkvExitAnim = pkvExitAnim->GetNextKey();
}
}
//-----------------------------------------------------------------------------
// Purpose: Parse the transition information
// Input : *pTransitionKeyValues - key values to parse
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCSeatTransition( KeyValues *pTransitionKeyValues, CPassengerSeatTransition *pTransition )
{
// Store it
const char *lpszAnimName = pTransitionKeyValues->GetString( "animation" );
pTransition->m_strAnimationName = AllocPooledString( lpszAnimName );
pTransition->m_nPriority = pTransitionKeyValues->GetInt( "priority" );
}
//-----------------------------------------------------------------------------
// Purpose: Sorting function for vehicle seat animation priorities
//-----------------------------------------------------------------------------
typedef CPassengerSeatTransition SortSeatPriorityType;
int __cdecl SeatPrioritySort( const SortSeatPriorityType *s1, const SortSeatPriorityType *s2 )
{
return ( s1->GetPriority() > s2->GetPriority() );
}
//-----------------------------------------------------------------------------
// Purpose: Parse one set of entry/exit data
// Input : *pSetKeyValues - Key values for this set
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCPassengerSeat( KeyValues *pSetKeyValues, CPassengerSeat *pSeat )
{
CBaseAnimating *pAnimating = (CBaseAnimating *) m_pVehicle;
// Get our attachment name
const char *lpszAttachmentName = pSetKeyValues->GetString( "target_attachment" );
int nAttachmentID = pAnimating->LookupAttachment( lpszAttachmentName );
pSeat->m_nAttachmentID = nAttachmentID;
pSeat->m_strSeatName = AllocPooledString( lpszAttachmentName );
KeyValues *pKey = pSetKeyValues->GetFirstSubKey();
while ( pKey != NULL )
{
const char *lpszName = pKey->GetName();
if ( Q_stricmp( lpszName, "entry" ) == 0 )
{
int nIndex = pSeat->m_EntryTransitions.AddToTail();
Assert( pSeat->m_EntryTransitions.IsValidIndex( nIndex ) );
ParseNPCSeatTransition( pKey, &pSeat->m_EntryTransitions[nIndex] );
}
else if ( Q_stricmp( lpszName, "exit" ) == 0 )
{
int nIndex = pSeat->m_ExitTransitions.AddToTail();
Assert( pSeat->m_ExitTransitions.IsValidIndex( nIndex ) );
ParseNPCSeatTransition( pKey, &pSeat->m_ExitTransitions[nIndex] );
}
// Advance
pKey = pKey->GetNextKey();
}
// Sort the seats based on their priority
pSeat->m_EntryTransitions.Sort( SeatPrioritySort );
pSeat->m_ExitTransitions.Sort( SeatPrioritySort );
}
//-----------------------------------------------------------------------------
// Purpose: Find a passenger role (by name), or create a new one of that names
// Input : strName - name of the role
// : *nIndex - the index into the CUtlBuffer where this role resides
// Output : CPassengerRole * - Role found or created
//-----------------------------------------------------------------------------
CPassengerRole *CBaseServerVehicle::FindOrCreatePassengerRole( string_t strName, int *nIndex )
{
// Try to find an already created container of the same name
for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
{
// If we match, return it
if ( FStrEq( STRING( m_PassengerRoles[i].m_strName ), STRING( strName ) ) )
{
// Supply the index, if requested
if ( nIndex != NULL )
{
*nIndex = i;
}
return &m_PassengerRoles[i];
}
}
// Create a new container
int nNewIndex = m_PassengerRoles.AddToTail();
Assert( m_PassengerRoles.IsValidIndex( nNewIndex ) );
m_PassengerRoles[nNewIndex].m_strName = strName;
// Supply the index, if requested
if ( nIndex != NULL )
{
*nIndex = nNewIndex;
}
return &m_PassengerRoles[nNewIndex];
}
ConVar g_debug_npc_vehicle_roles( "g_debug_npc_vehicle_roles", "0" );
//-----------------------------------------------------------------------------
// Purpose: Parse NPC entry and exit anim data
// Input : *pModelKeyValues - Key values from the vehicle model
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCRoles( KeyValues *pkvPassengerList )
{
// Get the definition section
if ( pkvPassengerList == NULL )
return;
// Get our animating class
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
Assert( pAnimating != NULL );
if ( pAnimating == NULL )
return;
// For attachment polling
CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
Assert( pStudioHdr != NULL );
if ( pStudioHdr == NULL )
return;
// Parse all subkeys
int nRoleIndex;
KeyValues *pkvPassengerKey = pkvPassengerList->GetFirstSubKey();
while ( pkvPassengerKey != NULL )
{
string_t strRoleName = AllocPooledString( pkvPassengerKey->GetName() );
// Find or create the container
CPassengerRole *pRole = FindOrCreatePassengerRole( strRoleName, &nRoleIndex );
if ( pRole == NULL )
continue;
// Add a new role
int nSeatIndex = pRole->m_PassengerSeats.AddToTail();
Assert( pRole->m_PassengerSeats.IsValidIndex( nSeatIndex ) );
// Parse the information
ParseNPCPassengerSeat( pkvPassengerKey, &pRole->m_PassengerSeats[nSeatIndex] );
// Add a matching entry into our passenger manifest
int nPassengerIndex = m_PassengerInfo.AddToTail();
m_PassengerInfo[nPassengerIndex].m_hPassenger = NULL;
m_PassengerInfo[nPassengerIndex].m_nSeat = nSeatIndex;
m_PassengerInfo[nPassengerIndex].m_nRole = nRoleIndex;
// The following are used for index fix-ups after save game restoration
m_PassengerInfo[nPassengerIndex].m_strRoleName = strRoleName;
m_PassengerInfo[nPassengerIndex].m_strSeatName = pRole->m_PassengerSeats[nSeatIndex].m_strSeatName;
// Advance to the next key
pkvPassengerKey = pkvPassengerKey->GetNextKey();
}
// ======================================================================================================
// Debug print
if ( g_debug_npc_vehicle_roles.GetBool() )
{
Msg("Passenger Roles Parsed:\t%d\n\n", m_PassengerRoles.Count() );
for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
{
Msg("\tPassenger Role:\t%s (%d seats)\n", STRING(m_PassengerRoles[i].m_strName), m_PassengerRoles[i].m_PassengerSeats.Count() );
// Iterate through all information sets under this name
for ( int j = 0; j < m_PassengerRoles[i].m_PassengerSeats.Count(); j++ )
{
Msg("\t\tAttachment: %d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_nAttachmentID );
// Entries
Msg("\t\tEntries:\t%d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions.Count() );
Msg("\t\t=====================\n" );
for ( int nEntry = 0; nEntry < m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions.Count(); nEntry++ )
{
Msg("\t\t\tAnimation:\t%s\t(Priority %d)\n", STRING(m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions[nEntry].m_strAnimationName),
m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions[nEntry].m_nPriority );
}
Msg("\n");
// Exits
Msg("\t\tExits:\t%d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions.Count() );
Msg("\t\t=====================\n" );
for ( int nExits = 0; nExits < m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions.Count(); nExits++ )
{
Msg("\t\t\tAnimation:\t%s\t(Priority %d)\n", STRING(m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions[nExits].m_strAnimationName),
m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions[nExits].m_nPriority );
}
}
Msg("\n");
}
}
// ======================================================================================================
}
//-----------------------------------------------------------------------------
// Purpose: Get an attachment point at a specified time in its cycle (note: not exactly a speedy query, use sparingly!)
// Input : nSequence - sequence to test
// nAttachmentIndex - attachment to test
// flCyclePoint - 0.0 - 1.0
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetLocalAttachmentAtTime( int nQuerySequence, int nAttachmentIndex, float flCyclePoint, Vector *vecOriginOut, QAngle *vecAnglesOut )
{
CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
if ( pAnimating == NULL )
return false;
// TODO: It's annoying to stomp and restore this off each time when we're just going to stomp it again later, but the function
// should really leave the car in an acceptable state to run this query -- jdw
// Store this off for restoration later
int nOldSequence = pAnimating->GetSequence();
float flOldCycle = pAnimating->GetCycle();
// Setup the model for the query
pAnimating->SetSequence( nQuerySequence );
pAnimating->SetCycle( flCyclePoint );
pAnimating->InvalidateBoneCache();
// Query for the point
Vector vecOrigin;
QAngle vecAngles;
pAnimating->GetAttachmentLocal( nAttachmentIndex, vecOrigin, vecAngles );
if ( vecOriginOut != NULL )
{
*vecOriginOut = vecOrigin;
}
if ( vecAnglesOut != NULL )
{
*vecAnglesOut = vecAngles;
}
// Restore the model after the query
pAnimating->SetSequence( nOldSequence );
pAnimating->SetCycle( flOldCycle );
pAnimating->InvalidateBoneCache();
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Get an attachment point at a specified time in its cycle (note: not exactly a speedy query, use sparingly!)
// Input : lpszAnimName - name of the sequence to test
// nAttachmentIndex - attachment to test
// flCyclePoint - 0.0 - 1.0
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetLocalAttachmentAtTime( const char *lpszAnimName, int nAttachmentIndex, float flCyclePoint, Vector *vecOriginOut, QAngle *vecAnglesOut )
{
CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
if ( pAnimating == NULL )
return false;
int nQuerySequence = pAnimating->LookupSequence( lpszAnimName );
if ( nQuerySequence < 0 )
return false;
return GetLocalAttachmentAtTime( nQuerySequence, nAttachmentIndex, flCyclePoint, vecOriginOut, vecAnglesOut );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::CacheEntryExitPoints( void )
{
CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
if ( pAnimating == NULL )
return;
int nAttachment = pAnimating->LookupAttachment( "vehicle_driver_eyes" );
// For each exit animation, determine where the end point is and cache it
for ( int i = 0; i < m_ExitAnimations.Count(); i++ )
{
if ( GetLocalAttachmentAtTime( m_ExitAnimations[i].szAnimName, nAttachment, 1.0f, &m_ExitAnimations[i].vecExitPointLocal, &m_ExitAnimations[i].vecExitAnglesLocal ) == false )
{
Warning("Exit animation %s failed to cache target points properly!\n", m_ExitAnimations[i].szAnimName );
}
if ( g_debug_vehicleexit.GetBool() )
{
Vector vecExitPoint = m_ExitAnimations[i].vecExitPointLocal;
QAngle vecExitAngles = m_ExitAnimations[i].vecExitAnglesLocal;
UTIL_ParentToWorldSpace( pAnimating, vecExitPoint, vecExitAngles );
NDebugOverlay::Box( vecExitPoint, -Vector(8,8,8), Vector(8,8,8), 0, 255, 0, 0, 20.0f );
NDebugOverlay::Axis( vecExitPoint, vecExitAngles, 8.0f, true, 20.0f );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseEntryExitAnims( void )
{
// Try and find the right animation to play in the model's keyvalues
KeyValues *modelKeyValues = new KeyValues("");
if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( m_pVehicle->GetModel() ), modelinfo->GetModelKeyValueText( m_pVehicle->GetModel() ) ) )
{
// Do we have an entry section?
KeyValues *pkvEntryList = modelKeyValues->FindKey("vehicle_entry");
if ( pkvEntryList )
{
// Look through the entry animations list
KeyValues *pkvEntryAnim = pkvEntryList->GetFirstSubKey();
while ( pkvEntryAnim )
{
// Add 'em to our list
int iIndex = m_EntryAnimations.AddToTail();
Q_strncpy( m_EntryAnimations[iIndex].szAnimName, pkvEntryAnim->GetName(), sizeof(m_EntryAnimations[iIndex].szAnimName) );
m_EntryAnimations[iIndex].iHitboxGroup = pkvEntryAnim->GetInt();
pkvEntryAnim = pkvEntryAnim->GetNextKey();
}
}
// Do we have an exit section?
KeyValues *pkvExitList = modelKeyValues->FindKey("vehicle_exit");
if ( pkvExitList )
{
ParseExitAnim( pkvExitList, false );
}
// Do we have an exit section?
pkvExitList = modelKeyValues->FindKey("vehicle_escape_exit");
if ( pkvExitList )
{
ParseExitAnim( pkvExitList, true );
}
// Parse the NPC vehicle roles as well
KeyValues *pkvPassengerList = modelKeyValues->FindKey( "vehicle_npc_passengers" );
if ( pkvPassengerList )
{
ParseNPCRoles( pkvPassengerList );
}
}
modelKeyValues->deleteThis();
// Determine the entry and exit points for the
CacheEntryExitPoints();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::HandlePassengerEntry( CBaseCombatCharacter *pPassenger, bool bAllowEntryOutsideZone )
{
CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
if ( pPlayer != NULL )
{
// Find out which hitbox the player's eyepoint is within
int iEntryAnim = GetEntryAnimForPoint( pPlayer->EyePosition() );
// Get this interface for animation queries
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( !pAnimating )
return;
// Are we in an entrypoint zone?
if ( iEntryAnim == ACTIVITY_NOT_AVAILABLE )
{
// Normal get in refuses to allow entry
if ( !bAllowEntryOutsideZone )
return;
// We failed to find a valid entry anim, but we've got to get back in because the player's
// got stuck exiting the vehicle. For now, just use the first get in anim
// UNDONE: We need a better solution for this.
iEntryAnim = pAnimating->LookupSequence( m_EntryAnimations[0].szAnimName );
}
// Check to see if this vehicle can be controlled or if it's locked
if ( GetDrivableVehicle()->CanEnterVehicle( pPlayer ) )
{
// Make sure the passenger can get in as well
if ( pPlayer->CanEnterVehicle( this, VEHICLE_ROLE_DRIVER ) )
{
// Setup the "enter" vehicle sequence and skip the animation if it isn't present.
pAnimating->SetCycle( 0 );
pAnimating->m_flAnimTime = gpGlobals->curtime;
pAnimating->ResetSequence( iEntryAnim );
pAnimating->ResetClientsideFrame();
pAnimating->InvalidateBoneCache(); // This is necessary because we need to query attachment points this frame for blending!
GetDrivableVehicle()->SetVehicleEntryAnim( true );
pPlayer->GetInVehicle( this, VEHICLE_ROLE_DRIVER );
}
}
}
else
{
// NPCs handle transitioning themselves, they should NOT call this function
Assert( 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::HandlePassengerExit( CBaseCombatCharacter *pPassenger )
{
CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
if ( pPlayer != NULL )
{
// Clear hud hints
UTIL_HudHintText( pPlayer, "" );
vbs_sound_update_t params;
InitSoundParams(params);
params.bExitVehicle = true;
SoundState_Update( params );
// Find the right exit anim to use based on available exit points.
Vector vecExitPoint;
bool bAllPointsBlocked;
int iSequence = GetExitAnimToUse( vecExitPoint, bAllPointsBlocked );
// If all exit points were blocked and this vehicle doesn't allow exiting in
// these cases, bail.
Vector vecNewPos = pPlayer->GetAbsOrigin();
QAngle angNewAngles = pPlayer->GetAbsAngles();
int nRole = GetPassengerRole( pPlayer );
if ( ( bAllPointsBlocked ) || ( iSequence == ACTIVITY_NOT_AVAILABLE ) )
{
// Animation-driven exit points are all blocked, or we have none. Fall back to the more simple static exit points.
if ( !GetPassengerExitPoint( nRole, &vecNewPos, &angNewAngles ) && !GetDrivableVehicle()->AllowBlockedExit( pPlayer, nRole ) )
return false;
// At this point, the player has exited the vehicle but did so without playing an animation. We need to give the vehicle a
// chance to do any post-animation clean-up it may need to perform.
HandleEntryExitFinish( false, true );
}
// Now we either have an exit sequence to play, a valid static exit position, or we don't care
// whether we're blocked or not. We're getting out, one way or another.
GetDrivableVehicle()->PreExitVehicle( pPlayer, nRole );
if ( iSequence > ACTIVITY_NOT_AVAILABLE )
{
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( pAnimating )
{
pAnimating->SetCycle( 0 );
pAnimating->m_flAnimTime = gpGlobals->curtime;
pAnimating->ResetSequence( iSequence );
pAnimating->ResetClientsideFrame();
GetDrivableVehicle()->SetVehicleExitAnim( true, vecExitPoint );
// Re-deploy our weapon
if ( pPlayer && pPlayer->IsAlive() )
{
if ( pPlayer->GetActiveWeapon() )
{
pPlayer->GetActiveWeapon()->Deploy();
pPlayer->ShowCrosshair( true );
}
}
// To prevent anything moving into the volume the player's going to occupy at the end of the exit
// NOTE: Set the player as the blocker's owner so the player is allowed to intersect it
Vector vecExitFeetPoint = vecExitPoint - VEC_VIEW;
m_hExitBlocker = CEntityBlocker::Create( vecExitFeetPoint, VEC_HULL_MIN, VEC_HULL_MAX, pPlayer, true );
// We may as well stand where we're going to get out at and stop being parented
pPlayer->SetAbsOrigin( vecExitFeetPoint );
pPlayer->SetParent( NULL );
return true;
}
}
// Couldn't find an animation, so exit immediately
pPlayer->LeaveVehicle( vecNewPos, angNewAngles );
return true;
}
else
{
// NPCs handle transitioning themselves, they should NOT call this function
Assert( 0 );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetEntryAnimForPoint( const Vector &vecEyePoint )
{
// Parse the vehicle animations the first time they get in the vehicle
if ( !m_bParsedAnimations )
{
// Load the entry/exit animations from the vehicle
ParseEntryExitAnims();
m_bParsedAnimations = true;
}
// No entry anims? Vehicles with no entry anims are always enterable.
if ( !m_EntryAnimations.Count() )
return 0;
// Figure out which entrypoint hitbox the player is in
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( !pAnimating )
return 0;
CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
if (!pStudioHdr)
return 0;
int iHitboxSet = FindHitboxSetByName( pStudioHdr, "entryboxes" );
mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( iHitboxSet );
if ( !set || !set->numhitboxes )
return 0;
// Loop through the hitboxes and find out which one we're in
for ( int i = 0; i < set->numhitboxes; i++ )
{
mstudiobbox_t *pbox = set->pHitbox( i );
Vector vecPosition;
QAngle vecAngles;
pAnimating->GetBonePosition( pbox->bone, vecPosition, vecAngles );
// Build a rotation matrix from orientation
matrix3x4_t fRotateMatrix;
AngleMatrix( vecAngles, vecPosition, fRotateMatrix);
Vector localEyePoint;
VectorITransform( vecEyePoint, fRotateMatrix, localEyePoint );
if ( IsPointInBox( localEyePoint, pbox->bbmin, pbox->bbmax ) )
{
// Find the entry animation for this hitbox
int iCount = m_EntryAnimations.Count();
for ( int entry = 0; entry < iCount; entry++ )
{
if ( m_EntryAnimations[entry].iHitboxGroup == pbox->group )
{
// Get the sequence for the animation
return pAnimating->LookupSequence( m_EntryAnimations[entry].szAnimName );
}
}
}
}
// Fail
return ACTIVITY_NOT_AVAILABLE;
}
//-----------------------------------------------------------------------------
// Purpose: Find an exit animation that'll get the player to a valid position
// Input : vecEyeExitEndpoint - Returns with the final eye position after exiting.
// bAllPointsBlocked - Returns whether all exit points were found to be blocked.
// Output :
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetExitAnimToUse( Vector &vecEyeExitEndpoint, bool &bAllPointsBlocked )
{
bAllPointsBlocked = false;
// Parse the vehicle animations the first time they get in the vehicle
if ( !m_bParsedAnimations )
{
// Load the entry/exit animations from the vehicle
ParseEntryExitAnims();
m_bParsedAnimations = true;
}
// No exit anims?
if ( !m_ExitAnimations.Count() )
return ACTIVITY_NOT_AVAILABLE;
// Figure out which entrypoint hitbox the player is in
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
if ( !pAnimating )
return ACTIVITY_NOT_AVAILABLE;
CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
if (!pStudioHdr)
return ACTIVITY_NOT_AVAILABLE;
bool bUpright = IsVehicleUpright();
// Loop through the exit animations and find one that ends in a clear position
// Also attempt to choose the animation which brings you closest to your view direction.
CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
if ( pPlayer == NULL )
return ACTIVITY_NOT_AVAILABLE;
int nRole = GetPassengerRole( pPlayer );
int nBestExitAnim = -1;
bool bBestExitIsEscapePoint = true;
Vector vecViewDirection, vecViewOrigin, vecBestExitPoint( 0, 0, 0 );
vecViewOrigin = pPlayer->EyePosition();
pPlayer->EyeVectors( &vecViewDirection );
vecViewDirection.z = 0.0f;
VectorNormalize( vecViewDirection );
float flMaxCosAngleDelta = -2.0f;
int iCount = m_ExitAnimations.Count();
for ( int i = 0; i < iCount; i++ )
{
if ( m_ExitAnimations[i].bUpright != bUpright )
continue;
// Don't use an escape point if we found a non-escape point already
if ( !bBestExitIsEscapePoint && m_ExitAnimations[i].bEscapeExit )
continue;
Vector vehicleExitOrigin;
QAngle vehicleExitAngles;
// NOTE: HL2 and Ep1 used a method that relied on the animators to place attachment points in the model which marked where
// the player would exit to. This was rendered unnecessary in Ep2, but the choreo vehicles of these older products
// did not have proper exit animations and relied on the exact queries that were happening before. For choreo vehicles,
// we now just allow them to perform those older queries to keep those products happy. - jdw
// Get the position we think we're going to end up at
if ( m_bUseLegacyExitChecks )
{
pAnimating->GetAttachment( m_ExitAnimations[i].szAnimName, vehicleExitOrigin, vehicleExitAngles );
}
else
{
vehicleExitOrigin = m_ExitAnimations[i].vecExitPointLocal;
vehicleExitAngles = m_ExitAnimations[i].vecExitAnglesLocal;
UTIL_ParentToWorldSpace( pAnimating, vehicleExitOrigin, vehicleExitAngles );
}
// Don't bother checking points which are farther from our view direction.
Vector vecDelta;
VectorSubtract( vehicleExitOrigin, vecViewOrigin, vecDelta );
vecDelta.z = 0.0f;
VectorNormalize( vecDelta );
float flCosAngleDelta = DotProduct( vecDelta, vecViewDirection );
// But always check non-escape exits if our current best exit is an escape exit.
if ( !bBestExitIsEscapePoint || m_ExitAnimations[i].bEscapeExit )
{
if ( flCosAngleDelta < flMaxCosAngleDelta )
continue;
}
// The attachment points are where the driver's eyes will end up, so we subtract the view offset
// to get the actual exit position.
vehicleExitOrigin -= VEC_VIEW;
Vector vecMove(0,0,64);
Vector vecStart = vehicleExitOrigin + vecMove;
Vector vecEnd = vehicleExitOrigin - vecMove;
// Starting at the exit point, trace a flat plane down until we hit ground
// NOTE: The hull has no vertical span because we want to test the lateral constraints against the ground, not height (yet)
trace_t tr;
UTIL_TraceHull( vecStart, vecEnd, VEC_HULL_MIN, Vector( VEC_HULL_MAX.x, VEC_HULL_MAX.y, VEC_HULL_MIN.z ), MASK_PLAYERSOLID, NULL, COLLISION_GROUP_NONE, &tr );
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::SweptBox( vecStart, vecEnd, VEC_HULL_MIN, Vector( VEC_HULL_MAX.x, VEC_HULL_MAX.y, VEC_HULL_MIN.y ), vec3_angle, 255, 255, 255, 8.0f, 20.0f );
}
if ( tr.fraction < 1.0f )
{
// If we hit the ground, try to now "stand up" at that point to see if we'll fit
UTIL_TraceHull( tr.endpos, tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, NULL, COLLISION_GROUP_NONE, &tr );
// See if we're unable to stand at this space
if ( tr.startsolid )
{
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 255, 0, 0, 8.0f, 20.0f );
}
continue;
}
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 0, 255, 0, 8.0f, 20.0f );
}
}
else if ( tr.allsolid || ( ( tr.fraction == 1.0 ) && !GetDrivableVehicle()->AllowMidairExit( pPlayer, nRole ) ) )
{
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 255,0,0, 64, 10 );
}
continue;
}
// Calculate the exit endpoint & viewpoint
Vector vecExitEndPoint = tr.endpos;
// Make sure we can trace to the center of the exit point
UTIL_TraceLine( vecViewOrigin, vecExitEndPoint, MASK_PLAYERSOLID, pAnimating, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction != 1.0 )
{
#ifdef HL2_EPISODIC
// DEMEZ LOOK AT THIS NOW
//if ( ShouldVehicleIgnoreEntity( GetVehicleEnt(), tr.m_pEnt ) == false )
#endif //HL2_EPISODIC
{
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Line( vecViewOrigin, vecExitEndPoint, 255,0,0, true, 10 );
}
continue;
}
}
bBestExitIsEscapePoint = m_ExitAnimations[i].bEscapeExit;
vecBestExitPoint = vecExitEndPoint;
nBestExitAnim = i;
flMaxCosAngleDelta = flCosAngleDelta;
}
if ( nBestExitAnim >= 0 )
{
m_vecCurrentExitEndPoint = vecBestExitPoint;
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Cross3D( m_vecCurrentExitEndPoint, 16, 0, 255, 0, true, 10 );
NDebugOverlay::Box( m_vecCurrentExitEndPoint, VEC_HULL_MIN, VEC_HULL_MAX, 255,255,255, 8, 10 );
}
vecEyeExitEndpoint = vecBestExitPoint + VEC_VIEW;
m_iCurrentExitAnim = nBestExitAnim;
return pAnimating->LookupSequence( m_ExitAnimations[m_iCurrentExitAnim].szAnimName );
}
// Fail, all exit points were blocked.
bAllPointsBlocked = true;
return ACTIVITY_NOT_AVAILABLE;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::HandleEntryExitFinish( bool bExitAnimOn, bool bResetAnim )
{
// Parse the vehicle animations. This is needed because they may have
// saved, and loaded during exit anim, which would clear the exit anim.
if ( !m_bParsedAnimations )
{
// Load the entry/exit animations from the vehicle
ParseEntryExitAnims();
m_bParsedAnimations = true;
}
// Figure out which entrypoint hitbox the player is in
CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
if ( !pAnimating )
return;
// Did the entry anim just finish?
if ( bExitAnimOn )
{
// The exit animation just finished
CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
if ( pPlayer != NULL )
{
Vector vecEyes;
QAngle vecEyeAng;
if ( m_iCurrentExitAnim >= 0 && m_iCurrentExitAnim < m_ExitAnimations.Count() )
{
// Convert our offset points to worldspace ones
vecEyes = m_ExitAnimations[m_iCurrentExitAnim].vecExitPointLocal;
vecEyeAng = m_ExitAnimations[m_iCurrentExitAnim].vecExitAnglesLocal;
UTIL_ParentToWorldSpace( pAnimating, vecEyes, vecEyeAng );
// Use the endpoint we figured out when we exited
vecEyes = m_vecCurrentExitEndPoint;
}
else
{
pAnimating->GetAttachment( "vehicle_driver_eyes", vecEyes, vecEyeAng );
}
if ( g_debug_vehicleexit.GetBool() )
{
NDebugOverlay::Box( vecEyes, -Vector(2,2,2), Vector(2,2,2), 255,0,0, 64, 10.0 );
}
// If the end point isn't clear, get back in the vehicle
/*
trace_t tr;
UTIL_TraceHull( vecEyes, vecEyes, VEC_HULL_MIN, VEC_HULL_MAX, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid && tr.fraction < 1.0 )
{
pPlayer->LeaveVehicle( vecEyes, vecEyeAng );
m_pVehicle->Use( pPlayer, pPlayer, USE_TOGGLE, 1 );
return;
}
*/
pPlayer->LeaveVehicle( vecEyes, vecEyeAng );
}
}
// Only reset the animation if we're told to
if ( bResetAnim )
{
// Start the vehicle idling again
int iSequence = pAnimating->SelectWeightedSequence( ACT_IDLE );
if ( iSequence > ACTIVITY_NOT_AVAILABLE )
{
pAnimating->SetCycle( 0 );
pAnimating->m_flAnimTime = gpGlobals->curtime;
pAnimating->ResetSequence( iSequence );
pAnimating->ResetClientsideFrame();
}
}
GetDrivableVehicle()->SetVehicleEntryAnim( false );
GetDrivableVehicle()->SetVehicleExitAnim( false, vec3_origin );
}
//-----------------------------------------------------------------------------
// Purpose: Where does the passenger see from?
//-----------------------------------------------------------------------------
void CBaseServerVehicle::GetVehicleViewPosition( int nRole, Vector *pAbsOrigin, QAngle *pAbsAngles, float *pFOV /*= NULL*/ )
{
Assert( nRole == VEHICLE_ROLE_DRIVER );
CBaseCombatCharacter *pPassenger = GetPassenger( VEHICLE_ROLE_DRIVER );
Assert( pPassenger );
CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
if ( pPlayer != NULL )
{
// Call through the player to resolve the actual position (if available)
if ( pAbsOrigin != NULL )
{
*pAbsOrigin = pPlayer->EyePosition();
}
if ( pAbsAngles != NULL )
{
*pAbsAngles = pPlayer->EyeAngles();
}
if ( pFOV )
{
*pFOV = pPlayer->GetFOV();
}
}
else
{
// NPCs are not supported
Assert( 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move )
{
GetDrivableVehicle()->SetupMove( player, ucmd, pHelper, move );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMoveData )
{
GetDrivableVehicle()->ProcessMovement( pPlayer, pMoveData );
trace_t tr;
UTIL_TraceLine( pPlayer->GetAbsOrigin(), pPlayer->GetAbsOrigin() - Vector( 0, 0, 256 ), MASK_PLAYERSOLID, GetVehicleEnt(), COLLISION_GROUP_NONE, &tr );
// If our gamematerial has changed, tell any player surface triggers that are watching
IPhysicsSurfaceProps *physprops = MoveHelper()->GetSurfaceProps();
const surfacedata_t *pSurfaceProp = physprops->GetSurfaceData( tr.surface.surfaceProps );
char cCurrGameMaterial = pSurfaceProp->game.material;
// Changed?
if ( m_chPreviousTextureType != cCurrGameMaterial )
{
CEnvPlayerSurfaceTrigger::SetPlayerSurface( pPlayer, cCurrGameMaterial );
}
m_chPreviousTextureType = cCurrGameMaterial;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::FinishMove( CBasePlayer *player, CUserCmd *ucmd, CMoveData *move )
{
GetDrivableVehicle()->FinishMove( player, ucmd, move );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ItemPostFrame( CBasePlayer *player )
{
Assert( player == GetDriver() );
GetDrivableVehicle()->ItemPostFrame( player );
if ( player->m_afButtonPressed & IN_USE )
{
if ( GetDrivableVehicle()->CanExitVehicle(player) )
{
if ( !HandlePassengerExit( player ) && ( player != NULL ) )
{
player->PlayUseDenySound();
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleForward( void )
{
m_nNPCButtons |= IN_FORWARD;
m_nNPCButtons &= ~IN_BACK;
m_nNPCButtons &= ~IN_JUMP;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleReverse( void )
{
m_nNPCButtons |= IN_BACK;
m_nNPCButtons &= ~IN_FORWARD;
m_nNPCButtons &= ~IN_JUMP;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleCenter( void )
{
m_nNPCButtons &= ~IN_FORWARD;
m_nNPCButtons &= ~IN_BACK;
m_nNPCButtons &= ~IN_JUMP;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_Brake( void )
{
m_nNPCButtons &= ~IN_FORWARD;
m_nNPCButtons &= ~IN_BACK;
m_nNPCButtons |= IN_JUMP;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnLeft( float flDegrees )
{
m_nNPCButtons |= IN_MOVELEFT;
m_nNPCButtons &= ~IN_MOVERIGHT;
m_flTurnDegrees = -flDegrees;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnRight( float flDegrees )
{
m_nNPCButtons |= IN_MOVERIGHT;
m_nNPCButtons &= ~IN_MOVELEFT;
m_flTurnDegrees = flDegrees;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnCenter( void )
{
m_nNPCButtons &= ~IN_MOVERIGHT;
m_nNPCButtons &= ~IN_MOVELEFT;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_PrimaryFire( void )
{
m_nNPCButtons |= IN_ATTACK;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_SecondaryFire( void )
{
m_nNPCButtons |= IN_ATTACK2;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Weapon_PrimaryRanges( float *flMinRange, float *flMaxRange )
{
*flMinRange = 64;
*flMaxRange = 1024;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Weapon_SecondaryRanges( float *flMinRange, float *flMaxRange )
{
*flMinRange = 64;
*flMaxRange = 1024;
}
//-----------------------------------------------------------------------------
// Purpose: Return the time at which this vehicle's primary weapon can fire again
//-----------------------------------------------------------------------------
float CBaseServerVehicle::Weapon_PrimaryCanFireAt( void )
{
return gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose: Return the time at which this vehicle's secondary weapon can fire again
//-----------------------------------------------------------------------------
float CBaseServerVehicle::Weapon_SecondaryCanFireAt( void )
{
return gpGlobals->curtime;
}
const char *pSoundStateNames[] =
{
"SS_NONE",
"SS_SHUTDOWN",
"SS_SHUTDOWN_WATER",
"SS_START_WATER",
"SS_START_IDLE",
"SS_IDLE",
"SS_GEAR_0",
"SS_GEAR_1",
"SS_GEAR_2",
"SS_GEAR_3",
"SS_GEAR_4",
"SS_SLOWDOWN",
"SS_SLOWDOWN_HIGHSPEED",
"SS_GEAR_0_RESUME",
"SS_GEAR_1_RESUME",
"SS_GEAR_2_RESUME",
"SS_GEAR_3_RESUME",
"SS_GEAR_4_RESUME",
"SS_TURBO",
"SS_REVERSE",
};
static int SoundStateIndexFromName( const char *pName )
{
for ( int i = 0; i < SS_NUM_STATES; i++ )
{
Assert( i < ARRAYSIZE(pSoundStateNames) );
if ( !strcmpi( pSoundStateNames[i], pName ) )
return i;
}
return -1;
}
static const char *SoundStateNameFromIndex( int index )
{
index = clamp(index, 0, SS_NUM_STATES-1 );
return pSoundStateNames[index];
}
void CBaseServerVehicle::PlaySound( const char *pSound )
{
if ( !pSound || !pSound[0] )
return;
if ( g_debug_vehiclesound.GetInt() )
{
Msg("Playing non-looping vehicle sound: %s\n", pSound );
}
m_pVehicle->EmitSound( pSound );
}
void CBaseServerVehicle::StopLoopingSound( float fadeTime )
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
if ( m_pStateSoundFade )
{
controller.SoundDestroy( m_pStateSoundFade );
m_pStateSoundFade = NULL;
}
if ( m_pStateSound )
{
m_pStateSoundFade = m_pStateSound;
m_pStateSound = NULL;
controller.SoundFadeOut( m_pStateSoundFade, fadeTime, false );
}
}
void CBaseServerVehicle::PlayLoopingSound( const char *pSoundName )
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
CPASAttenuationFilter filter( m_pVehicle );
CSoundPatch *pNewSound = NULL;
if ( pSoundName && pSoundName[0] )
{
pNewSound = controller.SoundCreate( filter, m_pVehicle->entindex(), CHAN_STATIC, pSoundName, ATTN_NORM );
}
if ( m_pStateSound && pNewSound && controller.SoundGetName( pNewSound ) == controller.SoundGetName( m_pStateSound ) )
{
// if the sound is the same, don't play this, just re-use the old one
controller.SoundDestroy( pNewSound );
pNewSound = m_pStateSound;
controller.SoundChangeVolume( pNewSound, 1.0f, 0.0f );
m_pStateSound = NULL;
}
else if ( g_debug_vehiclesound.GetInt() )
{
const char *pStopSound = m_pStateSound ? controller.SoundGetName( m_pStateSound ).ToCStr() : "NULL";
const char *pStartSound = pNewSound ? controller.SoundGetName( pNewSound ).ToCStr() : "NULL";
Msg("Stop %s, start %s\n", pStopSound, pStartSound );
}
StopLoopingSound();
m_pStateSound = pNewSound;
if ( m_pStateSound )
{
controller.Play( m_pStateSound, 1.0f, 100 );
}
}
static sound_states MapGearToState( vbs_sound_update_t ¶ms, int gear )
{
switch( gear )
{
case 0: return params.bReverse ? SS_REVERSE : SS_GEAR_0;
case 1: return SS_GEAR_1;
case 2: return SS_GEAR_2;
case 3: return SS_GEAR_3;
default:case 4: return SS_GEAR_4;
}
}
static sound_states MapGearToMidState( vbs_sound_update_t ¶ms, int gear )
{
switch( gear )
{
case 0: return params.bReverse ? SS_REVERSE : SS_GEAR_0_RESUME;
case 1: return SS_GEAR_1_RESUME;
case 2: return SS_GEAR_2_RESUME;
case 3: return SS_GEAR_3_RESUME;
default:case 4: return SS_GEAR_4_RESUME;
}
}
bool CBaseServerVehicle::PlayCrashSound( float speed )
{
int i;
float delta = 0;
float absSpeed = fabs(speed);
float absLastSpeed = fabs(m_lastSpeed);
if ( absLastSpeed > absSpeed )
{
delta = fabs(m_lastSpeed - speed);
}
float rumble = delta / 8.0f;
if( rumble > 60.0f )
rumble = 60.0f;
if( rumble > 5.0f )
{
if ( GetDriver() )
{
UTIL_ScreenShake( GetDriver()->GetAbsOrigin(), rumble, 150.0f, 1.0f, 240.0f, SHAKE_START_RUMBLEONLY, true );
}
}
for ( i = 0; i < m_vehicleSounds.crashSounds.Count(); i++ )
{
const vehicle_crashsound_t &crash = m_vehicleSounds.crashSounds[i];
if ( !crash.gearLimit )
continue;
if ( m_iSoundGear <= crash.gearLimit )
{
if ( delta > crash.flMinDeltaSpeed && absLastSpeed > crash.flMinSpeed )
{
PlaySound( crash.iszCrashSound.ToCStr() );
return true;
}
}
}
for ( i = m_vehicleSounds.crashSounds.Count()-1; i >= 0; --i )
{
const vehicle_crashsound_t &crash = m_vehicleSounds.crashSounds[i];
if ( delta > crash.flMinDeltaSpeed && absLastSpeed > crash.flMinSpeed )
{
PlaySound( crash.iszCrashSound.ToCStr() );
return true;
}
}
return false;
}
bool CBaseServerVehicle::CheckCrash( vbs_sound_update_t ¶ms )
{
if ( params.bVehicleInWater )
return false;
bool bCrashed = PlayCrashSound( params.flWorldSpaceSpeed );
if ( bCrashed )
{
if ( g_debug_vehiclesound.GetInt() )
{
Msg("Crashed!: speed %.2f, lastSpeed %.2f\n", params.flWorldSpaceSpeed, m_lastSpeed );
}
}
m_lastSpeed = params.flWorldSpaceSpeed;
return bCrashed;
}
sound_states CBaseServerVehicle::SoundState_ChooseState( vbs_sound_update_t ¶ms )
{
float timeInState = gpGlobals->curtime - m_soundStateStartTime;
bool bInStateForMinTime = timeInState > m_vehicleSounds.minStateTime[m_soundState] ? true : false;
sound_states stateOut = m_soundState;
// exit overrides everything else
if ( params.bExitVehicle )
{
switch ( m_soundState )
{
case SS_NONE:
case SS_SHUTDOWN:
case SS_SHUTDOWN_WATER:
return m_soundState;
}
return SS_SHUTDOWN;
}
// check global state in states that don't mask them
switch( m_soundState )
{
// global states masked for these states.
case SS_NONE:
case SS_START_IDLE:
case SS_SHUTDOWN:
break;
case SS_START_WATER:
case SS_SHUTDOWN_WATER:
if ( !params.bVehicleInWater )
return SS_START_IDLE;
break;
case SS_TURBO:
if ( params.bVehicleInWater )
return SS_SHUTDOWN_WATER;
if ( CheckCrash(params) )
return SS_IDLE;
break;
case SS_IDLE:
if ( params.bVehicleInWater )
return SS_SHUTDOWN_WATER;
break;
case SS_REVERSE:
case SS_GEAR_0:
case SS_GEAR_1:
case SS_GEAR_2:
case SS_GEAR_3:
case SS_GEAR_4:
case SS_SLOWDOWN:
case SS_SLOWDOWN_HIGHSPEED:
case SS_GEAR_0_RESUME:
case SS_GEAR_1_RESUME:
case SS_GEAR_2_RESUME:
case SS_GEAR_3_RESUME:
case SS_GEAR_4_RESUME:
if ( params.bVehicleInWater )
{
return SS_SHUTDOWN_WATER;
}
if ( params.bTurbo )
{
return SS_TURBO;
}
if ( CheckCrash(params) )
return SS_IDLE;
break;
}
switch( m_soundState )
{
case SS_START_IDLE:
if ( bInStateForMinTime || params.bThrottleDown )
return SS_IDLE;
break;
case SS_IDLE:
if ( bInStateForMinTime && params.bThrottleDown )
{
if ( params.bTurbo )
return SS_TURBO;
return params.bReverse ? SS_REVERSE : SS_GEAR_0;
}
break;
case SS_GEAR_0_RESUME:
case SS_GEAR_0:
if ( (bInStateForMinTime && !params.bThrottleDown) || params.bReverse )
{
return SS_IDLE;
}
if ( m_iSoundGear > 0 )
{
return SS_GEAR_1;
}
break;
case SS_GEAR_1_RESUME:
case SS_GEAR_1:
if ( bInStateForMinTime )
{
if ( !params.bThrottleDown )
return SS_SLOWDOWN;
}
if ( m_iSoundGear != 1 )
return MapGearToState( params, m_iSoundGear);
break;
case SS_GEAR_2_RESUME:
case SS_GEAR_2:
if ( bInStateForMinTime )
{
if ( !params.bThrottleDown )
return SS_SLOWDOWN;
else if ( m_iSoundGear != 2 )
return MapGearToState(params, m_iSoundGear);
}
break;
case SS_GEAR_3_RESUME:
case SS_GEAR_3:
if ( bInStateForMinTime )
{
if ( !params.bThrottleDown )
return SS_SLOWDOWN;
else if ( m_iSoundGear != 3 )
return MapGearToState(params, m_iSoundGear);
}
break;
case SS_GEAR_4_RESUME:
case SS_GEAR_4:
if ( bInStateForMinTime && !params.bThrottleDown )
{
return SS_SLOWDOWN;
}
if ( m_iSoundGear != 4 )
{
return MapGearToMidState(params, m_iSoundGear);
}
break;
case SS_REVERSE:
if ( bInStateForMinTime && !params.bReverse )
{
return SS_SLOWDOWN;
}
break;
case SS_SLOWDOWN_HIGHSPEED:
case SS_SLOWDOWN:
if ( params.bThrottleDown )
{
// map gears
return MapGearToMidState(params, m_iSoundGear);
}
if ( m_iSoundGear == 0 )
{
return SS_IDLE;
}
break;
case SS_NONE:
stateOut = params.bVehicleInWater ? SS_START_WATER : SS_START_IDLE;
break;
case SS_TURBO:
if ( bInStateForMinTime && !params.bTurbo )
{
return MapGearToMidState(params, m_iSoundGear);
}
break;
default:
break;
}
return stateOut;
}
const char *CBaseServerVehicle::StateSoundName( sound_states state )
{
return m_vehicleSounds.iszStateSounds[state].ToCStr();
}
void CBaseServerVehicle::SoundState_OnNewState( sound_states lastState )
{
if ( g_debug_vehiclesound.GetInt() )
{
int index = m_soundState;
Msg("Switched to state: %d (%s)\n", m_soundState, SoundStateNameFromIndex(index) );
}
switch ( m_soundState )
{
case SS_SHUTDOWN:
case SS_SHUTDOWN_WATER:
case SS_START_WATER:
StopLoopingSound();
PlaySound( StateSoundName(m_soundState) );
break;
case SS_IDLE:
m_lastSpeed = -1;
PlayLoopingSound( StateSoundName(m_soundState) );
break;
case SS_START_IDLE:
case SS_REVERSE:
case SS_GEAR_0:
case SS_GEAR_0_RESUME:
case SS_GEAR_1:
case SS_GEAR_1_RESUME:
case SS_GEAR_2:
case SS_GEAR_2_RESUME:
case SS_GEAR_3:
case SS_GEAR_3_RESUME:
case SS_GEAR_4:
case SS_GEAR_4_RESUME:
case SS_TURBO:
PlayLoopingSound( StateSoundName(m_soundState) );
break;
case SS_SLOWDOWN_HIGHSPEED:
case SS_SLOWDOWN:
if ( m_iSoundGear < 2 )
{
PlayLoopingSound( StateSoundName( SS_SLOWDOWN ) );
}
else
{
PlayLoopingSound( StateSoundName( SS_SLOWDOWN_HIGHSPEED ) );
}
break;
default:break;
}
m_soundStateStartTime = gpGlobals->curtime;
}
void CBaseServerVehicle::SoundState_Update( vbs_sound_update_t ¶ms )
{
sound_states newState = SoundState_ChooseState( params );
if ( newState != m_soundState )
{
sound_states lastState = m_soundState;
m_soundState = newState;
SoundState_OnNewState( lastState );
}
switch( m_soundState )
{
case SS_SHUTDOWN:
case SS_SHUTDOWN_WATER:
case SS_START_WATER:
case SS_START_IDLE:
case SS_IDLE:
case SS_REVERSE:
case SS_GEAR_0:
case SS_GEAR_4:
case SS_SLOWDOWN_HIGHSPEED:
case SS_SLOWDOWN:
case SS_GEAR_0_RESUME:
case SS_GEAR_4_RESUME:
break;
default:break;
}
}
void CBaseServerVehicle::InitSoundParams( vbs_sound_update_t ¶ms )
{
params.Defaults();
params.bVehicleInWater = IsVehicleBodyInWater();
}
//-----------------------------------------------------------------------------
// Purpose: Vehicle Sound Start
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundStart()
{
StartEngineRumble();
m_soundState = SS_NONE;
vbs_sound_update_t params;
InitSoundParams(params);
SoundState_Update( params );
}
// vehicle is starting up disabled, but in some cases you still want to play a sound
// HACK: handle those here.
void CBaseServerVehicle::SoundStartDisabled()
{
m_soundState = SS_NONE;
vbs_sound_update_t params;
InitSoundParams(params);
sound_states newState = SoundState_ChooseState( params );
switch( newState )
{
case SS_START_WATER:
PlaySound( StateSoundName(newState) );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundShutdown( float flFadeTime )
{
StopEngineRumble();
// Stop any looping sounds that may be running, as the following stop sound may not exist
// and thus leave a looping sound playing after the user gets out.
for ( int i = 0; i < NUM_SOUNDS_TO_STOP_ON_EXIT; i++ )
{
StopSound( g_iSoundsToStopOnExit[i] );
}
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
if ( m_pStateSoundFade )
{
controller.SoundFadeOut( m_pStateSoundFade, flFadeTime, true );
m_pStateSoundFade = NULL;
}
if ( m_pStateSound )
{
controller.SoundFadeOut( m_pStateSound, flFadeTime, true );
m_pStateSound = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundUpdate( vbs_sound_update_t ¶ms )
{
if ( g_debug_vehiclesound.GetInt() > 1 )
{
Msg("Throttle: %s, Reverse: %s\n", params.bThrottleDown?"on":"off", params.bReverse?"on":"off" );
}
float flCurrentSpeed = params.flCurrentSpeedFraction;
if ( g_debug_vehiclesound.GetInt() > 1 )
{
Msg("CurrentSpeed: %.3f ", flCurrentSpeed );
}
// Figure out our speed for the purposes of sound playing.
// We slow the transition down a little to make the gear changes slower.
if ( m_vehicleSounds.pGears.Count() > 0 )
{
if ( flCurrentSpeed > m_flSpeedPercentage )
{
// don't accelerate when the throttle isn't down
if ( !params.bThrottleDown )
{
flCurrentSpeed = m_flSpeedPercentage;
}
flCurrentSpeed = Approach( flCurrentSpeed, m_flSpeedPercentage, params.flFrameTime * m_vehicleSounds.pGears[m_iSoundGear].flSpeedApproachFactor );
}
}
m_flSpeedPercentage = clamp( flCurrentSpeed, 0.0f, 1.0f );
if ( g_debug_vehiclesound.GetInt() > 1 )
{
Msg("Sound Speed: %.3f\n", m_flSpeedPercentage );
}
// Only do gear changes when the throttle's down
RecalculateSoundGear( params );
SoundState_Update( params );
}
//-----------------------------------------------------------------------------
// Purpose: Play a non-gear based vehicle sound
//-----------------------------------------------------------------------------
void CBaseServerVehicle::PlaySound( vehiclesound iSound )
{
if ( m_vehicleSounds.iszSound[iSound] != NULL_STRING )
{
CPASAttenuationFilter filter( m_pVehicle );
EmitSound_t ep;
ep.m_nChannel = CHAN_VOICE;
ep.m_pSoundName = STRING(m_vehicleSounds.iszSound[iSound]);
ep.m_flVolume = m_flVehicleVolume;
ep.m_SoundLevel = SNDLVL_NORM;
CBaseEntity::EmitSound( filter, m_pVehicle->entindex(), ep );
if ( g_debug_vehiclesound.GetInt() )
{
Msg("Playing vehicle sound: %s\n", ep.m_pSoundName );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Stop a non-gear based vehicle sound
//-----------------------------------------------------------------------------
void CBaseServerVehicle::StopSound( vehiclesound iSound )
{
if ( m_vehicleSounds.iszSound[iSound] != NULL_STRING )
{
CBaseEntity::StopSound( m_pVehicle->entindex(), CHAN_VOICE, STRING(m_vehicleSounds.iszSound[iSound]) );
}
}
//-----------------------------------------------------------------------------
// Purpose: Calculate the gear we should be in based upon the vehicle's current speed
//-----------------------------------------------------------------------------
void CBaseServerVehicle::RecalculateSoundGear( vbs_sound_update_t ¶ms )
{
int iNumGears = m_vehicleSounds.pGears.Count();
for ( int i = (iNumGears-1); i >= 0; i-- )
{
if ( m_flSpeedPercentage > m_vehicleSounds.pGears[i].flMinSpeed )
{
m_iSoundGear = i;
break;
}
}
// If we're going in reverse, we want to stay in first gear
if ( params.bReverse )
{
m_iSoundGear = 0;
}
}
//---------------------------------------------------------
//---------------------------------------------------------
void CBaseServerVehicle::StartEngineRumble()
{
return;
}
//---------------------------------------------------------
//---------------------------------------------------------
void CBaseServerVehicle::StopEngineRumble()
{
return;
}
//-----------------------------------------------------------------------------
// Purpose: Find the passenger in the given seat of the vehicle
// Input : nSeatID - seat ID to check
// Output : CBaseCombatCharacter - character in the seat
//-----------------------------------------------------------------------------
CBaseCombatCharacter *CBaseServerVehicle::NPC_GetPassengerInSeat( int nRoleID, int nSeatID )
{
// Search all passengers in the vehicle
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
// If the seat ID matches, return the entity in that seat
if ( m_PassengerInfo[i].GetSeat() == nSeatID && m_PassengerInfo[i].GetRole() == nRoleID )
return m_PassengerInfo[i].m_hPassenger;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Find the first available seat (ranked by priority)
// Input : nRoleID - Role index
// Output : int - Seat by index
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat_Any( CBaseCombatCharacter *pPassenger, int nRoleID )
{
// Look through all available seats
for ( int i = 0; i < m_PassengerRoles[nRoleID].m_PassengerSeats.Count(); i++ )
{
// See if anyone is already in this seat
CBaseCombatCharacter *pCurrentPassenger = NPC_GetPassengerInSeat( nRoleID, i );
if ( pCurrentPassenger != NULL && pCurrentPassenger != pPassenger )
continue;
// This seat is open
return i;
}
// Nothing found
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Find the seat with the nearest entry point to the querier
// Input : *pPassenger - Terget to be nearest to
// nRoleID - Role index
// Output : int - Seat by index
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat_Nearest( CBaseCombatCharacter *pPassenger, int nRoleID )
{
// Not yet implemented
Assert( 0 );
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Get a seat in the vehicle based on our role and criteria
// Input : *pPassenger - Entity attempting to find a seat
// strRoleName - Role the seat must serve
// nQueryType - Method for choosing the best seat (if multiple)
// Output : int - Seat by unique ID
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat( CBaseCombatCharacter *pPassenger, string_t strRoleName, VehicleSeatQuery_e nQueryType )
{
// Parse the vehicle animations the first time they get in the vehicle
if ( m_bParsedAnimations == false )
{
// Load the entry/exit animations from the vehicle
ParseEntryExitAnims();
m_bParsedAnimations = true;
}
// Get the role index
int nRole = FindRoleIndexByName( strRoleName );
if ( m_PassengerRoles.IsValidIndex( nRole ) == false )
return -1;
switch( nQueryType )
{
case VEHICLE_SEAT_ANY:
return NPC_GetAvailableSeat_Any( pPassenger, nRole );
break;
case VEHICLE_SEAT_NEAREST:
return NPC_GetAvailableSeat_Nearest( pPassenger, nRole );
break;
default:
Assert( 0 );
break;
};
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Determine if there's an available seat of a given role name
// Input : strRoleName - name of the role
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_HasAvailableSeat( string_t strRoleName )
{
return ( NPC_GetAvailableSeat( NULL, strRoleName, VEHICLE_SEAT_ANY ) != -1 );
}
//-----------------------------------------------------------------------------
// Purpose: Find a role index by name
// Input : strRoleName - name of the role
//-----------------------------------------------------------------------------
int CBaseServerVehicle::FindRoleIndexByName( string_t strRoleName )
{
// Search through all our known roles
for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
{
// Return the index if the name matches
if ( FStrEq( STRING( m_PassengerRoles[i].GetName() ), STRING( strRoleName ) ) )
return i;
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Find a seat index by its name
// Input : strSeatName - name of the seat
//-----------------------------------------------------------------------------
int CBaseServerVehicle::FindSeatIndexByName( int nRoleIndex, string_t strSeatName )
{
// Role must be valid
if ( m_PassengerRoles.IsValidIndex( nRoleIndex ) == false )
return -1;
// Used for attachment polling
CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(GetVehicleEnt());
if ( pAnimating == NULL )
return -1;
// Get the index of the named attachment in the model
int nAttachmentID = pAnimating->LookupAttachment( STRING( strSeatName ) );
// Look through the roles for this seat attachment ID
for ( int i = 0; i < m_PassengerRoles[nRoleIndex].m_PassengerSeats.Count(); i++ )
{
// Return that index if found
if ( m_PassengerRoles[nRoleIndex].m_PassengerSeats[i].GetAttachmentID() == nAttachmentID )
return i;
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Called after loading a saved game
//-----------------------------------------------------------------------------
void CBaseServerVehicle::RestorePassengerInfo( void )
{
// If there is passenger information, then we have passengers in the vehicle
if ( m_PassengerInfo.Count() != 0 && m_bParsedAnimations == false )
{
// Load the entry/exit animations from the vehicle
ParseEntryExitAnims();
m_bParsedAnimations = true;
}
// FIXME: If a passenger cannot fix-up its indices, it must be removed from the vehicle!
// Fix-up every passenger with updated indices
for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
{
// Fix up the role first
int nRoleIndex = FindRoleIndexByName( m_PassengerInfo[i].m_strRoleName );
if ( m_PassengerRoles.IsValidIndex( nRoleIndex ) )
{
// New role index
m_PassengerInfo[i].m_nRole = nRoleIndex;
// Then fix up the seat via attachment name
int nSeatIndex = FindSeatIndexByName( nRoleIndex, m_PassengerInfo[i].m_strSeatName );
if ( m_PassengerRoles[nRoleIndex].m_PassengerSeats.IsValidIndex( nSeatIndex ) )
{
// New seat index
m_PassengerInfo[i].m_nSeat = nSeatIndex;
}
else
{
// The seat attachment was not found. This most likely means that the seat attachment name has changed
// in the target vehicle and the NPC passenger is now stranded!
Assert( 0 );
}
}
else
{
// The role was not found. This most likely means that the role names have changed
// in the target vehicle and the NPC passenger is now stranded!
Assert( 0 );
}
}
}
void CBaseServerVehicle::ReloadScript()
{
if ( m_pDrivableVehicle )
{
string_t script = m_pDrivableVehicle->GetVehicleScriptName();
IPhysicsVehicleController *pController = GetVehicleController();
vehicleparams_t *pVehicleParams = pController ? &(pController->GetVehicleParamsForChange()) : NULL;
PhysFindOrAddVehicleScript( script.ToCStr(), pVehicleParams, &m_vehicleSounds );
if ( pController )
{
pController->VehicleDataReload();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Passes this call down into the server vehicle where the tests are done
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::PassengerShouldReceiveDamage( CTakeDamageInfo &info )
{
if ( GetDrivableVehicle() )
return GetDrivableVehicle()->PassengerShouldReceiveDamage( info );
return true;
}
//===========================================================================================================
// Vehicle Sounds
//===========================================================================================================
// These are sounds that are to be automatically stopped whenever the vehicle's driver leaves it
vehiclesound g_iSoundsToStopOnExit[] =
{
VS_ENGINE2_START,
VS_ENGINE2_STOP,
};
char *vehiclesound_parsenames[VS_NUM_SOUNDS] =
{
"skid_lowfriction",
"skid_normalfriction",
"skid_highfriction",
"engine2_start",
"engine2_stop",
"misc1",
"misc2",
"misc3",
"misc4",
};
CVehicleSoundsParser::CVehicleSoundsParser( void )
{
// UNDONE: Revisit this pattern - move sub-block processing ideas into the parser architecture
m_iCurrentGear = -1;
m_iCurrentState = -1;
m_iCurrentCrashSound = -1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVehicleSoundsParser::ParseKeyValue( void *pData, const char *pKey, const char *pValue )
{
vehiclesounds_t *pSounds = (vehiclesounds_t *)pData;
// New gear?
if ( !strcmpi( pKey, "gear" ) )
{
// Create, initialize, and add a new gear to our list
int iNewGear = pSounds->pGears.AddToTail();
pSounds->pGears[iNewGear].flMaxSpeed = 0;
pSounds->pGears[iNewGear].flSpeedApproachFactor = 1.0;
// Set our min speed to the previous gear's max
if ( iNewGear == 0 )
{
// First gear, so our minspeed is 0
pSounds->pGears[iNewGear].flMinSpeed = 0;
}
else
{
pSounds->pGears[iNewGear].flMinSpeed = pSounds->pGears[iNewGear-1].flMaxSpeed;
}
// Remember which gear we're reading data from
m_iCurrentGear = iNewGear;
}
else if ( !strcmpi( pKey, "state" ) )
{
m_iCurrentState = 0;
}
else if ( !strcmpi( pKey, "crashsound" ) )
{
m_iCurrentCrashSound = pSounds->crashSounds.AddToTail();
pSounds->crashSounds[m_iCurrentCrashSound].flMinSpeed = 0;
pSounds->crashSounds[m_iCurrentCrashSound].flMinDeltaSpeed = 0;
pSounds->crashSounds[m_iCurrentCrashSound].iszCrashSound = NULL_STRING;
}
else
{
int i;
// Are we currently in a gear block?
if ( m_iCurrentGear >= 0 )
{
Assert( m_iCurrentGear < pSounds->pGears.Count() );
// Check gear keys
if ( !strcmpi( pKey, "max_speed" ) )
{
pSounds->pGears[m_iCurrentGear].flMaxSpeed = atof(pValue);
return;
}
if ( !strcmpi( pKey, "speed_approach_factor" ) )
{
pSounds->pGears[m_iCurrentGear].flSpeedApproachFactor = atof(pValue);
return;
}
}
// We're done reading a gear, so stop checking them.
m_iCurrentGear = -1;
if ( m_iCurrentState >= 0 )
{
if ( !strcmpi( pKey, "name" ) )
{
m_iCurrentState = SoundStateIndexFromName( pValue );
pSounds->iszStateSounds[m_iCurrentState] = NULL_STRING;
pSounds->minStateTime[m_iCurrentState] = 0.0f;
return;
}
else if ( !strcmpi( pKey, "sound" ) )
{
pSounds->iszStateSounds[m_iCurrentState] = AllocPooledString(pValue);
return;
}
else if ( !strcmpi( pKey, "min_time" ) )
{
pSounds->minStateTime[m_iCurrentState] = atof(pValue);
return;
}
}
//
m_iCurrentState = -1;
if ( m_iCurrentCrashSound >= 0 )
{
if ( !strcmpi( pKey, "min_speed" ) )
{
pSounds->crashSounds[m_iCurrentCrashSound].flMinSpeed = atof(pValue);
return;
}
else if ( !strcmpi( pKey, "sound" ) )
{
pSounds->crashSounds[m_iCurrentCrashSound].iszCrashSound = AllocPooledString(pValue);
return;
}
else if ( !strcmpi( pKey, "min_speed_change" ) )
{
pSounds->crashSounds[m_iCurrentCrashSound].flMinDeltaSpeed = atof(pValue);
return;
}
else if ( !strcmpi( pKey, "gear_limit" ) )
{
pSounds->crashSounds[m_iCurrentCrashSound].gearLimit = atoi(pValue);
return;
}
}
m_iCurrentCrashSound = -1;
for ( i = 0; i < VS_NUM_SOUNDS; i++ )
{
if ( !strcmpi( pKey, vehiclesound_parsenames[i] ) )
{
pSounds->iszSound[i] = AllocPooledString(pValue);
return;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVehicleSoundsParser::SetDefaults( void *pData )
{
vehiclesounds_t *pSounds = (vehiclesounds_t *)pData;
pSounds->Init();
}
| [
"demizexp@gmail.com"
] | demizexp@gmail.com |
8a9cdb99278c900c1051e73ac1956f06b8b5ea97 | cbcc01c6ac83c12ee1283122685c8aa59d7f2469 | /MAGE/MAGE/src/model/model.cpp | 2bbe6256322c3ef089a040236bbb084c445d3185 | [] | no_license | sienaiwun/MAGE | ece6ff3072f1d2d89c3fa8abd223700e3d11fda1 | e3fda321f08e4c69d416bfd1aa0414cfab63490b | refs/heads/master | 2021-01-01T05:53:46.678567 | 2017-07-02T18:24:30 | 2017-07-02T18:24:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | //-----------------------------------------------------------------------------
// Engine Includes
//-----------------------------------------------------------------------------
#pragma region
#include "model\model.hpp"
#pragma endregion
//-----------------------------------------------------------------------------
// Engine Definitions
//-----------------------------------------------------------------------------
namespace mage {
Model::Model(SharedPtr< const Mesh > mesh, size_t start_index, size_t nb_indices,
const AABB &aabb, const BS &bs, const ShadedMaterial &material)
: m_mesh(mesh), m_start_index(start_index), m_nb_indices(nb_indices),
m_aabb(aabb), m_bs(bs), m_material(std::make_unique< ShadedMaterial >(material)) {}
Model::Model(const Model &model)
: m_mesh(model.m_mesh), m_start_index(model.m_start_index), m_nb_indices(model.m_nb_indices),
m_material(std::make_unique< ShadedMaterial >(*model.m_material)) {}
Model::Model(Model &&model) = default;
Model::~Model() = default;
UniquePtr< Model > Model::CloneImplementation() const {
return std::make_unique< Model >(*this);
}
} | [
"matthias.moulin@gmail.com"
] | matthias.moulin@gmail.com |
4b973ca36d6178f090afac629ac1500076d8f80d | da7a86697bf357a2389b776ea1c18ae5c36ba75b | /source/StandardDragDropHandler.cpp | 6073566cc57e0e1bf4a5c63648a41e06e4a95cfd | [
"BSD-3-Clause"
] | permissive | Vistaus/gpick | c99bd993907edb1963ef525fa7402b561a570ea2 | 0e858d33fd28d98d2689d0ebb92c975729a9f7bc | refs/heads/master | 2023-04-25T16:35:49.363198 | 2021-05-28T17:31:13 | 2021-05-29T05:58:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,428 | cpp | /*
* Copyright (c) 2009-2020, Albertas Vyšniauskas
* 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 the software author 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 "StandardDragDropHandler.h"
#include "GlobalState.h"
#include "ColorObject.h"
#include "Converter.h"
#include "dynv/Map.h"
#include "IDroppableColorUI.h"
#include "gtk/ColorWidget.h"
#include <sstream>
struct State {
GlobalState &gs;
Converters::Type converterType;
std::vector<ColorObject> colorObjects;
GtkWidget *dragWidget;
bool supportsMove;
State(GlobalState &gs, Converters::Type converterType, bool supportsMove):
gs(gs),
converterType(converterType),
dragWidget(nullptr),
supportsMove(supportsMove) {
}
};
enum class Target : guint {
string = 1,
color,
colorObjectList,
serializedColorObjectList,
};
static GtkTargetEntry targets[] = {
{ const_cast<gchar *>("color-object-list"), GTK_TARGET_SAME_APP, static_cast<guint>(Target::colorObjectList) },
{ const_cast<gchar *>("application/x-color_object-list"), GTK_TARGET_OTHER_APP, static_cast<guint>(Target::serializedColorObjectList) },
{ const_cast<gchar *>("application/x-color-object-list"), GTK_TARGET_OTHER_APP, static_cast<guint>(Target::serializedColorObjectList) },
{ const_cast<gchar *>("application/x-color"), 0, static_cast<guint>(Target::color) },
{ const_cast<gchar *>("text/plain"), 0, static_cast<guint>(Target::string) },
{ const_cast<gchar *>("UTF8_STRING"), 0, static_cast<guint>(Target::string) },
{ const_cast<gchar *>("STRING"), 0, static_cast<guint>(Target::string) },
};
static const size_t targetCount = sizeof(targets) / sizeof(GtkTargetEntry);
struct ColorObjectList {
std::vector<ColorObject> *colorObjects;
};
static bool setColor(ColorObject &colorObject, IReadonlyColorUI *readonlyColorUI, int x, int y) {
auto *droppableColorUI = dynamic_cast<IDroppableColorUI*>(readonlyColorUI);
if (droppableColorUI) {
droppableColorUI->setColorAt(colorObject, x, y);
return true;
}
auto *editableColorUI = dynamic_cast<IEditableColorUI*>(readonlyColorUI);
if (editableColorUI) {
editableColorUI->setColor(colorObject);
return true;
}
return false;
}
static bool setColors(std::vector<ColorObject> &colorObjects, IReadonlyColorUI *readonlyColorUI, int x, int y) {
if (colorObjects.size() == 0)
return false;
if (colorObjects.size() == 1) {
auto *droppableColorUI = dynamic_cast<IDroppableColorUI*>(readonlyColorUI);
if (droppableColorUI) {
droppableColorUI->setColorAt(colorObjects[0], x, y);
return true;
}
auto *editableColorUI = dynamic_cast<IEditableColorUI*>(readonlyColorUI);
if (editableColorUI) {
editableColorUI->setColor(colorObjects[0]);
return true;
}
return false;
}
auto *droppableColorsUI = dynamic_cast<IDroppableColorsUI*>(readonlyColorUI);
if (droppableColorsUI) {
droppableColorsUI->setColorsAt(colorObjects, x, y);
return true;
}
auto *droppableColorUI = dynamic_cast<IDroppableColorUI*>(readonlyColorUI);
if (droppableColorUI) {
droppableColorUI->setColorAt(colorObjects[0], x, y);
return true;
}
auto *editableColorsUI = dynamic_cast<IEditableColorsUI*>(readonlyColorUI);
if (editableColorsUI) {
editableColorsUI->setColors(colorObjects);
return true;
}
auto *editableColorUI = dynamic_cast<IEditableColorUI*>(readonlyColorUI);
if (editableColorUI) {
editableColorUI->setColor(colorObjects[0]);
return true;
}
return false;
}
static void onDragDataReceived(GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selectionData, Target targetType, guint time, IReadonlyColorUI *readonlyColorUI) {
if ((selectionData == nullptr) || (gtk_selection_data_get_length(selectionData) == 0)) {
gtk_drag_finish(context, false, gdk_drag_context_get_actions(context) == GDK_ACTION_MOVE, time);
return;
}
auto &state = *reinterpret_cast<State *>(g_object_get_data(G_OBJECT(widget), "dragDropState"));
bool success = false;
switch (targetType) {
case Target::colorObjectList: {
auto *dataPointer = gtk_selection_data_get_data(selectionData);
if (!dataPointer)
break;
const auto &data = *reinterpret_cast<const ColorObjectList *>(dataPointer);
success = setColors(*data.colorObjects, readonlyColorUI, x, y);
} break;
case Target::serializedColorObjectList: {
auto data = gtk_selection_data_get_data(selectionData);
auto text = std::string(reinterpret_cast<const char *>(data), reinterpret_cast<const char *>(data) + gtk_selection_data_get_length(selectionData));
std::stringstream textStream(text);
dynv::Map values;
if (!values.deserializeXml(textStream))
break;
auto colors = values.getMaps("colors");
if (colors.size() == 0)
break;
static Color defaultColor = {};
std::vector<ColorObject> colorObjects;
colorObjects.reserve(colors.size());
for (size_t i = 0; i < colors.size(); i++) {
colorObjects.emplace_back(colors[i]->getString("name", ""), colors[i]->getColor("color", defaultColor));
}
success = setColors(colorObjects, readonlyColorUI, x, y);
} break;
case Target::string: {
gchar *data = (gchar *)gtk_selection_data_get_data(selectionData);
ColorObject colorObject;
if (!state.gs.converters().deserialize(std::string(data, data + gtk_selection_data_get_length(selectionData)), colorObject)) {
gtk_drag_finish(context, false, false, time);
return;
}
success = setColor(colorObject, readonlyColorUI, x, y);
} break;
case Target::color: {
guint16 *data = (guint16 *)gtk_selection_data_get_data(selectionData);
Color color;
color.rgb.red = static_cast<float>(data[0] / static_cast<double>(0xFFFF));
color.rgb.green = static_cast<float>(data[1] / static_cast<double>(0xFFFF));
color.rgb.blue = static_cast<float>(data[2] / static_cast<double>(0xFFFF));
color[3] = 0;
ColorObject colorObject("", color);
success = setColor(colorObject, readonlyColorUI, x, y);
} break;
}
gtk_drag_finish(context, success, gdk_drag_context_get_actions(context) == GDK_ACTION_MOVE, time);
}
static gboolean onDragMotion(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, IReadonlyColorUI *readonlyColorUI) {
GdkDragAction suggestedAction;
bool suggestedActionSet = true;
auto &state = *reinterpret_cast<State *>(g_object_get_data(G_OBJECT(widget), "dragDropState"));
if (state.supportsMove) {
bool draggingMoves = state.gs.settings().getBool("gpick.main.dragging_moves", true);
if (draggingMoves) {
if ((gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE) == GDK_ACTION_MOVE)
suggestedAction = GDK_ACTION_MOVE;
else if ((gdk_drag_context_get_actions(context) & GDK_ACTION_COPY) == GDK_ACTION_COPY)
suggestedAction = GDK_ACTION_COPY;
else
suggestedActionSet = false;
} else {
if ((gdk_drag_context_get_actions(context) & GDK_ACTION_COPY) == GDK_ACTION_COPY)
suggestedAction = GDK_ACTION_COPY;
else if ((gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE) == GDK_ACTION_MOVE)
suggestedAction = GDK_ACTION_MOVE;
else
suggestedActionSet = false;
}
} else {
suggestedActionSet = false;
}
auto *droppableColorUI = dynamic_cast<IDroppableColorUI*>(readonlyColorUI);
if (!droppableColorUI) {
GdkAtom target = gtk_drag_dest_find_target(widget, context, 0);
if (target) {
gdk_drag_status(context, suggestedActionSet ? suggestedAction : gdk_drag_context_get_selected_action(context), time);
} else {
gdk_drag_status(context, suggestedActionSet ? suggestedAction : GdkDragAction(0), time);
}
return true;
}
if (droppableColorUI->testDropAt(x, y)) {
GdkAtom target = gtk_drag_dest_find_target(widget, context, 0);
if (target) {
gdk_drag_status(context, suggestedActionSet ? suggestedAction : gdk_drag_context_get_selected_action(context), time);
} else {
gdk_drag_status(context, suggestedActionSet ? suggestedAction : GdkDragAction(0), time);
}
} else {
gdk_drag_status(context, suggestedActionSet ? suggestedAction : GdkDragAction(0), time);
}
return true;
}
static gboolean onDragDrop(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, IReadonlyColorUI *readonlyColorUI) {
GdkAtom target = gtk_drag_dest_find_target(widget, context, 0);
auto *droppableColorUI = dynamic_cast<IDroppableColorUI*>(readonlyColorUI);
if (target != GDK_NONE) {
gtk_drag_get_data(widget, context, target, time);
if (droppableColorUI)
droppableColorUI->dropEnd(gdk_drag_context_get_selected_action(context) == GDK_ACTION_MOVE);
return true;
}
if (droppableColorUI)
droppableColorUI->dropEnd(gdk_drag_context_get_selected_action(context) == GDK_ACTION_MOVE);
return false;
}
static void onDragDataGet(GtkWidget *widget, GdkDragContext *context, GtkSelectionData *selectionData, Target targetType, guint time, IReadonlyColorUI *readonlyColorUI) {
if (!selectionData)
return;
auto &state = *reinterpret_cast<State *>(g_object_get_data(G_OBJECT(widget), "dragDropState"));
if (state.colorObjects.size() == 0)
return;
Color color;
switch (targetType) {
case Target::colorObjectList: {
ColorObjectList data;
data.colorObjects = &state.colorObjects;
gtk_selection_data_set(selectionData, gdk_atom_intern("color-object", false), 8, reinterpret_cast<const guchar *>(&data), sizeof(ColorObjectList));
} break;
case Target::serializedColorObjectList: {
std::vector<dynv::Ref> colors;
colors.reserve(state.colorObjects.size());
for (uint32_t i = 0; i < state.colorObjects.size(); i++) {
auto color = dynv::Map::create();
color->set("name", state.colorObjects[i].getName());
color->set("color", state.colorObjects[i].getColor());
colors.push_back(color);
}
dynv::Map values;
values.set("colors", colors);
std::stringstream str;
values.serializeXml(str);
auto data = str.str();
if (!data.empty())
gtk_selection_data_set(selectionData, gdk_atom_intern("application/x-color-object-list", false), 8, (const guchar *)&data.front(), data.length());
else
gtk_selection_data_set(selectionData, gdk_atom_intern("application/x-color-object-list", false), 8, (const guchar *)"", 0);
} break;
case Target::string: {
std::stringstream ss;
ConverterSerializePosition position(state.colorObjects.size());
auto converter = state.gs.converters().firstCopy();
if (converter) {
for (size_t i = 0, count = state.colorObjects.size(); i < count; i++) {
if (position.index() + 1 == position.count())
position.last(true);
if (position.first()) {
ss << converter->serialize(state.colorObjects[i], position);
position.first(false);
} else {
ss << "\n" << converter->serialize(state.colorObjects[i], position);
}
position.incrementIndex();
}
}
std::string text = ss.str();
gtk_selection_data_set_text(selectionData, text.c_str(), text.length());
} break;
case Target::color: {
const auto &colorObject = state.colorObjects[0];
color = colorObject.getColor();
guint16 dataColor[4];
dataColor[0] = int(color.rgb.red * 0xFFFF);
dataColor[1] = int(color.rgb.green * 0xFFFF);
dataColor[2] = int(color.rgb.blue * 0xFFFF);
dataColor[3] = 0xffff;
gtk_selection_data_set(selectionData, gdk_atom_intern("application/x-color", false), 16, (guchar *)dataColor, 8);
} break;
}
}
static void onDragBegin(GtkWidget *widget, GdkDragContext *context, IReadonlyColorUI *readonlyColorUI) {
auto &state = *reinterpret_cast<State *>(g_object_get_data(G_OBJECT(widget), "dragDropState"));
auto *readonlyColorsUI = dynamic_cast<IReadonlyColorsUI *>(readonlyColorUI);
if (readonlyColorsUI) {
if (!readonlyColorsUI->hasSelectedColor())
return;
auto colorObjects = readonlyColorsUI->getColors(true);
if (colorObjects.size() == 0)
return;
state.colorObjects = colorObjects;
auto dragWindow = gtk_window_new(GTK_WINDOW_POPUP);
auto hbox = gtk_vbox_new(true, 0);
gtk_container_add(GTK_CONTAINER(dragWindow), hbox);
auto showColors = std::min<size_t>(colorObjects.size(), 5);
gtk_widget_set_size_request(dragWindow, 164, 24 * showColors);
auto converter = state.gs.converters().forType(state.converterType);
if (converter) {
for (size_t i = 0; i < showColors; i++) {
auto colorWidget = gtk_color_new();
auto text = converter ? converter->serialize(colorObjects[i]) : "";
Color color = colorObjects[i].getColor();
gtk_color_set_color(GTK_COLOR(colorWidget), &color, text.c_str());
gtk_box_pack_start(GTK_BOX(hbox), colorWidget, true, true, 0);
}
}
gtk_drag_set_icon_widget(context, dragWindow, 0, 0);
gtk_widget_show_all(dragWindow);
state.dragWidget = dragWindow;
return;
}
if (!readonlyColorUI->hasSelectedColor())
return;
auto colorObject = readonlyColorUI->getColor();
state.colorObjects.push_back(colorObject);
auto dragWindow = gtk_window_new(GTK_WINDOW_POPUP);
auto colorWidget = gtk_color_new();
gtk_container_add(GTK_CONTAINER(dragWindow), colorWidget);
gtk_widget_set_size_request(dragWindow, 164, 24);
auto text = state.gs.converters().serialize(colorObject, state.converterType);
Color color = colorObject.getColor();
gtk_color_set_color(GTK_COLOR(colorWidget), &color, text.c_str());
gtk_drag_set_icon_widget(context, dragWindow, 0, 0);
gtk_widget_show_all(dragWindow);
state.dragWidget = dragWindow;
return;
}
static void onDragEnd(GtkWidget *widget, GdkDragContext *context, IReadonlyColorUI *readonlyColorUI) {
auto &state = *reinterpret_cast<State *>(g_object_get_data(G_OBJECT(widget), "dragDropState"));
state.colorObjects.resize(0);
state.colorObjects.shrink_to_fit();
if (state.dragWidget) {
gtk_widget_destroy(state.dragWidget);
state.dragWidget = nullptr;
}
auto *draggableColorUI= dynamic_cast<IDraggableColorUI*>(readonlyColorUI);
if (draggableColorUI)
draggableColorUI->dragEnd(gdk_drag_context_get_selected_action(context) == GDK_ACTION_MOVE);
}
static void onStateDestroy(State *state){
delete state;
}
StandardDragDropHandler::Options::Options():
m_afterEvents(true),
m_supportsMove(false),
m_allowDrop(true),
m_allowDrag(true),
m_converterType(Converters::Type::display) {
}
StandardDragDropHandler::Options &StandardDragDropHandler::Options::afterEvents(bool enable) {
m_afterEvents = enable;
return *this;
}
StandardDragDropHandler::Options &StandardDragDropHandler::Options::supportsMove(bool enable) {
m_supportsMove = enable;
return *this;
}
StandardDragDropHandler::Options &StandardDragDropHandler::Options::allowDrop(bool enable) {
m_allowDrop = enable;
return *this;
}
StandardDragDropHandler::Options &StandardDragDropHandler::Options::allowDrag(bool enable) {
m_allowDrag = enable;
return *this;
}
StandardDragDropHandler::Options &StandardDragDropHandler::Options::converterType(Converters::Type type) {
m_converterType = type;
return *this;
}
void StandardDragDropHandler::forWidget(GtkWidget *widget, GlobalState *gs, Interface interface, Options options) {
void *data = boost::apply_visitor([](auto *interface) -> void * {
return interface;
}, interface);
auto flags = options.m_afterEvents ? G_CONNECT_AFTER : static_cast<GConnectFlags>(0);
if (options.m_allowDrag) {
if (options.m_supportsMove)
gtk_drag_source_set(widget, GDK_BUTTON1_MASK, 0, 0, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_ASK));
else
gtk_drag_source_set(widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY);
GtkTargetList *targetList = gtk_drag_source_get_target_list(widget);
if (targetList) {
gtk_target_list_add_table(targetList, targets, targetCount);
} else {
targetList = gtk_target_list_new(targets, targetCount);
gtk_drag_source_set_target_list(widget, targetList);
}
g_signal_connect_data(widget, "drag-data-get", G_CALLBACK(onDragDataGet), data, nullptr, flags);
g_signal_connect_data(widget, "drag-begin", G_CALLBACK(onDragBegin), data, nullptr, flags);
g_signal_connect_data(widget, "drag-end", G_CALLBACK(onDragEnd), data, nullptr, flags);
}
auto *editableColorUI = dynamic_cast<IEditableColorUI *>(static_cast<IReadonlyColorUI *>(data));
if (options.m_allowDrop && editableColorUI) {
if (options.m_supportsMove)
gtk_drag_dest_set(widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_ASK));
else
gtk_drag_dest_set(widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY);
GtkTargetList *targetList = gtk_drag_dest_get_target_list(widget);
if (targetList) {
gtk_target_list_add_table(targetList, targets, targetCount);
} else {
targetList = gtk_target_list_new(targets, targetCount);
gtk_drag_dest_set_target_list(widget, targetList);
}
g_signal_connect_data(widget, "drag-data-received", G_CALLBACK(onDragDataReceived), data, nullptr, flags);
g_signal_connect_data(widget, "drag-motion", G_CALLBACK(onDragMotion), data, nullptr, flags);
g_signal_connect_data(widget, "drag-drop", G_CALLBACK(onDragDrop), data, nullptr, flags);
}
auto state = new State(*gs, options.m_converterType, options.m_supportsMove);
g_object_set_data_full(G_OBJECT(widget), "dragDropState", state, GDestroyNotify(onStateDestroy));
}
| [
"thezbyg@gmail.com"
] | thezbyg@gmail.com |
d08ac8859df331e68556d9f187db59328cfe8385 | 32cb2f19760079beea29f16bfadaefe675476623 | /recursive-algorithms/1703.cpp | 9317e9cd0679e9291a4916bd02e7e5aa3053d17b | [] | no_license | junkkerrigan/algorithmics | d00b438ebd9909c0afc73a1a6e0bdd0579b2c240 | a7493bcefb2a09987a4891b6de955db57ac9ed8a | refs/heads/master | 2021-05-23T14:06:12.730092 | 2020-06-08T17:59:31 | 2020-06-08T17:59:31 | 253,329,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | cpp | #include <iostream>
using namespace std;
int n, answer = 0;
char S[100];
int main()
{
cin >> n;
gets(S);
for (int i = 0; i < n; i++)
{
gets(S);
if (S[0] == S[3])
answer++;
}
cout << answer << endl;
} | [
"andriipav@wix.com"
] | andriipav@wix.com |
3c11dd547abacf8297edd2d186b2a2dd7cd38079 | 88885e8e59855530c09ac930ae57914cbe4fe0f8 | /Source/privateinclude/ObjectTmpl.inl | 0b96579f60e1479a4ee94047600babebaaef777d | [] | no_license | klainqin/LandXmlSDK | 8767c46c36b2257d388e50a25e64956c7c6ed020 | ca52863d66d172b00835f66cef636790e668a52f | refs/heads/master | 2021-01-10T08:30:45.007060 | 2015-11-25T10:20:13 | 2015-11-25T10:20:13 | 46,108,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,821 | inl | #if !defined(__LX_OBJECTTMPL_INL)
#define __LX_OBJECTTMPL_INL
#include "stdafx.h"
#include "ObjectTmpl.h"
#include "DocumentImpl.h"
#include "Exception.h"
/////////////////////////////////////////////////////////////////////////////
//
// File: Object.cpp
//
// Description:
// Contains the implementation of the Object class
//
// $History: Object.cpp $
//
/////////////////////////////////////////////////////////////////////////////
namespace LX
{
template<class T>
ObjectTmpl<T>::ObjectTmpl ()
{
m_pDoc = NULL;
m_pCollectionLocation = NULL;
}
template<class T>
ObjectTmpl<T>::ObjectTmpl (DocumentImpl* pDoc)
{
m_pDoc = pDoc;
m_pCollectionLocation = NULL;
}
template<class T>
ObjectTmpl<T>::~ObjectTmpl ()
{
}
template<class T>
void ObjectTmpl<T>::toXml (
IStream& stream)
{
// Do nothing.
stream;
}
template<class T>
String ObjectTmpl<T>::toString () const
{
return L"";
}
template<class T>
void ObjectTmpl<T>::toStream (
IStream& stream) const
{
// To Stream.
stream;
}
template<class T>
Document* ObjectTmpl<T>::getDocument ()
{
return m_pDoc;
}
template<class T>
void ObjectTmpl<T>::setContainingCollectionLocation (
CollectionLocation* pLocation)
{
// If the new location pointer equals the current location then
// bail.
if (pLocation == m_pCollectionLocation)
{
return;
}
// If the iterator is being set to NULL then just set it.
if (pLocation == NULL)
{
// Release the original location pointer if there was one.
if (m_pCollectionLocation)
m_pCollectionLocation->release();
// Object is being taken out of a collection, so set the
// iterator to NULL.
m_pCollectionLocation = NULL;
}
else
{
// Object is being added to a collection.
// Make sure its not already in a collection.
if (m_pCollectionLocation)
{
throw Exception(Exception::kObjectIsAlreadyInCollection, L"Object is already in a collection.");
}
// Set the iterator.
m_pCollectionLocation = pLocation;
}
}
template<class T>
CollectionLocation* ObjectTmpl<T>::getContainingCollectionLocation ()
{
return m_pCollectionLocation;
}
template<class T>
Object* ObjectTmpl<T>::getGlobalCollection ()
{
return NULL;
}
template<class T>
Object::ValidityEnum ObjectTmpl<T>::validate (IValidationEventSink* pEventSink) const
{
pEventSink; // Do nothing.
return Object::kValid;
}
template<class T>
void ObjectTmpl<T>::release ()
{
if (m_pCollectionLocation)
m_pCollectionLocation->release();
m_pCollectionLocation = NULL;
delete this;
}
};
#endif
| [
"qink@shac02q6273g8wn.ads.autodesk.com"
] | qink@shac02q6273g8wn.ads.autodesk.com |
209549ce4ff16703690345bd38aaefccfcb46837 | 8fc42a7b9d1b311279325c277af49883062b673f | /PoC/main.cpp | 37962bbeacbe763b24f79347f7716e19863d39a5 | [] | no_license | wpehrett/adamark | cc6b526774caaa5d4cefc19fd070225ff71cbd39 | 6be741f24dd97334572d694c562306b370de6fef | refs/heads/master | 2020-04-01T15:38:51.487971 | 2018-11-19T17:40:03 | 2018-11-19T17:40:03 | 153,345,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,780 | cpp | //FIXME Warning: EVERYWHERE: ensure created objects are eventually delete'd ("delete <objname>;")!
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
//Required headers for simulator operation
#include "prototypes.hpp"
//#include your custom module headers here
#include "simplememory.hpp"
using namespace std;
vector<Module*> modules;
unsigned int clkGlobal = 0;
bool verbose = 0;
void* data_output; //TODO make a dynamically resizing array of arbitrary/testcase-defined type
//TODO: make an abstract object template for "testcase" and then dynamically type all this stuff based upon the instantiated testcase's input/output/etc types?!?!
int cleanList() {
//Sort modules vector by ID to improve efficiency of message delivery in sim
sort(modules.begin(), modules.end(), [](const Module* a, const Module* b) {return a->id < b->id;});
//Scan modules vector to ensure all (user-assigned) IDs are unique and strictly sequential; if not, message delivery would break
for (int i=0; i<modules.size()-1; i++) {
if ((modules[i]->id)+1 != modules[i+1]->id) return -1;
}
return 0;
}
void init() {
//Set global input to first module
//TODO generalize this
int* testint = (int*)malloc(sizeof(int));
*testint = 2;
(*modules.begin())->inputs.push_back(new Message((void*)(new MemReqParams(0, sizeof(int), true, (void*)testint)), -1, 0));
(*modules.begin())->inputs.push_back(new Message((void*)(new MemReqParams(0, sizeof(int), false, NULL)), -1, 0));
}
int step() {
int result = 0;
//Phase 1: for each module: process() per current inputs and update energy
for (int i=0; i<modules.size(); i++) {
Module* m = modules[i];
if (verbose) printf("Processing module with id=%d...\n", m->id);
m->cumulativeEnergy += m->process();
}
//Phase 2: interconnect: for each module: check outputs, propagate to next module's inputs (or global outputs)
//TODO revise/generalize
for (int i=0; i<modules.size(); i++) {
Module* m = modules[i];
if (verbose) printf("Examining outputs for module with id=%d...\n", m->id);
while ((m->outputs).size() > 0) {
Message* msg = (m->outputs).front();
int src = msg->src;
int dest = msg->dest;
void* data = msg->data;
if (verbose) printf("Found message: src=%d, dest=%d\n", src, dest);
//Parse and handle messages to system
if (dest == -1) {
//Data type must be ThReqParams object
ThReqParams* trp = (ThReqParams*)data;
switch (trp->type) {
case Start:
//TODO
break;
case Done: //TODO: consider whether this is actually the best way of checking finish condition (vs if it'd be too weird to handle like this in a Module that's supposed to be representative of real hardware)!
/*(
FIXME: A better way would probably be:
1) do the event-based thing and then finish when the event queue is completely empty... implement as a linked-list with O(n) insertion and O(1) removal, where n=length of event queue, instead of the current module loop where every cycle is O(m) (where m=total number of total modules in the system)
- Another potential benefit here: would permit simple same-cycle data xfer (if, e.g., want to simulate multiple submodules where some may feed data into others in the same cycle
2) maybe do a hybrid where modules are scanned each cycle, but they can be skipped by setting a flag in a statically sized bitmask to tell whether they're stalled or on-delay until a later cycle? or have an m-sized int array where each value is the cycle on which the module will next need attention, then check that vs the current cycle count each sim step?
So, the key questions to ask are:
a) How many modules do we expect to have?
b) How active are those modules on average?
c) How long do we expect the event queues to become, and stretching how far into future time?
d) If sticking with the check-every-cycle model, or if doing (2), how can the system supply a "done" signal without breaking the "correctness"/realism of the simulation?
- Maybe a meta-module at the front- and back-end of the simulated system, user-defined, that are designed to do this checking and handle all direct testharness interactions?
)*/
//Finish after all remaining messages delivered
result = -1;
break;
case GetData:
//TODO
break;
case PutData:
//TODO
break;
}
delete trp;
//result = data;
}
delete msg;
(m->outputs).pop_front();
}
}
//Step 3: update metrics per module activity
//TODO later (if needed; i.e., if not done at top-level)
return result;
}
int main(int argc, char* argv[]) {
printf("Hi!\n\n");
//Parse command-line args
//TODO allow plaintext system configuration files, specification of particular tests or test subsets, etc.
//TODO make the verbose flag a global, well-defined, well-documented parameter accessible by other, user-defined modules!
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "-v")==0 || strcmp(argv[i], "--verbose")==0) verbose=1;
}
//Init: instantiate system (TODO revise this part/make more user-friendly, and enable reading from a config file)
SimpleMemory* sm = new SimpleMemory(0, 8); //Note: each module must take a unique sequential ID (!= -1) as a parameter and set it in its constructor
modules.push_back(sm);
if (cleanList() == -1) {
printf("Error: problem with module IDs (non-unique and/or non-sequential)! Exiting.\n");
return -1;
}
//Init: set up inputs (TODO parameterize somehow to more easily permit varying testcases; maybe just multiple different init() functions, incl stuff that can (wlog) stream large data from disk-stored files as needed?)
printf("Initializing...\n");
init();
//Sim loop: step(), check if done after each step, break when done
printf("Beginning simulation...\n");
while(1) {
if (verbose) printf("**** CYCLE %d ****\n", clkGlobal);
int result = step();
if (result == -1) {
printf("Done signal detected\n\n");
break;
}
if (clkGlobal > 3) { if (verbose) printf("\n"); break; }
clkGlobal++;
if (verbose) printf("\n");
}
//Check results
//TODO
//Cleanup: compute final metrics, display results, exit
printf("Simulation complete, cleaning up...\n");
double totalEnergy = 0.0;
for (int i=0; i<modules.size(); i++) {
Module* m = modules[i];
if (verbose) printf("Metrics for module with id=%d...\n", m->id);
printf("Energy for module with id=%d: %.6f nJ\n", m->id, m->cumulativeEnergy);
totalEnergy += m->cumulativeEnergy;
}
printf("Total energy: %.6f nJ\n", totalEnergy);
printf("Total cycles: %d\n", clkGlobal+1); //note clkGlobal is 0-indexed
delete sm;
return 0;
}
/************************/
| [
"wpehrett@umich.edu"
] | wpehrett@umich.edu |
3581ba6800d748d36cfbcdb3478cff06dc5b1429 | 66dcd8757e7c865d1147978bbdb29ed8eeea0a7a | /game-specific/Final Fantasy PSP/tests/LZ77Tests/main.cpp | a38ae5e6b903181269d0dcf7d55e46165e450fff | [] | no_license | YAGAMI55/consolgames-tools | 9f03106c10161dad130cf0e6f47fa4871c2dfdec | 9cb5b20e0411ef3708fc1f747823246e5bfcc40d | refs/heads/master | 2022-04-12T11:50:58.730962 | 2019-03-13T21:14:54 | 2019-03-13T21:14:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 251 | cpp | #include "LZ77DecoderTests.h"
#include "LZ77EncoderTests.h"
#include <QtTest>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QTest::qExec(&LZ77DecoderTests());
QTest::qExec(&LZ77EncoderTests());
return 0;
}
| [
"mbystryantsev@users.noreply.github.com"
] | mbystryantsev@users.noreply.github.com |
6e75f9af3b981aa713871766130a5e285ce5e91c | 5386865e2ea964397b8127aba4b2592d939cd9f2 | /shkola_razgrad/strings/hash.cpp | 2a0133294eda3fb946bb72e8135c6c0e35cf9430 | [] | no_license | HekpoMaH/Olimpiads | e380538b3de39ada60b3572451ae53e6edbde1be | d358333e606e60ea83e0f4b47b61f649bd27890b | refs/heads/master | 2021-07-07T14:51:03.193642 | 2017-10-04T16:38:11 | 2017-10-04T16:38:11 | 105,790,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | cpp | #include<iostream>
#include<string>
using namespace std;
unsigned long long h1[100005],h2[100005],p=29,mod=122345540;
string a,b;
unsigned long long pp,br;
int main()
{
cin>>a>>b;
h1[0]=(int)(a[0]-'a'+1);
for(int i=1;i<a.size();i++)
{
h1[i]=h1[i-1]*p;
h1[i]+=(int)(a[i]-'a'+1);
h1[i]%=mod;
}
h2[0]=(int)(b[0]-'a'+1);
for(int i=1;i<b.size();i++)
{
h2[i]=h2[i-1]*p;
h2[i]+=(int)(b[i]-'a'+1);
h2[i]%=mod;
}
for(int i=0;i<a.size();i++)cout<<h1[i]<<" ";
cout<<endl;
for(int i=0;i<b.size();i++)cout<<h2[i]<<" ";
cout<<endl;
for(int i=0;i<=a.size()-b.size()+1;i++)
{
pp=1;
for(int j=0;j<b.size();j++)pp*=p,pp%=mod;
if(h2[b.size()-1]==(h1[i+b.size()-1]+mod-(h1[i-1]*pp%mod))%mod)br++;
}
cout<<br<<endl;
return 0;
} | [
"dgg30"
] | dgg30 |
c4cf784275bdc0a8275fda632d60906b0795dcbe | aae79375bee5bbcaff765fc319a799f843b75bac | /srm_6xx/srm_630/Egalitarianism3.cpp | c65bd108167c113bb17ea5c31d485fec98635ae1 | [] | no_license | firewood/topcoder | b50b6a709ea0f5d521c2c8870012940f7adc6b19 | 4ad02fc500bd63bc4b29750f97d4642eeab36079 | refs/heads/master | 2023-08-17T18:50:01.575463 | 2023-08-11T10:28:59 | 2023-08-11T10:28:59 | 1,628,606 | 21 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 4,840 | cpp | // BEGIN CUT HERE
/*
SRM 630 Div1 Easy (250)
問題
-N個の都市がある
-それぞれの都市はN-1本の道路で接続されておりそれぞれの長さが与えられる
-どの2都市の距離も全て等しいという条件を満たす最大の都市数を求める
*/
// END CUT HERE
#include <algorithm>
#include <string>
#include <set>
#include <vector>
#include <iostream>
#include <sstream>
#include <string.h>
using namespace std;
typedef set<int> IntSet;
class Egalitarianism3 {
public:
int maxCities(int n, vector <int> a, vector <int> b, vector <int> len) {
if (n <= 2) {
return n;
}
int d[50][50];
memset(d, 0x3f, sizeof(d));
for (int i = 0; i < (int)a.size(); ++i) {
d[a[i]-1][b[i]-1] = len[i];
d[b[i]-1][a[i]-1] = len[i];
}
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
int ans = 2;
for (int i = 0; i < n; ++i) {
for (int j = i+1; j < n; ++j) {
int r = d[i][j];
if (r < 1e6) {
IntSet s;
s.insert(i);
s.insert(j);
for (int k = 0; k < n; ++k) {
if (i != k && j != k) {
IntSet::const_iterator it;
for (it = s.begin(); it != s.end(); ++it){
if (d[k][*it] != r) {
break;
}
}
if (it == s.end()){
s.insert(k);
}
}
}
ans = max(ans, (int)s.size());
}
}
}
return ans;
}
// BEGIN CUT HERE
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
public:
void run_test(int Case) {
int n = 0;
// test_case_0
if ((Case == -1) || (Case == n)){
int Arg0 = 4;
int Arr1[] = {1,1,1};
int Arr2[] = {2,3,4};
int Arr3[] = {1,1,1};
int Arg4 = 3;
vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0])));
vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0])));
vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0])));
verify_case(n, Arg4, maxCities(Arg0, Arg1, Arg2, Arg3));
}
n++;
// test_case_1
if ((Case == -1) || (Case == n)){
int Arg0 = 6;
int Arr1[] = {1,2,3,2,3};
int Arr2[] = {2,3,4,5,6};
int Arr3[] = {2,1,3,2,3};
int Arg4 = 3;
vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0])));
vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0])));
vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0])));
verify_case(n, Arg4, maxCities(Arg0, Arg1, Arg2, Arg3));
}
n++;
// test_case_2
if ((Case == -1) || (Case == n)){
int Arg0 = 10;
int Arr1[] = {1,1,1,1,1,1,1,1,1};
int Arr2[] = {2,3,4,5,6,7,8,9,10};
int Arr3[] = {1000,1000,1000,1000,1000,1000,1000,1000,1000};
int Arg4 = 9;
vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0])));
vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0])));
vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0])));
verify_case(n, Arg4, maxCities(Arg0, Arg1, Arg2, Arg3));
}
n++;
// test_case_3
if ((Case == -1) || (Case == n)){
int Arg0 = 1;
// int Arr1[] = {};
// int Arr2[] = {};
// int Arr3[] = {};
int Arg4 = 1;
vector <int> Arg1;
vector <int> Arg2;
vector <int> Arg3;
verify_case(n, Arg4, maxCities(Arg0, Arg1, Arg2, Arg3));
}
n++;
if ((Case == -1) || (Case == n)){
int Arg0 = 36;
int Arr1[] = { 30, 30, 20, 21, 10, 17, 2, 4, 35, 2, 34, 7, 13, 23, 28, 32, 35, 8, 5, 11, 24, 7, 23, 20, 7, 27, 29, 33, 20, 30, 15, 24, 8, 7, 9 };
int Arr2[] = { 8, 1, 17, 15, 28, 21, 14, 6, 9, 26, 5, 25, 35, 16, 33, 19, 3, 11, 32, 23, 34, 31, 24, 7, 22, 12, 30, 27, 2, 10, 29, 36, 13, 4, 18 };
int Arr3[] = { 8, 9, 8, 5, 6, 1, 6, 1, 9, 1, 7, 5, 3, 5, 3, 9, 8, 5, 3, 5, 5, 5, 7, 4, 5, 1, 8, 5, 1, 7, 3, 3, 3, 9, 3 };
int Arg4 = 4;
vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0])));
vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0])));
vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0])));
verify_case(n, Arg4, maxCities(Arg0, Arg1, Arg2, Arg3));
}
n++;
}
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
Egalitarianism3 ___test;
/// ___test.run_test(0);
// ___test.run_test(1);
// ___test.run_test(2);
// ___test.run_test(3);
// ___test.run_test(4);
// ___test.run_test(5);
___test.run_test(-1);
}
// END CUT HERE
| [
"karamaki@gmail.com"
] | karamaki@gmail.com |
29707f648335a2c2089e5bcc7b8d2c71976c1c8b | e8389dfaf892a410909f9fa975a30e8c83689b38 | /engines/ep/src/conn_store_fwd.h | e09255352fced3011605cdcdf6cc8a734e643038 | [
"Apache-2.0"
] | permissive | daverigby/kv_engine | 9c03f13d6388e1f564a37eff125fda733d0caff8 | 82f8b20bcd3851bf31c196bd0f228b8c45eb0632 | refs/heads/master | 2022-12-10T12:36:36.917117 | 2020-08-05T10:18:24 | 2020-09-09T10:55:49 | 91,691,505 | 0 | 2 | BSD-3-Clause | 2019-10-11T14:02:25 | 2017-05-18T12:37:22 | C++ | UTF-8 | C++ | false | false | 975 | h | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <unordered_map>
class ConnHandler;
// Not part of ConnStore as some consumers of the class will need this type.
using CookieToConnectionMap =
std::unordered_map<const void*, std::shared_ptr<ConnHandler>>;
class ConnStore;
| [
"daver@couchbase.com"
] | daver@couchbase.com |
c115348e6dbc9cef4ded1e2cd3f143e5128bf1b6 | 739732d3a6b548404f432ad8ff918841249a18ec | /src/LanguageTools/thai/Perceptron.cpp | c75c3b7d76e6732acbea4a25aecf27e5dbcc192f | [] | no_license | yiique/TranslationSystemSimple | 9417e14c198c9622fbb9e1f046445ba1462b458f | 62a9eea538bae1739b7a4e2bfa39fd0e27d8967d | refs/heads/master | 2020-04-09T21:25:23.550131 | 2016-09-12T12:59:12 | 2016-09-12T12:59:12 | 68,007,511 | 0 | 0 | null | 2016-09-12T12:59:12 | 2016-09-12T12:37:25 | C++ | GB18030 | C++ | false | false | 910 | cpp | #include <fstream>
#include <iostream>
#include "Perceptron.h"
using namespace thaiSeg;
CPerceptron::CPerceptron()
{
}
CPerceptron::~CPerceptron()
{
}
//初始化
bool CPerceptron::Initialize(const string &model)
{
ifstream fin(model.c_str());
if (!fin)
{
cout << "Can not open model file: " << model << endl;
return false;
}
string line;
while (getline(fin, line))
{
size_t split = line.find('\t');
string pred = line.substr(0, split);
string weight = line.substr(split + 1, line.length() - split - 1);
double weightVal = atof(weight.c_str());
m_mPredWeight.insert(map<string, double>::value_type(pred, weightVal));
}
fin.close();
return true;
}
//获取该推断的分值
double CPerceptron::PredWeight(const string &pred)
{
map<string, double>::iterator it = m_mPredWeight.find(pred);
if (it != m_mPredWeight.end())
{
return it->second;
}
else
{
return 0.0;
}
}
| [
"liushuman@liushumandeMBP.lan"
] | liushuman@liushumandeMBP.lan |
3cdf6cfa74119a45cbc32aafb9a0e0d5d826fe9c | 321cccc759a2982afa70b67a349087ac4c86513d | /src/shared/linux_waitpid.h | e0841ccf55f4135b577454aeb63dcafce996bee0 | [
"MIT"
] | permissive | martykadlcek/trading-bot | 3037887d667556ea125f8ba9e8fba56e5dc6111c | c2f34ef1e6746f02642dde3cb3d11010213f0121 | refs/heads/master | 2022-04-19T23:41:04.354678 | 2020-04-20T15:26:40 | 2020-04-20T15:26:40 | 257,055,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,885 | h | /*
* linux_waitpid.h
*
* Created on: 16. 10. 2019
* Author: ondra
*/
#ifndef ONDRA_SHARED_SRC_SHARED_LINUX_WAITPID_H_6876910645
#define ONDRA_SHARED_SRC_SHARED_LINUX_WAITPID_H_6876910645
#include <signal.h>
#include <mutex>
#include <errno.h>
#include <semaphore.h>
#include "linear_map.h"
namespace ondra_shared {
namespace _details {
class WaitPidSvc {
protected:
using Sync = std::unique_lock<std::recursive_mutex>;
using Key = std::pair<int, size_t>;
using Value = std::pair<sem_t *, int>;
using Map = linear_map<Key,Value>;
using Set = linear_set<pid_t>;
class SignalGuard {
public:
SignalGuard(int sig) {
sigset_t newset;
sigemptyset(&newset);
sigaddset(&newset, sig);
pthread_sigmask(SIG_BLOCK, &newset, &oldset);
}
~SignalGuard() {
pthread_sigmask(SIG_SETMASK, &oldset, NULL);
}
protected:
sigset_t oldset;
};
public:
size_t beginWait(pid_t pid, sem_t *mtc) {
SignalGuard _s(SIGCHLD);
Sync _(mtx);
int status = -1;
pid_t q = waitpid(pid, &status, WNOHANG);
std::size_t reg = nextReg++;
if (q) {
//support for copying the status
auto iter = map.lower_bound(Key(pid,0));
if (iter != map.end() && iter->first.first == pid) {
status = iter->second.second;
}
//signal if signaled
sem_post(mtc);
}
map.emplace(Key(pid, reg), Value(mtc, status));
return reg;
}
int endWait(pid_t pid, size_t regId) {
SignalGuard _s(SIGCHLD);
Sync _(mtx);
auto iter = map.find(Key(pid, regId));
int status = -1;
if (iter != map.end()) {
status = iter->second.second;
map.erase(iter);
}
return status;
}
int getExitCode(pid_t pid, size_t regId) const {
SignalGuard _s(SIGCHLD);
Sync _(mtx);
auto iter = map.find(Key(pid, regId));
int ret = -1;
if (iter != map.end()) {
ret = iter->second.second;
}
return ret;
}
void signal_enter() {
int status;
Sync _(mtx);
pid_t p = -1;
bool exited = false;
for (auto &r : map) {
if (r.first.first != p) {
p = r.first.first;
status = -1;
exited = false;
int st = waitpid(p,&status, WNOHANG);
if (st < 0) {
exited = true;
status = errno;
} else if (st > 0) {
exited = true;
}
}
if (exited) {
r.second.second = status;
sem_post(r.second.first);
}
}
}
static WaitPidSvc &getSignleton() {
static WaitPidSvc instance;
return instance;
}
static void signal_enter_static(int) {
getSignleton().signal_enter();
init();
}
static void init() {
signal(SIGCHLD, &signal_enter_static);
}
protected:
mutable std::recursive_mutex mtx;
size_t nextReg = 0;
Map map;
};
}
///Handles waiting for child process asynchronously
/**
* When object of this class is created, it starts to wait on exit of specified child.
* The waiting is done asynchronously - at background.
*
* If you need to determine, whether the child processes exited, you can
* call one of the wait function. You can wait as many as you want. Once the
* child exits, the object becomes signaled and any wait function immediately returns
*
* The object uses Linux's signal SIGCHLD and installs global handler for the purpose.
* It also needs to remove any blocking of this signal.
*
* The object is not considered as MT safe. It becomes immediately signaled, when there
* is no such child running or pending. There can be also multiple WaitPid instances
* for the single child. You can also copy the WaitPid instance while the signaled
* state and status is also copied
*
*/
class WaitPid {
public:
///Constructs WaitPid object.
/**
* @param pid pid of the child process.
*
* @note if you constructs the very first instance, the signal handler is
* also installed
*/
WaitPid(pid_t pid):svc(_details::WaitPidSvc::getSignleton()),pid(pid) {
sem_init(&sm,0,0);
_details::WaitPidSvc::init();
reg = svc.beginWait(pid, &sm);
}
///Destructor
/** Stops waiting for the process */
~WaitPid() {
svc.endWait(pid,reg);
sem_close(&sm);
}
///Returns exit code of exited child
/**
* @return exit code. If the child did not exited yet, not exists, or other
* error happened, the function returns -1. Other value is similar to status
* value returned by wait, wait2 or waitpid, etc. You can use WEXITSTATUS, etc.
*/
int getExitCode() const {
return svc.getExitCode(pid, reg);
}
///Determines, whether the child processes exited
/**
* @retval true exited
* @retval false still running
*/
bool trywait() const {
if (sem_trywait(&sm) == 0) {
sem_post(&sm);
return true;
} else {
return false;
}
}
///Waits for child exit
/** This is equivalent to wait() function
*
* @retval true success
* @retval false failure. Standard errno specifies reason. EINTR is sanitized, you
* don't need to check it
*/
bool wait() const {
while (sem_wait(&sm) != 0) {
if (errno != EINTR) return false;
}
sem_post(&sm);
return true;
}
///Waits for specified duration
/**
* @param dur specifies duration
* @retval true success
* @retval false failure or timeout. Standard errno specifies reason. EINTR is sanitized, you
* don't need to check it.
*/
template<typename Duration>
bool wait_for(const Duration &dur) const {
using namespace std::chrono;
auto tp = std::chrono::system_clock::now() + dur;
auto secs = time_point_cast<seconds>(tp);
auto ns = time_point_cast<nanoseconds>(tp) -
time_point_cast<nanoseconds>(secs);
timespec tmout{static_cast<time_t>(secs.time_since_epoch().count()),static_cast<long>(ns.count())};
while (sem_timedwait(&sm, &tmout) != 0) {
if (errno != EINTR) return false;
}
sem_post(&sm);
return true;
}
///Creates a copy
WaitPid(const WaitPid &other):WaitPid(other.pid) {}
protected:
mutable sem_t sm;
_details::WaitPidSvc &svc;
size_t reg;
pid_t pid;
};
}
#endif /* ONDRA_SHARED_SRC_SHARED_LINUX_WAITPID_H_6876910645 */
| [
"martinkadlcek.mk@gmail.com"
] | martinkadlcek.mk@gmail.com |
9ababd4439640dcdb1e3b4daab0fc5d864941162 | fc259edfee10c8e2517c32f9fba147be132655f7 | /catkin_ws/src/yara_controller/src/YaraLowLevelComm.cpp | 38dc38af20d35357659c7e93f046d971655128a0 | [] | no_license | fpadula/Yara_ROS | c664b0ce2fdaa45be71347587da505a075f0cf96 | 8dae7cedecd0795d1bb1fed372fe311ed6e4aeb4 | refs/heads/master | 2023-07-11T14:25:15.142058 | 2021-08-11T20:31:12 | 2021-08-11T20:31:12 | 305,587,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,300 | cpp | #include <YaraLowLevelComm.h>
YaraLowLevelComm::YaraLowLevelComm(const char *hostname, uint16_t port){
this->hostname = hostname;
this->port = port;
this->send_msg = false;
this->send_t_msg = false;
this->position_set = false;
this->terminate = false;
this->connect_to_socket();
this->communication_handler_t = std::thread(&YaraLowLevelComm::communication_handler, this);
}
YaraLowLevelComm::~YaraLowLevelComm(){
this->terminate = true;
this->communication_handler_t.join();
}
bool YaraLowLevelComm::send_joint_pos_vel(float *joint_pos, float *joint_vel){
ros::Rate loop_rate(1000);
int curr_loop, max_loops;
curr_loop = 0;
max_loops = 10000; // 10000 loops at 1000Hz = 10s
memset(this->send_buffer, 0, sizeof(this->send_buffer));
sprintf(send_buffer, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,", joint_pos[0], joint_pos[1], joint_pos[2], joint_pos[3], joint_pos[4], joint_pos[5], joint_vel[0], joint_vel[1], joint_vel[2], joint_vel[3], joint_vel[4], joint_vel[5]);
// std::cout<<send_buffer<<std::endl;
this->send_msg = true;
// this->position_set = false;
return this->wait_position_set();
}
bool YaraLowLevelComm::wait_position_set(){
ros::Rate loop_rate(1000);
int curr_loop, max_loops;
curr_loop = 0;
max_loops = 50000;
while(!this->position_set){
if(curr_loop > max_loops){ // Taking too long -> fail
return false;
}
loop_rate.sleep();
curr_loop++;
}
return true;
}
void YaraLowLevelComm::send_joint_pos_vel_t(float joint_pos[100][6], float joint_vel[100][6], unsigned int no_of_points){
ros::Rate loop_rate(1000);
int curr_loop, max_loops;
char local_send_buffer[256];
curr_loop = 0;
max_loops = 10000; // 10000 loops at 1000Hz = 10s
this->traj_size = no_of_points;
memset(this->send_buffer, 0, sizeof(this->send_buffer));
for(int i = 0; i < no_of_points; i++){
memset(local_send_buffer, 0, sizeof(local_send_buffer));
sprintf(local_send_buffer, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,", joint_pos[i][0], joint_pos[i][1], joint_pos[i][2], joint_pos[i][3], joint_pos[i][4], joint_pos[i][5], joint_vel[i][0], joint_vel[i][1], joint_vel[i][2], joint_vel[i][3], joint_vel[i][4], joint_vel[i][5]);
strcat(this->send_buffer,local_send_buffer);
}
this->position_set = false;
this->send_t_msg = true;
}
// void YaraLowLevelComm::set_joint_pos_callback(const sensor_msgs::JointState::ConstPtr& msg){
// bool success;
// float joint_array[6];
// joint_array[0] = msg->position[0];
// joint_array[1] = msg->position[1];
// joint_array[2] = msg->position[2];
// joint_array[3] = msg->position[3];
// joint_array[4] = msg->position[4];
// joint_array[5] = msg->position[5];
// ROS_INFO("Setting pos to: [%f, %f, %f, %f, %f, %f]...", joint_array[0],joint_array[1],joint_array[2], joint_array[3], joint_array[4], joint_array[5]);
// success = this->send_joint_pos(joint_array);
// if(success)
// ROS_INFO("Done!");
// else
// ROS_INFO("Error setting joint position!");
// }
char* YaraLowLevelComm::get_host_ip(){
struct addrinfo hints, *res;
int errcode;
char *addrstr;
void *ptr;
addrstr = (char *)malloc(sizeof(char)*100);
memset (&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
errcode = getaddrinfo (this->hostname, NULL, &hints, &res);
if (errcode != 0){
perror ("getaddrinfo");
return NULL;
}
inet_ntop (res->ai_family, res->ai_addr->sa_data, addrstr, 100);
ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
inet_ntop (res->ai_family, ptr, addrstr, 100);
return addrstr;
}
int YaraLowLevelComm::connect_to_socket(){
int valread;
struct sockaddr_in serv_addr;
char *addrstr;
addrstr = this->get_host_ip();
if ((this->sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(this->port);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, addrstr, &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(this->sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
free(addrstr);
}
void YaraLowLevelComm::readXBytes(int socket, unsigned int x, void* buffer){
int bytesRead = 0;
int result;
while (bytesRead < x){
result = read(socket, buffer + bytesRead, x - bytesRead);
if (result < 1 ){
// Throw your error.
printf("\nREADING ERROR!!!!\n");
}
bytesRead += result;
}
}
void YaraLowLevelComm::communication_handler(){
int valread, i;
char read_buffer[256] = {0}, *ptr;
unsigned int length;
// float joint_positions[6];
while(!this->terminate){
// Checking to see if we need to send a message to the device:
if(this->send_msg){
this->send_msg = false;
length = strlen(this->send_buffer);
send(this->sock , (void*)&length, 4, 0);
send(this->sock , this->send_buffer, length, 0);
}
if(this->send_t_msg){
this->send_t_msg = false;
// Sending number of waypoints:
send(this->sock , (void*)&this->traj_size, 4, 0);
length = strlen(this->send_buffer);
// Sending buffer string size:
send(this->sock , (void*)&length, 4, 0);
// Sending buffer data:
ROS_INFO("Sending buffer of size %u", length);
send(this->sock , this->send_buffer, length, 0);
}
// Reading message from server:
// Setting buffer to 0:
memset(read_buffer, 0, sizeof(read_buffer));
// First we need to read the message length:
this->readXBytes(this->sock, 4, (void*)&length);
// Then we read the message if length is bigger than 0:
if(length > 0){
this->readXBytes(this->sock, length, (void*)read_buffer);
// std::cout << "[" << length << "]" << read_buffer <<std::endl;
// Parsing message:
// ROS_INFO("Read buffer of size %u. Message: %s", length, read_buffer);
if(strcmp("done",read_buffer) == 0){
// This is a done message, so done_flag must be set to true:
this->position_set = true;
}
else{
// This is a info message. Floats need to be parsed:
i = 0;
ptr = strtok(read_buffer, ",");
while(ptr != NULL){
this->last_read_joint_positions[i] = atof(ptr);
i++;
ptr = strtok(NULL, ",");
}
// printf("%.2f, %.2f, %.2f, %.2f, %.2f, %.2f\n", joint_positions[0],joint_positions[1],joint_positions[2],joint_positions[3],joint_positions[4],joint_positions[5]);
}
}
}
} | [
"fpadula92@gmail.com"
] | fpadula92@gmail.com |
4622c9c3a0a6d333312f01e975a42a587ce7e080 | 47c1ed4c7eb0a52642f259ddf783279baf638325 | /kmp.cpp | f638daa37065b5982f410d0a5195bc2b8457638c | [] | no_license | Aaaazdy/datastructure | c46b86ccbb29df1e41e8151a6d93fa06c7342b83 | 1fe6d27bcf56f715f0979eff221fe5b8bc7b76de | refs/heads/master | 2023-07-04T19:42:44.035716 | 2021-08-30T07:52:24 | 2021-08-30T07:52:24 | 393,696,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
void getnext(char*t,int *next)
{
int length=strlen(t);
int j=0;
int i=-1;
next[0]=-1;
while(j<length)
{
if(i==-1||t[i]==t[j])
{
i++;
j++;
next[j]=i;
}
else
i=next[i];
}
}
int kmp(char*s,char*t,int pos,int *next)
{
int lengtht=strlen(t);
int lengths=strlen(s);
int j=pos-1;
int i=0;
while(j<lengths&&i<lengtht)
{
if(i==-1||s[j]==t[i])
{
i++;
j++;
}
else
i=next[i];
}
if(i==lengtht)
return j-i+1;
else
return -1;
}
int main()
{
char s[100];
char t[100];
gets(s);
gets(t);
int lengtht=strlen(t);
int lengths=strlen(s);
int next[lengtht+1];
getnext(t,next);
for(int i=0;i<lengtht;i++)
printf("%d,",next[i]);
int m=0;
int x=0;
int i;
while(m<lengths)
{
i=kmp(s,t,m+1,next);
if(i==-1)
break;
printf("\n%d",i);
m=i;
x++;
}
if(x==0)
printf("-1");
system("pause");
} | [
"1169400012@qq.com"
] | 1169400012@qq.com |
81926cd14901772b046d6bcf81fa7e8ea8f1f355 | 96b635859636dd1ba03994f42e9d87db21e348ce | /src/devices/bin/driver_manager/driver_runner_test.cc | c6845ec96d8f48ca0651e9a7c8e96adbe9b57cd4 | [
"BSD-3-Clause"
] | permissive | lypenghao/fuchsia | bf6c87e4ffe5825027876c5b2069082a65236374 | e5b73c2600ca4b82f7b93f11602df44bfc349e48 | refs/heads/master | 2023-01-08T10:21:36.843784 | 2020-11-18T09:20:42 | 2020-11-18T09:20:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,836 | cc | // Copyright 2020 The Fuchsia 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 "src/devices/bin/driver_manager/driver_runner.h"
#include <fuchsia/driver/framework/cpp/fidl_test_base.h>
#include <fuchsia/io/cpp/fidl_test_base.h>
#include <fuchsia/sys2/cpp/fidl_test_base.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/gtest/test_loop_fixture.h>
#include <lib/sys/cpp/testing/component_context_provider.h>
#include <gtest/gtest.h>
namespace fdata = llcpp::fuchsia::data;
namespace fdf = fuchsia::driver::framework;
namespace fio = fuchsia::io;
namespace frunner = llcpp::fuchsia::component::runner;
namespace fsys = fuchsia::sys2;
class TestRealm : public fsys::testing::Realm_TestBase {
public:
using BindChildHandler =
fit::function<void(fsys::ChildRef child, fidl::InterfaceRequest<fio::Directory> exposed_dir)>;
using CreateChildHandler =
fit::function<void(fsys::CollectionRef collection, fsys::ChildDecl decl)>;
void SetBindChildHandler(BindChildHandler bind_child_handler) {
bind_child_handler_ = std::move(bind_child_handler);
}
void SetCreateChildHandler(CreateChildHandler create_child_handler) {
create_child_handler_ = std::move(create_child_handler);
}
private:
void BindChild(fsys::ChildRef child, fidl::InterfaceRequest<fio::Directory> exposed_dir,
BindChildCallback callback) override {
bind_child_handler_(std::move(child), std::move(exposed_dir));
callback(fsys::Realm_BindChild_Result(fit::ok()));
}
void CreateChild(fsys::CollectionRef collection, fsys::ChildDecl decl,
CreateChildCallback callback) override {
create_child_handler_(std::move(collection), std::move(decl));
callback(fsys::Realm_CreateChild_Result(fit::ok()));
}
void NotImplemented_(const std::string& name) override {
printf("Not implemented: Realm::%s\n", name.data());
}
BindChildHandler bind_child_handler_;
CreateChildHandler create_child_handler_;
};
class TestDirectory : public fio::testing::Directory_TestBase {
public:
using OpenHandler =
fit::function<void(std::string path, fidl::InterfaceRequest<fio::Node> object)>;
void SetOpenHandler(OpenHandler open_handler) { open_handler_ = std::move(open_handler); }
private:
void Open(uint32_t flags, uint32_t mode, std::string path,
fidl::InterfaceRequest<fio::Node> object) override {
open_handler_(std::move(path), std::move(object));
}
void NotImplemented_(const std::string& name) override {
printf("Not implemented: Directory::%s\n", name.data());
}
OpenHandler open_handler_;
};
class TestDriverHost : public fdf::testing::DriverHost_TestBase {
public:
using StartHandler = fit::function<void(fdf::DriverStartArgs start_args,
fidl::InterfaceRequest<fdf::Driver> driver)>;
void SetStartHandler(StartHandler start_handler) { start_handler_ = std::move(start_handler); }
private:
void Start(fdf::DriverStartArgs start_args, fidl::InterfaceRequest<fdf::Driver> driver) override {
start_handler_(std::move(start_args), std::move(driver));
}
void NotImplemented_(const std::string& name) override {
printf("Not implemented: DriverHost::%s\n", name.data());
}
StartHandler start_handler_;
};
class TestTransaction : public fidl::Transaction {
public:
TestTransaction(bool close) : close_(close) {}
private:
std::unique_ptr<Transaction> TakeOwnership() override {
EXPECT_TRUE(false);
return nullptr;
}
zx_status_t Reply(fidl::OutgoingMessage* message) override {
EXPECT_TRUE(false);
return ZX_OK;
}
void Close(zx_status_t epitaph) override { EXPECT_TRUE(close_); }
bool close_;
};
struct Driver {
std::string url;
std::string binary;
bool colocate = false;
bool close = false;
};
class DriverRunnerTest : public gtest::TestLoopFixture {
public:
void SetUp() override {
TestLoopFixture::SetUp();
fidl::InterfaceRequestHandler<fsys::Realm> handler = [this](auto request) {
EXPECT_EQ(ZX_OK, realm_binding_.Bind(std::move(request), loop_.dispatcher()));
};
ASSERT_EQ(ZX_OK, provider_.context()->outgoing()->AddPublicService(std::move(handler)));
}
protected:
async::Loop& loop() { return loop_; }
TestRealm& realm() { return realm_; }
TestDirectory& directory() { return directory_; }
TestDriverHost& driver_host() { return driver_host_; }
zx::channel ConnectToRealm() {
fsys::RealmPtr realm;
provider_.ConnectToPublicService(realm.NewRequest(loop_.dispatcher()));
return realm.Unbind().TakeChannel();
}
DriverIndex CreateDriverIndex() {
return DriverIndex([](auto args) -> zx::status<MatchResult> {
std::string_view name(args.name().data(), args.name().size());
if (name == "root") {
return zx::ok(MatchResult{
.url = "fuchsia-boot:///#meta/root-driver.cm",
.matched_args = std::move(args),
});
} else if (name == "second") {
return zx::ok(MatchResult{
.url = "fuchsia-boot:///#meta/second-driver.cm",
.matched_args = std::move(args),
});
} else {
return zx::error(ZX_ERR_NOT_FOUND);
}
});
}
void StartDriverHost(std::string coll, std::string name) {
realm().SetCreateChildHandler(
[coll, name](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ(coll, collection.name);
EXPECT_EQ(name, decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/driver_host2.cm", decl.url());
});
realm().SetBindChildHandler([this, coll, name](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ(coll, child.collection.value_or(""));
EXPECT_EQ(name, child.name);
EXPECT_EQ(ZX_OK, directory_binding_.Bind(std::move(exposed_dir), loop_.dispatcher()));
});
directory().SetOpenHandler([this](std::string path, auto object) {
EXPECT_EQ(fdf::DriverHost::Name_, path);
EXPECT_EQ(ZX_OK, driver_host_binding_.Bind(object.TakeChannel(), loop_.dispatcher()));
});
}
zx::channel StartDriver(DriverRunner* driver_runner, Driver driver) {
fidl::StringView binary = fidl::unowned_str(driver.binary);
auto colocate = driver.colocate ? fidl::StringView("true") : fidl::StringView("false");
fdata::DictionaryEntry program_entries[] = {
{
.key = "binary",
.value = fdata::DictionaryValue::WithStr(fidl::unowned_ptr(&binary)),
},
{
.key = "colocate",
.value = fdata::DictionaryValue::WithStr(fidl::unowned_ptr(&colocate)),
},
};
auto entries = fidl::unowned_vec(program_entries);
auto program = fdata::Dictionary::Builder(std::make_unique<fdata::Dictionary::Frame>())
.set_entries(fidl::unowned_ptr(&entries))
.build();
auto url = fidl::unowned_str(driver.url);
fidl::VectorView<frunner::ComponentNamespaceEntry> ns;
zx::channel outgoing_client_end, outgoing_server_end;
EXPECT_EQ(ZX_OK, zx::channel::create(0, &outgoing_client_end, &outgoing_server_end));
auto start_info = frunner::ComponentStartInfo::UnownedBuilder()
.set_resolved_url(fidl::unowned_ptr(&url))
.set_program(fidl::unowned_ptr(&program))
.set_ns(fidl::unowned_ptr(&ns))
.set_outgoing_dir(fidl::unowned_ptr(&outgoing_server_end));
zx::channel controller_client_end, controller_server_end;
EXPECT_EQ(ZX_OK, zx::channel::create(0, &controller_client_end, &controller_server_end));
TestTransaction transaction(driver.close);
{
frunner::ComponentRunner::Interface::StartCompleter::Sync completer(&transaction);
static_cast<frunner::ComponentRunner::Interface*>(driver_runner)
->Start(start_info.build(), std::move(controller_server_end), completer);
}
loop().RunUntilIdle();
return controller_client_end;
}
zx::status<zx::channel> StartRootDriver(std::string_view name, DriverRunner* driver_runner) {
realm().SetCreateChildHandler([](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ("drivers", collection.name);
EXPECT_EQ("driver-0", decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/root-driver.cm", decl.url());
});
realm().SetBindChildHandler([](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ("drivers", child.collection);
EXPECT_EQ("driver-0", child.name);
});
auto start = driver_runner->StartRootDriver(name);
if (start.is_error()) {
return start.take_error();
}
loop().RunUntilIdle();
StartDriverHost("driver_hosts", "driver_host-1");
zx::channel controller =
StartDriver(driver_runner, {
.url = "fuchsia-boot:///#meta/root-driver.cm",
.binary = "driver/root-driver.so",
});
return zx::ok(std::move(controller));
}
void Unbind() {
driver_host_binding_.Unbind();
loop().RunUntilIdle();
}
private:
TestRealm realm_;
TestDirectory directory_;
TestDriverHost driver_host_;
fidl::Binding<fsys::Realm> realm_binding_{&realm_};
fidl::Binding<fio::Directory> directory_binding_{&directory_};
fidl::Binding<fdf::DriverHost> driver_host_binding_{&driver_host_};
async::Loop loop_{&kAsyncLoopConfigNoAttachToCurrentThread};
sys::testing::ComponentContextProvider provider_{loop_.dispatcher()};
};
// Start the root driver.
TEST_F(DriverRunnerTest, StartRootDriver) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
Unbind();
}
// Start the root driver, and add a child node owned by the root driver.
TEST_F(DriverRunnerTest, StartRootDriver_AddOwnedChild) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([this](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
fdf::NodeControllerPtr node_controller;
fdf::NodePtr second_node;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()),
second_node.NewRequest(loop().dispatcher()));
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
Unbind();
}
// Start the root driver, add a child node, then remove it.
TEST_F(DriverRunnerTest, StartRootDriver_RemoveOwnedChild) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
fdf::NodeControllerPtr node_controller;
fdf::NodePtr second_node;
driver_host().SetStartHandler([this, &node_controller, &second_node](
fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()),
second_node.NewRequest(loop().dispatcher()));
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
node_controller->Remove();
loop().RunUntilIdle();
ASSERT_FALSE(second_node.is_bound());
Unbind();
}
// Start the root driver, and add a child node with duplicate symbols. The child
// node is unowned, so if we did not have duplicate symbols, the second driver
// would bind to it.
TEST_F(DriverRunnerTest, StartRootDriver_AddUnownedChild_DuplicateSymbols) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
fdf::NodeControllerPtr node_controller;
driver_host().SetStartHandler([this, &node_controller](fdf::DriverStartArgs start_args,
auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
args.mutable_symbols()->emplace_back(
std::move(fdf::DriverSymbol().set_name("sym").set_address(0xfeed)));
args.mutable_symbols()->emplace_back(
std::move(fdf::DriverSymbol().set_name("sym").set_address(0xf00d)));
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
loop().RunUntilIdle();
ASSERT_FALSE(node_controller.is_bound());
Unbind();
}
// Start an unknown driver.
TEST_F(DriverRunnerTest, StartRootDriver_UnknownDriver) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
ASSERT_TRUE(StartRootDriver("unknown-driver", &driver_runner).is_error());
}
// Start the root driver, and then start a second driver in a new driver host.
TEST_F(DriverRunnerTest, StartSecondDriver_NewDriverHost) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([this](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
realm().SetCreateChildHandler([](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ("drivers", collection.name);
EXPECT_EQ("driver-2", decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/second-driver.cm", decl.url());
});
realm().SetBindChildHandler([](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ("drivers", child.collection);
EXPECT_EQ("driver-2", child.name);
});
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
args.mutable_symbols()->emplace_back(
std::move(fdf::DriverSymbol().set_name("sym").set_address(0xfeed)));
fdf::NodeControllerPtr node_controller;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
driver_host().SetStartHandler([](fdf::DriverStartArgs start_args, auto driver) {
EXPECT_TRUE(start_args.symbols().empty());
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/second-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
});
StartDriverHost("driver_hosts", "driver_host-3");
StartDriver(&driver_runner, {
.url = "fuchsia-boot:///#meta/second-driver.cm",
.binary = "driver/second-driver.so",
});
Unbind();
}
// Start the root driver, and then start a second driver in the same driver
// host.
TEST_F(DriverRunnerTest, StartSecondDriver_SameDriverHost) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([this](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
realm().SetCreateChildHandler([](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ("drivers", collection.name);
EXPECT_EQ("driver-2", decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/second-driver.cm", decl.url());
});
realm().SetBindChildHandler([](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ("drivers", child.collection);
EXPECT_EQ("driver-2", child.name);
});
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
args.mutable_symbols()->emplace_back(
std::move(fdf::DriverSymbol().set_name("sym").set_address(0xfeed)));
fdf::NodeControllerPtr node_controller;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
driver_host().SetStartHandler([](fdf::DriverStartArgs start_args, auto driver) {
auto& symbols = start_args.symbols();
EXPECT_EQ(1u, symbols.size());
EXPECT_EQ("sym", symbols[0].name());
EXPECT_EQ(0xfeedu, symbols[0].address());
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/second-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("true", entries[1].value->str());
});
StartDriver(&driver_runner, {
.url = "fuchsia-boot:///#meta/second-driver.cm",
.binary = "driver/second-driver.so",
.colocate = true,
});
Unbind();
}
// Start the root driver, and then add a child node that does not bind to a
// second driver.
TEST_F(DriverRunnerTest, StartSecondDriver_UnknownNode) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([this](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("unknown-node");
fdf::NodeControllerPtr node_controller;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
StartDriver(&driver_runner, {.close = true});
Unbind();
}
// Start the second driver, and then unbind its associated node.
TEST_F(DriverRunnerTest, StartSecondDriver_UnbindSecondNode) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
driver_host().SetStartHandler([this](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
realm().SetCreateChildHandler([](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ("drivers", collection.name);
EXPECT_EQ("driver-2", decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/second-driver.cm", decl.url());
});
realm().SetBindChildHandler([](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ("drivers", child.collection);
EXPECT_EQ("driver-2", child.name);
});
fdf::NodePtr root_node;
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
fdf::NodeControllerPtr node_controller;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
ASSERT_TRUE(StartRootDriver("root", &driver_runner).is_ok());
fdf::NodePtr second_node;
driver_host().SetStartHandler([this, &second_node](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/second-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
EXPECT_EQ(ZX_OK,
second_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
});
;
StartDriverHost("driver_hosts", "driver_host-3");
zx::channel second_driver_controller =
StartDriver(&driver_runner, {
.url = "fuchsia-boot:///#meta/second-driver.cm",
.binary = "driver/second-driver.so",
});
// Unbinding the second node stops the driver bound to it.
second_node.Unbind();
loop().RunUntilIdle();
zx_signals_t signals = 0;
ASSERT_EQ(ZX_OK, second_driver_controller.wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite(),
&signals));
ASSERT_TRUE(signals & ZX_CHANNEL_PEER_CLOSED);
Unbind();
}
// Start the second driver, and then unbind the root node.
TEST_F(DriverRunnerTest, StartSecondDriver_UnbindRootNode) {
auto driver_index = CreateDriverIndex();
DriverRunner driver_runner(ConnectToRealm(), &driver_index, loop().dispatcher());
fdf::NodePtr root_node;
driver_host().SetStartHandler([this, &root_node](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/root-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
realm().SetCreateChildHandler([](fsys::CollectionRef collection, fsys::ChildDecl decl) {
EXPECT_EQ("drivers", collection.name);
EXPECT_EQ("driver-2", decl.name());
EXPECT_EQ("fuchsia-boot:///#meta/second-driver.cm", decl.url());
});
realm().SetBindChildHandler([](fsys::ChildRef child, auto exposed_dir) {
EXPECT_EQ("drivers", child.collection);
EXPECT_EQ("driver-2", child.name);
});
EXPECT_EQ(ZX_OK, root_node.Bind(start_args.mutable_node()->TakeChannel(), loop().dispatcher()));
fdf::NodeAddArgs args;
args.set_name("second");
fdf::NodeControllerPtr node_controller;
root_node->AddChild(std::move(args), node_controller.NewRequest(loop().dispatcher()), {});
});
auto root_driver = StartRootDriver("root", &driver_runner);
ASSERT_TRUE(root_driver.is_ok());
driver_host().SetStartHandler([](fdf::DriverStartArgs start_args, auto driver) {
auto& entries = start_args.program().entries();
EXPECT_EQ(2u, entries.size());
EXPECT_EQ("binary", entries[0].key);
EXPECT_EQ("driver/second-driver.so", entries[0].value->str());
EXPECT_EQ("colocate", entries[1].key);
EXPECT_EQ("false", entries[1].value->str());
});
;
StartDriverHost("driver_hosts", "driver_host-3");
zx::channel second_driver_controller =
StartDriver(&driver_runner, {
.url = "fuchsia-boot:///#meta/second-driver.cm",
.binary = "driver/second-driver.so",
});
// Unbinding the root node stops all drivers.
root_node.Unbind();
loop().RunUntilIdle();
zx_signals_t signals = 0;
ASSERT_EQ(ZX_OK, second_driver_controller.wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite(),
&signals));
ASSERT_TRUE(signals & ZX_CHANNEL_PEER_CLOSED);
ASSERT_EQ(ZX_OK, root_driver->wait_one(ZX_CHANNEL_PEER_CLOSED, zx::time::infinite(), &signals));
ASSERT_TRUE(signals & ZX_CHANNEL_PEER_CLOSED);
Unbind();
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
af34f491e1c095e1ff64d8f4bf1b127f60b55839 | 3282ccae547452b96c4409e6b5a447f34b8fdf64 | /SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSlabType.hxx | 6c3ed4a4bc9ec83c6bc88bb21b1e4dbca5dba7a0 | [
"MIT"
] | permissive | EnEff-BIM/EnEffBIM-Framework | c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | refs/heads/master | 2021-01-18T00:16:06.546875 | 2017-04-18T08:03:40 | 2017-04-18T08:03:40 | 28,960,534 | 3 | 0 | null | 2017-04-18T08:03:40 | 2015-01-08T10:19:18 | C++ | UTF-8 | C++ | false | false | 11,293 | hxx | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
#ifndef SIM_SLAB_TYPE_HXX
#define SIM_SLAB_TYPE_HXX
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 4000000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
namespace xml_schema
{
// anyType and anySimpleType.
//
typedef ::xsd::cxx::tree::type type;
typedef ::xsd::cxx::tree::simple_type< char, type > simple_type;
typedef ::xsd::cxx::tree::type container;
// 8-bit
//
typedef signed char byte;
typedef unsigned char unsigned_byte;
// 16-bit
//
typedef short short_;
typedef unsigned short unsigned_short;
// 32-bit
//
typedef int int_;
typedef unsigned int unsigned_int;
// 64-bit
//
typedef long long long_;
typedef unsigned long long unsigned_long;
// Supposed to be arbitrary-length integral types.
//
typedef long long integer;
typedef long long non_positive_integer;
typedef unsigned long long non_negative_integer;
typedef unsigned long long positive_integer;
typedef long long negative_integer;
// Boolean.
//
typedef bool boolean;
// Floating-point types.
//
typedef float float_;
typedef double double_;
typedef double decimal;
// String types.
//
typedef ::xsd::cxx::tree::string< char, simple_type > string;
typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string;
typedef ::xsd::cxx::tree::token< char, normalized_string > token;
typedef ::xsd::cxx::tree::name< char, token > name;
typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken;
typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens;
typedef ::xsd::cxx::tree::ncname< char, name > ncname;
typedef ::xsd::cxx::tree::language< char, token > language;
// ID/IDREF.
//
typedef ::xsd::cxx::tree::id< char, ncname > id;
typedef ::xsd::cxx::tree::idref< char, ncname, type > idref;
typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs;
// URI.
//
typedef ::xsd::cxx::tree::uri< char, simple_type > uri;
// Qualified name.
//
typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname;
// Binary.
//
typedef ::xsd::cxx::tree::buffer< char > buffer;
typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary;
typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary;
// Date/time.
//
typedef ::xsd::cxx::tree::time_zone time_zone;
typedef ::xsd::cxx::tree::date< char, simple_type > date;
typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time;
typedef ::xsd::cxx::tree::duration< char, simple_type > duration;
typedef ::xsd::cxx::tree::gday< char, simple_type > gday;
typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth;
typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day;
typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear;
typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month;
typedef ::xsd::cxx::tree::time< char, simple_type > time;
// Entity.
//
typedef ::xsd::cxx::tree::entity< char, ncname > entity;
typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities;
typedef ::xsd::cxx::tree::content_order content_order;
// Flags and properties.
//
typedef ::xsd::cxx::tree::flags flags;
typedef ::xsd::cxx::tree::properties< char > properties;
// Parsing/serialization diagnostics.
//
typedef ::xsd::cxx::tree::severity severity;
typedef ::xsd::cxx::tree::error< char > error;
typedef ::xsd::cxx::tree::diagnostics< char > diagnostics;
// Exceptions.
//
typedef ::xsd::cxx::tree::exception< char > exception;
typedef ::xsd::cxx::tree::bounds< char > bounds;
typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id;
typedef ::xsd::cxx::tree::parsing< char > parsing;
typedef ::xsd::cxx::tree::expected_element< char > expected_element;
typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element;
typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute;
typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator;
typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content;
typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping;
typedef ::xsd::cxx::tree::no_type_info< char > no_type_info;
typedef ::xsd::cxx::tree::not_derived< char > not_derived;
// Error handler callback interface.
//
typedef ::xsd::cxx::xml::error_handler< char > error_handler;
// DOM interaction.
//
namespace dom
{
// Automatic pointer for DOMDocument.
//
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
// DOM user data key for back pointers to tree nodes.
//
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
// Forward declarations.
//
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
class SimSlabType;
}
}
}
#include <memory> // ::std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include "simobjecttypedefinition.hxx"
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
class SimSlabType: public ::schema::simxml::SimModelCore::SimObjectTypeDefinition
{
public:
// RepresentationMaps
//
typedef ::xml_schema::idrefs RepresentationMaps_type;
typedef ::xsd::cxx::tree::optional< RepresentationMaps_type > RepresentationMaps_optional;
typedef ::xsd::cxx::tree::traits< RepresentationMaps_type, char > RepresentationMaps_traits;
const RepresentationMaps_optional&
RepresentationMaps () const;
RepresentationMaps_optional&
RepresentationMaps ();
void
RepresentationMaps (const RepresentationMaps_type& x);
void
RepresentationMaps (const RepresentationMaps_optional& x);
void
RepresentationMaps (::std::auto_ptr< RepresentationMaps_type > p);
// Tag
//
typedef ::xml_schema::string Tag_type;
typedef ::xsd::cxx::tree::optional< Tag_type > Tag_optional;
typedef ::xsd::cxx::tree::traits< Tag_type, char > Tag_traits;
const Tag_optional&
Tag () const;
Tag_optional&
Tag ();
void
Tag (const Tag_type& x);
void
Tag (const Tag_optional& x);
void
Tag (::std::auto_ptr< Tag_type > p);
// MaterialLayerSet
//
typedef ::xml_schema::idref MaterialLayerSet_type;
typedef ::xsd::cxx::tree::optional< MaterialLayerSet_type > MaterialLayerSet_optional;
typedef ::xsd::cxx::tree::traits< MaterialLayerSet_type, char > MaterialLayerSet_traits;
const MaterialLayerSet_optional&
MaterialLayerSet () const;
MaterialLayerSet_optional&
MaterialLayerSet ();
void
MaterialLayerSet (const MaterialLayerSet_type& x);
void
MaterialLayerSet (const MaterialLayerSet_optional& x);
void
MaterialLayerSet (::std::auto_ptr< MaterialLayerSet_type > p);
// Constructors.
//
SimSlabType ();
SimSlabType (const RefId_type&);
SimSlabType (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
SimSlabType (const SimSlabType& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
virtual SimSlabType*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
SimSlabType&
operator= (const SimSlabType& x);
virtual
~SimSlabType ();
// Implementation.
//
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
RepresentationMaps_optional RepresentationMaps_;
Tag_optional Tag_;
MaterialLayerSet_optional MaterialLayerSet_;
};
}
}
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // SIM_SLAB_TYPE_HXX
| [
"PRemmen@eonerc.rwth-aachen.de"
] | PRemmen@eonerc.rwth-aachen.de |
44367549ebbdcab26927b7228e12b0aa8eeee962 | bb90ad20468f9fe2039b8c16858bd8eae8bbc050 | /src/node/rpc/node_operation_interface.h | 4b09c5efb42476b3daa352b54a0ab92aa7693c89 | [
"Apache-2.0"
] | permissive | microsoft/CCF | 0997fd81a924d36d775b219720b26b4ff196b18a | 2fbf87840b9e8334c141f4a9c9b25aae979b0540 | refs/heads/main | 2023-09-05T15:39:37.265089 | 2023-09-05T15:27:25 | 2023-09-05T15:27:25 | 180,112,558 | 687 | 229 | Apache-2.0 | 2023-09-14T14:28:39 | 2019-04-08T09:13:04 | C++ | UTF-8 | C++ | false | false | 1,874 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/crypto/pem.h"
#include "ccf/ds/quote_info.h"
#include "ccf/node/quote.h"
#include "ccf/node_startup_state.h"
#include "ccf/node_subsystem_interface.h"
#include "ccf/service/tables/code_id.h"
#include "ccf/tx.h"
#include "node/session_metrics.h"
namespace ccf
{
using ExtendedState = std::tuple<
NodeStartupState,
std::optional<kv::Version> /* recovery_target_seqno */,
std::optional<kv::Version> /* last_recovered_seqno */>;
class AbstractNodeOperation : public ccf::AbstractNodeSubSystem
{
public:
virtual ~AbstractNodeOperation() = default;
static char const* get_subsystem_name()
{
return "NodeOperation";
}
virtual ExtendedState state() = 0;
virtual bool is_in_initialised_state() const = 0;
virtual bool is_part_of_public_network() const = 0;
virtual bool is_part_of_network() const = 0;
virtual bool is_reading_public_ledger() const = 0;
virtual bool is_reading_private_ledger() const = 0;
virtual bool is_user_frontend_open() = 0;
virtual bool is_member_frontend_open() = 0;
virtual bool is_accessible_to_members() const = 0;
virtual bool can_replicate() = 0;
virtual kv::Version get_last_recovered_signed_idx() = 0;
virtual kv::Version get_startup_snapshot_seqno() = 0;
virtual SessionMetrics get_session_metrics() = 0;
virtual size_t get_jwt_attempts() = 0;
virtual QuoteVerificationResult verify_quote(
kv::ReadOnlyTx& tx,
const QuoteInfo& quote_info,
const std::vector<uint8_t>& expected_node_public_key_der,
pal::PlatformAttestationMeasurement& measurement) = 0;
virtual void initiate_private_recovery(kv::Tx& tx) = 0;
virtual crypto::Pem get_self_signed_node_certificate() = 0;
};
} | [
"noreply@github.com"
] | microsoft.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.