hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c853343e984e98ccab0433ea4a7811454c4fbe54
738
cpp
C++
src/nnfusion/core/operators/generic_op/generic_op_define/GatherGrad.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/GatherGrad.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/GatherGrad.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "nnfusion/core/operators/generic_op/generic_op.hpp" REGISTER_OP(GatherGrad) .attr<int>("axis", 0) .attr<std::vector<int>>("x_shape") .infershape([](std::shared_ptr<graph::GNode> gnode) -> void { NNFUSION_CHECK(gnode->get_input_size() == 3); auto x_grad_type = gnode->get_input_element_type(1); auto generic_op = std::dynamic_pointer_cast<nnfusion::op::GenericOp>(gnode->get_op_ptr()); std::vector<int> x_shape = generic_op->localOpConfig.getRoot()["x_shape"]; nnfusion::Shape output_shape_0; gnode->set_output_type_and_shape(0, x_grad_type, Shape(x_shape.begin(), x_shape.end())); });
36.9
98
0.684282
lynex
c85866bbfb9edc86ad5b1d4719b5c85af3859c63
1,185
cpp
C++
3rdParty/vcglib/apps/unsupported/extractors/extractor/main.cpp
TonyGauss/tg3DLib
d425e91567b9e1642e7411330738d8e2b0880a2b
[ "MIT" ]
27
2016-11-10T16:11:28.000Z
2021-12-21T20:11:39.000Z
3rdParty/vcglib/apps/unsupported/extractors/extractor/main.cpp
TonyGauss/tg3DLib
d425e91567b9e1642e7411330738d8e2b0880a2b
[ "MIT" ]
8
2016-10-27T10:10:05.000Z
2019-12-07T21:27:02.000Z
3rdParty/vcglib/apps/unsupported/extractors/extractor/main.cpp
TonyGauss/tg3DLib
d425e91567b9e1642e7411330738d8e2b0880a2b
[ "MIT" ]
14
2015-07-21T04:47:52.000Z
2020-03-12T12:31:25.000Z
#include <stdio.h> #include <wrap/io_trimesh/export_ply.h> #include "Definitions.h" #include "Volume.h" #include "Walker.h" #include <vcg/complex/algorithms/create/marching_cubes.h> #include <vcg/complex/algorithms/create/extended_marching_cubes.h> int main(int argc, char *argv[]) { BoundingBox bbox(vcg::Point3i(-20, -20, -20), vcg::Point3i(20, 20, 20)); vcg::Point3i resolution(40, 40, 40); Volume volume; Walker walker(bbox, resolution); typedef vcg::tri::MarchingCubes<Mesh, Walker> MarchingCubes; typedef vcg::tri::ExtendedMarchingCubes<Mesh, Walker> ExtendedMarchingCubes; // MARCHING CUBES Mesh mc_mesh; printf("[MARCHING CUBES] Building mesh..."); MarchingCubes mc(mc_mesh, walker); walker.BuildMesh<MarchingCubes>(mc_mesh, volume, mc); vcg::tri::io::ExporterPLY<Mesh>::Save( mc_mesh, "marching_cubes.ply"); printf("OK!\n"); // EXTENDED MARCHING CUBES Mesh emc_mesh; printf("[EXTENDED MARCHING CUBES] Building mesh..."); ExtendedMarchingCubes emc(emc_mesh, walker, 30); walker.BuildMesh<ExtendedMarchingCubes>(emc_mesh, volume, emc); vcg::tri::io::ExporterPLY<Mesh>::Save( emc_mesh, "extended_marching_cubes.ply"); printf("OK!\n"); };
32.027027
81
0.729958
TonyGauss
c8596aa347d1c103f00b0032ac4985869ec1acca
5,323
cpp
C++
src/collisionhandler.cpp
adct-the-experimenter/Door-To-Life-Minimal
a4a08d13443bdf21d4efc27f8509f5d5f8d57584
[ "BSD-2-Clause" ]
null
null
null
src/collisionhandler.cpp
adct-the-experimenter/Door-To-Life-Minimal
a4a08d13443bdf21d4efc27f8509f5d5f8d57584
[ "BSD-2-Clause" ]
null
null
null
src/collisionhandler.cpp
adct-the-experimenter/Door-To-Life-Minimal
a4a08d13443bdf21d4efc27f8509f5d5f8d57584
[ "BSD-2-Clause" ]
null
null
null
#include "collisionhandler.h" CollisonHandler::CollisonHandler() { repeatPlay = false; } CollisonHandler::~CollisonHandler() { } void CollisonHandler::addPlayerToCollisionSystem(CollisionObject* thisObject) { //Initialize collision type to none thisObject->typeOfCollision = CollisionType::NONE; //assign player collision object global pointer to this object m_playerCollisionObject_ptr = thisObject; } void CollisonHandler::addObjectToCollisionSystem(CollisionObject* thisObject) { //Initialize collision type to none thisObject->typeOfCollision = CollisionType::NONE; collisionObjectsVector.push_back(thisObject); } void CollisonHandler::addPlayerEquippedWeaponToCollisionSystem(Weapon* thisWeapon) { //Initialize collision type to none thisWeapon->getCollisionObjectPtr()->typeOfCollision = CollisionType::NONE; playerEquippedWeapon = thisWeapon; } void CollisonHandler::removeObjectFromCollisionSystem(CollisionObject* thisObject) { //Initialize collision type to none thisObject->typeOfCollision = CollisionType::NONE; } void CollisonHandler::setCameraForCollisionSystem(SDL_Rect* camera) { cameraCollisionHandler = camera; } void CollisonHandler::run_collision_handler() { //for every collision object element in vector for(size_t i = 0; i < collisionObjectsVector.size(); ++i) { //if collision object pointer not pointing to nullptr if(collisionObjectsVector[i] != nullptr) { if(repeatPlay) { std::cout << "repeat Play" << std::endl; } if(collisionObjectsVector.at(i)->ownerType != CollisionBoxOwnerType::NONE) { if(collisionObjectsVector.at(i)->ptrToCollisionBox) { //if object is within camera if(checkCollision( *collisionObjectsVector.at(i)->ptrToCollisionBox,*cameraCollisionHandler )) { //check if object hits player CollisonHandler::runPlayerCollisionOperations(*collisionObjectsVector[i]); //check if object collided with player's equipped weapon CollisonHandler::runPlayerWeaponCollisionOperations(*collisionObjectsVector[i]); } } else { std::cout << "Error, i: " << i << " collision pointer is not initialized.\n"; } } else { std::cout << "Uninitialized collision object at i=" << i <<" ! \n"; } } } } //function to check if object collided with player void CollisonHandler::runPlayerCollisionOperations(CollisionObject& thisObject) { //if player collision object pointer is not pointing to nullptr if(m_playerCollisionObject_ptr != nullptr) { //if collides with player if(checkCollision( *m_playerCollisionObject_ptr->ptrToCollisionBox, *thisObject.ptrToCollisionBox ) ) { //set collision type of enemy collision object to type hit player thisObject.typeOfCollision = CollisionType::HIT_PLAYER; CollisionType typeCollisionToPlayer; //set collision type of player collision object based on switch(thisObject.ownerType ) { case CollisionBoxOwnerType::COCKROACH :{ typeCollisionToPlayer = CollisionType::HIT_BY_COCKROACH; break;} case CollisionBoxOwnerType::GREEDY_ZOMBIE :{ typeCollisionToPlayer = CollisionType::HIT_BY_ZOMBIE; break;} case CollisionBoxOwnerType::HOLE:{ typeCollisionToPlayer = CollisionType::COLLIDING_WITH_HOLE; break;} default:{typeCollisionToPlayer = CollisionType::NONE; break;} } m_playerCollisionObject_ptr->typeOfCollision = typeCollisionToPlayer; } //else set collision type to none else{thisObject.typeOfCollision = CollisionType::NONE;} } } //function to check if object collided with player weapon void CollisonHandler::runPlayerWeaponCollisionOperations(CollisionObject& thisObject) { if(playerEquippedWeapon != nullptr) { if(playerEquippedWeapon->checkCollisionWithWeapon(*thisObject.ptrToCollisionBox)) { //type of collision to object //initialize to previous collision type CollisionType typeCollisionToObject = thisObject.typeOfCollision; //set collision type of enemy collision object //based on owner type of equipped weapon switch(playerEquippedWeapon->getCollisionObjectPtr()->ownerType) { case CollisionBoxOwnerType::SWORD:{typeCollisionToObject = CollisionType::HIT_BY_SWORD; break;} case CollisionBoxOwnerType::BULLET:{typeCollisionToObject = CollisionType::HIT_BY_BULLET; break;} default:{ break;} } thisObject.typeOfCollision = typeCollisionToObject; //set direction of collision of object to direction of collision of player's weapon thisObject.directionOfCollision = playerEquippedWeapon->getCollisionObjectPtr()->directionOfCollision; } } } void CollisonHandler::EmptyCollisionObjectVector() { collisionObjectsVector.empty(); } void CollisonHandler::EmptyPlayerEquippedWeapon() { playerEquippedWeapon = nullptr; }
31.874251
122
0.683261
adct-the-experimenter
c85de337c19073225558a9d9317e8a6a83c29dac
5,393
cpp
C++
nntrainer/src/loss_layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
nntrainer/src/loss_layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
nntrainer/src/loss_layer.cpp
kparichay/nntrainer
79e37918a3ced623346e285993d6714cb5d1e14b
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2020 Samsung Electronics Co., Ltd. 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. * * * @file loss_layer.cpp * @date 12 June 2020 * @brief This is Loss Layer Class for Neural Network * @see https://github.com/nnstreamer/nntrainer * @author Parichay Kapoor <pk.kapoor@samsung.com> * @bug No known bugs except for NYI items * */ #include <activation_layer.h> #include <layer.h> #include <lazy_tensor.h> #include <loss_layer.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <util_func.h> namespace nntrainer { int LossLayer::initialize() { int status = ML_ERROR_NONE; output_dim = input_dim; return status; } sharedConstTensor LossLayer::forwarding(sharedConstTensor in, sharedConstTensor label) { input = *in; Tensor y2 = *label; Tensor y = input; Tensor l; switch (loss_type) { case LossType::LOSS_MSE: { // y2 <- y2 - y; Tensor residual = y2.subtract(y); l = residual.chain().multiply_i(residual).average().run(); } break; case LossType::LOSS_ENTROPY_SIGMOID: { // @todo: change this to apply_i // @note: the output should be logit before applying sigmoid // log(1 + exp(-abs(y))) + max(y, 0) Tensor mid_term = y.apply(static_cast<float (*)(float)>(&std::fabs)) .multiply(-1.0) .apply(static_cast<float (*)(float)>(&std::exp)) .add(1.0) .apply(logFloat); mid_term = mid_term.add(y.apply(ActivationLayer::relu)); // y * y2 Tensor end_term = y2.chain().multiply_i(y).run(); // loss = log(1 + exp(-abs(y))) + max(y, 0) - (y * y2) l = mid_term.subtract(end_term).average(); y = y.apply(ActivationLayer::sigmoid); } break; case LossType::LOSS_ENTROPY_SOFTMAX: { y = y.apply(ActivationLayer::softmax); l = y2.chain() .multiply_i(y.apply(logFloat)) .run() .sum_by_batch() .multiply(-1); } break; case LossType::LOSS_ENTROPY: { throw std::runtime_error( "Error: Cross Entropy not supported without softmax or sigmoid."); } case LossType::LOSS_UNKNOWN: /** intended */ default: { throw std::runtime_error("Error: Unknown loss_type."); } } updateLoss(l); return MAKE_SHARED_TENSOR(std::move(y)); } sharedConstTensor LossLayer::forwarding(sharedConstTensor in) { Tensor ret; switch (loss_type) { case LossType::LOSS_MSE: return in; case LossType::LOSS_ENTROPY_SIGMOID: ret = in->apply(ActivationLayer::sigmoid); return MAKE_SHARED_TENSOR(std::move(ret)); case LossType::LOSS_ENTROPY_SOFTMAX: ret = in->apply(ActivationLayer::softmax); return MAKE_SHARED_TENSOR(std::move(ret)); case LossType::LOSS_ENTROPY: throw std::runtime_error( "Error: Cross Entropy not supported without softmax or sigmoid."); case LossType::LOSS_UNKNOWN: /** intended */ default: throw std::runtime_error("Error: Unknown loss_type."); } } void LossLayer::updateLoss(const Tensor &l) { float loss_sum = 0.0f; const float *data = l.getData(); for (unsigned int i = 0; i < l.batch(); i++) { loss_sum += data[i]; } loss = loss_sum / (float)l.batch(); } void LossLayer::copy(std::shared_ptr<Layer> l) { std::shared_ptr<LossLayer> from = std::static_pointer_cast<LossLayer>(l); this->input.copy(from->input); this->loss_type = from->loss_type; this->loss = from->loss; } sharedConstTensor LossLayer::backwarding(sharedConstTensor derivative, int iteration) { Tensor ret_derivative; Tensor y2 = *derivative; Tensor y = input; switch (loss_type) { case LossType::LOSS_MSE: ret_derivative = y.subtract(y2).multiply(2).divide(y.getDim().getDataLen()); break; case LossType::LOSS_ENTROPY_SIGMOID: y = y.apply(ActivationLayer::sigmoid); ret_derivative = y.subtract(y2).divide(y.getDim().getDataLen()); break; case LossType::LOSS_ENTROPY_SOFTMAX: y = y.apply(ActivationLayer::softmax); ret_derivative = y.subtract(y2).divide(y.batch()); break; case LossType::LOSS_ENTROPY: throw std::runtime_error( "Error: Cross Entropy not supported without softmax or sigmoid."); case LossType::LOSS_UNKNOWN: /** intended */ default: throw std::runtime_error("Unknown loss_type."); } return MAKE_SHARED_TENSOR(std::move(ret_derivative)); } int LossLayer::setLoss(LossType l) { int status = ML_ERROR_NONE; if (l == LossType::LOSS_UNKNOWN) { ml_loge("Error: Unknown loss type"); return ML_ERROR_INVALID_PARAMETER; } loss_type = l; return status; } void LossLayer::setProperty(const PropertyType type, const std::string &value) { throw exception::not_supported("[Loss Layer] setProperty not supported"); } } /* namespace nntrainer */
30.128492
80
0.664936
kparichay
c85ff7915ae49ea397b03b9fcb5997015e797a9e
3,323
cpp
C++
PofDroid/src/testApp.cpp
Ant1r/POF
b80210527454484f64003b7a09c8e7f9f8a09ac3
[ "BSD-2-Clause" ]
64
2015-03-26T00:03:34.000Z
2021-12-30T12:27:49.000Z
PofDroid/src/testApp.cpp
Ant1r/POF
b80210527454484f64003b7a09c8e7f9f8a09ac3
[ "BSD-2-Clause" ]
7
2015-03-27T09:26:29.000Z
2021-05-08T22:59:52.000Z
PofDroid/src/testApp.cpp
Ant1r/POF
b80210527454484f64003b7a09c8e7f9f8a09ac3
[ "BSD-2-Clause" ]
7
2015-07-02T11:00:36.000Z
2020-04-05T18:48:38.000Z
/* * Copyright (c) 2014 Antoine Rousseau <antoine@metalu.net> * BSD Simplified License, see the file "LICENSE.txt" in this distribution. * See https://github.com/Ant1r/ofxPof for documentation and updates. */ #include "testApp.h" #include "pofBase.h" #include "ofxAccelerometer.h" using namespace std; using namespace pd; //-------------------------------------------------------------- void testApp::setup() { // the number of libpd ticks per buffer, // used to compute the audio buffer len: tpb * blocksize (always 64) //#ifdef TARGET_LINUX_ARM // longer latency for Raspberry PI //int ticksPerBuffer = 32; // 32 * 64 = buffer len of 2048 //int numInputs = 0; // no built in mic //#else int ticksPerBuffer = 1; // 8 * 64 = buffer len of 512 int numInputs = 1; //#endif ofSetFrameRate(60); ofSetVerticalSync(true); ofLogNotice("OF", "init sound"); // setup OF sound stream //ofSoundStreamSetup(2, numInputs, this, 44100, ofxPd::blockSize()*ticksPerBuffer, 4); os = NULL; os = opensl_open(44100, numInputs, 2, ticksPerBuffer*PdBase::blockSize(), testApp::opensl_process, (void*)this); ofxAccelerometer.setup(); ofLogNotice("OF", "init pd"); if(!puda.init(2, numInputs, 44100, ticksPerBuffer)) { ofExit(); } ofLogNotice("OF", "init pof"); pofBase::setup(); ofLogNotice("OF", "start pd"); puda.start(); ofLogNotice("OF", "load patch"); Patch patch = puda.openPatch(ofToDataPath("pd/pof_main.pd")); if(os) opensl_start(os); } //-------------------------------------------------------------- void testApp::update() { pofBase::updateAll(); } //-------------------------------------------------------------- void testApp::draw() { pofBase::drawAll(); } //-------------------------------------------------------------- void testApp::exit() {} //-------------------------------------------------------------- void testApp::keyPressed(int key) {} //-------------------------------------------------------------- void testApp::touchDown(int x, int y, int id){ pofBase::touchDownAll(x, y, id); } void testApp::touchMoved(int x, int y, int id){ pofBase::touchMovedAll(x, y, id); } void testApp::touchUp(int x, int y, int id){ pofBase::touchUpAll(x, y, id); } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { pofBase::windowResized(w,h); } //-------------------------------------------------------------- void testApp::audioReceived(float * input, int bufferSize, int nChannels) { puda.audioIn(input, bufferSize, nChannels); } //-------------------------------------------------------------- void testApp::audioRequested(float * output, int bufferSize, int nChannels) { puda.audioOut(output, bufferSize, nChannels); } //-------------------------------------------------------------- void testApp::reloadTextures() { pofBase::reloadTextures(); } void testApp::unloadTextures() { pofBase::unloadTextures(); } //-------------------------------------------------------------- short testInBuf[1024], testOutBuf[1024]; void testApp::opensl_process(void *app, int sample_rate, int buffer_frames, int input_channels, const short *input_buffer, int output_channels, short *output_buffer) { ((testApp*)app)->puda.PdBase::processShort(/*buffer_frames*/1,(short *)input_buffer, output_buffer); }
28.646552
113
0.550406
Ant1r
c8610270a1e7f77b9f40270894682a310daec69a
5,163
hh
C++
hackt_docker/hackt/src/sim/prsim/TimingChecker.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/sim/prsim/TimingChecker.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/sim/prsim/TimingChecker.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "sim/prsim/TimingChecker.hh" Classes for timing constraint checking. */ #ifndef __HAC_SIM_PRSIM_TIMING_CHECKER_HH____ #define __HAC_SIM_PRSIM_TIMING_CHECKER_HH____ #include <vector> #include <set> #include <map> #include "sim/time.hh" #include "sim/prsim/Exception.hh" #include "sim/prsim/enums.hh" #include "util/memory/array_pool.hh" namespace HAC { namespace SIM { namespace PRSIM { using std::vector; using std::pair; class State; class ExprAlloc; //============================================================================= /** Structure responsible for maintaining timing constraint checking. */ class TimingChecker { typedef real_time time_type; public: struct timing_exception : public generic_exception { /// value of trigger node value_enum tvalue; /// reference node index node_index_type reference; // reference node /// direction of clock edge true:pos, false:neg bool dir; /// type of timing violation (eventually enum) bool is_setup; // else hold /// process id that owns this constraint process_index_type pid; /// min_delay value of constraint time_type min_delay; timing_exception() : generic_exception(INVALID_NODE_INDEX, ERROR_FATAL) { /* uninitialized */ } timing_exception(const node_index_type r, const node_index_type t, const value_enum v, const bool d, const bool type, const process_index_type p, const time_type m, const error_policy_enum e) : generic_exception(t, e), tvalue(v), reference(r), dir(d), is_setup(type), pid(p), min_delay(m) { } void save(ostream&) const; void load(istream&); error_policy_enum inspect(const State&, ostream&) const; ostream& dump_checkpoint(ostream&) const; }; // end timing_exception private: const State& state; // back-reference public: /// setup time violation policy error_policy_enum setup_violation_policy; /// hold time violation policy error_policy_enum hold_violation_policy; private: enum { ERROR_DEFAULT_SETUP_VIOLATION = ERROR_WARN, ERROR_DEFAULT_HOLD_VIOLATION = ERROR_BREAK }; /** key: index of node that triggers timing check(s) PRSIM_FWD_POST_TIMING_CHECKS:0 -- key is the trigger node PRSIM_FWD_POST_TIMING_CHECKS:1 -- key is the reference node value: set of processes that need to check the node These should be unique and sorted. */ typedef std::set<node_index_type> local_node_ids_type; typedef std::map<node_index_type, std::map<process_index_type, local_node_ids_type> > timing_constraint_process_map_type; timing_constraint_process_map_type setup_check_map; timing_constraint_process_map_type hold_check_map; #if PRSIM_FWD_POST_TIMING_CHECKS // can we use a timing_exception? typedef size_t timing_check_index_type; typedef util::memory::array_pool<vector<timing_exception>, vector<timing_check_index_type> > timing_check_pool_type; typedef pair<timing_check_index_type, node_index_type> timing_check_queue_entry; typedef std::multimap<time_type, timing_check_queue_entry> timing_check_queue_type; typedef std::map<node_index_type, std::set<timing_check_index_type> > timing_check_map_type; /// this owns the actual timing_exception objects timing_check_pool_type timing_check_pool; /// time-ordered queue of pointers to active checks timing_check_queue_type timing_check_queue; /// per-node set of active timing checks timing_check_map_type active_timing_check_map; #endif // PRSIM_FWD_POST_TIMING_CHECKS public: explicit TimingChecker(const State&); ~TimingChecker(); /** \param g global node index \param p global process index \param l local node index in that process */ void register_setup_check(const node_index_type g, const process_index_type p, const node_index_type l) { setup_check_map[g][p].insert(l); } void register_hold_check(const node_index_type g, const process_index_type p, const node_index_type l) { hold_check_map[g][p].insert(l); } void reset(void); void set_mode_fatal(void); #if PRSIM_FWD_POST_TIMING_CHECKS void register_timing_check(const timing_exception&, const time_type&); void post_setup_check(const node_index_type, const value_enum); void post_hold_check(const node_index_type, const value_enum); void expire_timing_checks(void); void destroy_timing_checks(void); void check_active_timing_constraints(State&, const node_index_type, const value_enum); // for checkpointing void save_active_timing_checks(ostream&) const; void load_active_timing_checks(istream&); static ostream& dump_active_timing_checks(ostream&, istream&); #else void do_setup_check(State&, const node_index_type, const value_enum); void do_hold_check(State&, const node_index_type, const value_enum); #endif void save_checkpoint(ostream&) const; void load_checkpoint(istream&); static ostream& dump_checkpoint(ostream&, istream&); }; // end class TimingChecker //============================================================================= } // end namespace PRSIM } // end namespace SIM } // end namespace HAC #endif // __HAC_SIM_PRSIM_TIMING_CHECKER_HH____
24.703349
79
0.739493
broken-wheel
c8635e55a4164adb1bc6beaf257da0cba8207cdf
22,128
hpp
C++
recipes-coinutils/coinutils/coinutils/src/CoinMessageHandler.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-coinutils/coinutils/coinutils/src/CoinMessageHandler.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-coinutils/coinutils/coinutils/src/CoinMessageHandler.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #ifndef CoinMessageHandler_H #define CoinMessageHandler_H #include "CoinUtilsConfig.h" #include "CoinPragma.hpp" #include "CoinTypes.h" #include <iostream> #include <cstdio> #include <string> #include <vector> /** \file CoinMessageHandler.hpp \brief This is a first attempt at a message handler. The COIN Project is in favo(u)r of multi-language support. This implementation of a message handler tries to make it as lightweight as possible in the sense that only a subset of messages need to be defined --- the rest default to US English. The default handler at present just prints to stdout or to a FILE pointer \todo This needs to be worked over for correct operation with ISO character codes. */ /* I (jjf) am strongly in favo(u)r of language support for an open source project, but I have tried to make it as lightweight as possible in the sense that only a subset of messages need to be defined - the rest default to US English. There will be different sets of messages for each component - so at present there is a Clp component and a Coin component. Because messages are only used in a controlled environment and have no impact on code and are tested by other tests I have included tests such as language and derivation in other unit tests. */ /* Where there are derived classes I (jjf) have started message numbers at 1001. */ /** \brief Class for one massaged message. A message consists of a text string with formatting codes (#message_), an integer identifier (#externalNumber_) which also determines the severity level (#severity_) of the message, and a detail (logging) level (#detail_). CoinOneMessage is just a container to hold this information. The interpretation is set by CoinMessageHandler, which see. */ class COINUTILSLIB_EXPORT CoinOneMessage { public: /**@name Constructors etc */ //@{ /** Default constructor. */ CoinOneMessage(); /** Normal constructor */ CoinOneMessage(int externalNumber, char detail, const char *message); /** Destructor */ ~CoinOneMessage(); /** The copy constructor */ CoinOneMessage(const CoinOneMessage &); /** assignment operator. */ CoinOneMessage &operator=(const CoinOneMessage &); //@} /**@name Useful stuff */ //@{ /// Replace message text (<i>e.g.</i>, text in a different language) void replaceMessage(const char *message); //@} /**@name Get and set methods */ //@{ /** Get message ID number */ inline int externalNumber() const { return externalNumber_; } /** \brief Set message ID number In the default CoinMessageHandler, this number is printed in the message prefix and is used to determine the message severity level. */ inline void setExternalNumber(int number) { externalNumber_ = number; } /// Severity inline char severity() const { return severity_; } /// Set detail level inline void setDetail(int level) { detail_ = static_cast< char >(level); } /// Get detail level inline int detail() const { return detail_; } /// Return the message text inline char *message() const { return message_; } //@} /**@name member data */ //@{ /// number to print out (also determines severity) int externalNumber_; /// Will only print if detail matches char detail_; /// Severity char severity_; /// Messages (in correct language) (not all 400 may exist) mutable char message_[400]; //@} }; /** \brief Class to hold and manipulate an array of massaged messages. Note that the message index used to reference a message in the array of messages is completely distinct from the external ID number stored with the message. */ class COINUTILSLIB_EXPORT CoinMessages { public: /** \brief Supported languages These are the languages that are supported. At present only us_en is serious and the rest are for testing. */ enum Language { us_en = 0, uk_en, it }; /**@name Constructors etc */ //@{ /** Constructor with number of messages. */ CoinMessages(int numberMessages = 0); /** Destructor */ ~CoinMessages(); /** The copy constructor */ CoinMessages(const CoinMessages &); /** assignment operator. */ CoinMessages &operator=(const CoinMessages &); //@} /**@name Useful stuff */ //@{ /*! \brief Installs a new message in the specified index position Any existing message is replaced, and a copy of the specified message is installed. */ void addMessage(int messageNumber, const CoinOneMessage &message); /*! \brief Replaces the text of the specified message Any existing text is deleted and the specified text is copied into the specified message. */ void replaceMessage(int messageNumber, const char *message); /** Language. Need to think about iso codes */ inline Language language() const { return language_; } /** Set language */ void setLanguage(Language newlanguage) { language_ = newlanguage; } /// Change detail level for one message void setDetailMessage(int newLevel, int messageNumber); /** \brief Change detail level for several messages messageNumbers is expected to contain the indices of the messages to be changed. If numberMessages >= 10000 or messageNumbers is NULL, the detail level is changed on all messages. */ void setDetailMessages(int newLevel, int numberMessages, int *messageNumbers); /** Change detail level for all messages with low <= ID number < high */ void setDetailMessages(int newLevel, int low, int high); /// Returns class inline int getClass() const { return class_; } /// Moves to compact format void toCompact(); /// Moves from compact format void fromCompact(); //@} /**@name member data */ //@{ /// Number of messages int numberMessages_; /// Language Language language_; /// Source (null-terminated string, maximum 4 characters). char source_[5]; /// Class - see later on before CoinMessageHandler int class_; /** Length of fake CoinOneMessage array. First you get numberMessages_ pointers which point to stuff */ int lengthMessages_; /// Messages CoinOneMessage **message_; //@} }; // for convenience eol enum CoinMessageMarker { CoinMessageEol = 0, CoinMessageNewline = 1 }; /** Base class for message handling The default behavior is described here: messages are printed, and (if the severity is sufficiently high) execution will be aborted. Inherit and redefine the methods #print and #checkSeverity to augment the behaviour. Messages can be printed with or without a prefix; the prefix will consist of a source string, the external ID number, and a letter code, <i>e.g.</i>, Clp6024W. A prefix makes the messages look less nimble but is very useful for "grep" <i>etc</i>. <h3> Usage </h3> The general approach to using the COIN messaging facility is as follows: <ul> <li> Define your messages. For each message, you must supply an external ID number, a log (detail) level, and a format string. Typically, you define a convenience structure for this, something that's easy to use to create an array of initialised message definitions at compile time. <li> Create a CoinMessages object, sized to accommodate the number of messages you've defined. (Incremental growth will happen if necessary as messages are loaded, but it's inefficient.) <li> Load the messages into the CoinMessages object. Typically this entails creating a CoinOneMessage object for each message and passing it as a parameter to CoinMessages::addMessage(). You specify the message's internal ID as the other parameter to addMessage. <li> Create and use a CoinMessageHandler object to print messages. </ul> See, for example, CoinMessage.hpp and CoinMessage.cpp for an example of the first three steps. `Format codes' below has a simple example of printing a message. <h3> External ID numbers and severity </h3> CoinMessageHandler assumes the following relationship between the external ID number of a message and the severity of the message: \li <3000 are informational ('I') \li <6000 warnings ('W') \li <9000 non-fatal errors ('E') \li >=9000 aborts the program (after printing the message) ('S') <h3> Log (detail) levels </h3> The default behaviour is that a message will print if its detail level is less than or equal to the handler's log level. If all you want to do is set a single log level for the handler, use #setLogLevel(int). If you want to get fancy, here's how it really works: There's an array, #logLevels_, which you can manipulate with #setLogLevel(int,int). Each entry logLevels_[i] specifies the log level for messages of class i (see CoinMessages::class_). If logLevels_[0] is set to the magic number -1000 you get the simple behaviour described above, whatever the class of the messages. If logLevels_[0] is set to a valid log level (>= 0), then logLevels_[i] really is the log level for messages of class i. <h3> Format codes </h3> CoinMessageHandler can print integers (normal, long, and long long), doubles, characters, and strings. See the descriptions of the various << operators. When processing a standard message with a format string, the formatting codes specified in the format string will be passed to the sprintf function, along with the argument. When generating a message with no format string, each << operator uses a simple format code appropriate for its argument. Consult the documentation for the standard printf facility for further information on format codes. The special format code `%?' provides a hook to enable or disable printing. For each `%?' code, there must be a corresponding call to printing(bool). This provides a way to define optional parts in messages, delineated by the code `%?' in the format string. Printing can be suppressed for these optional parts, but any operands must still be supplied. For example, given the message string \verbatim "A message with%? an optional integer %d and%? a double %g." \endverbatim installed in CoinMessages \c exampleMsgs with index 5, and \c CoinMessageHandler \c hdl, the code \code hdl.message(5,exampleMsgs) ; hdl.printing(true) << 42 ; hdl.printing(true) << 53.5 << CoinMessageEol ; \endcode will print \verbatim A message with an optional integer 42 and a double 53.5. \endverbatim while \code hdl.message(5,exampleMsgs) ; hdl.printing(false) << 42 ; hdl.printing(true) << 53.5 << CoinMessageEol ; \endcode will print \verbatim A message with a double 53.5. \endverbatim For additional examples of usage, see CoinMessageHandlerUnitTest in CoinMessageHandlerTest.cpp. */ class COINUTILSLIB_EXPORT CoinMessageHandler { friend bool CoinMessageHandlerUnitTest(); public: /**@name Virtual methods that the derived classes may provide */ //@{ /** Print message, return 0 normally. */ virtual int print(); /** Check message severity - if too bad then abort */ virtual void checkSeverity(); //@} /**@name Constructors etc */ //@{ /// Constructor CoinMessageHandler(); /// Constructor to put to file pointer (won't be closed) CoinMessageHandler(FILE *fp); /** Destructor */ virtual ~CoinMessageHandler(); /** The copy constructor */ CoinMessageHandler(const CoinMessageHandler &); /** Assignment operator. */ CoinMessageHandler &operator=(const CoinMessageHandler &); /// Clone virtual CoinMessageHandler *clone() const; //@} /**@name Get and set methods */ //@{ /// Get detail level of a message. inline int detail(int messageNumber, const CoinMessages &normalMessage) const { return normalMessage.message_[messageNumber]->detail(); } /** Get current log (detail) level. */ inline int logLevel() const { return logLevel_; } /** \brief Set current log (detail) level. If the log level is equal or greater than the detail level of a message, the message will be printed. A rough convention for the amount of output expected is - 0 - none - 1 - minimal - 2 - normal low - 3 - normal high - 4 - verbose Please assign log levels to messages accordingly. Log levels of 8 and above (8,16,32, <i>etc</i>.) are intended for selective debugging. The logical AND of the log level specified in the message and the current log level is used to determine if the message is printed. (In other words, you're using individual bits to determine which messages are printed.) */ void setLogLevel(int value); /** Get alternative log level. */ inline int logLevel(int which) const { return logLevels_[which]; } /*! \brief Set alternative log level value. Can be used to store alternative log level information within the handler. */ void setLogLevel(int which, int value); /// Set the number of significant digits for printing floating point numbers void setPrecision(unsigned int new_precision); /// Current number of significant digits for printing floating point numbers inline int precision() { return (g_precision_); } /// Switch message prefix on or off. void setPrefix(bool yesNo); /// Current setting for printing message prefix. bool prefix() const; /*! \brief Values of double fields already processed. As the parameter for a double field is processed, the value is saved and can be retrieved using this function. */ double doubleValue(int position) const; /*! \brief Number of double fields already processed. Incremented each time a field of type double is processed. */ int numberDoubleFields() const; /*! \brief Values of integer fields already processed. As the parameter for a integer field is processed, the value is saved and can be retrieved using this function. */ CoinBigIndex intValue(int position) const; /*! \brief Number of integer fields already processed. Incremented each time a field of type integer is processed. */ int numberIntFields() const; /*! \brief Values of char fields already processed. As the parameter for a char field is processed, the value is saved and can be retrieved using this function. */ char charValue(int position) const; /*! \brief Number of char fields already processed. Incremented each time a field of type char is processed. */ int numberCharFields() const; /*! \brief Values of string fields already processed. As the parameter for a string field is processed, the value is saved and can be retrieved using this function. */ std::string stringValue(int position) const; /*! \brief Number of string fields already processed. Incremented each time a field of type string is processed. */ int numberStringFields() const; /// Current message CoinOneMessage currentMessage() const; /// Source of current message std::string currentSource() const; /// Output buffer inline const char *messageBuffer() const { return messageBuffer_; } /// Highest message number (indicates any errors) inline int highestNumber() const { return highestNumber_; } /// Get current file pointer inline FILE *filePointer() const { return fp_; } /// Set new file pointer inline void setFilePointer(FILE *fp) { fp_ = fp; } //@} /**@name Actions to create a message */ //@{ /*! \brief Start a message Look up the specified message. A prefix will be generated if enabled. The message will be printed if the current log level is equal or greater than the log level of the message. */ CoinMessageHandler &message(int messageNumber, const CoinMessages &messages); /*! \brief Start or continue a message With detail = -1 (default), does nothing except return a reference to the handler. (I.e., msghandler.message() << "foo" is precisely equivalent to msghandler << "foo".) If \p msgDetail is >= 0, is will be used as the detail level to determine whether the message should print (assuming class 0). This can be used with any of the << operators. One use is to start a message which will be constructed entirely from scratch. Another use is continuation of a message after code that interrupts the usual sequence of << operators. */ CoinMessageHandler &message(int detail = -1); /*! \brief Print a complete message Generate a standard prefix and append \c msg `as is'. This is intended as a transition mechanism. The standard prefix is generated (if enabled), and \c msg is appended. The message must be ended with a CoinMessageEol marker. Attempts to add content with << will have no effect. The default value of \p detail will not change printing status. If \p detail is >= 0, it will be used as the detail level to determine whether the message should print (assuming class 0). */ CoinMessageHandler &message(int externalNumber, const char *source, const char *msg, char severity, int detail = -1); /*! \brief Process an integer parameter value. The default format code is `%d'. */ CoinMessageHandler &operator<<(int intvalue); /*! \brief Process a long integer parameter value. The default format code is `%ld'. */ CoinMessageHandler &operator<<(long longvalue); /*! \brief Process a long long integer parameter value. The default format code is `%lld'. */ CoinMessageHandler &operator<<(long long longvalue); /*! \brief Process a double parameter value. The default format code is `%d'. */ CoinMessageHandler &operator<<(double doublevalue); /*! \brief Process a STL string parameter value. The default format code is `%g'. */ CoinMessageHandler &operator<<(const std::string &stringvalue); /*! \brief Process a char parameter value. The default format code is `%s'. */ CoinMessageHandler &operator<<(char charvalue); /*! \brief Process a C-style string parameter value. The default format code is `%c'. */ CoinMessageHandler &operator<<(const char *stringvalue); /*! \brief Process a marker. The default format code is `%s'. */ CoinMessageHandler &operator<<(CoinMessageMarker); /** Finish (and print) the message. Equivalent to using the CoinMessageEol marker. */ int finish(); /*! \brief Enable or disable printing of an optional portion of a message. Optional portions of a message are delimited by `%?' markers, and printing processes one %? marker. If \c onOff is true, the subsequent portion of the message (to the next %? marker or the end of the format string) will be printed. If \c onOff is false, printing is suppressed. Parameters must still be supplied, whether printing is suppressed or not. See the class documentation for an example. */ CoinMessageHandler &printing(bool onOff); //@} /** Log levels will be by type and will then use type given in CoinMessage::class_ - 0 - Branch and bound code or similar - 1 - Solver - 2 - Stuff in Coin directory - 3 - Cut generators */ #define COIN_NUM_LOG 4 /// Maximum length of constructed message (characters) #define COIN_MESSAGE_HANDLER_MAX_BUFFER_SIZE 1200 protected: /**@name Protected member data */ //@{ /// values in message std::vector< double > doubleValue_; std::vector< CoinBigIndex > longValue_; std::vector< char > charValue_; std::vector< std::string > stringValue_; /// Log level int logLevel_; /// Log levels int logLevels_[COIN_NUM_LOG]; /// Whether we want prefix (may get more subtle so is int) int prefix_; /// Current message CoinOneMessage currentMessage_; /// Internal number for use with enums int internalNumber_; /// Format string for message (remainder) char *format_; /// Output buffer char messageBuffer_[COIN_MESSAGE_HANDLER_MAX_BUFFER_SIZE]; /// Position in output buffer char *messageOut_; /// Current source of message std::string source_; /** 0 - Normal. 1 - Put in values, move along format, but don't print. 2 - A complete message was provided; nothing more to do but print when CoinMessageEol is processed. Any << operators are treated as noops. 3 - do nothing except look for CoinMessageEol (i.e., the message detail level was not sufficient to cause it to print). */ int printStatus_; /// Highest message number (indicates any errors) int highestNumber_; /// File pointer FILE *fp_; /// Current format for floating point numbers char g_format_[8]; /// Current number of significant digits for floating point numbers int g_precision_; //@} private: /** The body of the copy constructor and the assignment operator */ void gutsOfCopy(const CoinMessageHandler &rhs); /*! \brief Internal function to locate next format code. Intended for internal use. Side effects modify the format string. */ char *nextPerCent(char *start, const bool initial = false); /*! \brief Internal printing function. Makes it easier to split up print into clean, print and check severity */ int internalPrint(); /// Decide if this message should print. void calcPrintStatus(int msglvl, int msgclass); }; //############################################################################# /** A function that tests the methods in the CoinMessageHandler class. The only reason for it not to be a member method is that this way it doesn't have to be compiled into the library. And that's a gain, because the library should be compiled with optimization on, but this method should be compiled with debugging. */ bool CoinMessageHandlerUnitTest(); #endif /* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2 */
31.976879
79
0.702052
Justin790126
c864668914e7a62df19e20a0549645bf48ef7a7e
5,069
cpp
C++
tests/net/tcp_test.cpp
TiFu/thrill-hyperloglog
bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf
[ "BSD-2-Clause" ]
2
2021-01-03T19:29:25.000Z
2021-01-03T19:29:31.000Z
tests/net/tcp_test.cpp
TiFu/thrill-hyperloglog
bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf
[ "BSD-2-Clause" ]
null
null
null
tests/net/tcp_test.cpp
TiFu/thrill-hyperloglog
bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * tests/net/tcp_test.cpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <gtest/gtest.h> #include <thrill/mem/manager.hpp> #include <thrill/net/dispatcher_thread.hpp> #include <thrill/net/tcp/group.hpp> #include <thrill/net/tcp/select_dispatcher.hpp> #include <random> #include <string> #include <thread> #include <vector> #include "flow_control_test_base.hpp" #include "group_test_base.hpp" using namespace thrill; // NOLINT static void RealGroupTest( const std::function<void(net::Group*)>& thread_function) { // execute locally connected TCP stream socket tests net::ExecuteGroupThreads( net::tcp::Group::ConstructLocalRealTCPMesh(6), thread_function); } static void LocalGroupTest( const std::function<void(net::Group*)>& thread_function) { // execute local stream socket tests net::ExecuteGroupThreads( net::tcp::Group::ConstructLoopbackMesh(6), thread_function); } /*[[[perl require("tests/net/test_gen.pm"); generate_group_tests("RealTcpGroup", "RealGroupTest"); generate_group_tests("LocalTcpGroup", "LocalGroupTest"); generate_flow_control_tests("LocalTcpGroup", "LocalGroupTest"); ]]]*/ TEST(RealTcpGroup, NoOperation) { RealGroupTest(TestNoOperation); } TEST(RealTcpGroup, SendRecvCyclic) { RealGroupTest(TestSendRecvCyclic); } TEST(RealTcpGroup, BroadcastIntegral) { RealGroupTest(TestBroadcastIntegral); } TEST(RealTcpGroup, SendReceiveAll2All) { RealGroupTest(TestSendReceiveAll2All); } TEST(RealTcpGroup, PrefixSumHypercube) { RealGroupTest(TestPrefixSumHypercube); } TEST(RealTcpGroup, PrefixSumHypercubeString) { RealGroupTest(TestPrefixSumHypercubeString); } TEST(RealTcpGroup, PrefixSum) { RealGroupTest(TestPrefixSum); } TEST(RealTcpGroup, Broadcast) { RealGroupTest(TestBroadcast); } TEST(RealTcpGroup, Reduce) { RealGroupTest(TestReduce); } TEST(RealTcpGroup, ReduceString) { RealGroupTest(TestReduceString); } TEST(RealTcpGroup, AllReduceString) { RealGroupTest(TestAllReduceString); } TEST(RealTcpGroup, AllReduceHypercubeString) { RealGroupTest(TestAllReduceHypercubeString); } TEST(RealTcpGroup, DispatcherSyncSendAsyncRead) { RealGroupTest(TestDispatcherSyncSendAsyncRead); } TEST(RealTcpGroup, DispatcherLaunchAndTerminate) { RealGroupTest(TestDispatcherLaunchAndTerminate); } TEST(LocalTcpGroup, NoOperation) { LocalGroupTest(TestNoOperation); } TEST(LocalTcpGroup, SendRecvCyclic) { LocalGroupTest(TestSendRecvCyclic); } TEST(LocalTcpGroup, BroadcastIntegral) { LocalGroupTest(TestBroadcastIntegral); } TEST(LocalTcpGroup, SendReceiveAll2All) { LocalGroupTest(TestSendReceiveAll2All); } TEST(LocalTcpGroup, PrefixSumHypercube) { LocalGroupTest(TestPrefixSumHypercube); } TEST(LocalTcpGroup, PrefixSumHypercubeString) { LocalGroupTest(TestPrefixSumHypercubeString); } TEST(LocalTcpGroup, PrefixSum) { LocalGroupTest(TestPrefixSum); } TEST(LocalTcpGroup, Broadcast) { LocalGroupTest(TestBroadcast); } TEST(LocalTcpGroup, Reduce) { LocalGroupTest(TestReduce); } TEST(LocalTcpGroup, ReduceString) { LocalGroupTest(TestReduceString); } TEST(LocalTcpGroup, AllReduceString) { LocalGroupTest(TestAllReduceString); } TEST(LocalTcpGroup, AllReduceHypercubeString) { LocalGroupTest(TestAllReduceHypercubeString); } TEST(LocalTcpGroup, DispatcherSyncSendAsyncRead) { LocalGroupTest(TestDispatcherSyncSendAsyncRead); } TEST(LocalTcpGroup, DispatcherLaunchAndTerminate) { LocalGroupTest(TestDispatcherLaunchAndTerminate); } TEST(LocalTcpGroup, SingleThreadPrefixSum) { LocalGroupTest(TestSingleThreadPrefixSum); } TEST(LocalTcpGroup, SingleThreadVectorPrefixSum) { LocalGroupTest(TestSingleThreadVectorPrefixSum); } TEST(LocalTcpGroup, SingleThreadBroadcast) { LocalGroupTest(TestSingleThreadBroadcast); } TEST(LocalTcpGroup, MultiThreadBroadcast) { LocalGroupTest(TestMultiThreadBroadcast); } TEST(LocalTcpGroup, MultiThreadReduce) { LocalGroupTest(TestMultiThreadReduce); } TEST(LocalTcpGroup, SingleThreadAllReduce) { LocalGroupTest(TestSingleThreadAllReduce); } TEST(LocalTcpGroup, MultiThreadAllReduce) { LocalGroupTest(TestMultiThreadAllReduce); } TEST(LocalTcpGroup, MultiThreadPrefixSum) { LocalGroupTest(TestMultiThreadPrefixSum); } TEST(LocalTcpGroup, PredecessorManyItems) { LocalGroupTest(TestPredecessorManyItems); } TEST(LocalTcpGroup, PredecessorFewItems) { LocalGroupTest(TestPredecessorFewItems); } TEST(LocalTcpGroup, PredecessorOneItem) { LocalGroupTest(TestPredecessorOneItem); } TEST(LocalTcpGroup, HardcoreRaceConditionTest) { LocalGroupTest(TestHardcoreRaceConditionTest); } // [[[end]]] /******************************************************************************/
29.300578
80
0.742553
TiFu
c8653e75033ba15c25d03486baab62e48e4e072b
679
hpp
C++
include/Client/BombPlaceSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
include/Client/BombPlaceSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
include/Client/BombPlaceSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
#ifndef CLIENT_BOMBPLACESYSTEM_HPP_INCLUDED #define CLIENT_BOMBPLACESYSTEM_HPP_INCLUDED #include <anax/System.hpp> #include <Client/EntityFactory.hpp> #include <Client/PlayerInputComponent.hpp> #include <Client/BombLayerComponent.hpp> namespace Client { class BombPlaceSystem : public anax::System<anax::Requires<PlayerInputComponent, BombLayerComponent>> { public: BombPlaceSystem(EntityFactory *entityFactory); virtual ~BombPlaceSystem(); void update(); void lockBombPlacing(bool state); private: EntityFactory *m_entityFactory; bool m_noBombPlacing = false; }; } #endif
24.25
105
0.696613
maximaximal
c86c8703ff98d2a032a179f353ec63a2b1f90bef
2,935
hpp
C++
clients/include/testing_gemm_strided_batched_kernel_name.hpp
aaronenyeshi/rocBLAS
90d52d221a8f0f778557317d094ae57c4fced1b6
[ "MIT" ]
null
null
null
clients/include/testing_gemm_strided_batched_kernel_name.hpp
aaronenyeshi/rocBLAS
90d52d221a8f0f778557317d094ae57c4fced1b6
[ "MIT" ]
null
null
null
clients/include/testing_gemm_strided_batched_kernel_name.hpp
aaronenyeshi/rocBLAS
90d52d221a8f0f778557317d094ae57c4fced1b6
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016 Advanced Micro Devices, Inc. * ************************************************************************ */ #include <sys/time.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include "rocblas.hpp" #include "arg_check.h" #include "rocblas_test_unique_ptr.hpp" #include "utility.h" #include "cblas_interface.h" #include "norm.h" #include "unit.h" #include "flops.h" #include <typeinfo> using namespace std; template <typename T> rocblas_status testing_gemm_strided_batched_kernel_name(Arguments argus) { rocblas_int M = argus.M; rocblas_int N = argus.N; rocblas_int K = argus.K; T h_alpha = argus.alpha; T h_beta = argus.beta; rocblas_int lda = argus.lda; rocblas_int ldb = argus.ldb; rocblas_int ldc = argus.ldc; rocblas_int batch_count = argus.batch_count; rocblas_operation transA = char2rocblas_operation(argus.transA_option); rocblas_operation transB = char2rocblas_operation(argus.transB_option); rocblas_int safe_size = 100; // arbitrarily set to 100 rocblas_status status; std::unique_ptr<rocblas_test::handle_struct> unique_ptr_handle(new rocblas_test::handle_struct); rocblas_handle handle = unique_ptr_handle->handle; rocblas_int A_row = transA == rocblas_operation_none ? M : K; rocblas_int A_col = transA == rocblas_operation_none ? K : M; rocblas_int B_row = transB == rocblas_operation_none ? K : N; rocblas_int B_col = transB == rocblas_operation_none ? N : K; // make bsa, bsb, bsc two times minimum size so matrices are non-contiguous rocblas_int bsa = lda * A_col * 2; rocblas_int bsb = ldb * B_col * 2; rocblas_int bsc = ldc * N * 2; T *dA, *dB, *dC; return rocblas_gemm_strided_batched_kernel_name<T>(handle, transA, transB, M, N, K, &h_alpha, dA, lda, bsa, dB, ldb, bsb, &h_beta, dC, ldc, bsc, batch_count); }
37.628205
100
0.443612
aaronenyeshi
c86ec0b1cfe7f308cb048a72b12ee73b7d0fc8c3
2,866
hpp
C++
libvast/vast/system/indexer.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/indexer.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/indexer.hpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/column_index.hpp" #include "vast/fwd.hpp" #include "vast/path.hpp" #include "vast/system/accountant.hpp" #include "vast/system/instrumentation.hpp" #include "vast/type.hpp" #include "vast/uuid.hpp" #include <caf/actor.hpp> #include <caf/event_based_actor.hpp> #include <caf/stateful_actor.hpp> #include <string> namespace vast::system { struct indexer_state { // -- constructors, destructors, and assignment operators -------------------- indexer_state(); ~indexer_state(); // -- member functions ------------------------------------------------------- caf::error init(caf::event_based_actor* self, path filename, type column_type, caf::settings index_opts, caf::actor index, uuid partition_id, std::string fqn); void send_report(); // -- member variables ------------------------------------------------------- union { column_index col; }; caf::actor index; accountant_type accountant; caf::event_based_actor* self; uuid partition_id; std::string fqn; measurement m; bool streaming_done; static inline const char* name = "indexer"; }; /// Indexes a single column of table slices. /// @param self The actor handle. /// @param filename The file in which to store the index column. /// @param column_type The type of the indexed column. /// @param index_opts Runtime options to parameterize the value index. /// @param index A handle to the index actor. /// @param partition_id The partition ID that this INDEXER belongs to. /// @param fqn The fully-qualified name of the indexed column. /// @returns the initial behavior of the INDEXER. caf::behavior indexer(caf::stateful_actor<indexer_state>* self, path filename, type column_type, caf::settings index_opts, caf::actor index, uuid partition_id, std::string fqn); } // namespace vast::system
34.95122
80
0.543266
frerich
c875b71b6e98aa9b2e8d3bf4be1d3ca90b8c61f0
853
hpp
C++
DoremiEngine/Graphic/Include/Interface/Mesh/MeshInfo.hpp
meraz/doremi
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:05.000Z
2020-03-23T15:42:05.000Z
DoremiEngine/Graphic/Include/Interface/Mesh/MeshInfo.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
DoremiEngine/Graphic/Include/Interface/Mesh/MeshInfo.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
#pragma once #include <string> struct ID3D11Buffer; namespace DoremiEngine { namespace Graphic { class MeshInfo { public: virtual const size_t& GetVerticeCount() const = 0; virtual const size_t& GetIndexCount() const = 0; virtual ID3D11Buffer* GetBufferHandle() const = 0; virtual ID3D11Buffer* GetIndexBufferHandle() const = 0; virtual const std::string& GetFileName() const = 0; virtual void SetIndexBufferHandle(ID3D11Buffer* p_bufferHandle) = 0; virtual void SetVerticeCount(size_t p_verticeCount) = 0; virtual void SetIndexCount(size_t p_indexCount) = 0; virtual void SetFileName(std::string p_fileName) = 0; virtual void SetBufferHandle(ID3D11Buffer* p_bufferHandle) = 0; }; } }
30.464286
80
0.631887
meraz
c87aa25d447d42dbbd5338a12b9a79883aebd2e7
3,439
hpp
C++
src/sched/entry/epilogue_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/epilogue_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/epilogue_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "sched/entry/entry.hpp" class epilogue_entry : public sched_entry, public postponed_fields<epilogue_entry, ccl_sched_entry_field_in_buf, ccl_sched_entry_field_in_cnt, ccl_sched_entry_field_in_dtype> { public: static constexpr const char* class_name() noexcept { return "EPILOGUE"; } epilogue_entry() = delete; epilogue_entry(ccl_sched* sched, ccl_epilogue_fn_t fn, const ccl_buffer in_buf, size_t in_cnt, ccl_datatype_internal_t in_dtype, ccl_buffer out_buf, size_t expected_out_cnt, ccl_datatype_internal_t out_dtype) : sched_entry(sched), fn(fn), in_buf(in_buf), in_cnt(in_cnt), in_dtype(in_dtype), out_buf(out_buf), expected_out_cnt(expected_out_cnt), out_dtype(out_dtype) { } void start() override { update_fields(); size_t in_bytes = in_cnt * ccl_datatype_get_size(in_dtype); size_t offset = in_buf.get_offset(); const ccl_fn_context_t context = {sched->coll_attr.match_id.c_str(), offset}; fn(in_buf.get_ptr(in_bytes), in_cnt, in_dtype->type, out_buf.get_ptr(), &out_cnt, &context, out_dtype->type); CCL_ASSERT(expected_out_cnt == out_cnt, "incorrect values ", expected_out_cnt, " ", out_cnt); status = ccl_sched_entry_status_complete; } const char* name() const override { return class_name(); } ccl_buffer& get_field_ref(field_id_t<ccl_sched_entry_field_in_buf> id) { return in_buf; } size_t& get_field_ref(field_id_t<ccl_sched_entry_field_in_cnt> id) { return in_cnt; } ccl_datatype_internal_t& get_field_ref(field_id_t<ccl_sched_entry_field_in_dtype> id) { return in_dtype; } protected: void dump_detail(std::stringstream& str) const override { ccl_logger::format(str, "in_dt ", ccl_datatype_get_name(in_dtype), ", in_cnt ", in_cnt, ", in_buf ", in_buf, ", out_dt ", ccl_datatype_get_name(out_dtype), ", out_cnt ", out_cnt, ", out_buf ", out_buf, ", fn ", fn, ", exp_out_count ", expected_out_cnt, "\n"); } private: ccl_epilogue_fn_t fn; ccl_buffer in_buf; size_t in_cnt; ccl_datatype_internal_t in_dtype; ccl_buffer out_buf; size_t out_cnt; size_t expected_out_cnt; ccl_datatype_internal_t out_dtype; };
32.443396
117
0.601047
mshiryaev
c87c0bb1c881199c4f74b41eeb02f7d2d04d4986
8,970
hpp
C++
StickWatch/src/ArduinoJson_6.2.0-beta/ArduinoJson/MsgPack/MsgPackDeserializer.hpp
stahifpv/StickWatch
b9f2b3824e62b4e2366859559dbb19a531560758
[ "Apache-2.0" ]
83
2019-01-24T01:32:21.000Z
2022-02-20T06:54:43.000Z
src/ArduinoJson_6.2.0-beta/ArduinoJson/MsgPack/MsgPackDeserializer.hpp
sysdl132/m5stack-stickwatch
968087b9f1b06e64e45699b0f4ac22ffb3e6f2a9
[ "Apache-2.0" ]
5
2019-02-18T12:19:31.000Z
2020-04-26T01:37:47.000Z
src/ArduinoJson_6.2.0-beta/ArduinoJson/MsgPack/MsgPackDeserializer.hpp
sysdl132/m5stack-stickwatch
968087b9f1b06e64e45699b0f4ac22ffb3e6f2a9
[ "Apache-2.0" ]
27
2019-01-26T14:12:14.000Z
2022-02-28T14:38:14.000Z
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #pragma once #include "../Deserialization/deserialize.hpp" #include "../JsonVariant.hpp" #include "../Memory/JsonBuffer.hpp" #include "../Polyfills/type_traits.hpp" #include "./endianess.hpp" #include "./ieee754.hpp" namespace ArduinoJson { namespace Internals { template <typename TReader, typename TStringStorage> class MsgPackDeserializer { public: MsgPackDeserializer(JsonBuffer *buffer, TReader reader, TStringStorage stringStorage, uint8_t nestingLimit) : _buffer(buffer), _reader(reader), _stringStorage(stringStorage), _nestingLimit(nestingLimit) {} DeserializationError parse(JsonVariant &variant) { uint8_t code; if (!readByte(code)) return DeserializationError::IncompleteInput; if ((code & 0x80) == 0) { variant = code; return DeserializationError::Ok; } if ((code & 0xe0) == 0xe0) { variant = static_cast<int8_t>(code); return DeserializationError::Ok; } if ((code & 0xe0) == 0xa0) { return readString(variant, code & 0x1f); } if ((code & 0xf0) == 0x90) return readArray(variant, code & 0x0F); if ((code & 0xf0) == 0x80) return readObject(variant, code & 0x0F); switch (code) { case 0xc0: variant = static_cast<char *>(0); return DeserializationError::Ok; case 0xc2: variant = false; return DeserializationError::Ok; case 0xc3: variant = true; return DeserializationError::Ok; case 0xcc: return readInteger<uint8_t>(variant); case 0xcd: return readInteger<uint16_t>(variant); case 0xce: return readInteger<uint32_t>(variant); case 0xcf: #if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64 return readInteger<uint64_t>(variant); #else readInteger<uint32_t>(); return readInteger<uint32_t>(variant); #endif case 0xd0: return readInteger<int8_t>(variant); case 0xd1: return readInteger<int16_t>(variant); case 0xd2: return readInteger<int32_t>(variant); case 0xd3: #if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64 return readInteger<int64_t>(variant); #else if (!skip(4)) return DeserializationError::IncompleteInput; return readInteger<int32_t>(variant); #endif case 0xca: return readFloat<float>(variant); case 0xcb: return readDouble<double>(variant); case 0xd9: return readString<uint8_t>(variant); case 0xda: return readString<uint16_t>(variant); case 0xdb: return readString<uint32_t>(variant); case 0xdc: return readArray<uint16_t>(variant); case 0xdd: return readArray<uint32_t>(variant); case 0xde: return readObject<uint16_t>(variant); case 0xdf: return readObject<uint32_t>(variant); default: return DeserializationError::NotSupported; } } private: // Prevent VS warning "assignment operator could not be generated" MsgPackDeserializer &operator=(const MsgPackDeserializer &); bool skip(uint8_t n) { while (n--) { if (_reader.ended()) return false; _reader.read(); } return true; } bool readByte(uint8_t &value) { if (_reader.ended()) return false; value = static_cast<uint8_t>(_reader.read()); return true; } bool readBytes(uint8_t *p, size_t n) { for (size_t i = 0; i < n; i++) { if (!readByte(p[i])) return false; } return true; } template <typename T> bool readBytes(T &value) { return readBytes(reinterpret_cast<uint8_t *>(&value), sizeof(value)); } template <typename T> T readInteger() { T value; readBytes(value); fixEndianess(value); return value; } template <typename T> bool readInteger(T &value) { if (!readBytes(value)) return false; fixEndianess(value); return true; } template <typename T> DeserializationError readInteger(JsonVariant &variant) { T value; if (!readInteger(value)) return DeserializationError::IncompleteInput; variant = value; return DeserializationError::Ok; } template <typename T> typename enable_if<sizeof(T) == 4, DeserializationError>::type readFloat( JsonVariant &variant) { T value; if (!readBytes(value)) return DeserializationError::IncompleteInput; fixEndianess(value); variant = value; return DeserializationError::Ok; } template <typename T> typename enable_if<sizeof(T) == 8, DeserializationError>::type readDouble( JsonVariant &variant) { T value; if (!readBytes(value)) return DeserializationError::IncompleteInput; fixEndianess(value); variant = value; return DeserializationError::Ok; } template <typename T> typename enable_if<sizeof(T) == 4, DeserializationError>::type readDouble( JsonVariant &variant) { uint8_t i[8]; // input is 8 bytes T value; // output is 4 bytes uint8_t *o = reinterpret_cast<uint8_t *>(&value); if (!readBytes(i, 8)) return DeserializationError::IncompleteInput; doubleToFloat(i, o); fixEndianess(value); variant = value; return DeserializationError::Ok; } template <typename T> DeserializationError readString(JsonVariant &variant) { T size; if (!readInteger(size)) return DeserializationError::IncompleteInput; return readString(variant, size); } DeserializationError readString(JsonVariant &variant, size_t n) { typename remove_reference<TStringStorage>::type::String str = _stringStorage.startString(); for (; n; --n) { uint8_t c; if (!readBytes(c)) return DeserializationError::IncompleteInput; str.append(static_cast<char>(c)); } const char *s = str.c_str(); if (s == NULL) return DeserializationError::NoMemory; variant = s; return DeserializationError::Ok; } template <typename TSize> DeserializationError readArray(JsonVariant &variant) { TSize size; if (!readInteger(size)) return DeserializationError::IncompleteInput; return readArray(variant, size); } DeserializationError readArray(JsonVariant &variant, size_t n) { JsonArray array(_buffer); if (array.isNull()) return DeserializationError::NoMemory; variant = array; return readArray(array, n); } DeserializationError readArray(JsonArray array, size_t n) { if (_nestingLimit == 0) return DeserializationError::TooDeep; --_nestingLimit; for (; n; --n) { JsonVariant variant; DeserializationError err = parse(variant); if (err) return err; if (!array.add(variant)) return DeserializationError::NoMemory; } ++_nestingLimit; return DeserializationError::Ok; } template <typename TSize> DeserializationError readObject(JsonVariant &variant) { TSize size; if (!readInteger(size)) return DeserializationError::IncompleteInput; return readObject(variant, size); } DeserializationError readObject(JsonVariant &variant, size_t n) { JsonObject object(_buffer); if (object.isNull()) return DeserializationError::NoMemory; variant = object; return readObject(object, n); } DeserializationError readObject(JsonObject object, size_t n) { if (_nestingLimit == 0) return DeserializationError::TooDeep; --_nestingLimit; for (; n; --n) { DeserializationError err; JsonVariant variant; err = parse(variant); if (err) return err; const char *key = variant.as<char *>(); if (!key) return DeserializationError::NotSupported; err = parse(variant); if (err) return err; if (!object.set(key, variant)) return DeserializationError::NoMemory; } ++_nestingLimit; return DeserializationError::Ok; } JsonBuffer *_buffer; TReader _reader; TStringStorage _stringStorage; uint8_t _nestingLimit; }; } // namespace Internals template <typename TDocument, typename TInput> DeserializationError deserializeMsgPack(TDocument &doc, const TInput &input) { using namespace Internals; return deserialize<MsgPackDeserializer>(doc, input); } template <typename TDocument, typename TInput> DeserializationError deserializeMsgPack(TDocument &doc, TInput *input) { using namespace Internals; return deserialize<MsgPackDeserializer>(doc, input); } template <typename TDocument, typename TInput> DeserializationError deserializeMsgPack(TDocument &doc, TInput *input, size_t inputSize) { using namespace Internals; return deserialize<MsgPackDeserializer>(doc, input, inputSize); } template <typename TDocument, typename TInput> DeserializationError deserializeMsgPack(TDocument &doc, TInput &input) { using namespace Internals; return deserialize<MsgPackDeserializer>(doc, input); } } // namespace ArduinoJson
27.515337
78
0.6767
stahifpv
c87e432d960cfac138b3bbac76cd0f34c87dae2c
950
cpp
C++
libraries/plugins/apis/network_broadcast_api/network_broadcast_api_plugin.cpp
dappnet-one/dappnet
2d117787867924b800b2cf02dfb7128bb05c9cf4
[ "MIT" ]
2
2019-06-30T21:57:49.000Z
2019-06-30T23:56:17.000Z
libraries/plugins/apis/network_broadcast_api/network_broadcast_api_plugin.cpp
dappnet-one/steem
2d117787867924b800b2cf02dfb7128bb05c9cf4
[ "MIT" ]
1
2019-07-02T03:08:03.000Z
2019-07-02T03:08:03.000Z
libraries/plugins/apis/network_broadcast_api/network_broadcast_api_plugin.cpp
dappnet-one/steem
2d117787867924b800b2cf02dfb7128bb05c9cf4
[ "MIT" ]
null
null
null
#include <dpn/plugins/network_broadcast_api/network_broadcast_api_plugin.hpp> #include <dpn/plugins/network_broadcast_api/network_broadcast_api.hpp> namespace dpn { namespace plugins { namespace network_broadcast_api { network_broadcast_api_plugin::network_broadcast_api_plugin() {} network_broadcast_api_plugin::~network_broadcast_api_plugin() {} void network_broadcast_api_plugin::set_program_options( options_description& cli, options_description& cfg ) {} void network_broadcast_api_plugin::plugin_initialize( const variables_map& options ) { api = std::make_shared< network_broadcast_api >(); FC_ASSERT( !appbase::app().get_plugin< rc::rc_plugin >().get_rc_plugin_skip_flags().skip_reject_not_enough_rc, "rc-skip-reject-not-enough-rc=false is required to broadcast transactions" ); } void network_broadcast_api_plugin::plugin_startup() {} void network_broadcast_api_plugin::plugin_shutdown() {} } } } // dpn::plugins::test_api
43.181818
113
0.809474
dappnet-one
c87e76836aaa21ddd454e20eeafb0d1a8f49e90a
1,516
hpp
C++
src/BonjourRegistrar.hpp
jdgordy/slideshow-apple-tv-bb10
968e0f0c07dad3a6f91804d69b470a5eb095aa24
[ "Apache-2.0" ]
null
null
null
src/BonjourRegistrar.hpp
jdgordy/slideshow-apple-tv-bb10
968e0f0c07dad3a6f91804d69b470a5eb095aa24
[ "Apache-2.0" ]
null
null
null
src/BonjourRegistrar.hpp
jdgordy/slideshow-apple-tv-bb10
968e0f0c07dad3a6f91804d69b470a5eb095aa24
[ "Apache-2.0" ]
null
null
null
/* * BonjourRegistrar.hpp * * Created on: Apr 8, 2013 * Author: jgordy */ #ifndef BONJOURREGISTRAR_HPP_ #define BONJOURREGISTRAR_HPP_ #include <QtCore/QObject> #include <QtCore/QVariantMap> #include <QtCore/QSocketNotifier> #include "BonjourRecord.hpp" #include "dns_sd.h" // // BonjourRegistrar // class BonjourRegistrar : public QObject { Q_OBJECT; public: // Constructor / destructor BonjourRegistrar(QObject* pParent = NULL); virtual ~BonjourRegistrar(); // Register service bool registerService(const BonjourRecord& record, quint16 servicePort, const QVariantMap& txtRecord); // Unregister service void unregisterService(); // Retrieve registered record BonjourRecord registeredRecord() const; Q_SIGNALS: // Emitted when service is registered void serviceRegistered(const BonjourRecord& record); // Emitted on error void error(DNSServiceErrorType err); protected Q_SLOTS: // Handler for socket read notification void bonjourSocketReadyRead(); protected: // Callback function for registration replies static void DNSSD_API bonjourRegisterService( DNSServiceRef, DNSServiceFlags, DNSServiceErrorType, const char*, const char*, const char*, void*); // Service records DNSServiceRef m_serviceRef; QSocketNotifier* m_pSocket; BonjourRecord m_record; }; #endif /* BONJOURBROWSER_HPP_ */
22.626866
106
0.677441
jdgordy
c8804b6a0843a335abc8072a23497430b7b801b7
3,097
cpp
C++
src/asset.cpp
lahwran/Rack
d63e23b2b64cdad54da7609ee8e018d9f45ced2f
[ "Zlib", "BSD-3-Clause" ]
84
2018-05-02T13:15:42.000Z
2019-11-25T15:53:59.000Z
src/asset.cpp
lahwran/Rack
d63e23b2b64cdad54da7609ee8e018d9f45ced2f
[ "Zlib", "BSD-3-Clause" ]
17
2018-05-02T13:18:44.000Z
2019-10-29T00:16:56.000Z
src/asset.cpp
lahwran/Rack
d63e23b2b64cdad54da7609ee8e018d9f45ced2f
[ "Zlib", "BSD-3-Clause" ]
9
2018-05-06T18:39:58.000Z
2019-10-03T15:15:26.000Z
#include "asset.hpp" #include "util/common.hpp" #include "osdialog.h" #if ARCH_MAC #include <CoreFoundation/CoreFoundation.h> #include <pwd.h> #endif #if ARCH_WIN #include <Windows.h> #include <Shlobj.h> #endif #if ARCH_LIN #include <unistd.h> #include <sys/types.h> #include <pwd.h> #endif namespace rack { static std::string localDir; static std::string globalDir; static std::string hiddenDir; void assetInit() { // Global #if ARCH_MAC && RELEASE CFBundleRef bundle = CFBundleGetMainBundle(); assert(bundle); CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(bundle); char buf[PATH_MAX]; Boolean success = CFURLGetFileSystemRepresentation(resourcesUrl, TRUE, (UInt8 *)buf, sizeof(buf)); assert(success); CFRelease(resourcesUrl); globalDir = buf; #else globalDir = "."; #endif // Local #if ARCH_MAC // Use home directory struct passwd *pw = getpwuid(getuid()); assert(pw); localDir = pw->pw_dir; localDir += "/Documents"; systemCreateDirectory(localDir); #endif #if ARCH_WIN // Use My Documents folder char buf[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buf); assert(result == S_OK); localDir = buf; localDir += "/Rack"; CreateDirectory(localDir.c_str(), NULL); #endif #if ARCH_LIN const char *home = getenv("HOME"); if (!home) { struct passwd *pw = getpwuid(getuid()); assert(pw); home = pw->pw_dir; } localDir = home; // If the distro already has Documents folder, use it, otherwise just use home folder if (systemIsDirectory(localDir+"/Documents")) localDir += "/Documents"; #endif #if ARCH_WEB localDir = "/work"; #endif // Hidden #ifndef ARCH_WEB #if RELEASE #if ARCH_MAC // Use Application Support folder struct passwd *pw = getpwuid(getuid()); assert(pw); hiddenDir = pw->pw_dir; hiddenDir += "/Library/Application Support/miRack"; systemCreateDirectory(hiddenDir); #endif #if ARCH_WIN // Use Application Data folder char buf[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, buf); assert(result == S_OK); hiddenDir = buf; hiddenDir += "/miRack"; CreateDirectory(hiddenDir.c_str(), NULL); #endif #if ARCH_LIN // Use a hidden directory const char *home = getenv("HOME"); if (!home) { struct passwd *pw = getpwuid(getuid()); assert(pw); home = pw->pw_dir; } hiddenDir = home; hiddenDir += "/.miRack"; systemCreateDirectory(hiddenDir); #endif #else hiddenDir = "."; #endif #else hiddenDir = "/work"; #endif } // Resources folder if packaged as an app on Mac, current (executable) folder otherwise std::string assetGlobal(std::string filename) { return globalDir + "/" + filename; } // User Documents folder always std::string assetLocal(std::string filename) { return localDir + "/" + filename; } // Platform-specific folder if RELEASE, current folder otherwise std::string assetHidden(std::string filename) { return hiddenDir + "/" + filename; } std::string assetPlugin(Plugin *plugin, std::string filename) { assert(plugin); return plugin->path + "/" + filename; } } // namespace rack
20.375
99
0.712302
lahwran
c883a37de7583e6854d327d181d83484e3be62c8
5,539
cpp
C++
src/plugins/process/dwi_basic_thresholding/medItkDWIBasicThresholdingProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
61
2015-04-14T13:00:50.000Z
2022-03-09T22:22:18.000Z
src/plugins/process/dwi_basic_thresholding/medItkDWIBasicThresholdingProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
510
2016-02-03T13:28:18.000Z
2022-03-23T10:23:44.000Z
src/plugins/process/dwi_basic_thresholding/medItkDWIBasicThresholdingProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
36
2015-03-03T22:58:19.000Z
2021-12-28T18:19:23.000Z
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2018. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medItkDWIBasicThresholdingProcess.h> #include <dtkLog> #include <itkImage.h> #include <itkExtractImageFilter.h> #include <itkBinaryThresholdImageFilter.h> #include <itkCommand.h> #include <medAbstractImageData.h> #include <medAbstractDataFactory.h> medItkDWIBasicThresholdingProcess::medItkDWIBasicThresholdingProcess(QObject *parent) : medAbstractDWIMaskingProcess(parent) { m_extractfilter = 0; m_thresholdfilter = 0; m_b0VolumeNumber = new medIntParameter("b0_volume_number", this); m_b0VolumeNumber->setCaption("B0 volume index"); m_b0VolumeNumber->setDescription("B0 volume index to threshold"); m_b0VolumeNumber->setValue(0); m_thresholdValue = new medIntParameter("threshold_value", this); m_thresholdValue->setCaption("Lower threshold value"); m_thresholdValue->setDescription("Lower threshold value"); m_thresholdValue->setRange(0,5000); m_thresholdValue->setValue(100); } medItkDWIBasicThresholdingProcess::~medItkDWIBasicThresholdingProcess() { } medIntParameter *medItkDWIBasicThresholdingProcess::b0VolumeNumberParameter() const { return m_b0VolumeNumber; } medIntParameter *medItkDWIBasicThresholdingProcess::thresholdValueParameter() const { return m_thresholdValue; } void medItkDWIBasicThresholdingProcess::setInput(medAbstractImageData* data) { this->medAbstractDWIMaskingProcess::setInput(data); m_b0VolumeNumber->setRange(0,data->tDimension() - 1); } QString medItkDWIBasicThresholdingProcess::caption() const { return "DWI basic thresholding"; } QString medItkDWIBasicThresholdingProcess::description() const { return "Use ITK BinaryThresholdImageFilter to extract a binary mask"; } medAbstractJob::medJobExitStatus medItkDWIBasicThresholdingProcess::run() { medAbstractJob::medJobExitStatus jobExitSatus = medAbstractJob::MED_JOB_EXIT_FAILURE; if(this->input()) { QString id = this->input()->identifier(); if ( id == "itkDataImageChar4" ) { jobExitSatus = this->_run<char>(); } else if ( id == "itkDataImageUChar4" ) { jobExitSatus = this->_run<unsigned char>(); } else if ( id == "itkDataImageShort4" ) { jobExitSatus = this->_run<short>(); } else if ( id == "itkDataImageUShort4" ) { jobExitSatus = this->_run<unsigned short>(); } else if ( id == "itkDataImageInt4" ) { jobExitSatus = this->_run<int>(); } else if ( id == "itkDataImageUInt4" ) { jobExitSatus = this->_run<unsigned int>(); } else if ( id == "itkDataImageLong4" ) { jobExitSatus = this->_run<long>(); } else if ( id== "itkDataImageULong4" ) { jobExitSatus = this->_run<unsigned long>(); } else if ( id == "itkDataImageFloat4" ) { jobExitSatus = this->_run<float>(); } else if ( id == "itkDataImageDouble4" ) { jobExitSatus = this->_run<double>(); } } return jobExitSatus; } template <class inputType> medAbstractJob::medJobExitStatus medItkDWIBasicThresholdingProcess::_run() { typedef itk::Image<inputType, 4> ImageType; typedef itk::Image<inputType, 3> Image3DType; typename ImageType::Pointer inData = dynamic_cast<ImageType *>((itk::Object*)(this->input()->data())); if(inData.IsNotNull()) { typedef itk::ExtractImageFilter <ImageType, Image3DType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetDirectionCollapseToGuess(); typename ImageType::RegionType extractRegion = inData->GetLargestPossibleRegion(); extractRegion.SetIndex(3,m_b0VolumeNumber->value()); extractRegion.SetSize(3,0); filter->SetExtractionRegion(extractRegion); m_extractfilter = filter; filter->SetInput(0,inData); typedef itk::Image <unsigned char, 3> MaskImageType; typedef itk::BinaryThresholdImageFilter <Image3DType, MaskImageType> ThresholdFilterType; typename ThresholdFilterType::Pointer thr_filter = ThresholdFilterType::New(); thr_filter->SetLowerThreshold(m_thresholdValue->value()); thr_filter->SetInsideValue(1); m_thresholdfilter = thr_filter; thr_filter->SetInput(0,filter->GetOutput()); try { m_thresholdfilter->Update(); } catch(itk::ProcessAborted &) { return medAbstractJob::MED_JOB_EXIT_CANCELLED; } medAbstractImageData *out = qobject_cast<medAbstractImageData *>(medAbstractDataFactory::instance()->create("itkDataImageUChar3")); out->setData(thr_filter->GetOutput()); this->setOutput(out); return medAbstractJob::MED_JOB_EXIT_SUCCESS; } return medAbstractJob::MED_JOB_EXIT_FAILURE; } void medItkDWIBasicThresholdingProcess::cancel() { if(this->isRunning() && m_thresholdfilter.IsNotNull()) { m_thresholdfilter->AbortGenerateDataOn(); } }
29.620321
139
0.653728
arthursw
c887a78ceba3497f2e8233ef9099acd1b0eca215
4,874
cpp
C++
far/cache.cpp
lidacity/FarManager
4ff6edbd53b6652d3ab1d9ae86f66873be850209
[ "BSD-3-Clause" ]
null
null
null
far/cache.cpp
lidacity/FarManager
4ff6edbd53b6652d3ab1d9ae86f66873be850209
[ "BSD-3-Clause" ]
null
null
null
far/cache.cpp
lidacity/FarManager
4ff6edbd53b6652d3ab1d9ae86f66873be850209
[ "BSD-3-Clause" ]
null
null
null
/* cache.cpp Кеширование записи в файл/чтения из файла */ /* Copyright © 2009 Far Group 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. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Self: #include "cache.hpp" // Internal: #include "platform.fs.hpp" // Platform: // Common: // External: //---------------------------------------------------------------------------- CachedRead::CachedRead(os::fs::file& File, size_t BufferSize): m_File(File), m_Alignment(512), m_Buffer(BufferSize? aligned_size(BufferSize, m_Alignment) : 65536) { } void CachedRead::AdjustAlignment() { if (!m_File) return; auto BufferSize = m_Buffer.size(); STORAGE_PROPERTY_QUERY Spq{}; Spq.QueryType = PropertyStandardQuery; Spq.PropertyId = StorageAccessAlignmentProperty; STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR Saad; DWORD BytesReturned; if (m_File.IoControl(IOCTL_STORAGE_QUERY_PROPERTY, &Spq, sizeof(Spq), &Saad, sizeof(Saad), &BytesReturned)) { if (Saad.BytesPerPhysicalSector > 512 && Saad.BytesPerPhysicalSector <= 256*1024) { m_Alignment = static_cast<int>(Saad.BytesPerPhysicalSector); BufferSize = 16 * Saad.BytesPerPhysicalSector; } (void)m_File.IoControl(FSCTL_ALLOW_EXTENDED_DASD_IO, nullptr, 0, nullptr, 0, &BytesReturned, nullptr); } if (BufferSize > m_Buffer.size()) { m_Buffer.resize(BufferSize); } Clear(); } void CachedRead::Clear() { m_ReadSize = 0; m_BytesLeft = 0; m_LastPtr = 0; } bool CachedRead::Read(void* Data, size_t DataSize, size_t* BytesRead) { const auto Ptr = m_File.GetPointer(); if (Ptr != m_LastPtr) { const auto ValidRangeBegin = m_LastPtr + m_BytesLeft; const auto ValidRangeEnd = ValidRangeBegin - m_ReadSize; if (Ptr >= ValidRangeEnd && Ptr < ValidRangeBegin) { m_BytesLeft -= static_cast<int>(Ptr - m_LastPtr); } else { m_BytesLeft = 0; } m_LastPtr = Ptr; } bool Result = false; *BytesRead = 0; if (DataSize <= m_Buffer.size()) { while (DataSize) { if (!m_BytesLeft) { FillBuffer(); if (!m_BytesLeft) break; } Result = true; const auto Actual = std::min(m_BytesLeft, DataSize); memcpy(Data, &m_Buffer[m_ReadSize - m_BytesLeft], Actual); Data = static_cast<char*>(Data) + Actual; m_BytesLeft -= Actual; m_File.SetPointer(Actual, &m_LastPtr, FILE_CURRENT); *BytesRead += Actual; DataSize -= Actual; } } else { Result = m_File.Read(Data, DataSize, *BytesRead); } return Result; } bool CachedRead::Unread(size_t BytesUnread) { if (m_BytesLeft + BytesUnread > m_ReadSize) return false; m_BytesLeft += BytesUnread; const long long Offset = BytesUnread; m_File.SetPointer(-Offset, &m_LastPtr, FILE_CURRENT); return true; } bool CachedRead::FillBuffer() { if (m_File.Eof()) return false; const auto Pointer = m_File.GetPointer(); auto Shift = static_cast<int>(Pointer % m_Alignment); if (Pointer > m_Buffer.size() / 2 + Shift) Shift += static_cast<int>(m_Buffer.size() / 2); if (Shift) m_File.SetPointer(-Shift, nullptr, FILE_CURRENT); auto ReadSize = m_Buffer.size(); unsigned long long FileSize = 0; if (m_File.GetSize(FileSize) && Pointer - Shift + m_Buffer.size() > FileSize) ReadSize = FileSize - Pointer + Shift; auto Result = m_File.Read(m_Buffer.data(), ReadSize, m_ReadSize); if (Result) { if (m_ReadSize > static_cast<size_t>(Shift)) { m_BytesLeft = m_ReadSize - Shift; m_File.SetPointer(Pointer, nullptr, FILE_BEGIN); } else { m_BytesLeft = 0; } } else { if (Shift) m_File.SetPointer(Pointer, nullptr, FILE_BEGIN); m_ReadSize = 0; m_BytesLeft = 0; } return Result; }
24.492462
108
0.712351
lidacity
c888f5654d4ce02f3ea2bf0df6e8b29bee00aded
13,042
cpp
C++
source/rrConfig.cpp
madhavmurthy93/roadrunner
f22b86b154fb3a51b19ab9142d9345f74b33d318
[ "Apache-2.0" ]
null
null
null
source/rrConfig.cpp
madhavmurthy93/roadrunner
f22b86b154fb3a51b19ab9142d9345f74b33d318
[ "Apache-2.0" ]
null
null
null
source/rrConfig.cpp
madhavmurthy93/roadrunner
f22b86b154fb3a51b19ab9142d9345f74b33d318
[ "Apache-2.0" ]
null
null
null
/* * Config.cpp * * Created on: Mar 24, 2014 * Author: andy */ #include "rrUtils.h" #include "rrConfig.h" #include "rrLogger.h" #if (__cplusplus >= 201103L) || defined(_MSC_VER) #include <memory> #include <unordered_map> #define cxx11_ns std #else #include <tr1/memory> #include <tr1/unordered_map> #define cxx11_ns std::tr1 #endif #include <stdexcept> #include <cctype> #include <cstdlib> #include <algorithm> #include <fstream> // std::ofstream #include <assert.h> // TODO When we have gcc 4.4 as minimal compiler, drop poco and use C++ standard regex #include <Poco/RegularExpression.h> #include <Poco/Path.h> // somebody will likely call this multithread and then bitch and moan if // there is an issue, so lock it. #include <Poco/Mutex.h> // default values of sbml consistency check #include <sbml/SBMLDocument.h> // default values of model reset #include <rrSelectionRecord.h> using Poco::Mutex; using Poco::RegularExpression; using std::string; namespace rr { typedef cxx11_ns::unordered_map<std::string, int> StringIntMap; /** * check range of key */ #define CHECK_RANGE(key) { \ if (key < 0 || key >= rr::Config::CONFIG_END) { \ throw std::out_of_range("invalid Config key"); \ } \ } /** * strip any leading or trailing whitespace */ static std::string strip(const std::string& in) { std::string out; std::string::const_iterator b = in.begin(), e = in.end(); // skipping leading spaces while (std::isspace(*b)){ ++b; } if (b != e){ // skipping trailing spaces while (std::isspace(*(e-1))){ --e; } } out.assign(b, e); return out; } static Variant values[] = { Variant(false), // LOADSBMLOPTIONS_CONSERVED_MOIETIES Variant(false), // LOADSBMLOPTIONS_RECOMPILE Variant(false), // LOADSBMLOPTIONS_READ_ONLY Variant(true), // LOADSBMLOPTIONS_MUTABLE_INITIAL_CONDITIONS Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_GVN Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_CFG_SIMPLIFICATION Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_COMBINING Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_DEAD_INST_ELIMINATION Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_DEAD_CODE_ELIMINATION Variant(false), // LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_SIMPLIFIER Variant(false), // LOADSBMLOPTIONS_USE_MCJIT Variant(50), // SIMULATEOPTIONS_STEPS, Variant(5), // SIMULATEOPTIONS_DURATION, Variant(1.e-10), // SIMULATEOPTIONS_ABSOLUTE, Variant(1.e-5), // SIMULATEOPTIONS_RELATIVE, Variant(false), // SIMULATEOPTIONS_STRUCTURED_RESULT, Variant(false), // SIMULATEOPTIONS_STIFF, Variant(false), // SIMULATEOPTIONS_MULTI_STEP, Variant(false), // SIMULATEOPTIONS_DETERMINISTIC_VARIABLE_STEP, Variant(true), // SIMULATEOPTIONS_STOCHASTIC_VARIABLE_STEP, Variant(std::string("CVODE")), // SIMULATEOPTIONS_INTEGRATOR Variant(-1), // SIMULATEOPTIONS_INITIAL_TIMESTEP, Variant(-1), // SIMULATEOPTIONS_MINIMUM_TIMESTEP, Variant(-1), // SIMULATEOPTIONS_MAXIMUM_TIMESTEP, Variant(-1), // SIMULATEOPTIONS_MAXIMUM_NUM_STEPS Variant(0), // ROADRUNNER_DISABLE_WARNINGS Variant(false), // ROADRUNNER_DISABLE_PYTHON_DYNAMIC_PROPERTIES Variant(int(AllChecksON & UnitsCheckOFF)), //SBML_APPLICABLEVALIDATORS Variant(0.00001), // ROADRUNNER_JACOBIAN_STEP_SIZE Variant((int)(SelectionRecord::TIME | SelectionRecord::RATE | SelectionRecord::FLOATING)), // MODEL_RESET Variant(1.e-10), // CVODE_MIN_ABSOLUTE Variant(1.e-5), // CVODE_MIN_RELATIVE Variant(true), // SIMULATEOPTIONS_COPY_RESULT Variant(1.e-4), // STEADYSTATE_RELATIVE Variant(100), // STEADYSTATE_MAXIMUM_NUM_STEPS Variant(1.e-16), // STEADYSTATE_MINIMUM_DAMPING Variant((int)Config::ROADRUNNER_JACOBIAN_MODE_CONCENTRATIONS), // ROADRUNNER_JACOBIAN_MODE Variant(std::string(".")), // TEMP_DIR_PATH, Variant(std::string("")) // LOGGER_LOG_FILE_PATH, // add space after develop keys to clean up merging }; static bool initialized = false; static Mutex configMutex; static void readDefaultConfig() { Mutex::ScopedLock lock(configMutex); if(!initialized) { assert(rr::Config::CONFIG_END == sizeof(values) / sizeof(Variant) && "values array size different than CONFIG_END"); string confPath = rr::Config::getConfigFilePath(); try { if(confPath.size() > 0) { rr::Config::readConfigFile(confPath); } } catch(std::exception& e) { Log(rr::Logger::LOG_WARNING) << "error reading configuration file: " << confPath << ", " << e.what(); } initialized = true; } } /** * load the names of the keys and values into a map */ static void getKeyNames(StringIntMap& keys) { keys["LOADSBMLOPTIONS_CONSERVED_MOIETIES"] = rr::Config::LOADSBMLOPTIONS_CONSERVED_MOIETIES; keys["LOADSBMLOPTIONS_RECOMPILE"] = rr::Config::LOADSBMLOPTIONS_RECOMPILE; keys["LOADSBMLOPTIONS_READ_ONLY"] = rr::Config::LOADSBMLOPTIONS_READ_ONLY; keys["LOADSBMLOPTIONS_MUTABLE_INITIAL_CONDITIONS"] = rr::Config::LOADSBMLOPTIONS_MUTABLE_INITIAL_CONDITIONS; keys["LOADSBMLOPTIONS_OPTIMIZE_GVN"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_GVN; keys["LOADSBMLOPTIONS_OPTIMIZE_CFG_SIMPLIFICATION"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_CFG_SIMPLIFICATION; keys["LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_COMBINING"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_COMBINING; keys["LOADSBMLOPTIONS_OPTIMIZE_DEAD_INST_ELIMINATION"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_DEAD_INST_ELIMINATION; keys["LOADSBMLOPTIONS_OPTIMIZE_DEAD_CODE_ELIMINATION"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_DEAD_CODE_ELIMINATION; keys["LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_SIMPLIFIER"] = rr::Config::LOADSBMLOPTIONS_OPTIMIZE_INSTRUCTION_SIMPLIFIER; keys["LOADSBMLOPTIONS_USE_MCJIT"] = rr::Config::LOADSBMLOPTIONS_USE_MCJIT; keys["SIMULATEOPTIONS_STEPS"] = rr::Config::SIMULATEOPTIONS_STEPS; keys["SIMULATEOPTIONS_DURATION"] = rr::Config::SIMULATEOPTIONS_DURATION; keys["SIMULATEOPTIONS_ABSOLUTE"] = rr::Config::SIMULATEOPTIONS_ABSOLUTE; keys["SIMULATEOPTIONS_RELATIVE"] = rr::Config::SIMULATEOPTIONS_RELATIVE; keys["SIMULATEOPTIONS_STRUCTURED_RESULT"] = rr::Config::SIMULATEOPTIONS_STRUCTURED_RESULT; keys["SIMULATEOPTIONS_STIFF"] = rr::Config::SIMULATEOPTIONS_STIFF; keys["SIMULATEOPTIONS_MULTI_STEP"] = rr::Config::SIMULATEOPTIONS_MULTI_STEP; keys["SIMULATEOPTIONS_DETERMINISTIC_VARIABLE_STEP"] = rr::Config::SIMULATEOPTIONS_DETERMINISTIC_VARIABLE_STEP; keys["SIMULATEOPTIONS_STOCHASTIC_VARIABLE_STEP"] = rr::Config::SIMULATEOPTIONS_STOCHASTIC_VARIABLE_STEP; keys["SIMULATEOPTIONS_INTEGRATOR"] = rr::Config::SIMULATEOPTIONS_INTEGRATOR; keys["SIMULATEOPTIONS_INITIAL_TIMESTEP"] = rr::Config::SIMULATEOPTIONS_INITIAL_TIMESTEP; keys["SIMULATEOPTIONS_MINIMUM_TIMESTEP"] = rr::Config::SIMULATEOPTIONS_MINIMUM_TIMESTEP; keys["SIMULATEOPTIONS_MAXIMUM_TIMESTEP"] = rr::Config::SIMULATEOPTIONS_MAXIMUM_TIMESTEP; keys["SIMULATEOPTIONS_MAXIMUM_NUM_STEPS"] = rr::Config::SIMULATEOPTIONS_MAXIMUM_NUM_STEPS; keys["ROADRUNNER_DISABLE_WARNINGS"] = rr::Config::ROADRUNNER_DISABLE_WARNINGS; keys["ROADRUNNER_DISABLE_PYTHON_DYNAMIC_PROPERTIES"] = rr::Config::ROADRUNNER_DISABLE_PYTHON_DYNAMIC_PROPERTIES; keys["SBML_APPLICABLEVALIDATORS"] = rr::Config::SBML_APPLICABLEVALIDATORS; keys["ROADRUNNER_JACOBIAN_STEP_SIZE"] = rr::Config::ROADRUNNER_JACOBIAN_STEP_SIZE; keys["MODEL_RESET"] = rr::Config::MODEL_RESET; keys["CVODE_MIN_ABSOLUTE"] = rr::Config::CVODE_MIN_ABSOLUTE; keys["CVODE_MIN_RELATIVE"] = rr::Config::CVODE_MIN_RELATIVE; keys["SIMULATEOPTIONS_COPY_RESULT"] = rr::Config::SIMULATEOPTIONS_COPY_RESULT; keys["STEADYSTATE_RELATIVE"] = rr::Config::STEADYSTATE_RELATIVE; keys["STEADYSTATE_MAXIMUM_NUM_STEPS"] = rr::Config::STEADYSTATE_MAXIMUM_NUM_STEPS; keys["STEADYSTATE_MINIMUM_DAMPING"] = rr::Config::STEADYSTATE_MINIMUM_DAMPING; keys["ROADRUNNER_JACOBIAN_MODE"] = rr::Config::ROADRUNNER_JACOBIAN_MODE; keys["TEMP_DIR_PATH"] = rr::Config::TEMP_DIR_PATH; keys["LOGGER_LOG_FILE_PATH"] = rr::Config::LOGGER_LOG_FILE_PATH; // add space after develop keys to clean up merging. assert(rr::Config::CONFIG_END == sizeof(values) / sizeof(Variant) && "values array size different than CONFIG_END"); assert(rr::Config::CONFIG_END == keys.size() && "number of keys in map does not match static values"); } std::string Config::getString(Keys key) { readDefaultConfig(); CHECK_RANGE(key); return values[key].convert<std::string>(); } int Config::getInt(Keys key) { readDefaultConfig(); CHECK_RANGE(key); return values[key].convert<int>(); } double Config::getDouble(Keys key) { readDefaultConfig(); CHECK_RANGE(key); return values[key].convert<double>(); } std::string Config::getConfigFilePath() { // check env var const char* env = std::getenv("ROADRUNNER_CONFIG"); std::string path; Poco::Path ppath; Log(rr::Logger::LOG_DEBUG) << "trying config file from ROADRUNNER_CONFIG " << (env ? env : "NULL"); if (env && rr::fileExists(env, 4)) { return env; } // check home dir ppath.assign(Poco::Path::home()); ppath.setFileName("roadrunner.conf"); path = ppath.toString(); Log(rr::Logger::LOG_DEBUG) << "trying config file " << path; if (rr::fileExists(path, 4)) { return path; } ppath.setFileName(".roadrunner.conf"); path = ppath.toString(); Log(rr::Logger::LOG_DEBUG) << "trying config file " << path; if (rr::fileExists(path, 4)) { return path; } // this could be an empty string if we are in a statically // linked executable, if so, Poco::Path will puke if popDir is called string chkDir = rr::getCurrentSharedLibDir(); if (chkDir.empty()) { chkDir = rr::getCurrentExeFolder(); } assert(!chkDir.empty() && "could not get either shared lib or exe dir"); // check in library dir ppath.assign(chkDir); ppath.setFileName("roadrunner.conf"); path = ppath.toString(); Log(rr::Logger::LOG_DEBUG) << "trying config file " << path; if (rr::fileExists(path, 4)) { return path; } // check one level up ppath.assign(chkDir); ppath.popDirectory(); ppath.setFileName("roadrunner.conf"); path = ppath.toString(); Log(rr::Logger::LOG_DEBUG) << "trying config file " << path; if (rr::fileExists(path, 4)) { return path; } Log(rr::Logger::LOG_DEBUG) << "no config file found; using built-in defaults"; return ""; } void Config::setValue(Keys key, const Variant& value) { readDefaultConfig(); CHECK_RANGE(key); values[key] = value; } void Config::readConfigFile(const std::string& path) { Mutex::ScopedLock lock(configMutex); const Poco::RegularExpression re("^\\s*(\\w*)\\s*:\\s*(.*)\\s*$", RegularExpression::RE_CASELESS); StringIntMap keys; std::ifstream in(path.c_str()); if(!in) { throw std::ifstream::failure("could not open " + path + " for reading"); } getKeyNames(keys); std::string line; while(std::getline(in, line)) { std::vector<std::string> matches; int nmatch = re.split(line, matches); if (nmatch == 3) { StringIntMap::const_iterator i = keys.find(matches[1]); if(i != keys.end()) { values[i->second] = Variant::parse((matches[2])); Log(Logger::LOG_INFORMATION) << "read key " << i->first << " with value: " << values[i->second].toString(); } else { Log(Logger::LOG_WARNING) << "invalid key: \"" << matches[1] << "\" in " << path; } } } initialized = true; } const Variant& Config::getValue(Keys key) { readDefaultConfig(); CHECK_RANGE(key); return values[key]; } bool Config::getBool(Keys key) { readDefaultConfig(); CHECK_RANGE(key); return values[key].convert<bool>(); } void Config::writeConfigFile(const std::string& path) { Mutex::ScopedLock lock(configMutex); std::ofstream out(path.c_str()); if(!out) { throw std::ofstream::failure("could not open " + path + " for writing"); } StringIntMap keys; std::ifstream in(path.c_str()); getKeyNames(keys); for (StringIntMap::const_iterator i = keys.begin(); i != keys.end(); ++i) { out << i->first << ": " << values[i->second].toString() << std::endl; } } }
30.471963
123
0.667996
madhavmurthy93
c88c27980ac84499be6463dbe5093e9510d54dc5
1,385
hpp
C++
include/uri/phoenix/basic_uri_accessor.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
include/uri/phoenix/basic_uri_accessor.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
include/uri/phoenix/basic_uri_accessor.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
#ifndef uri__phoenix__adapted_basic_uri_accessor_hpp #define uri__phoenix__adapted_basic_uri_accessor_hpp #include <boost/phoenix/fusion/at.hpp> namespace uri { namespace phoenix { //namespace { // enum index // { // scheme = 0, // userinfo = 1, // host = 2, // port = 3, // path = 4, // query = 5, // fragment = 6 // }; //} // namespace template <typename ArgT> decltype(auto) scheme_(const ArgT & arg) { return boost::phoenix::at_c<0>(arg); } template <typename ArgT> decltype(auto) userinfo_(const ArgT & arg) { return boost::phoenix::at_c<1>(arg); } template <typename ArgT> decltype(auto) host_(const ArgT & arg) { return boost::phoenix::at_c<2>(arg); } template <typename ArgT> decltype(auto) port_(const ArgT & arg) { return boost::phoenix::at_c<3>(arg); } template <typename ArgT> decltype(auto) path_(const ArgT & arg) { return boost::phoenix::at_c<4>(arg); } template <typename ArgT> decltype(auto) query_(const ArgT & arg) { return boost::phoenix::at_c<5>(arg); } template <typename ArgT> decltype(auto) fragment_(const ArgT & arg) { return boost::phoenix::at_c<6>(arg); } } // namespace phoenix } // namespace uri #endif // uri__phoenix__adapted_basic_uri_accessor_hpp
20.984848
54
0.609386
ledocc
c88ee792ed7a7fc62e338a68d14b904d3b901665
16,546
cpp
C++
corelib/src/LocalMap.cpp
supersaiyajinggod/VISFS
6567df9b064437a32dc96d6f03ef6cd4ea1b24ce
[ "BSD-3-Clause" ]
3
2021-06-09T13:20:59.000Z
2022-01-14T13:31:11.000Z
corelib/src/LocalMap.cpp
supersaiyajinggod/VISFS
6567df9b064437a32dc96d6f03ef6cd4ea1b24ce
[ "BSD-3-Clause" ]
null
null
null
corelib/src/LocalMap.cpp
supersaiyajinggod/VISFS
6567df9b064437a32dc96d6f03ef6cd4ea1b24ce
[ "BSD-3-Clause" ]
null
null
null
#include "LocalMap.h" #include "MultiviewGeometry.h" #include "Stl.h" #include "Timer.h" #include "Log.h" #include <memory> namespace VISFS { LocalMap::LocalMap(const ParametersMap & _parameters) : keySignature_(true), localMapSize_(Parameters::defaultLocalMapMapSize()), maxFeature_(Parameters::defaultTrackerMaxFeatures()), minParallax_(Parameters::defaultLocalMapMinParallax()), minTranslation_(3*Parameters::defaultLocalMapMinTranslation()*Parameters::defaultLocalMapMinTranslation()), newFeatureCount_(0), signatureCount_(0), parallaxCount_(0.f), translationCount_(Eigen::Vector3d(0.0, 0.0, 0.0)), minInliers_(Parameters::defaultEstimatorMinInliers()), numRangeDataLimit_(Parameters::defaultLocalMapNumRangeDataLimit()), gridType_(static_cast<Map::GridType>(Parameters::defaultLocalMapGridMapType())), mapResolution_(Parameters::defaultLocalMapMapResolution()), insertFreeSpace_(Parameters::defaultLocalMapInsertFreeSpace()), hitProbability_(Parameters::defaultLocalMapHitProbability()), missProbability_(Parameters::defaultLocalMapMissProbability()) { Parameters::parse(_parameters, Parameters::kLocalMapMapSize(), localMapSize_); Parameters::parse(_parameters, Parameters::kTrackerMaxFeatures(), maxFeature_); Parameters::parse(_parameters, Parameters::kLocalMapMinParallax(), minParallax_); Parameters::parse(_parameters, Parameters::kLocalMapMinTranslation(), minTranslation_); minTranslation_ = 3 * minTranslation_ * minTranslation_; Parameters::parse(_parameters, Parameters::kEstimatorMinInliers(), minInliers_); Parameters::parse(_parameters, Parameters::kLocalMapNumRangeDataLimit(), numRangeDataLimit_); int gridType; Parameters::parse(_parameters, Parameters::kLocalMapGridMapType(), gridType); gridType_ = static_cast<Map::GridType>(gridType); Parameters::parse(_parameters, Parameters::kLocalMapMapResolution(), mapResolution_); Parameters::parse(_parameters, Parameters::kLocalMapInsertFreeSpace(), insertFreeSpace_); Parameters::parse(_parameters, Parameters::kLocalMapHitProbability(), hitProbability_); Parameters::parse(_parameters, Parameters::kLocalMapMissProbability(), missProbability_); activeSubmap2D_ = std::make_unique<Map::ActiveSubmaps2D>(numRangeDataLimit_, gridType_, mapResolution_, insertFreeSpace_, hitProbability_, missProbability_); } bool LocalMap::insertSignature(const Signature & _signature, const Eigen::Vector3d & _translation) { if (_signature.getWords3d().size() == 0 || _signature.empty()) { LOG_ERROR << "Error: LocalMap::insertSignature failed."; return false; } const std::map<std::size_t, cv::KeyPoint> & featuresInRight = _signature.getKeyPointsMatchesImageRight(); const std::map<std::size_t, cv::KeyPoint> & featuresInNewSignatrue = _signature.getWords(); const std::map<std::size_t, cv::KeyPoint> & featuresInFormer = _signature.getCovisibleWords(); const std::map<std::size_t, cv::Point3f> & features3d = _signature.getWords3d(); const Eigen::Isometry3d Twr = _signature.getPose(); for (auto iter = featuresInNewSignatrue.begin(); iter != featuresInNewSignatrue.end(); iter++) { auto jter = features_.find(iter->first); if (jter == features_.end()) { // Make sure outliers will not be treated as new feature. // add new feature if (features_.size() > maxFeature_) { if(iter->first <= features_.rbegin()->first) continue; } if(features3d.find(iter->first) == features3d.end()) { continue; } else { if(!isFinite(features3d.at(iter->first))) { continue; } } const cv::Point3f feature3d = features3d.at(iter->first); Feature newFeature(iter->first, _signature.getId(), Twr * Eigen::Vector3d(feature3d.x, feature3d.y, feature3d.z)); newFeature.featureStatusInSigantures_.emplace(_signature.getId(), FeatureStatusInSiganature(iter->second.pt, featuresInRight.at(iter->first).pt, features3d.at(iter->first))); features_.emplace(iter->first, newFeature); ++newFeatureCount_; } else { // update feature jter->second.featureStatusInSigantures_.emplace(_signature.getId(), FeatureStatusInSiganature(iter->second.pt, featuresInRight.at(iter->first).pt, features3d.at(iter->first))); jter->second.setEndSignatureId(_signature.getId()); if (jter->second.getObservedTimes() > (localMapSize_)) { if (jter->second.getFeatureState() == Feature::eFeatureState::NEW_ADDED) { jter->second.setFeatureState(Feature::eFeatureState::STABLE); } } } } // add signature signatures_.emplace(_signature.getId(), _signature); // KeySignature check. keySignature_ = false; ++signatureCount_; translationCount_ += _translation.cwiseAbs(); if (newFeatureCount_ > 0.2 * maxFeature_) { keySignature_ = true; clearCounters(); // std::cout << "Feature condition satisfied!!!" << std::endl; } else if ((signatureCount_ > 10) && ((translationCount_.x()*translationCount_.x() + translationCount_.y()*translationCount_.y() + translationCount_.z()*translationCount_.z()) > minTranslation_)) { keySignature_ = true; clearCounters(); // std::cout << "Translation condition satisfied!!!" << std::endl; } else { // Compute parallax std::vector<std::size_t> matches = findCorrespondences(featuresInFormer, featuresInNewSignatrue); float parallaxSum = 0.f; const int parallaxNum = static_cast<int>(matches.size()); for (auto id : matches) { auto keyPointFrom = featuresInFormer.at(id); auto keyPointTo = featuresInNewSignatrue.at(id); const float du = keyPointFrom.pt.x - keyPointTo.pt.x; const float dv = keyPointFrom.pt.y - keyPointTo.pt.y; parallaxSum += std::max(0.f, sqrt(du*du + dv*dv)); } parallaxCount_ += (parallaxSum / static_cast<float>(parallaxNum)); if (parallaxCount_ >= minParallax_) { keySignature_ = true; clearCounters(); // std::cout << "Keyframe condition satisfied!. parallax!, compute result= " << parallaxCount_ << ", minParallax_= " << minParallax_ << "." << std::endl; } } LOG_DEBUG << "Signature: " << _signature.getId() << " is " << (keySignature_? "key" : "none key") << " signature."; return true; } void LocalMap::removeSignature() { if (signatures_.size() != localMapSize_ + 1) { if (signatures_.size() <= localMapSize_) { return; } else { LOG_FATAL << "Error: size of local Map is : " << signatures_.size() << " . Which is larger than " << localMapSize_ + 1; assert(signatures_.size() < localMapSize_ + 2); } } else { std::size_t rmId; if (keySignature_) { rmId = signatures_.begin()->first; } else { rmId = (++signatures_.rbegin())->first; } for (auto iter = features_.begin(); iter != features_.end();) { if (iter->second.featureStatusInSigantures_.find(rmId) != iter->second.featureStatusInSigantures_.end()) { iter->second.featureStatusInSigantures_.erase(rmId); } // Check size // std::cout << "Feature id :" << iter->first << ", observedTimes: " << iter->second.getObservedTimes() << std::endl; assert(iter->second.getObservedTimes() <= localMapSize_+1); if ((iter->second.getObservedTimes() == 0) && ((iter->second.getFeatureState() == Feature::eFeatureState::STABLE) || (iter->second.getEndSignatureId() < signatures_.begin()->first))) { iter = features_.erase(iter); } else { ++iter; } } signatures_.erase(rmId); } LOG_DEBUG << "After remove, size of local Map is : " << signatures_.size() << " feature size: " << features_.size(); } void LocalMap::updateLocalMap(const std::map<std::size_t, Eigen::Isometry3d> & _poses, const std::map<std::size_t, std::tuple<Eigen::Vector3d, bool>> & _point3d, const std::vector<std::tuple<std::size_t, std::size_t>> & _outliers, std::set<std::size_t> & _errorVertex) { for (auto pose : _poses) { if (!(signatures_.find(pose.first) == signatures_.end())) { signatures_.at(pose.first).setPose(pose.second); } else { LOG_FATAL << "[Error]: LocalMap, update signature pose unexist."; } } for (auto featurePose : _point3d) { if (!(features_.find(featurePose.first) == features_.end())) { Feature & feature = features_.at(featurePose.first); if (feature.getFeatureState() == Feature::eFeatureState::NEW_ADDED) { auto [pose, fixSymbol] = featurePose.second; feature.setFeaturePose(pose); } } else { LOG_FATAL << "[Error]: LocalMap, update feature pose unexist."; } } int i = 0; for (auto outlier : _outliers) { // if (!(features_.find(outlier) == features_.end())) { // const Feature & feature = features_.at(outlier); // if (feature.getObservedTimes() >= 2) { // features_.erase(outlier); // i++; // } else { // _outliers.erase(outlier); // } // } else { // LOG_ERROR << "[Error]: LocalMap, cull out unexist feature."; // } auto [featureId, signatureId] = outlier; auto iter = features_.find(featureId); if (iter != features_.end()) { auto jter = iter->second.featureStatusInSigantures_.find(signatureId); if (jter != iter->second.featureStatusInSigantures_.end()) { iter->second.featureStatusInSigantures_.erase(jter); // Discuss which vertex should be blocked. bool c1 = iter->second.getObservedTimes() == 0; bool c2 = iter->second.getFeatureState() == Feature::NEW_ADDED; auto secondSignature = signatures_.rbegin(); secondSignature++; secondSignature++; bool c3 = iter->second.getStartSignatureId() < secondSignature->second.getId(); if (c1 && c2 && c3) { _errorVertex.emplace(featureId); LOG_DEBUG << "Cull out feature: " << featureId << ". With condition c1: " << c1 << " c2: " << c2 << " c3: " << c3; } } else { LOG_ERROR << "LocalMap: find feature but not find observation matches signature."; } } else { LOG_ERROR << "LocalMap: No such feature in localmap"; } } } bool LocalMap::getSignaturePoses(std::map<std::size_t, Eigen::Isometry3d> & _poses) { for (auto iter = signatures_.begin(); iter != signatures_.end(); ++iter) { _poses.emplace(iter->first, iter->second.getPose()); } // for (auto pose : _poses) { // LOG_INFO << "signature id in _pose: " << pose.first << ", with pose:\n" << pose.second.matrix(); // } return true; } bool LocalMap::getSignatureLinks(std::map<std::size_t,std::tuple<std::size_t, std::size_t, Eigen::Isometry3d>> & _links) { // Eigen::Matrix<double, 6, 6> covariance, information; // covariance.setZero(); // covariance(0, 0) = 0.00001; // covariance(1, 1) = 0.00001; // covariance(2, 2) = 0.00001; // covariance(3, 3) = 0.00001; // covariance(4, 4) = 0.00001; // covariance(5, 5) = 0.00001; // information = covariance.inverse(); std::size_t i = 1; for (auto iter = signatures_.begin();;) { auto fromId = iter->first; auto fromPose = iter++->second.getWheelOdomPose(); auto toId = iter->first; auto toPose = iter->second.getWheelOdomPose(); if ((!fromPose.isApprox(Eigen::Isometry3d(Eigen::Matrix4d::Zero()))) && (!toPose.isApprox(Eigen::Isometry3d(Eigen::Matrix4d::Zero())))) { auto transform = fromPose.inverse()*toPose; // _links.emplace(i, std::make_tuple(fromId, toId, transform)); _links.emplace(std::piecewise_construct, std::forward_as_tuple(i), std::forward_as_tuple(fromId, toId, transform)); } if (++i == signatures_.size()) break; } // for (auto link : _links) { // auto [fromId, toId, transfrom, information] = link.second; // std::cout << "link id : " << link.first << " from id : " << fromId << " to id : " << toId << std::endl; // } return true; } bool LocalMap::getFeaturePosesAndObservations(std::map<std::size_t, std::tuple<Eigen::Vector3d, bool>> & _points, std::map<std::size_t, std::map<std::size_t, Optimizer::FeatureBA>> & _observations) { const Eigen::Isometry3d transformRobotToImage = signatures_.begin()->second.getCameraModel().getTansformImageToRobot().inverse(); for (auto feature : features_) { if (feature.second.getObservedTimes() > 1) { bool fixSymbol = feature.second.getFeatureState() == Feature::STABLE ? true : false; _points.emplace(feature.first, std::make_tuple(feature.second.getFeaturePose(), fixSymbol)); std::map<std::size_t, Optimizer::FeatureBA> ptMap; for (auto observation : feature.second.featureStatusInSigantures_) { float depth = transformPoint(observation.second.point3d, transformRobotToImage).z; const cv::KeyPoint kpt = cv::KeyPoint(observation.second.uv, 1.f); ptMap.emplace(observation.first, Optimizer::FeatureBA(kpt, depth)); } _observations.emplace(feature.first, ptMap); } } assert(_points.size() == _observations.size()); return true; } bool LocalMap::checkMapAvaliable() { if ((signatures_.size() < 2) || features_.size() < minInliers_) { return false; } return true; } std::vector<std::size_t> LocalMap::findCorrespondences(const std::map<std::size_t, cv::KeyPoint> & _wordsFrom, const std::map<std::size_t, cv::KeyPoint> & _wordsTo) { std::vector<std::size_t> matches; std::vector<size_t> ids = uKeys(_wordsTo); std::size_t oi = 0; matches.resize(ids.size()); for (std::size_t i = 0; i < ids.size(); ++i) { std::map<std::size_t, cv::KeyPoint>::const_iterator iter = _wordsFrom.find(ids[i]); if (iter != _wordsFrom.end()) { matches[oi++] = ids[i]; } } matches.resize(oi); return matches; } inline void LocalMap::clearCounters() { // Print check // std::string time = getCurrentReadableTime(); // std::cout << time << ", newFeatureCount_: " << newFeatureCount_ << " parallaxCount_: " << parallaxCount_ << " signatureCount_: " << signatureCount_ << " translationCount_: " << translationCount_.transpose() << std::endl; newFeatureCount_ = 0; signatureCount_ = 0; parallaxCount_ = 0.f; translationCount_.setZero(); } inline bool LocalMap::checkCounters() { const bool c1 = newFeatureCount_ > 50; const bool c2 = parallaxCount_ > 50.f; const bool c3 = signatureCount_ > 10; const bool c4 = ((translationCount_.x()*translationCount_.x() + translationCount_.y()*translationCount_.y() + translationCount_.z()*translationCount_.z()) > 3*0.05*0.05); if (c1 || c2 || (c3 && c4)) return true; return false; } const std::vector<Sensor::PointCloud> LocalMap::getLaserHitPointCloud(std::size_t _signatureId) { std::vector<Sensor::PointCloud> result; auto it = signatures_.find(_signatureId); if (it != signatures_.end()) { auto rangeDataes = it->second.getPretreatedRangeData(); for (auto rangeData : rangeDataes) { result.emplace_back(rangeData.returns); } } return result; } std::vector<std::shared_ptr<const Map::Submap2D>> LocalMap::insertMatchingSubMap2d(const std::vector<Sensor::RangeData> & _rangeDatas, const Eigen::Isometry3d & _globalPose) { for (auto rangeData : _rangeDatas) { activeSubmap2D_->insertRangeData(rangeData, _globalPose); } return activeSubmap2D_->submaps(); } } // namespace
45.707182
270
0.622628
supersaiyajinggod
c88fa401500e3542900c5e11d081caa51033e4e3
3,727
hpp
C++
libecole/include/ecole/environment/default.hpp
gasse/ecole
2fe85e3fece61feaae04b3e8d0be8b912e42cb1b
[ "BSD-3-Clause" ]
null
null
null
libecole/include/ecole/environment/default.hpp
gasse/ecole
2fe85e3fece61feaae04b3e8d0be8b912e42cb1b
[ "BSD-3-Clause" ]
null
null
null
libecole/include/ecole/environment/default.hpp
gasse/ecole
2fe85e3fece61feaae04b3e8d0be8b912e42cb1b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <map> #include <random> #include <tuple> #include <type_traits> #include "ecole/abstract.hpp" #include "ecole/environment/exception.hpp" #include "ecole/scip/model.hpp" #include "ecole/scip/type.hpp" #include "ecole/traits.hpp" namespace ecole { namespace environment { template <typename Dynamics, typename ObservationFunction, typename RewardFunction> class EnvironmentComposer : public Environment< trait::action_of_t<Dynamics>, trait::action_set_of_t<Dynamics>, trait::observation_of_t<ObservationFunction>> { public: using Observation = trait::observation_of_t<ObservationFunction>; using Action = trait::action_of_t<Dynamics>; using ActionSet = trait::action_set_of_t<Dynamics>; /** * User facing constructor for the Environment. */ template <typename... Args> EnvironmentComposer( ObservationFunction obs_func = {}, RewardFunction reward_func = {}, std::map<std::string, scip::Param> scip_params = {}, Args&&... args) : m_dynamics(std::forward<Args>(args)...), m_obs_func(std::move(obs_func)), m_reward_func(std::move(reward_func)), m_scip_params(std::move(scip_params)), random_engine(std::random_device{}()) {} /** * @copydoc ecole::environment::Environment::seed */ void seed(Seed new_seed) override { random_engine.seed(new_seed); } /** * @copydoc ecole::environment::Environment::reset */ std::tuple<Observation, ActionSet, Reward, bool> reset(scip::Model&& new_model) override { can_transition = true; try { // Create clean new Model model() = std::move(new_model); model().set_params(scip_params()); dynamics().set_dynamics_random_state(model(), random_engine); // Bring model to initial state and reset state functions bool done; ActionSet action_set; std::tie(done, action_set) = dynamics().reset_dynamics(model()); obs_func().reset(model()); reward_func().reset(model()); can_transition = !done; auto const reward_offset = reward_func().obtain_reward(model(), done); return {obs_func().obtain_observation(model()), std::move(action_set), reward_offset, done}; } catch (std::exception const&) { can_transition = false; throw; } } /** * @copydoc ecole::environment::Environment::reset */ std::tuple<Observation, ActionSet, Reward, bool> reset(std::string const& filename) override { return reset(scip::Model::from_file(filename)); } /** * @copydoc ecole::environment::Environment::reset */ std::tuple<Observation, ActionSet, Reward, bool> reset(scip::Model const& model) override { return reset(model.copy_orig()); } /** * @copydoc ecole::environment::Environment::step */ std::tuple<Observation, ActionSet, Reward, bool, Info> step(Action const& action) override { if (!can_transition) throw Exception("Environment need to be reset."); try { bool done; ActionSet action_set; std::tie(done, action_set) = dynamics().step_dynamics(model(), action); can_transition = !done; auto const reward = reward_func().obtain_reward(model(), done); return { obs_func().obtain_observation(model()), std::move(action_set), reward, done, Info{}, }; } catch (std::exception const&) { can_transition = false; throw; } } auto& dynamics() { return m_dynamics; } auto& model() { return m_model; } auto& obs_func() { return m_obs_func; } auto& reward_func() { return m_reward_func; } auto& scip_params() { return m_scip_params; } private: Dynamics m_dynamics; scip::Model m_model; ObservationFunction m_obs_func; RewardFunction m_reward_func; std::map<std::string, scip::Param> m_scip_params; RandomEngine random_engine; bool can_transition = false; }; } // namespace environment } // namespace ecole
28.234848
95
0.708345
gasse
c8927098d8213645c8066be502696920c5d75cd7
79
hpp
C++
include/fogl/gl.hpp
glasmachers/foglpp
9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888
[ "MIT" ]
null
null
null
include/fogl/gl.hpp
glasmachers/foglpp
9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888
[ "MIT" ]
null
null
null
include/fogl/gl.hpp
glasmachers/foglpp
9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888
[ "MIT" ]
null
null
null
#pragma once /// The include of the gl implementation. #include <GLES2/gl2.h>
15.8
41
0.721519
glasmachers
c89355659d8aa5eb9496c7598a131cedf90aafcf
6,502
hh
C++
include/openroad/OpenRoad.hh
zzqiang866/OpenROAD
5d1eacebc2a9f8e3c41e09c63819ca2cb4a0eddf
[ "BSD-3-Clause-Clear" ]
null
null
null
include/openroad/OpenRoad.hh
zzqiang866/OpenROAD
5d1eacebc2a9f8e3c41e09c63819ca2cb4a0eddf
[ "BSD-3-Clause-Clear" ]
null
null
null
include/openroad/OpenRoad.hh
zzqiang866/OpenROAD
5d1eacebc2a9f8e3c41e09c63819ca2cb4a0eddf
[ "BSD-3-Clause-Clear" ]
1
2021-02-26T17:45:41.000Z
2021-02-26T17:45:41.000Z
///////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, OpenROAD // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #pragma once #include <string> #include <set> #include <vector> extern "C" { struct Tcl_Interp; } namespace odb { class dbDatabase; class dbBlock; class dbTech; class dbLib; class Point; class Rect; } namespace sta { class dbSta; class dbNetwork; class Resizer; class LibertyCell; } namespace rsz { class Resizer; } namespace ppl { class IOPlacer; } namespace cts { class TritonCTS; } namespace grt { class GlobalRouter; } namespace tap { class Tapcell; } namespace dpl { class Opendp; } namespace fin { class Finale; } namespace mpl { class TritonMacroPlace; } namespace gpl { class Replace; } namespace rcx { class Ext; } namespace triton_route { class TritonRoute; } namespace psm { class PDNSim; } namespace ant { class AntennaChecker; } namespace par { class PartitionMgr; } namespace utl { class Logger; } namespace ord { using std::string; class dbVerilogNetwork; // Only pointers to components so the header has no dependents. class OpenRoad { public: // Singleton accessor. // This accessor should ONLY be used for tcl commands. // Tools should use their initialization functions to get the // OpenRoad object and/or any other tools they need to reference. static OpenRoad *openRoad(); void init(Tcl_Interp *tcl_interp); Tcl_Interp *tclInterp() { return tcl_interp_; } utl::Logger *getLogger() { return logger_; } odb::dbDatabase *getDb() { return db_; } sta::dbSta *getSta() { return sta_; } sta::dbNetwork *getDbNetwork(); rsz::Resizer *getResizer() { return resizer_; } cts::TritonCTS *getTritonCts() { return tritonCts_; } dbVerilogNetwork *getVerilogNetwork() { return verilog_network_; } dpl::Opendp *getOpendp() { return opendp_; } fin::Finale *getFinale() { return finale_; } tap::Tapcell *getTapcell() { return tapcell_; } mpl::TritonMacroPlace *getTritonMp() { return tritonMp_; } rcx::Ext *getOpenRCX() { return extractor_; } triton_route::TritonRoute *getTritonRoute() { return detailed_router_; } gpl::Replace* getReplace() { return replace_; } psm::PDNSim* getPDNSim() { return pdnsim_; } grt::GlobalRouter* getFastRoute() { return fastRoute_; } par::PartitionMgr *getPartitionMgr() { return partitionMgr_; } ant::AntennaChecker *getAntennaChecker() { return antenna_checker_; } ppl::IOPlacer *getIOPlacer() { return ioPlacer_; } // Return the bounding box of the db rows. odb::Rect getCore(); // Return true if the command units have been initialized. bool unitsInitialized(); void readLef(const char *filename, const char *lib_name, bool make_tech, bool make_library); void readDef(const char *filename, bool order_wires, bool continue_on_errors); void writeDef(const char *filename, // major.minor (avoid including defout.h) string version); void readVerilog(const char *filename); // Write a flat verilog netlist for the database. void writeVerilog(const char *filename, bool sort, bool include_pwr_gnd, std::vector<sta::LibertyCell*> *remove_cells); void linkDesign(const char *top_cell_name); void readDb(const char *filename); void writeDb(const char *filename); // Observer interface class Observer { public: virtual ~Observer(); // Either pointer could be null virtual void postReadLef(odb::dbTech* tech, odb::dbLib* library) = 0; virtual void postReadDef(odb::dbBlock* block) = 0; virtual void postReadDb(odb::dbDatabase* db) = 0; private: OpenRoad* owner_ = nullptr; friend class OpenRoad; }; void addObserver(Observer *observer); void removeObserver(Observer *observer); protected: ~OpenRoad(); friend void deleteAllMemory(); private: OpenRoad(); Tcl_Interp *tcl_interp_; utl::Logger *logger_; odb::dbDatabase *db_; dbVerilogNetwork *verilog_network_; sta::dbSta *sta_; rsz::Resizer *resizer_; ppl::IOPlacer *ioPlacer_; dpl::Opendp *opendp_; fin::Finale *finale_; mpl::TritonMacroPlace *tritonMp_; grt::GlobalRouter *fastRoute_; cts::TritonCTS *tritonCts_; tap::Tapcell *tapcell_; rcx::Ext *extractor_; triton_route::TritonRoute *detailed_router_; ant::AntennaChecker *antenna_checker_; gpl::Replace *replace_; psm::PDNSim *pdnsim_; par::PartitionMgr *partitionMgr_; std::set<Observer *> observers_; // Singleton used by tcl command interpreter. static OpenRoad *openroad_; }; // Return the bounding box of the db rows. odb::Rect getCore(odb::dbBlock *block); // Return the point inside rect that is closest to pt. odb::Point closestPtInRect(odb::Rect rect, odb::Point pt); odb::Point closestPtInRect(odb::Rect rect, int x, int y); int tclAppInit(Tcl_Interp *interp); void deleteAllMemory(); } // namespace ord
25.007692
80
0.707013
zzqiang866
c896ae803759895d199b9d95c6c56dc4f35f74d4
1,008
hpp
C++
hyper/include/hyper/ast/declarations/translation_unit_declaration.hpp
HyperionOrg/HyperLang
30f7a1707d00fb5cc6dc22913764389a3b998f09
[ "MIT" ]
null
null
null
hyper/include/hyper/ast/declarations/translation_unit_declaration.hpp
HyperionOrg/HyperLang
30f7a1707d00fb5cc6dc22913764389a3b998f09
[ "MIT" ]
null
null
null
hyper/include/hyper/ast/declarations/translation_unit_declaration.hpp
HyperionOrg/HyperLang
30f7a1707d00fb5cc6dc22913764389a3b998f09
[ "MIT" ]
null
null
null
/* * Copyright (c) 2022-present, SkillerRaptor <skillerraptor@protonmail.com> * * SPDX-License-Identifier: MIT */ #pragma once #include "hyper/ast/declarations/declaration.hpp" #include <span> #include <string> #include <vector> namespace hyper { class TranslationUnitDeclaration final : public Declaration { public: TranslationUnitDeclaration( SourceRange source_range, std::string file, std::vector<Declaration *> declarations); ~TranslationUnitDeclaration() override; std::string_view file() const; std::span<Declaration *const> declarations() const; constexpr Category class_category() const override { return AstNode::Category::TranslationUnitDeclaration; } constexpr Kind class_kind() const override { return AstNode::Kind::Declaration; } constexpr std::string_view class_name() const override { return "TranslationUnitDeclaration"; } private: std::string m_file; std::vector<Declaration *> m_declarations = {}; }; } // namespace hyper
20.571429
75
0.733135
HyperionOrg
c8996371ccbfd1a3ca6f81846b4aef205fa16788
6,636
cpp
C++
src/Reflection/ObjectDatabaseForwardPopulator.cpp
sabachan/framework
e9b5fd620d876679a7b42ce5fdc1b1d2009d2abd
[ "MIT" ]
null
null
null
src/Reflection/ObjectDatabaseForwardPopulator.cpp
sabachan/framework
e9b5fd620d876679a7b42ce5fdc1b1d2009d2abd
[ "MIT" ]
null
null
null
src/Reflection/ObjectDatabaseForwardPopulator.cpp
sabachan/framework
e9b5fd620d876679a7b42ce5fdc1b1d2009d2abd
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ObjectDatabaseForwardPopulator.h" #include "BaseClass.h" #include "Metaclass.h" namespace sg { namespace reflection { //============================================================================= ObjectDatabaseForwardPopulator::ObjectDatabaseForwardPopulator(ObjectDatabase* iDatabase) : m_stack() , m_path() , m_database(iDatabase) , m_propertyContainsIdentifier(false) { } ObjectDatabaseForwardPopulator::~ObjectDatabaseForwardPopulator() { SG_ASSERT(m_stack.empty()); SG_ASSERT(m_path.Size() == 0); SG_ASSERT(!m_propertyContainsIdentifier); } void ObjectDatabaseForwardPopulator::BeginNamespace(char const* iName) { SG_ASSERT(m_stack.empty()); SG_ASSERT(!m_propertyContainsIdentifier); m_path = Identifier(m_path, iName); } void ObjectDatabaseForwardPopulator::EndNamespace() { SG_ASSERT(m_stack.empty()); SG_ASSERT(!m_propertyContainsIdentifier); m_path = m_path.ParentNamespace(); } void ObjectDatabaseForwardPopulator::BeginObject(ObjectVisibility iVisibility, char const* iName, Identifier const& iType) { SG_ASSERT(!m_propertyContainsIdentifier); using namespace reflection; if(!m_stack.empty()) BeginValue(); SG_CODE_FOR_ASSERT(std::string DEBUG_type = iType.AsString()); Metaclass const* mc = GetMetaclassIFP(m_path, iType); if(nullptr == mc) { // TODO error... } SG_ASSERT(nullptr != mc); BaseClass* object = mc->CreateObject(); m_stack.emplace_back(object); m_path = Identifier(m_path, iName); m_database->Add(iVisibility, m_path, object); } void ObjectDatabaseForwardPopulator::EndObject() { SG_ASSERT(!m_propertyContainsIdentifier); using namespace reflection; SG_ASSERT(!m_stack.empty()); SG_ASSERT(m_stack.back().type == StackNode::Type::Object); safeptr<BaseClass> object = m_stack.back().object.get(); SG_ASSERT(nullptr != object); m_stack.pop_back(); if(!m_stack.empty()) { refptr<IPrimitiveData> data = new PrimitiveData<refptr<BaseClass> >(object.get()); EndValue(data.get()); } m_path = m_path.ParentNamespace(); } void ObjectDatabaseForwardPopulator::Property(char const* iName) { SG_ASSERT(!m_stack.empty()); SG_ASSERT(m_stack.back().type == StackNode::Type::Object || m_stack.back().type == StackNode::Type::NamedList); SG_ASSERT(!m_propertyContainsIdentifier || m_stack.back().type != StackNode::Type::Object); SG_ASSERT(nullptr == m_stack.back().propertyName); m_stack.back().propertyName = iName; } void ObjectDatabaseForwardPopulator::Value(bool iValue) { BeginValue(); refptr<IPrimitiveData> data = new PrimitiveData<bool>(iValue); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::Value(int iValue) { BeginValue(); refptr<IPrimitiveData> data = new PrimitiveData<i32>(iValue); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::Value(float iValue) { BeginValue(); refptr<IPrimitiveData> data = new PrimitiveData<float>(iValue); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::Value(char const* iValue) { BeginValue(); refptr<IPrimitiveData> data = new PrimitiveData<std::string>(iValue); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::Value(nullptr_t) { BeginValue(); refptr<IPrimitiveData> data = new PrimitiveData<nullptr_t>(nullptr); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::Value(Identifier const& iValue) { BeginValue(); m_propertyContainsIdentifier = true; refptr<IPrimitiveData> data = new PrimitiveData<ObjectReference>( ObjectReference( m_database.get(), m_path, iValue)); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::BeginList() { BeginValue(); m_stack.emplace_back(StackNode::Type::List); m_stack.back().data = new PrimitiveData<PrimitiveDataList>(); } void ObjectDatabaseForwardPopulator::EndList() { refptr<IPrimitiveData> data = m_stack.back().data; m_stack.pop_back(); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::BeginBloc() { BeginValue(); m_stack.emplace_back(StackNode::Type::NamedList); m_stack.back().data = new PrimitiveData<PrimitiveDataNamedList>(); } void ObjectDatabaseForwardPopulator::EndBloc() { refptr<IPrimitiveData> data = m_stack.back().data; m_stack.pop_back(); EndValue(data.get()); } void ObjectDatabaseForwardPopulator::BeginValue() { SG_ASSERT(!m_stack.empty()); SG_ASSERT(nullptr != m_stack.back().propertyName || m_stack.back().type == StackNode::Type::List); } void ObjectDatabaseForwardPopulator::EndValue(IPrimitiveData* iData) { SG_ASSERT(iData->IsRefCounted_ForAssert()); StackNode& backNode = m_stack.back(); switch(backNode.type) { case StackNode::Type::Object: { SG_ASSERT(nullptr != backNode.object); SG_ASSERT(nullptr != backNode.propertyName); if(!m_propertyContainsIdentifier) { bool ok = backNode.object->SetPropertyROK(backNode.propertyName, iData); SG_ASSERT_AND_UNUSED(ok); } else { IProperty const* property = backNode.object->GetMetaclass()->GetPropertyIFP(backNode.propertyName); m_database->AddDeferredProperty(m_path, property, iData); m_propertyContainsIdentifier = false; } } break; case StackNode::Type::List: { SG_ASSERT(nullptr == backNode.object); SG_ASSERT(nullptr == backNode.propertyName); PrimitiveData<PrimitiveDataList>* nodeData = checked_cast<PrimitiveData<PrimitiveDataList>*>(backNode.data.get()); nodeData->GetForWriting().push_back(iData); } break; case StackNode::Type::NamedList: { SG_ASSERT(nullptr == backNode.object); SG_ASSERT(nullptr != backNode.propertyName); PrimitiveData<PrimitiveDataNamedList>* nodeData = checked_cast<PrimitiveData<PrimitiveDataNamedList>*>(backNode.data.get()); nodeData->GetForWriting().emplace_back(backNode.propertyName, iData); } break; default: SG_ASSERT_NOT_REACHED(); } backNode.propertyName = nullptr; } //============================================================================= } }
33.857143
137
0.650844
sabachan
c89c8477392d5b3d8619c3872936197a4b1baa38
3,435
cpp
C++
eb/src/v20210416/model/CkafkaTargetParams.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
eb/src/v20210416/model/CkafkaTargetParams.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
eb/src/v20210416/model/CkafkaTargetParams.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * 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/eb/v20210416/model/CkafkaTargetParams.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Eb::V20210416::Model; using namespace std; CkafkaTargetParams::CkafkaTargetParams() : m_topicNameHasBeenSet(false), m_retryPolicyHasBeenSet(false) { } CoreInternalOutcome CkafkaTargetParams::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("TopicName") && !value["TopicName"].IsNull()) { if (!value["TopicName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CkafkaTargetParams.TopicName` IsString=false incorrectly").SetRequestId(requestId)); } m_topicName = string(value["TopicName"].GetString()); m_topicNameHasBeenSet = true; } if (value.HasMember("RetryPolicy") && !value["RetryPolicy"].IsNull()) { if (!value["RetryPolicy"].IsObject()) { return CoreInternalOutcome(Core::Error("response `CkafkaTargetParams.RetryPolicy` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_retryPolicy.Deserialize(value["RetryPolicy"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_retryPolicyHasBeenSet = true; } return CoreInternalOutcome(true); } void CkafkaTargetParams::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_topicNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TopicName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_topicName.c_str(), allocator).Move(), allocator); } if (m_retryPolicyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RetryPolicy"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_retryPolicy.ToJsonObject(value[key.c_str()], allocator); } } string CkafkaTargetParams::GetTopicName() const { return m_topicName; } void CkafkaTargetParams::SetTopicName(const string& _topicName) { m_topicName = _topicName; m_topicNameHasBeenSet = true; } bool CkafkaTargetParams::TopicNameHasBeenSet() const { return m_topicNameHasBeenSet; } RetryPolicy CkafkaTargetParams::GetRetryPolicy() const { return m_retryPolicy; } void CkafkaTargetParams::SetRetryPolicy(const RetryPolicy& _retryPolicy) { m_retryPolicy = _retryPolicy; m_retryPolicyHasBeenSet = true; } bool CkafkaTargetParams::RetryPolicyHasBeenSet() const { return m_retryPolicyHasBeenSet; }
28.625
146
0.703639
suluner
c89f94eeb6710a717493fe7cb460d9e4146e762a
5,528
cpp
C++
tmt/src/v20180321/model/TextTranslateResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
tmt/src/v20180321/model/TextTranslateResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
tmt/src/v20180321/model/TextTranslateResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * 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/tmt/v20180321/model/TextTranslateResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tmt::V20180321::Model; using namespace std; TextTranslateResponse::TextTranslateResponse() : m_targetTextHasBeenSet(false), m_sourceHasBeenSet(false), m_targetHasBeenSet(false) { } CoreInternalOutcome TextTranslateResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("TargetText") && !rsp["TargetText"].IsNull()) { if (!rsp["TargetText"].IsString()) { return CoreInternalOutcome(Core::Error("response `TargetText` IsString=false incorrectly").SetRequestId(requestId)); } m_targetText = string(rsp["TargetText"].GetString()); m_targetTextHasBeenSet = true; } if (rsp.HasMember("Source") && !rsp["Source"].IsNull()) { if (!rsp["Source"].IsString()) { return CoreInternalOutcome(Core::Error("response `Source` IsString=false incorrectly").SetRequestId(requestId)); } m_source = string(rsp["Source"].GetString()); m_sourceHasBeenSet = true; } if (rsp.HasMember("Target") && !rsp["Target"].IsNull()) { if (!rsp["Target"].IsString()) { return CoreInternalOutcome(Core::Error("response `Target` IsString=false incorrectly").SetRequestId(requestId)); } m_target = string(rsp["Target"].GetString()); m_targetHasBeenSet = true; } return CoreInternalOutcome(true); } string TextTranslateResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_targetTextHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TargetText"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_targetText.c_str(), allocator).Move(), allocator); } if (m_sourceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Source"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_source.c_str(), allocator).Move(), allocator); } if (m_targetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Target"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_target.c_str(), allocator).Move(), allocator); } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } string TextTranslateResponse::GetTargetText() const { return m_targetText; } bool TextTranslateResponse::TargetTextHasBeenSet() const { return m_targetTextHasBeenSet; } string TextTranslateResponse::GetSource() const { return m_source; } bool TextTranslateResponse::SourceHasBeenSet() const { return m_sourceHasBeenSet; } string TextTranslateResponse::GetTarget() const { return m_target; } bool TextTranslateResponse::TargetHasBeenSet() const { return m_targetHasBeenSet; }
31.770115
128
0.673119
suluner
c8a301a34c8a9b1d38a41be45d15db32b2b42758
1,601
cc
C++
src/GSPH/WaveSpeeds/DavisWaveSpeed.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/GSPH/WaveSpeeds/DavisWaveSpeed.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
17
2020-01-05T08:41:46.000Z
2020-09-18T00:08:32.000Z
src/GSPH/WaveSpeeds/DavisWaveSpeed.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // DavisWaveSpeed // Davis S., (1988) "Simplified Second-Order Godunov-Type Methods" Siam. Sci. // Stat. Comput., 9(3):445-473 // // J.M. Pearl 2021 //----------------------------------------------------------------------------// #include "DavisWaveSpeed.hh" namespace Spheral { //------------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------------ template<typename Dimension> DavisWaveSpeed<Dimension>:: DavisWaveSpeed(){} //------------------------------------------------------------------------------ // Destructor //------------------------------------------------------------------------------ template<typename Dimension> DavisWaveSpeed<Dimension>:: ~DavisWaveSpeed(){} //------------------------------------------------------------------------------ // wave speed //------------------------------------------------------------------------------ template<typename Dimension> void DavisWaveSpeed<Dimension>:: waveSpeed(const typename Dimension::Scalar rhoi, const typename Dimension::Scalar rhoj, const typename Dimension::Scalar ci, const typename Dimension::Scalar cj, const typename Dimension::Scalar ui, const typename Dimension::Scalar uj, typename Dimension::Scalar& Si, typename Dimension::Scalar& Sj) const { Si = rhoi*(std::max(uj+cj,ui+ci)-ui); Sj = rhoj*(std::min(ui-ci,uj-cj)-uj); } }
34.804348
80
0.401624
jmikeowen
c8a3196d7aeee29c230a6b9a293348195b5c32fe
10,785
cc
C++
src/base/evloop.cc
gasinvein/zypak
89dd114427a114028f249ed9b2824d083f459eb5
[ "BSD-3-Clause" ]
null
null
null
src/base/evloop.cc
gasinvein/zypak
89dd114427a114028f249ed9b2824d083f459eb5
[ "BSD-3-Clause" ]
null
null
null
src/base/evloop.cc
gasinvein/zypak
89dd114427a114028f249ed9b2824d083f459eb5
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 Endless Mobile, Inc. // Portions copyright 2015 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 "base/evloop.h" #include <sys/eventfd.h> #include <sys/poll.h> #include <array> #include <cstdint> #include <systemd/sd-event.h> #include "base/base.h" #include "base/debug.h" namespace zypak { namespace { constexpr int kMillisecondsPerSecond = 1000; constexpr int kMicrosecondsPerMillisecond = 1000; constexpr int kDefaultAccuracyMs = 50; template <typename Handler> struct CallbackParams { zypak::EvLoop* evloop; Handler handler; std::vector<zypak::EvLoop::DestroyHandler> on_destroy; }; void DisableSource(sd_event_source* source) { Debug() << "Disable source " << source; ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_enabled(source, SD_EVENT_OFF)); ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_floating(source, false)); } } // namespace // static std::optional<EvLoop> EvLoop::Create() { unique_fd notify_defer(eventfd(0, EFD_NONBLOCK)); if (notify_defer.invalid()) { Errno() << "Failed to create notify eventfd"; return {}; } sd_event* event = nullptr; if (int err = sd_event_new(&event); err < 0) { Errno(-err) << "Failed to create event loop"; return {}; } return EvLoop(event, std::move(notify_defer)); } EvLoop::EvLoop(sd_event* event, unique_fd notify_defer_fd) : event_(event), notify_defer_fd_(std::move(notify_defer_fd)) {} EvLoop::SourceRef::State EvLoop::SourceRef::state() const { int enabled = -1; ZYPAK_ASSERT_SD_ERROR(sd_event_source_get_enabled(source_, &enabled)); switch (enabled) { case SD_EVENT_OFF: return State::kDisabled; case SD_EVENT_ONESHOT: return State::kActiveOnce; case SD_EVENT_ON: return State::kActiveForever; default: ZYPAK_ASSERT(false, << "Invalid sd-event state: " << enabled); } } void EvLoop::SourceRef::Disable() { DisableSource(source_); } void EvLoop::SourceRef::AddDestroyHandler(DestroyHandler handler) { on_destroy_->push_back(std::move(handler)); } void EvLoop::TriggerSourceRef::Trigger() { Debug() << "Trigger source " << source_.source_; ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_enabled(source_.source_, SD_EVENT_ONESHOT)); ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_floating(source_.source_, true)); ZYPAK_ASSERT_WITH_ERRNO(eventfd_write(notify_defer_fd_, 1) != -1); } std::optional<EvLoop::SourceRef> EvLoop::AddTask(EvLoop::EventHandler handler) { auto source = AddTaskNoNotify(std::move(handler)); if (!source) { return {}; } // Notify any waiters. if (eventfd_write(notify_defer_fd_.get(), 1) == -1) { Errno() << "WARNING: Failed to notify defer fd"; } return source; } std::optional<EvLoop::TriggerSourceRef> EvLoop::AddTrigger(EvLoop::EventHandler handler) { auto source = AddTaskNoNotify(handler); if (!source) { return {}; } ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_enabled(source->source_, SD_EVENT_OFF)); Debug() << "Lifting task " << source->source_ << " to trigger"; return TriggerSourceRef(std::move(*source), notify_defer_fd_.get()); } std::optional<EvLoop::SourceRef> EvLoop::AddTimerSec(int seconds, EvLoop::EventHandler handler) { return AddTimerMs(seconds * kMillisecondsPerSecond, handler); } std::optional<EvLoop::SourceRef> EvLoop::AddTimerMs(int ms, EvLoop::EventHandler handler) { ZYPAK_ASSERT(handler, << "Missing handler for timer, ms = " << ms); constexpr int kClock = CLOCK_MONOTONIC; std::uint64_t now; if (int err = sd_event_now(event_.get(), kClock, &now); err < 0) { Errno(-err) << "Failed to get current clock tick"; return {}; } std::uint64_t target_time = now + ms * kMicrosecondsPerMillisecond; sd_event_source* source = nullptr; if (int err = sd_event_add_time(event_.get(), &source, kClock, target_time, kDefaultAccuracyMs * kMicrosecondsPerMillisecond, &HandleTimeEvent, nullptr); err < 0) { Errno(-err) << "Failed to add timer event"; return {}; } Debug() << "Added timer source " << source << " with duration " << ms << "ms"; return SourceSetup(source, std::move(handler)); } std::optional<EvLoop::SourceRef> EvLoop::AddFd(int fd, Events events, EvLoop::IoEventHandler handler) { ZYPAK_ASSERT(!events.empty(), << "Missing events for fd" << fd); ZYPAK_ASSERT(handler, << "Missing handler for fd " << fd); int epoll_events = 0; if (events.contains(Events::Status::kRead)) { epoll_events |= EPOLLIN; } if (events.contains(Events::Status::kWrite)) { epoll_events |= EPOLLOUT; } sd_event_source* source; if (int err = sd_event_add_io(event_.get(), &source, fd, epoll_events, &HandleIoEvent, nullptr); err < 0) { Errno(-err) << "Failed to add I/O event"; return {}; } Debug() << "Adding I/O source " << source << " for " << fd; return SourceSetup(source, std::move(handler)); } std::optional<EvLoop::SourceRef> EvLoop::TakeFd(unique_fd fd, Events events, EvLoop::IoEventHandler handler) { auto source = AddFd(fd.get(), events, std::move(handler)); if (!source) { return {}; } sd_event_source_set_io_fd_own(source->source_, true); return source; } EvLoop::WaitResult EvLoop::Wait() { int pending = sd_event_prepare(event_.get()); if (pending < 0) { Errno(-pending) << "Failed to prepare event loop"; return WaitResult::kError; } else if (pending > 0) { // No need to wait, we know some events are ready. ClearNotifyDeferFd(); return WaitResult::kReady; } std::array<struct pollfd, 2> pfds; pfds[0].fd = sd_event_get_fd(event_.get()); ZYPAK_ASSERT_SD_ERROR(pfds[0].fd); pfds[1].fd = notify_defer_fd_.get(); pfds[0].events = pfds[1].events = POLLIN; pfds[0].revents = pfds[1].revents = 0; int ready = HANDLE_EINTR(poll(pfds.data(), pfds.size(), -1)); if (ready == -1) { Errno() << "Failed to poll on sd-event fd"; return WaitResult::kError; } if (ready > 0) { if ((pfds[0].revents | pfds[1].revents) & (POLLHUP | POLLERR)) { Log() << "sd-event fd is in an error state"; return WaitResult::kError; } if ((pfds[0].revents | pfds[1].revents) & POLLIN) { if (pfds[1].revents & POLLIN) { ClearNotifyDeferFd(); } return WaitResult::kReady; } ZYPAK_ASSERT((pfds[0].revents | pfds[1].revents) == 0, << "Unexpected revents values: " << pfds[0].revents << ' ' << pfds[1].revents); } Debug() << "Poll returned without events?"; return WaitResult::kIdle; } EvLoop::DispatchResult EvLoop::Dispatch() { if (sd_event_get_state(event_.get()) != SD_EVENT_PENDING) { int pending = sd_event_wait(event_.get(), 0); if (pending < 0) { Errno(-pending) << "Failed to update event loop waiting state"; return DispatchResult::kError; } else if (pending == 0) { Log() << "Wait found events, but sd-event found none"; return DispatchResult::kContinue; } } int result = sd_event_dispatch(event_.get()); if (result < 0) { Errno(-result) << "Failed to run event loop iteration"; return DispatchResult::kError; } else if (result == 0) { return DispatchResult::kExit; } return DispatchResult::kContinue; } bool EvLoop::Exit(EvLoop::ExitStatus status) { if (int err = sd_event_exit(event_.get(), static_cast<int>(status)); err < 0) { Errno(-err) << "Failed to exit event loop"; return false; } return true; } EvLoop::ExitStatus EvLoop::exit_status() const { int code; ZYPAK_ASSERT_SD_ERROR(sd_event_get_exit_code(event_.get(), &code)); return static_cast<EvLoop::ExitStatus>(code); } void EvLoop::ClearNotifyDeferFd() { std::uint64_t value; ZYPAK_ASSERT_WITH_ERRNO(eventfd_read(notify_defer_fd_.get(), &value) != -1 || errno == EAGAIN); } std::optional<EvLoop::SourceRef> EvLoop::AddTaskNoNotify(EvLoop::EventHandler handler) { ZYPAK_ASSERT(handler, << "Missing handler for task"); sd_event_source* source = nullptr; if (int err = sd_event_add_defer(event_.get(), &source, &GenericHandler<EventHandler>, nullptr); err < 0) { Errno(-err) << "Failed to add task"; return {}; } Debug() << "Added task source " << source; return SourceSetup(source, std::move(handler)); } template <typename Handler> // static EvLoop::SourceRef EvLoop::SourceSetup(sd_event_source* source, Handler handler) { auto* params = new CallbackParams<Handler>{this, std::move(handler)}; sd_event_source_set_floating(source, true); sd_event_source_set_userdata(source, params); sd_event_source_set_destroy_callback(source, [](void* data) { auto* params = static_cast<CallbackParams<Handler>*>(data); for (DestroyHandler handler : params->on_destroy) { handler(); } delete params; }); return SourceRef(source, &params->on_destroy); } template <typename Handler, typename... Args> // static int EvLoop::GenericHandler(sd_event_source* source, void* data, Args&&... args) { Debug() << "Received event from " << source; auto* params = static_cast<CallbackParams<Handler>*>(data); // SourceRef doesn't ref its argument, as it usually "steals" a brand-new source. However, if we // don't ref it here, it'll be unref'd in SourceRef's destructor, thus unref-ing the floating // reference the event loop has and likely causing memory errors. sd_event_source_ref(source); SourceRef source_ref(source, &params->on_destroy); params->handler(std::move(source_ref), std::forward<Args>(args)...); int enabled = -1; ZYPAK_ASSERT_SD_ERROR(sd_event_source_get_enabled(source, &enabled)); if (enabled != SD_EVENT_ON) { // If it's already disabled, make sure it's no longer floating so it won't leak. ZYPAK_ASSERT_SD_ERROR(sd_event_source_set_floating(source, false)); } return 0; } // static int EvLoop::HandleIoEvent(sd_event_source* source, int fd, std::uint32_t revents, void* data) { if (revents & (EPOLLHUP | EPOLLERR)) { std::string_view reason = revents & EPOLLHUP ? "connection closed" : "unknown error"; Log() << "Dropping " << source << " (" << fd << ") because of " << reason; DisableSource(source); return -ECONNRESET; } Events events(Events::Status::kNone); if (revents & EPOLLIN) { events |= Events::Status::kRead; } if (revents & EPOLLOUT) { events |= Events::Status::kWrite; } return GenericHandler<IoEventHandler>(source, data, events); } // static int EvLoop::HandleTimeEvent(sd_event_source* source, std::uint64_t us, void* data) { return GenericHandler<EventHandler>(source, data); } } // namespace zypak
29.710744
98
0.675661
gasinvein
c8a320dc744fd8c5bc4ca00cd16e7ceb277c12f7
58,762
cpp
C++
modules/stitching/src/seam_finders.cpp
tweenietomatoes/opencv
7d1094b7e102d4c44cfa09171f97b4f50fc850d7
[ "BSD-3-Clause" ]
1
2020-05-11T22:26:54.000Z
2020-05-11T22:26:54.000Z
modules/stitching/src/seam_finders.cpp
tweenietomatoes/opencv
7d1094b7e102d4c44cfa09171f97b4f50fc850d7
[ "BSD-3-Clause" ]
3
2019-08-21T07:13:41.000Z
2020-06-23T12:35:17.000Z
modules/stitching/src/seam_finders.cpp
tweenietomatoes/opencv
7d1094b7e102d4c44cfa09171f97b4f50fc850d7
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" #include <map> namespace cv { namespace detail { void PairwiseSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { LOGLN("Finding seams..."); if (src.size() == 0) return; #if ENABLE_LOG int64 t = getTickCount(); #endif images_ = src; sizes_.resize(src.size()); for (size_t i = 0; i < src.size(); ++i) sizes_[i] = src[i].size(); corners_ = corners; masks_ = masks; run(); LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec"); } void PairwiseSeamFinder::run() { for (size_t i = 0; i < sizes_.size() - 1; ++i) { for (size_t j = i + 1; j < sizes_.size(); ++j) { Rect roi; if (overlapRoi(corners_[i], corners_[j], sizes_[i], sizes_[j], roi)) findInPair(i, j, roi); } } } void VoronoiSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { PairwiseSeamFinder::find(src, corners, masks); } void VoronoiSeamFinder::find(const std::vector<Size> &sizes, const std::vector<Point> &corners, std::vector<UMat> &masks) { LOGLN("Finding seams..."); if (sizes.size() == 0) return; #if ENABLE_LOG int64 t = getTickCount(); #endif sizes_ = sizes; corners_ = corners; masks_ = masks; run(); LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec"); } void VoronoiSeamFinder::findInPair(size_t first, size_t second, Rect roi) { const int gap = 10; Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Size img1 = sizes_[first], img2 = sizes_[second]; Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW); Point tl1 = corners_[first], tl2 = corners_[second]; // Cut submasks with some gap for (int y = -gap; y < roi.height + gap; ++y) { for (int x = -gap; x < roi.width + gap; ++x) { int y1 = roi.y - tl1.y + y; int x1 = roi.x - tl1.x + x; if (y1 >= 0 && x1 >= 0 && y1 < img1.height && x1 < img1.width) submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1); else submask1.at<uchar>(y + gap, x + gap) = 0; int y2 = roi.y - tl2.y + y; int x2 = roi.x - tl2.x + x; if (y2 >= 0 && x2 >= 0 && y2 < img2.height && x2 < img2.width) submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2); else submask2.at<uchar>(y + gap, x + gap) = 0; } } Mat collision = (submask1 != 0) & (submask2 != 0); Mat unique1 = submask1.clone(); unique1.setTo(0, collision); Mat unique2 = submask2.clone(); unique2.setTo(0, collision); Mat dist1, dist2; distanceTransform(unique1 == 0, dist1, DIST_L1, 3); distanceTransform(unique2 == 0, dist2, DIST_L1, 3); Mat seam = dist1 < dist2; for (int y = 0; y < roi.height; ++y) { for (int x = 0; x < roi.width; ++x) { if (seam.at<uchar>(y + gap, x + gap)) mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0; else mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0; } } } DpSeamFinder::DpSeamFinder(CostFunction costFunc) : costFunc_(costFunc), ncomps_(0) {} void DpSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { LOGLN("Finding seams..."); #if ENABLE_LOG int64 t = getTickCount(); #endif if (src.size() == 0) return; std::vector<std::pair<size_t, size_t> > pairs; for (size_t i = 0; i+1 < src.size(); ++i) for (size_t j = i+1; j < src.size(); ++j) pairs.push_back(std::make_pair(i, j)); { std::vector<Mat> _src(src.size()); for (size_t i = 0; i < src.size(); ++i) _src[i] = src[i].getMat(ACCESS_READ); sort(pairs.begin(), pairs.end(), ImagePairLess(_src, corners)); } std::reverse(pairs.begin(), pairs.end()); for (size_t i = 0; i < pairs.size(); ++i) { size_t i0 = pairs[i].first, i1 = pairs[i].second; Mat mask0 = masks[i0].getMat(ACCESS_RW), mask1 = masks[i1].getMat(ACCESS_RW); process(src[i0].getMat(ACCESS_READ), src[i1].getMat(ACCESS_READ), corners[i0], corners[i1], mask0, mask1); } LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec"); } void DpSeamFinder::process( const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2) { CV_INSTRUMENT_REGION(); CV_Assert(image1.size() == mask1.size()); CV_Assert(image2.size() == mask2.size()); Point intersectTl(std::max(tl1.x, tl2.x), std::max(tl1.y, tl2.y)); Point intersectBr(std::min(tl1.x + image1.cols, tl2.x + image2.cols), std::min(tl1.y + image1.rows, tl2.y + image2.rows)); if (intersectTl.x >= intersectBr.x || intersectTl.y >= intersectBr.y) return; // there are no conflicts unionTl_ = Point(std::min(tl1.x, tl2.x), std::min(tl1.y, tl2.y)); unionBr_ = Point(std::max(tl1.x + image1.cols, tl2.x + image2.cols), std::max(tl1.y + image1.rows, tl2.y + image2.rows)); unionSize_ = Size(unionBr_.x - unionTl_.x, unionBr_.y - unionTl_.y); mask1_ = Mat::zeros(unionSize_, CV_8U); mask2_ = Mat::zeros(unionSize_, CV_8U); Mat tmp = mask1_(Rect(tl1.x - unionTl_.x, tl1.y - unionTl_.y, mask1.cols, mask1.rows)); mask1.copyTo(tmp); tmp = mask2_(Rect(tl2.x - unionTl_.x, tl2.y - unionTl_.y, mask2.cols, mask2.rows)); mask2.copyTo(tmp); // find both images contour masks contour1mask_ = Mat::zeros(unionSize_, CV_8U); contour2mask_ = Mat::zeros(unionSize_, CV_8U); for (int y = 0; y < unionSize_.height; ++y) { for (int x = 0; x < unionSize_.width; ++x) { if (mask1_(y, x) && ((x == 0 || !mask1_(y, x-1)) || (x == unionSize_.width-1 || !mask1_(y, x+1)) || (y == 0 || !mask1_(y-1, x)) || (y == unionSize_.height-1 || !mask1_(y+1, x)))) { contour1mask_(y, x) = 255; } if (mask2_(y, x) && ((x == 0 || !mask2_(y, x-1)) || (x == unionSize_.width-1 || !mask2_(y, x+1)) || (y == 0 || !mask2_(y-1, x)) || (y == unionSize_.height-1 || !mask2_(y+1, x)))) { contour2mask_(y, x) = 255; } } } findComponents(); findEdges(); resolveConflicts(image1, image2, tl1, tl2, mask1, mask2); } void DpSeamFinder::findComponents() { // label all connected components and get information about them ncomps_ = 0; labels_.create(unionSize_); states_.clear(); tls_.clear(); brs_.clear(); contours_.clear(); for (int y = 0; y < unionSize_.height; ++y) { for (int x = 0; x < unionSize_.width; ++x) { if (mask1_(y, x) && mask2_(y, x)) labels_(y, x) = std::numeric_limits<int>::max(); else if (mask1_(y, x)) labels_(y, x) = std::numeric_limits<int>::max()-1; else if (mask2_(y, x)) labels_(y, x) = std::numeric_limits<int>::max()-2; else labels_(y, x) = 0; } } for (int y = 0; y < unionSize_.height; ++y) { for (int x = 0; x < unionSize_.width; ++x) { if (labels_(y, x) >= std::numeric_limits<int>::max()-2) { if (labels_(y, x) == std::numeric_limits<int>::max()) states_.push_back(INTERS); else if (labels_(y, x) == std::numeric_limits<int>::max()-1) states_.push_back(FIRST); else if (labels_(y, x) == std::numeric_limits<int>::max()-2) states_.push_back(SECOND); floodFill(labels_, Point(x, y), ++ncomps_); tls_.push_back(Point(x, y)); brs_.push_back(Point(x+1, y+1)); contours_.push_back(std::vector<Point>()); } if (labels_(y, x)) { int l = labels_(y, x); int ci = l-1; tls_[ci].x = std::min(tls_[ci].x, x); tls_[ci].y = std::min(tls_[ci].y, y); brs_[ci].x = std::max(brs_[ci].x, x+1); brs_[ci].y = std::max(brs_[ci].y, y+1); if ((x == 0 || labels_(y, x-1) != l) || (x == unionSize_.width-1 || labels_(y, x+1) != l) || (y == 0 || labels_(y-1, x) != l) || (y == unionSize_.height-1 || labels_(y+1, x) != l)) { contours_[ci].push_back(Point(x, y)); } } } } } void DpSeamFinder::findEdges() { // find edges between components std::map<std::pair<int, int>, int> wedges; // weighted edges for (int ci = 0; ci < ncomps_-1; ++ci) { for (int cj = ci+1; cj < ncomps_; ++cj) { wedges[std::make_pair(ci, cj)] = 0; wedges[std::make_pair(cj, ci)] = 0; } } for (int ci = 0; ci < ncomps_; ++ci) { for (size_t i = 0; i < contours_[ci].size(); ++i) { int x = contours_[ci][i].x; int y = contours_[ci][i].y; int l = ci + 1; if (x > 0 && labels_(y, x-1) && labels_(y, x-1) != l) { wedges[std::make_pair(ci, labels_(y, x-1)-1)]++; wedges[std::make_pair(labels_(y, x-1)-1, ci)]++; } if (y > 0 && labels_(y-1, x) && labels_(y-1, x) != l) { wedges[std::make_pair(ci, labels_(y-1, x)-1)]++; wedges[std::make_pair(labels_(y-1, x)-1, ci)]++; } if (x < unionSize_.width-1 && labels_(y, x+1) && labels_(y, x+1) != l) { wedges[std::make_pair(ci, labels_(y, x+1)-1)]++; wedges[std::make_pair(labels_(y, x+1)-1, ci)]++; } if (y < unionSize_.height-1 && labels_(y+1, x) && labels_(y+1, x) != l) { wedges[std::make_pair(ci, labels_(y+1, x)-1)]++; wedges[std::make_pair(labels_(y+1, x)-1, ci)]++; } } } edges_.clear(); for (int ci = 0; ci < ncomps_-1; ++ci) { for (int cj = ci+1; cj < ncomps_; ++cj) { std::map<std::pair<int, int>, int>::iterator itr = wedges.find(std::make_pair(ci, cj)); if (itr != wedges.end() && itr->second > 0) edges_.insert(itr->first); itr = wedges.find(std::make_pair(cj, ci)); if (itr != wedges.end() && itr->second > 0) edges_.insert(itr->first); } } } void DpSeamFinder::resolveConflicts( const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2) { if (costFunc_ == COLOR_GRAD) computeGradients(image1, image2); // resolve conflicts between components bool hasConflict = true; while (hasConflict) { int c1 = 0, c2 = 0; hasConflict = false; for (std::set<std::pair<int, int> >::iterator itr = edges_.begin(); itr != edges_.end(); ++itr) { c1 = itr->first; c2 = itr->second; if ((states_[c1] & INTERS) && (states_[c1] & (~INTERS)) != states_[c2]) { hasConflict = true; break; } } if (hasConflict) { int l1 = c1+1, l2 = c2+1; if (hasOnlyOneNeighbor(c1)) { // if the first components has only one adjacent component for (int y = tls_[c1].y; y < brs_[c1].y; ++y) for (int x = tls_[c1].x; x < brs_[c1].x; ++x) if (labels_(y, x) == l1) labels_(y, x) = l2; states_[c1] = states_[c2] == FIRST ? SECOND : FIRST; } else { // if the first component has more than one adjacent component Point p1, p2; if (getSeamTips(c1, c2, p1, p2)) { std::vector<Point> seam; bool isHorizontalSeam; if (estimateSeam(image1, image2, tl1, tl2, c1, p1, p2, seam, isHorizontalSeam)) updateLabelsUsingSeam(c1, c2, seam, isHorizontalSeam); } states_[c1] = states_[c2] == FIRST ? INTERS_SECOND : INTERS_FIRST; } const int c[] = {c1, c2}; const int l[] = {l1, l2}; for (int i = 0; i < 2; ++i) { // update information about the (i+1)-th component int x0 = tls_[c[i]].x, x1 = brs_[c[i]].x; int y0 = tls_[c[i]].y, y1 = brs_[c[i]].y; tls_[c[i]] = Point(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()); brs_[c[i]] = Point(std::numeric_limits<int>::min(), std::numeric_limits<int>::min()); contours_[c[i]].clear(); for (int y = y0; y < y1; ++y) { for (int x = x0; x < x1; ++x) { if (labels_(y, x) == l[i]) { tls_[c[i]].x = std::min(tls_[c[i]].x, x); tls_[c[i]].y = std::min(tls_[c[i]].y, y); brs_[c[i]].x = std::max(brs_[c[i]].x, x+1); brs_[c[i]].y = std::max(brs_[c[i]].y, y+1); if ((x == 0 || labels_(y, x-1) != l[i]) || (x == unionSize_.width-1 || labels_(y, x+1) != l[i]) || (y == 0 || labels_(y-1, x) != l[i]) || (y == unionSize_.height-1 || labels_(y+1, x) != l[i])) { contours_[c[i]].push_back(Point(x, y)); } } } } } // remove edges edges_.erase(std::make_pair(c1, c2)); edges_.erase(std::make_pair(c2, c1)); } } // update masks int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y; int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y; for (int y = 0; y < mask2.rows; ++y) { for (int x = 0; x < mask2.cols; ++x) { int l = labels_(y - dy2, x - dx2); if (l > 0 && (states_[l-1] & FIRST) && mask1.at<uchar>(y - dy2 + dy1, x - dx2 + dx1)) mask2.at<uchar>(y, x) = 0; } } for (int y = 0; y < mask1.rows; ++y) { for (int x = 0; x < mask1.cols; ++x) { int l = labels_(y - dy1, x - dx1); if (l > 0 && (states_[l-1] & SECOND) && mask2.at<uchar>(y - dy1 + dy2, x - dx1 + dx2)) mask1.at<uchar>(y, x) = 0; } } } void DpSeamFinder::computeGradients(const Mat &image1, const Mat &image2) { CV_Assert(image1.channels() == 3 || image1.channels() == 4); CV_Assert(image2.channels() == 3 || image2.channels() == 4); CV_Assert(costFunction() == COLOR_GRAD); Mat gray; if (image1.channels() == 3) cvtColor(image1, gray, COLOR_BGR2GRAY); else if (image1.channels() == 4) cvtColor(image1, gray, COLOR_BGRA2GRAY); Sobel(gray, gradx1_, CV_32F, 1, 0); Sobel(gray, grady1_, CV_32F, 0, 1); if (image2.channels() == 3) cvtColor(image2, gray, COLOR_BGR2GRAY); else if (image2.channels() == 4) cvtColor(image2, gray, COLOR_BGRA2GRAY); Sobel(gray, gradx2_, CV_32F, 1, 0); Sobel(gray, grady2_, CV_32F, 0, 1); } bool DpSeamFinder::hasOnlyOneNeighbor(int comp) { std::set<std::pair<int, int> >::iterator begin, end; begin = lower_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::min())); end = upper_bound(edges_.begin(), edges_.end(), std::make_pair(comp, std::numeric_limits<int>::max())); return ++begin == end; } bool DpSeamFinder::closeToContour(int y, int x, const Mat_<uchar> &contourMask) { const int rad = 2; for (int dy = -rad; dy <= rad; ++dy) { if (y + dy >= 0 && y + dy < unionSize_.height) { for (int dx = -rad; dx <= rad; ++dx) { if (x + dx >= 0 && x + dx < unionSize_.width && contourMask(y + dy, x + dx)) { return true; } } } } return false; } bool DpSeamFinder::getSeamTips(int comp1, int comp2, Point &p1, Point &p2) { CV_Assert(states_[comp1] & INTERS); // find special points std::vector<Point> specialPoints; int l2 = comp2+1; for (size_t i = 0; i < contours_[comp1].size(); ++i) { int x = contours_[comp1][i].x; int y = contours_[comp1][i].y; if (closeToContour(y, x, contour1mask_) && closeToContour(y, x, contour2mask_) && ((x > 0 && labels_(y, x-1) == l2) || (y > 0 && labels_(y-1, x) == l2) || (x < unionSize_.width-1 && labels_(y, x+1) == l2) || (y < unionSize_.height-1 && labels_(y+1, x) == l2))) { specialPoints.push_back(Point(x, y)); } } if (specialPoints.size() < 2) return false; // find clusters std::vector<int> labels; cv::partition(specialPoints, labels, ClosePoints(10)); int nlabels = *std::max_element(labels.begin(), labels.end()) + 1; if (nlabels < 2) return false; std::vector<Point> sum(nlabels); std::vector<std::vector<Point> > points(nlabels); for (size_t i = 0; i < specialPoints.size(); ++i) { sum[labels[i]] += specialPoints[i]; points[labels[i]].push_back(specialPoints[i]); } // select two most distant clusters int idx[2] = {-1,-1}; double maxDist = -std::numeric_limits<double>::max(); for (int i = 0; i < nlabels-1; ++i) { for (int j = i+1; j < nlabels; ++j) { double size1 = static_cast<double>(points[i].size()), size2 = static_cast<double>(points[j].size()); double cx1 = cvRound(sum[i].x / size1), cy1 = cvRound(sum[i].y / size1); double cx2 = cvRound(sum[j].x / size2), cy2 = cvRound(sum[j].y / size2); double dist = (cx1 - cx2) * (cx1 - cx2) + (cy1 - cy2) * (cy1 - cy2); if (dist > maxDist) { maxDist = dist; idx[0] = i; idx[1] = j; } } } // select two points closest to the clusters' centers Point p[2]; for (int i = 0; i < 2; ++i) { double size = static_cast<double>(points[idx[i]].size()); double cx = cvRound(sum[idx[i]].x / size); double cy = cvRound(sum[idx[i]].y / size); size_t closest = points[idx[i]].size(); double minDist = std::numeric_limits<double>::max(); for (size_t j = 0; j < points[idx[i]].size(); ++j) { double dist = (points[idx[i]][j].x - cx) * (points[idx[i]][j].x - cx) + (points[idx[i]][j].y - cy) * (points[idx[i]][j].y - cy); if (dist < minDist) { minDist = dist; closest = j; } } p[i] = points[idx[i]][closest]; } p1 = p[0]; p2 = p[1]; return true; } namespace { template <typename T> float diffL2Square3(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2) { const T *r1 = image1.ptr<T>(y1); const T *r2 = image2.ptr<T>(y2); return static_cast<float>(sqr(r1[3*x1] - r2[3*x2]) + sqr(r1[3*x1+1] - r2[3*x2+1]) + sqr(r1[3*x1+2] - r2[3*x2+2])); } template <typename T> float diffL2Square4(const Mat &image1, int y1, int x1, const Mat &image2, int y2, int x2) { const T *r1 = image1.ptr<T>(y1); const T *r2 = image2.ptr<T>(y2); return static_cast<float>(sqr(r1[4*x1] - r2[4*x2]) + sqr(r1[4*x1+1] - r2[4*x2+1]) + sqr(r1[4*x1+2] - r2[4*x2+2])); } } // namespace void DpSeamFinder::computeCosts( const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, Mat_<float> &costV, Mat_<float> &costH) { CV_Assert(states_[comp] & INTERS); // compute costs float (*diff)(const Mat&, int, int, const Mat&, int, int) = 0; if (image1.type() == CV_32FC3 && image2.type() == CV_32FC3) diff = diffL2Square3<float>; else if (image1.type() == CV_8UC3 && image2.type() == CV_8UC3) diff = diffL2Square3<uchar>; else if (image1.type() == CV_32FC4 && image2.type() == CV_32FC4) diff = diffL2Square4<float>; else if (image1.type() == CV_8UC4 && image2.type() == CV_8UC4) diff = diffL2Square4<uchar>; else CV_Error(Error::StsBadArg, "both images must have CV_32FC3(4) or CV_8UC3(4) type"); int l = comp+1; Rect roi(tls_[comp], brs_[comp]); int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y; int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y; const float badRegionCost = normL2(Point3f(255.f, 255.f, 255.f), Point3f(0.f, 0.f, 0.f)); costV.create(roi.height, roi.width+1); for (int y = roi.y; y < roi.br().y; ++y) { for (int x = roi.x; x < roi.br().x+1; ++x) { if (x > 0 && x < labels_.cols && labels_(y, x) == l && labels_(y, x-1) == l ) { float costColor = (diff(image1, y + dy1, x + dx1 - 1, image2, y + dy2, x + dx2) + diff(image1, y + dy1, x + dx1, image2, y + dy2, x + dx2 - 1)) / 2; if (costFunc_ == COLOR) costV(y - roi.y, x - roi.x) = costColor; else if (costFunc_ == COLOR_GRAD) { float costGrad = std::abs(gradx1_(y + dy1, x + dx1)) + std::abs(gradx1_(y + dy1, x + dx1 - 1)) + std::abs(gradx2_(y + dy2, x + dx2)) + std::abs(gradx2_(y + dy2, x + dx2 - 1)) + 1.f; costV(y - roi.y, x - roi.x) = costColor / costGrad; } } else costV(y - roi.y, x - roi.x) = badRegionCost; } } costH.create(roi.height+1, roi.width); for (int y = roi.y; y < roi.br().y+1; ++y) { for (int x = roi.x; x < roi.br().x; ++x) { if (y > 0 && y < labels_.rows && labels_(y, x) == l && labels_(y-1, x) == l ) { float costColor = (diff(image1, y + dy1 - 1, x + dx1, image2, y + dy2, x + dx2) + diff(image1, y + dy1, x + dx1, image2, y + dy2 - 1, x + dx2)) / 2; if (costFunc_ == COLOR) costH(y - roi.y, x - roi.x) = costColor; else if (costFunc_ == COLOR_GRAD) { float costGrad = std::abs(grady1_(y + dy1, x + dx1)) + std::abs(grady1_(y + dy1 - 1, x + dx1)) + std::abs(grady2_(y + dy2, x + dx2)) + std::abs(grady2_(y + dy2 - 1, x + dx2)) + 1.f; costH(y - roi.y, x - roi.x) = costColor / costGrad; } } else costH(y - roi.y, x - roi.x) = badRegionCost; } } } bool DpSeamFinder::estimateSeam( const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, Point p1, Point p2, std::vector<Point> &seam, bool &isHorizontal) { CV_Assert(states_[comp] & INTERS); Mat_<float> costV, costH; computeCosts(image1, image2, tl1, tl2, comp, costV, costH); Rect roi(tls_[comp], brs_[comp]); Point src = p1 - roi.tl(); Point dst = p2 - roi.tl(); int l = comp+1; // estimate seam direction bool swapped = false; isHorizontal = std::abs(dst.x - src.x) > std::abs(dst.y - src.y); if (isHorizontal) { if (src.x > dst.x) { std::swap(src, dst); swapped = true; } } else if (src.y > dst.y) { swapped = true; std::swap(src, dst); } // find optimal control Mat_<uchar> control = Mat::zeros(roi.size(), CV_8U); Mat_<uchar> reachable = Mat::zeros(roi.size(), CV_8U); Mat_<float> cost = Mat::zeros(roi.size(), CV_32F); reachable(src) = 1; cost(src) = 0.f; int nsteps; std::pair<float, int> steps[3]; if (isHorizontal) { for (int x = src.x+1; x <= dst.x; ++x) { for (int y = 0; y < roi.height; ++y) { // seam follows along upper side of pixels nsteps = 0; if (labels_(y + roi.y, x + roi.x) == l) { if (reachable(y, x-1)) steps[nsteps++] = std::make_pair(cost(y, x-1) + costH(y, x-1), 1); if (y > 0 && reachable(y-1, x-1)) steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costH(y-1, x-1) + costV(y-1, x), 2); if (y < roi.height-1 && reachable(y+1, x-1)) steps[nsteps++] = std::make_pair(cost(y+1, x-1) + costH(y+1, x-1) + costV(y, x), 3); } if (nsteps) { std::pair<float, int> opt = *min_element(steps, steps + nsteps); cost(y, x) = opt.first; control(y, x) = (uchar)opt.second; reachable(y, x) = 255; } } } } else { for (int y = src.y+1; y <= dst.y; ++y) { for (int x = 0; x < roi.width; ++x) { // seam follows along left side of pixels nsteps = 0; if (labels_(y + roi.y, x + roi.x) == l) { if (reachable(y-1, x)) steps[nsteps++] = std::make_pair(cost(y-1, x) + costV(y-1, x), 1); if (x > 0 && reachable(y-1, x-1)) steps[nsteps++] = std::make_pair(cost(y-1, x-1) + costV(y-1, x-1) + costH(y, x-1), 2); if (x < roi.width-1 && reachable(y-1, x+1)) steps[nsteps++] = std::make_pair(cost(y-1, x+1) + costV(y-1, x+1) + costH(y, x), 3); } if (nsteps) { std::pair<float, int> opt = *min_element(steps, steps + nsteps); cost(y, x) = opt.first; control(y, x) = (uchar)opt.second; reachable(y, x) = 255; } } } } if (!reachable(dst)) return false; // restore seam Point p = dst; seam.clear(); seam.push_back(p + roi.tl()); if (isHorizontal) { for (; p.x != src.x; seam.push_back(p + roi.tl())) { if (control(p) == 2) p.y--; else if (control(p) == 3) p.y++; p.x--; } } else { for (; p.y != src.y; seam.push_back(p + roi.tl())) { if (control(p) == 2) p.x--; else if (control(p) == 3) p.x++; p.y--; } } if (!swapped) std::reverse(seam.begin(), seam.end()); CV_Assert(seam.front() == p1); CV_Assert(seam.back() == p2); return true; } void DpSeamFinder::updateLabelsUsingSeam( int comp1, int comp2, const std::vector<Point> &seam, bool isHorizontalSeam) { Mat_<int> mask = Mat::zeros(brs_[comp1].y - tls_[comp1].y, brs_[comp1].x - tls_[comp1].x, CV_32S); for (size_t i = 0; i < contours_[comp1].size(); ++i) mask(contours_[comp1][i] - tls_[comp1]) = 255; for (size_t i = 0; i < seam.size(); ++i) mask(seam[i] - tls_[comp1]) = 255; // find connected components after seam carving int l1 = comp1+1, l2 = comp2+1; int ncomps = 0; for (int y = 0; y < mask.rows; ++y) for (int x = 0; x < mask.cols; ++x) if (!mask(y, x) && labels_(y + tls_[comp1].y, x + tls_[comp1].x) == l1) floodFill(mask, Point(x, y), ++ncomps); for (size_t i = 0; i < contours_[comp1].size(); ++i) { int x = contours_[comp1][i].x - tls_[comp1].x; int y = contours_[comp1][i].y - tls_[comp1].y; bool ok = false; static const int dx[] = {-1, +1, 0, 0, -1, +1, -1, +1}; static const int dy[] = {0, 0, -1, +1, -1, -1, +1, +1}; for (int j = 0; j < 8; ++j) { int c = x + dx[j]; int r = y + dy[j]; if (c >= 0 && c < mask.cols && r >= 0 && r < mask.rows && mask(r, c) && mask(r, c) != 255) { ok = true; mask(y, x) = mask(r, c); } } if (!ok) mask(y, x) = 0; } if (isHorizontalSeam) { for (size_t i = 0; i < seam.size(); ++i) { int x = seam[i].x - tls_[comp1].x; int y = seam[i].y - tls_[comp1].y; if (y < mask.rows-1 && mask(y+1, x) && mask(y+1, x) != 255) mask(y, x) = mask(y+1, x); else mask(y, x) = 0; } } else { for (size_t i = 0; i < seam.size(); ++i) { int x = seam[i].x - tls_[comp1].x; int y = seam[i].y - tls_[comp1].y; if (x < mask.cols-1 && mask(y, x+1) && mask(y, x+1) != 255) mask(y, x) = mask(y, x+1); else mask(y, x) = 0; } } // find new components connected with the second component and // with other components except the ones we are working with std::map<int, int> connect2; std::map<int, int> connectOther; for (int i = 1; i <= ncomps; ++i) { connect2.insert(std::make_pair(i, 0)); connectOther.insert(std::make_pair(i, 0)); } for (size_t i = 0; i < contours_[comp1].size(); ++i) { int x = contours_[comp1][i].x; int y = contours_[comp1][i].y; if ((x > 0 && labels_(y, x-1) == l2) || (y > 0 && labels_(y-1, x) == l2) || (x < unionSize_.width-1 && labels_(y, x+1) == l2) || (y < unionSize_.height-1 && labels_(y+1, x) == l2)) { connect2[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++; } if ((x > 0 && labels_(y, x-1) != l1 && labels_(y, x-1) != l2) || (y > 0 && labels_(y-1, x) != l1 && labels_(y-1, x) != l2) || (x < unionSize_.width-1 && labels_(y, x+1) != l1 && labels_(y, x+1) != l2) || (y < unionSize_.height-1 && labels_(y+1, x) != l1 && labels_(y+1, x) != l2)) { connectOther[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++; } } std::vector<int> isAdjComp(ncomps + 1, 0); for (std::map<int, int>::iterator itr = connect2.begin(); itr != connect2.end(); ++itr) { double len = static_cast<double>(contours_[comp1].size()); int res = 0; if (itr->second / len > 0.05) { std::map<int, int>::const_iterator sub = connectOther.find(itr->first); if (sub != connectOther.end() && (sub->second / len < 0.1)) { res = 1; } } isAdjComp[itr->first] = res; } // update labels for (int y = 0; y < mask.rows; ++y) for (int x = 0; x < mask.cols; ++x) if (mask(y, x) && isAdjComp[mask(y, x)]) labels_(y + tls_[comp1].y, x + tls_[comp1].x) = l2; } class GraphCutSeamFinder::Impl CV_FINAL : public PairwiseSeamFinder { public: Impl(int cost_type, float terminal_cost, float bad_region_penalty) : cost_type_(cost_type), terminal_cost_(terminal_cost), bad_region_penalty_(bad_region_penalty) {} ~Impl() {} void find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) CV_OVERRIDE; void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; private: void setGraphWeightsColor(const Mat &img1, const Mat &img2, const Mat &mask1, const Mat &mask2, GCGraph<float> &graph); void setGraphWeightsColorGrad(const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2, const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2, GCGraph<float> &graph); std::vector<Mat> dx_, dy_; int cost_type_; float terminal_cost_; float bad_region_penalty_; }; void GraphCutSeamFinder::Impl::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { // Compute gradients dx_.resize(src.size()); dy_.resize(src.size()); Mat dx, dy; for (size_t i = 0; i < src.size(); ++i) { CV_Assert(src[i].channels() == 3); Sobel(src[i], dx, CV_32F, 1, 0); Sobel(src[i], dy, CV_32F, 0, 1); dx_[i].create(src[i].size(), CV_32F); dy_[i].create(src[i].size(), CV_32F); for (int y = 0; y < src[i].rows; ++y) { const Point3f* dx_row = dx.ptr<Point3f>(y); const Point3f* dy_row = dy.ptr<Point3f>(y); float* dx_row_ = dx_[i].ptr<float>(y); float* dy_row_ = dy_[i].ptr<float>(y); for (int x = 0; x < src[i].cols; ++x) { dx_row_[x] = normL2(dx_row[x]); dy_row_[x] = normL2(dy_row[x]); } } } PairwiseSeamFinder::find(src, corners, masks); } void GraphCutSeamFinder::Impl::setGraphWeightsColor(const Mat &img1, const Mat &img2, const Mat &mask1, const Mat &mask2, GCGraph<float> &graph) { const Size img_size = img1.size(); // Set terminal weights for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { int v = graph.addVtx(); graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f, mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f); } } // Set regular edge weights const float weight_eps = 1.f; for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { int v = y * img_size.width + x; if (x < img_size.width - 1) { float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1)) weight += bad_region_penalty_; graph.addEdges(v, v + 1, weight, weight); } if (y < img_size.height - 1) { float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x)) weight += bad_region_penalty_; graph.addEdges(v, v + img_size.width, weight, weight); } } } } void GraphCutSeamFinder::Impl::setGraphWeightsColorGrad( const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2, const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2, GCGraph<float> &graph) { const Size img_size = img1.size(); // Set terminal weights for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { int v = graph.addVtx(); graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f, mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f); } } // Set regular edge weights const float weight_eps = 1.f; for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { int v = y * img_size.width + x; if (x < img_size.width - 1) { float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) + dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps; float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1)) weight += bad_region_penalty_; graph.addEdges(v, v + 1, weight, weight); } if (y < img_size.height - 1) { float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) + dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps; float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x)) weight += bad_region_penalty_; graph.addEdges(v, v + img_size.width, weight, weight); } } } } void GraphCutSeamFinder::Impl::findInPair(size_t first, size_t second, Rect roi) { Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ); Mat dx1 = dx_[first], dx2 = dx_[second]; Mat dy1 = dy_[first], dy2 = dy_[second]; Mat mask1 = masks_[first].getMat(ACCESS_RW), mask2 = masks_[second].getMat(ACCESS_RW); Point tl1 = corners_[first], tl2 = corners_[second]; const int gap = 10; Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3); Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3); Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); // Cut subimages and submasks with some gap for (int y = -gap; y < roi.height + gap; ++y) { for (int x = -gap; x < roi.width + gap; ++x) { int y1 = roi.y - tl1.y + y; int x1 = roi.x - tl1.x + x; if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols) { subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1); submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1); subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1); subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1); } else { subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0); submask1.at<uchar>(y + gap, x + gap) = 0; subdx1.at<float>(y + gap, x + gap) = 0.f; subdy1.at<float>(y + gap, x + gap) = 0.f; } int y2 = roi.y - tl2.y + y; int x2 = roi.x - tl2.x + x; if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols) { subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2); submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2); subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2); subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2); } else { subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0); submask2.at<uchar>(y + gap, x + gap) = 0; subdx2.at<float>(y + gap, x + gap) = 0.f; subdy2.at<float>(y + gap, x + gap) = 0.f; } } } const int vertex_count = (roi.height + 2 * gap) * (roi.width + 2 * gap); const int edge_count = (roi.height - 1 + 2 * gap) * (roi.width + 2 * gap) + (roi.width - 1 + 2 * gap) * (roi.height + 2 * gap); GCGraph<float> graph(vertex_count, edge_count); switch (cost_type_) { case GraphCutSeamFinder::COST_COLOR: setGraphWeightsColor(subimg1, subimg2, submask1, submask2, graph); break; case GraphCutSeamFinder::COST_COLOR_GRAD: setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2, submask1, submask2, graph); break; default: CV_Error(Error::StsBadArg, "unsupported pixel similarity measure"); } graph.maxFlow(); for (int y = 0; y < roi.height; ++y) { for (int x = 0; x < roi.width; ++x) { if (graph.inSourceSegment((y + gap) * (roi.width + 2 * gap) + x + gap)) { if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x)) mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0; } else { if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x)) mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0; } } } } GraphCutSeamFinder::GraphCutSeamFinder(int cost_type, float terminal_cost, float bad_region_penalty) : impl_(new Impl(cost_type, terminal_cost, bad_region_penalty)) {} GraphCutSeamFinder::~GraphCutSeamFinder() {} void GraphCutSeamFinder::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { impl_->find(src, corners, masks); } #ifdef HAVE_OPENCV_CUDALEGACY void GraphCutSeamFinderGpu::find(const std::vector<UMat> &src, const std::vector<Point> &corners, std::vector<UMat> &masks) { // Compute gradients dx_.resize(src.size()); dy_.resize(src.size()); Mat dx, dy; for (size_t i = 0; i < src.size(); ++i) { CV_Assert(src[i].channels() == 3); Sobel(src[i], dx, CV_32F, 1, 0); Sobel(src[i], dy, CV_32F, 0, 1); dx_[i].create(src[i].size(), CV_32F); dy_[i].create(src[i].size(), CV_32F); for (int y = 0; y < src[i].rows; ++y) { const Point3f* dx_row = dx.ptr<Point3f>(y); const Point3f* dy_row = dy.ptr<Point3f>(y); float* dx_row_ = dx_[i].ptr<float>(y); float* dy_row_ = dy_[i].ptr<float>(y); for (int x = 0; x < src[i].cols; ++x) { dx_row_[x] = normL2(dx_row[x]); dy_row_[x] = normL2(dy_row[x]); } } } PairwiseSeamFinder::find(src, corners, masks); } void GraphCutSeamFinderGpu::findInPair(size_t first, size_t second, Rect roi) { Mat img1 = images_[first].getMat(ACCESS_READ), img2 = images_[second].getMat(ACCESS_READ); Mat dx1 = dx_[first], dx2 = dx_[second]; Mat dy1 = dy_[first], dy2 = dy_[second]; Mat mask1 = masks_[first].getMat(ACCESS_READ), mask2 = masks_[second].getMat(ACCESS_READ); Point tl1 = corners_[first], tl2 = corners_[second]; const int gap = 10; Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3); Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3); Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U); Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F); // Cut subimages and submasks with some gap for (int y = -gap; y < roi.height + gap; ++y) { for (int x = -gap; x < roi.width + gap; ++x) { int y1 = roi.y - tl1.y + y; int x1 = roi.x - tl1.x + x; if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols) { subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1); submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1); subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1); subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1); } else { subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0); submask1.at<uchar>(y + gap, x + gap) = 0; subdx1.at<float>(y + gap, x + gap) = 0.f; subdy1.at<float>(y + gap, x + gap) = 0.f; } int y2 = roi.y - tl2.y + y; int x2 = roi.x - tl2.x + x; if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols) { subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2); submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2); subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2); subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2); } else { subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0); submask2.at<uchar>(y + gap, x + gap) = 0; subdx2.at<float>(y + gap, x + gap) = 0.f; subdy2.at<float>(y + gap, x + gap) = 0.f; } } } Mat terminals, leftT, rightT, top, bottom; switch (cost_type_) { case GraphCutSeamFinder::COST_COLOR: setGraphWeightsColor(subimg1, subimg2, submask1, submask2, terminals, leftT, rightT, top, bottom); break; case GraphCutSeamFinder::COST_COLOR_GRAD: setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2, submask1, submask2, terminals, leftT, rightT, top, bottom); break; default: CV_Error(Error::StsBadArg, "unsupported pixel similarity measure"); } cuda::GpuMat terminals_d(terminals); cuda::GpuMat leftT_d(leftT); cuda::GpuMat rightT_d(rightT); cuda::GpuMat top_d(top); cuda::GpuMat bottom_d(bottom); cuda::GpuMat labels_d, buf_d; cuda::graphcut(terminals_d, leftT_d, rightT_d, top_d, bottom_d, labels_d, buf_d); Mat_<uchar> labels = (Mat)labels_d; for (int y = 0; y < roi.height; ++y) { for (int x = 0; x < roi.width; ++x) { if (labels(y + gap, x + gap)) { if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x)) mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0; } else { if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x)) mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0; } } } } void GraphCutSeamFinderGpu::setGraphWeightsColor(const Mat &img1, const Mat &img2, const Mat &mask1, const Mat &mask2, Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom) { const Size img_size = img1.size(); terminals.create(img_size, CV_32S); leftT.create(Size(img_size.height, img_size.width), CV_32S); rightT.create(Size(img_size.height, img_size.width), CV_32S); top.create(img_size, CV_32S); bottom.create(img_size, CV_32S); Mat_<int> terminals_(terminals); Mat_<int> leftT_(leftT); Mat_<int> rightT_(rightT); Mat_<int> top_(top); Mat_<int> bottom_(bottom); // Set terminal weights for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f; float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f; terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f); } } // Set regular edge weights const float weight_eps = 1.f; for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { if (x > 0) { float weight = normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) + normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + weight_eps; if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) || !mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x)) weight += bad_region_penalty_; leftT_(x, y) = saturate_cast<int>(weight * 255.f); } else leftT_(x, y) = 0; if (x < img_size.width - 1) { float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1)) weight += bad_region_penalty_; rightT_(x, y) = saturate_cast<int>(weight * 255.f); } else rightT_(x, y) = 0; if (y > 0) { float weight = normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) + normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + weight_eps; if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) || !mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x)) weight += bad_region_penalty_; top_(y, x) = saturate_cast<int>(weight * 255.f); } else top_(y, x) = 0; if (y < img_size.height - 1) { float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x)) weight += bad_region_penalty_; bottom_(y, x) = saturate_cast<int>(weight * 255.f); } else bottom_(y, x) = 0; } } } void GraphCutSeamFinderGpu::setGraphWeightsColorGrad( const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2, const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2, Mat &terminals, Mat &leftT, Mat &rightT, Mat &top, Mat &bottom) { const Size img_size = img1.size(); terminals.create(img_size, CV_32S); leftT.create(Size(img_size.height, img_size.width), CV_32S); rightT.create(Size(img_size.height, img_size.width), CV_32S); top.create(img_size, CV_32S); bottom.create(img_size, CV_32S); Mat_<int> terminals_(terminals); Mat_<int> leftT_(leftT); Mat_<int> rightT_(rightT); Mat_<int> top_(top); Mat_<int> bottom_(bottom); // Set terminal weights for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { float source = mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f; float sink = mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f; terminals_(y, x) = saturate_cast<int>((source - sink) * 255.f); } } // Set regular edge weights const float weight_eps = 1.f; for (int y = 0; y < img_size.height; ++y) { for (int x = 0; x < img_size.width; ++x) { if (x > 0) { float grad = dx1.at<float>(y, x - 1) + dx1.at<float>(y, x) + dx2.at<float>(y, x - 1) + dx2.at<float>(y, x) + weight_eps; float weight = (normL2(img1.at<Point3f>(y, x - 1), img2.at<Point3f>(y, x - 1)) + normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad + weight_eps; if (!mask1.at<uchar>(y, x - 1) || !mask1.at<uchar>(y, x) || !mask2.at<uchar>(y, x - 1) || !mask2.at<uchar>(y, x)) weight += bad_region_penalty_; leftT_(x, y) = saturate_cast<int>(weight * 255.f); } else leftT_(x, y) = 0; if (x < img_size.width - 1) { float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) + dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps; float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1)) weight += bad_region_penalty_; rightT_(x, y) = saturate_cast<int>(weight * 255.f); } else rightT_(x, y) = 0; if (y > 0) { float grad = dy1.at<float>(y - 1, x) + dy1.at<float>(y, x) + dy2.at<float>(y - 1, x) + dy2.at<float>(y, x) + weight_eps; float weight = (normL2(img1.at<Point3f>(y - 1, x), img2.at<Point3f>(y - 1, x)) + normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x))) / grad + weight_eps; if (!mask1.at<uchar>(y - 1, x) || !mask1.at<uchar>(y, x) || !mask2.at<uchar>(y - 1, x) || !mask2.at<uchar>(y, x)) weight += bad_region_penalty_; top_(y, x) = saturate_cast<int>(weight * 255.f); } else top_(y, x) = 0; if (y < img_size.height - 1) { float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) + dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps; float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) + normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad + weight_eps; if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) || !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x)) weight += bad_region_penalty_; bottom_(y, x) = saturate_cast<int>(weight * 255.f); } else bottom_(y, x) = 0; } } } #endif } // namespace detail } // namespace cv
35.144737
126
0.483442
tweenietomatoes
c8a99adc065d10b803e763b42e31410ddc93690d
215
hpp
C++
common/CMemoryUssage.hpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
common/CMemoryUssage.hpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
common/CMemoryUssage.hpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
#pragma once class CMemoryUssage { public: static int processMemoryUssage(int& maxMemoryUssage); static int processMemoryUssage(); static int processMaxMemoryUssage(); CMemoryUssage() = delete; };
17.916667
57
0.734884
ymuv
c8aa6b9bfa743bd22740e8a0f234cbc09f59cd11
8,311
cpp
C++
source/MaterialXRenderGlsl/GLTextureHandler.cpp
nzanepro/MaterialX
9100ac81231d87f7fbf4dc32f7030867e466bc41
[ "BSD-3-Clause" ]
null
null
null
source/MaterialXRenderGlsl/GLTextureHandler.cpp
nzanepro/MaterialX
9100ac81231d87f7fbf4dc32f7030867e466bc41
[ "BSD-3-Clause" ]
null
null
null
source/MaterialXRenderGlsl/GLTextureHandler.cpp
nzanepro/MaterialX
9100ac81231d87f7fbf4dc32f7030867e466bc41
[ "BSD-3-Clause" ]
null
null
null
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXRenderGlsl/GLTextureHandler.h> #include <MaterialXRenderGlsl/GlslProgram.h> #include <MaterialXRenderGlsl/External/GLew/glew.h> #include <MaterialXRender/ShaderRenderer.h> namespace MaterialX { GLTextureHandler::GLTextureHandler(ImageLoaderPtr imageLoader) : ImageHandler(imageLoader), _maxImageUnits(-1) { } ImagePtr GLTextureHandler::acquireImage(const FilePath& filePath, bool generateMipMaps, const Color4* fallbackColor, string* message) { // Resolve the input filepath. FilePath resolvedFilePath = filePath; if (_resolver) { resolvedFilePath = _resolver->resolve(resolvedFilePath, FILENAME_TYPE_STRING); } // Return a cached image if available. ImagePtr cachedDesc = getCachedImage(resolvedFilePath); if (cachedDesc) { return cachedDesc; } // Call the base acquire method. ImagePtr image = ImageHandler::acquireImage(resolvedFilePath, generateMipMaps, fallbackColor, message); if (!image) { return nullptr; } // Initialize OpenGL setup if needed. if (!glActiveTexture) { glewInit(); } if (_boundTextureLocations.empty()) { int maxTextureUnits; glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits); if (maxTextureUnits <= 0) { StringVec errors; errors.push_back("No texture units available"); throw ExceptionShaderRenderError("OpenGL context error.", errors); } _boundTextureLocations.resize(maxTextureUnits, MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID); } unsigned int resourceId = MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &resourceId); image->setResourceId(resourceId); int textureUnit = getNextAvailableTextureLocation(); if (textureUnit < 0) { return nullptr; } glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, image->getResourceId()); GLint internalFormat = GL_RGBA; GLenum type = GL_UNSIGNED_BYTE; if (image->getBaseType() == Image::BaseType::FLOAT) { internalFormat = GL_RGBA32F; type = GL_FLOAT; } else if (image->getBaseType() == Image::BaseType::HALF) { internalFormat = GL_RGBA16F; type = GL_HALF_FLOAT; } GLint format = GL_RGBA; switch (image->getChannelCount()) { case 3: { format = GL_RGB; // Map {RGB} to {RGB, 1} at shader access time GLint swizzleMaskRGB[] = { GL_RED, GL_GREEN, GL_BLUE, GL_ONE }; glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMaskRGB); break; } case 2: { format = GL_RG; // Map {red, green} to {red, alpha} at shader access time GLint swizzleMaskRG[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMaskRG); break; } case 1: { format = GL_RED; // Map { red } to {red, green, blue, 1} at shader access time GLint swizzleMaskR[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMaskR); break; } default: break; } glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, image->getWidth(), image->getHeight(), 0, format, type, image->getResourceBuffer()); if (generateMipMaps) { glGenerateMipmap(GL_TEXTURE_2D); } glBindTexture(GL_TEXTURE_2D, 0); return image; } bool GLTextureHandler::bindImage(ConstImagePtr image, const ImageSamplingProperties& samplingProperties) { // Bind a texture to the next available slot if (_maxImageUnits < 0) { glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &_maxImageUnits); } if (image->getResourceId() == MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID || image->getResourceId() == static_cast<unsigned int>(_maxImageUnits)) { return false; } // Update bound location if not already bound int textureUnit = getBoundTextureLocation(image->getResourceId()); if (textureUnit < 0) { textureUnit = getNextAvailableTextureLocation(); } if (textureUnit < 0) { return false; } _boundTextureLocations[textureUnit] = image->getResourceId(); glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, image->getResourceId()); // Set up texture properties GLint minFilterType = mapFilterTypeToGL(samplingProperties.filterType); GLint magFilterType = GL_LINEAR; // Magnification filters are more restrictive than minification GLint uaddressMode = mapAddressModeToGL(samplingProperties.uaddressMode); GLint vaddressMode = mapAddressModeToGL(samplingProperties.vaddressMode); Color4 borderColor(samplingProperties.defaultColor); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, uaddressMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vaddressMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilterType); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilterType); return true; } bool GLTextureHandler::unbindImage(ConstImagePtr image) { if (!glActiveTexture) { glewInit(); } if (image->getResourceId() != MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID) { int textureUnit = getBoundTextureLocation(image->getResourceId()); if (textureUnit >= 0) { glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID); _boundTextureLocations[textureUnit] = MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID; return true; } } return false; } void GLTextureHandler::deleteImage(ImagePtr image) { if (!glActiveTexture) { glewInit(); } // Unbind a texture from image unit if bound and delete the texture if (image->getResourceId() != MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID) { unbindImage(image); unsigned int resourceId = image->getResourceId(); glDeleteTextures(1, &resourceId); image->setResourceId(MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID); } // Delete any CPU side memory ImageHandler::deleteImage(image); } int GLTextureHandler::getBoundTextureLocation(unsigned int resourceId) { for(size_t i=0; i<_boundTextureLocations.size(); i++) { if(_boundTextureLocations[i] == resourceId) { return static_cast<int>(i); } } return -1; } int GLTextureHandler::getNextAvailableTextureLocation() { for(size_t i=0; i<_boundTextureLocations.size(); i++) { if(_boundTextureLocations[i] == MaterialX::GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID) { return static_cast<int>(i); } } return -1; } int GLTextureHandler::mapAddressModeToGL(ImageSamplingProperties::AddressMode addressModeEnum) { const vector<int> addressModes { // Constant color. Use clamp to border // with border color to achieve this GL_CLAMP_TO_BORDER, // Clamp GL_CLAMP_TO_EDGE, // Repeat GL_REPEAT, // Mirror GL_MIRRORED_REPEAT }; int addressMode = GL_REPEAT; if (addressModeEnum != ImageSamplingProperties::AddressMode::UNSPECIFIED) { addressMode = addressModes[static_cast<int>(addressModeEnum)]; } return addressMode; } int GLTextureHandler::mapFilterTypeToGL(ImageSamplingProperties::FilterType filterTypeEnum) { int filterType = GL_LINEAR_MIPMAP_LINEAR; if (filterTypeEnum == ImageSamplingProperties::FilterType::CLOSEST) { filterType = GL_NEAREST_MIPMAP_NEAREST; } return filterType; } }
29.367491
109
0.670076
nzanepro
c8ab4ee2bf37e1b0e2331ffc0cf9cc101b6d5478
687
hh
C++
Validation/inc/ValStrawDigiADCWaveform.hh
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
Validation/inc/ValStrawDigiADCWaveform.hh
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
Validation/inc/ValStrawDigiADCWaveform.hh
NamithaChitrazee/Offline-1
bcb6c74954f95dd48433d79a69d3ef3bdb99022e
[ "Apache-2.0" ]
null
null
null
#ifndef ValStrawDigiADCWaveform_HH_ #define ValStrawDigiADCWaveform_HH_ #include "Offline/RecoDataProducts/inc/StrawDigi.hh" #include "art/Framework/Principal/Event.h" #include "art_root_io/TFileDirectory.h" #include "TH1D.h" #include <string> namespace mu2e { class ValStrawDigiADCWaveform { public: ValStrawDigiADCWaveform(std::string name) : _name(name) {} int declare(const art::TFileDirectory& tfs); int fill(const StrawDigiADCWaveformCollection& coll, art::Event const& event); std::string& name() { return _name; } private: std::string _name; TH1D* _hVer; TH1D* _hN; TH1D* _hN2; TH1D* _hlen; TH1D* _hadc; TH1D* _hpmp; }; } // namespace mu2e #endif
20.818182
80
0.737991
NamithaChitrazee
c8aceefc6d6fca28d0cc79eb960909f99c3b4261
1,448
cxx
C++
Libraries/VtkVgCore/vtkVgImageIcon.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
1
2017-07-31T07:08:05.000Z
2017-07-31T07:08:05.000Z
Libraries/VtkVgCore/vtkVgImageIcon.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
null
null
null
Libraries/VtkVgCore/vtkVgImageIcon.cxx
judajake/vivia
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "vtkVgImageIcon.h" #include "vtkJPEGReader.h" #include "vtkObjectFactory.h" #include "vtkTexture.h" vtkStandardNewMacro(vtkVgImageIcon); //----------------------------------------------------------------------------- vtkVgImageIcon::vtkVgImageIcon() { this->Visibility = 1; this->Offset[0] = 0; this->Offset[1] = 0; this->JPEGReader = vtkSmartPointer<vtkJPEGReader>::New(); } //----------------------------------------------------------------------------- vtkVgImageIcon::~vtkVgImageIcon() { } //----------------------------------------------------------------------------- void vtkVgImageIcon::SetFileName(const char* fname) { this->JPEGReader->SetFileName(fname); this->JPEGReader->Update(); this->SetBalloonImage(this->JPEGReader->GetOutput()); this->Modified(); } //---------------------------------------------------------------------- void vtkVgImageIcon::ReleaseGraphicsResources(vtkWindow* w) { this->Texture->ReleaseGraphicsResources(w); this->Superclass::ReleaseGraphicsResources(w); } //----------------------------------------------------------------------------- void vtkVgImageIcon::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
28.96
79
0.540055
judajake
c8aeaadb3529329c28a1aab338e24aa9f39c3eb2
899
cpp
C++
src/test_main.cpp
sheayun-kmu/CarND-Kidnapped-Vehicle-Project
6ff584048d80bb79d8127537f61834fda81a4c2d
[ "MIT" ]
null
null
null
src/test_main.cpp
sheayun-kmu/CarND-Kidnapped-Vehicle-Project
6ff584048d80bb79d8127537f61834fda81a4c2d
[ "MIT" ]
null
null
null
src/test_main.cpp
sheayun-kmu/CarND-Kidnapped-Vehicle-Project
6ff584048d80bb79d8127537f61834fda81a4c2d
[ "MIT" ]
null
null
null
#include <uWS/uWS.h> #include <iostream> #include "particle_filter.h" /* int main() { uWS::Hub h; h.onMessage( [] ( uWS::WebSocket<uWS::SERVER> ws, char* data, size_t length, uWS::OpCode opCode ) { if (length && length > 2 && data[0] == '4' && data[1] == '2') } ); // end h.onMessage() } */ /* int main() { ParticleFilter pf; pf.init(4983, 5029, 1.201, (double[]) {2.0, 2.0, 0.05}); } */ #include <random> #include <map> int main() { std::default_random_engine gen; std::vector<double> weights; weights.push_back(0.4); weights.push_back(0.1); weights.push_back(0.4); weights.push_back(0.1); std::discrete_distribution<> d(weights.begin(), weights.end()); std::map<int, int> m; for(int n = 0; n < 10000; ++n) { ++m[d(gen)]; } for(auto p : m) { std::cout << p.first << " generated " << p.second << " times\n"; } }
18.729167
68
0.559511
sheayun-kmu
c8b09f316ff225495f23ac25914cf4d680bd251d
22,948
cc
C++
test/server/configuration_impl_test.cc
YaronKoller/envoy
367edfb2e36283b3c33a8fd433890666e9e10e04
[ "Apache-2.0" ]
1
2021-02-17T20:25:27.000Z
2021-02-17T20:25:27.000Z
test/server/configuration_impl_test.cc
YaronKoller/envoy
367edfb2e36283b3c33a8fd433890666e9e10e04
[ "Apache-2.0" ]
8
2020-08-07T00:52:28.000Z
2020-09-24T22:11:43.000Z
test/server/configuration_impl_test.cc
YaronKoller/envoy
367edfb2e36283b3c33a8fd433890666e9e10e04
[ "Apache-2.0" ]
2
2020-07-06T23:30:10.000Z
2020-08-04T21:58:32.000Z
#include <chrono> #include <list> #include <string> #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/config/metrics/v3/stats.pb.h" #include "common/api/api_impl.h" #include "common/config/well_known_names.h" #include "common/json/json_loader.h" #include "common/upstream/cluster_manager_impl.h" #include "server/configuration_impl.h" #include "extensions/stat_sinks/well_known_names.h" #include "test/common/upstream/utility.h" #include "test/mocks/common.h" #include "test/mocks/network/mocks.h" #include "test/mocks/server/instance.h" #include "test/test_common/environment.h" #include "test/test_common/utility.h" #include "fmt/printf.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "udpa/type/v1/typed_struct.pb.h" using testing::Return; namespace Envoy { namespace Server { namespace Configuration { namespace { TEST(FilterChainUtility, buildFilterChain) { Network::MockConnection connection; std::vector<Network::FilterFactoryCb> factories; ReadyWatcher watcher; Network::FilterFactoryCb factory = [&](Network::FilterManager&) -> void { watcher.ready(); }; factories.push_back(factory); factories.push_back(factory); EXPECT_CALL(watcher, ready()).Times(2); EXPECT_CALL(connection, initializeReadFilters()).WillOnce(Return(true)); EXPECT_EQ(FilterChainUtility::buildFilterChain(connection, factories), true); } TEST(FilterChainUtility, buildFilterChainFailWithBadFilters) { Network::MockConnection connection; std::vector<Network::FilterFactoryCb> factories; EXPECT_CALL(connection, initializeReadFilters()).WillOnce(Return(false)); EXPECT_EQ(FilterChainUtility::buildFilterChain(connection, factories), false); } class ConfigurationImplTest : public testing::Test { protected: ConfigurationImplTest() : api_(Api::createApiForTest()), cluster_manager_factory_( server_.admin(), server_.runtime(), server_.stats(), server_.threadLocal(), server_.random(), server_.dnsResolver(), server_.sslContextManager(), server_.dispatcher(), server_.localInfo(), server_.secretManager(), server_.messageValidationContext(), *api_, server_.httpContext(), server_.grpcContext(), server_.accessLogManager(), server_.singletonManager()) {} void addStatsdFakeClusterConfig(envoy::config::metrics::v3::StatsSink& sink) { envoy::config::metrics::v3::StatsdSink statsd_sink; statsd_sink.set_tcp_cluster_name("fake_cluster"); sink.mutable_typed_config()->PackFrom(statsd_sink); } Api::ApiPtr api_; NiceMock<Server::MockInstance> server_; Upstream::ProdClusterManagerFactory cluster_manager_factory_; }; TEST_F(ConfigurationImplTest, DefaultStatsFlushInterval) { envoy::config::bootstrap::v3::Bootstrap bootstrap; MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(std::chrono::milliseconds(5000), config.statsFlushInterval()); } TEST_F(ConfigurationImplTest, CustomStatsFlushInterval) { std::string json = R"EOF( { "stats_flush_interval": "0.500s", "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(std::chrono::milliseconds(500), config.statsFlushInterval()); } TEST_F(ConfigurationImplTest, SetUpstreamClusterPerConnectionBufferLimit) { const std::string json = R"EOF( { "static_resources": { "listeners" : [], "clusters": [ { "name": "test_cluster", "type": "static", "connect_timeout": "0.01s", "per_connection_buffer_limit_bytes": 8192, "lb_policy": "round_robin", "load_assignment": { "endpoints": [ { "lb_endpoints": [ { "endpoint": { "address": { "socket_address": { "address": "127.0.0.1", "port_value": 9999 } } } } ] } ] } } ] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); ASSERT_EQ(1U, config.clusterManager()->clusters().count("test_cluster")); EXPECT_EQ(8192U, config.clusterManager() ->clusters() .find("test_cluster") ->second.get() .info() ->perConnectionBufferLimitBytes()); server_.thread_local_.shutdownThread(); } TEST_F(ConfigurationImplTest, NullTracerSetWhenTracingConfigurationAbsent) { std::string json = R"EOF( { "static_resources": { "listeners" : [ { "address": { "socket_address": { "address": "127.0.0.1", "port_value": 1234 } }, "filter_chains": [] } ], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); server_.local_info_.node_.set_cluster(""); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_THAT(envoy::config::trace::v3::Tracing{}, ProtoEq(server_.httpContext().defaultTracingConfig())); } TEST_F(ConfigurationImplTest, NullTracerSetWhenHttpKeyAbsentFromTracerConfiguration) { std::string json = R"EOF( { "static_resources": { "listeners" : [ { "address": { "socket_address": { "address": "127.0.0.1", "port_value": 1234 } }, "filter_chains": [] } ], "clusters": [] }, "tracing": {}, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); server_.local_info_.node_.set_cluster(""); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_THAT(envoy::config::trace::v3::Tracing{}, ProtoEq(server_.httpContext().defaultTracingConfig())); } TEST_F(ConfigurationImplTest, ConfigurationFailsWhenInvalidTracerSpecified) { std::string json = R"EOF( { "static_resources": { "listeners" : [ { "address": { "socket_address": { "address": "127.0.0.1", "port_value": 1234 } }, "filter_chains": [] } ], "clusters": [] }, "tracing": { "http": { "name": "invalid", "typed_config": { "@type": "type.googleapis.com/udpa.type.v1.TypedStruct", "type_url": "type.googleapis.com/envoy.config.trace.v2.BlackHoleConfig", "value": { "collector_cluster": "cluster_0", "access_token_file": "/etc/envoy/envoy.cfg" } } } }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; EXPECT_THROW_WITH_MESSAGE(config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "Didn't find a registered implementation for name: 'invalid'"); } TEST_F(ConfigurationImplTest, ProtoSpecifiedStatsSink) { std::string json = R"EOF( { "static_resources": { "listeners": [], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); auto& sink = *bootstrap.mutable_stats_sinks()->Add(); sink.set_name(Extensions::StatSinks::StatsSinkNames::get().Statsd); addStatsdFakeClusterConfig(sink); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(1, config.statsSinks().size()); } TEST_F(ConfigurationImplTest, ProtoSpecifiedGrpcStreamDemuxer) { std::string json = R"EOF( { "static_resources": { "listeners": [], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } }, "grpc_stream_demuxers": { "subscription": "test_subscription", "address": "0.0.0.0", "port": 10001 } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(1, config.grpcStreamDemuxers().size()); } TEST_F(ConfigurationImplTest, StatsSinkWithInvalidName) { std::string json = R"EOF( { "static_resources": { "listeners": [], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); envoy::config::metrics::v3::StatsSink& sink = *bootstrap.mutable_stats_sinks()->Add(); sink.set_name("envoy.invalid"); MainImpl config; EXPECT_THROW_WITH_MESSAGE(config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "Didn't find a registered implementation for name: 'envoy.invalid'"); } TEST_F(ConfigurationImplTest, StatsSinkWithNoName) { std::string json = R"EOF( { "static_resources": { "listeners": [], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); bootstrap.mutable_stats_sinks()->Add(); MainImpl config; EXPECT_THROW_WITH_MESSAGE(config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "Provided name for static registration lookup was empty."); } TEST_F(ConfigurationImplTest, StatsSinkWithNoType) { std::string json = R"EOF( { "static_resources": { "listeners": [], "clusters": [] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); auto& sink = *bootstrap.mutable_stats_sinks()->Add(); udpa::type::v1::TypedStruct typed_struct; auto untyped_struct = typed_struct.mutable_value(); (*untyped_struct->mutable_fields())["foo"].set_string_value("bar"); sink.mutable_typed_config()->PackFrom(typed_struct); MainImpl config; EXPECT_THROW_WITH_MESSAGE(config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "Provided name for static registration lookup was empty."); } // An explicit non-empty LayeredRuntime is available to the server with no // changes made. TEST(InitialImplTest, LayeredRuntime) { const std::string yaml = R"EOF( layered_runtime: layers: - name: base static_layer: health_check: min_interval: 5 - name: root disk_layer: { symlink_root: /srv/runtime/current, subdirectory: envoy } - name: override disk_layer: { symlink_root: /srv/runtime/current, subdirectory: envoy_override, append_service_cluster: true } - name: admin admin_layer: {} )EOF"; const auto bootstrap = TestUtility::parseYaml<envoy::config::bootstrap::v3::Bootstrap>(yaml); InitialImpl config(bootstrap); EXPECT_THAT(config.runtime(), ProtoEq(bootstrap.layered_runtime())); } // An empty LayeredRuntime has an admin layer injected. TEST(InitialImplTest, EmptyLayeredRuntime) { const std::string bootstrap_yaml = R"EOF( layered_runtime: {} )EOF"; const auto bootstrap = TestUtility::parseYaml<envoy::config::bootstrap::v3::Bootstrap>(bootstrap_yaml); InitialImpl config(bootstrap); const std::string expected_yaml = R"EOF( layers: - admin_layer: {} )EOF"; const auto expected_runtime = TestUtility::parseYaml<envoy::config::bootstrap::v3::LayeredRuntime>(expected_yaml); EXPECT_THAT(config.runtime(), ProtoEq(expected_runtime)); } // An empty deprecated Runtime has an empty static and admin layer injected. TEST(InitialImplTest, EmptyDeprecatedRuntime) { const auto bootstrap = TestUtility::parseYaml<envoy::config::bootstrap::v3::Bootstrap>("{}"); InitialImpl config(bootstrap); const std::string expected_yaml = R"EOF( layers: - name: base static_layer: {} - name: admin admin_layer: {} )EOF"; const auto expected_runtime = TestUtility::parseYaml<envoy::config::bootstrap::v3::LayeredRuntime>(expected_yaml); EXPECT_THAT(config.runtime(), ProtoEq(expected_runtime)); } // A deprecated Runtime is transformed to the equivalent LayeredRuntime. TEST(InitialImplTest, DeprecatedRuntimeTranslation) { const std::string bootstrap_yaml = R"EOF( runtime: symlink_root: /srv/runtime/current subdirectory: envoy override_subdirectory: envoy_override base: health_check: min_interval: 5 )EOF"; const auto bootstrap = TestUtility::parseYaml<envoy::config::bootstrap::v3::Bootstrap>(bootstrap_yaml); InitialImpl config(bootstrap); const std::string expected_yaml = R"EOF( layers: - name: base static_layer: health_check: min_interval: 5 - name: root disk_layer: { symlink_root: /srv/runtime/current, subdirectory: envoy } - name: override disk_layer: { symlink_root: /srv/runtime/current, subdirectory: envoy_override, append_service_cluster: true } - name: admin admin_layer: {} )EOF"; const auto expected_runtime = TestUtility::parseYaml<envoy::config::bootstrap::v3::LayeredRuntime>(expected_yaml); EXPECT_THAT(config.runtime(), ProtoEq(expected_runtime)); } TEST_F(ConfigurationImplTest, AdminSocketOptions) { std::string json = R"EOF( { "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } }, "socket_options": [ { "level": 1, "name": 2, "int_value": 3, "state": "STATE_PREBIND" }, { "level": 4, "name": 5, "int_value": 6, "state": "STATE_BOUND" }, ] } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); InitialImpl config(bootstrap); Network::MockListenSocket socket_mock; ASSERT_EQ(config.admin().socketOptions()->size(), 2); auto detail = config.admin().socketOptions()->at(0)->getOptionDetails( socket_mock, envoy::config::core::v3::SocketOption::STATE_PREBIND); ASSERT_NE(detail, absl::nullopt); EXPECT_EQ(detail->name_, Envoy::Network::SocketOptionName(1, 2, "1/2")); detail = config.admin().socketOptions()->at(1)->getOptionDetails( socket_mock, envoy::config::core::v3::SocketOption::STATE_BOUND); ASSERT_NE(detail, absl::nullopt); EXPECT_EQ(detail->name_, Envoy::Network::SocketOptionName(4, 5, "4/5")); } TEST_F(ConfigurationImplTest, ExceedLoadBalancerHostWeightsLimit) { const std::string json = R"EOF( { "static_resources": { "listeners" : [], "clusters": [ { "name": "test_cluster", "type": "static", "connect_timeout": "0.01s", "per_connection_buffer_limit_bytes": 8192, "lb_policy": "RING_HASH", "load_assignment": { "cluster_name": "load_test_cluster", "endpoints": [ { "priority": 93 }, { "locality": { "zone": "zone1" }, "lb_endpoints": [ { "endpoint": { "address": { "pipe": { "path": "path/to/pipe" } } }, "health_status": "TIMEOUT", "load_balancing_weight": { "value": 4294967295 } }, { "endpoint": { "address": { "pipe": { "path": "path/to/pipe2" } } }, "health_status": "TIMEOUT", "load_balancing_weight": { "value": 1 } } ], "load_balancing_weight": { "value": 122 } } ] } } ] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; EXPECT_THROW_WITH_MESSAGE( config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "The sum of weights of all upstream hosts in a locality exceeds 4294967295"); } TEST_F(ConfigurationImplTest, ExceedLoadBalancerLocalityWeightsLimit) { const std::string json = R"EOF( { "static_resources": { "listeners" : [], "clusters": [ { "name": "test_cluster", "type": "static", "connect_timeout": "0.01s", "per_connection_buffer_limit_bytes": 8192, "lb_policy": "RING_HASH", "load_assignment": { "cluster_name": "load_test_cluster", "endpoints": [ { "priority": 93 }, { "locality": { "zone": "zone1" }, "lb_endpoints": [ { "endpoint": { "address": { "pipe": { "path": "path/to/pipe" } } }, "health_status": "TIMEOUT", "load_balancing_weight": { "value": 7 } } ], "load_balancing_weight": { "value": 4294967295 } }, { "locality": { "region": "domains", "sub_zone": "sub_zone1" }, "lb_endpoints": [ { "endpoint": { "address": { "pipe": { "path": "path/to/pipe" } } }, "health_status": "TIMEOUT", "load_balancing_weight": { "value": 8 } } ], "load_balancing_weight": { "value": 2 } } ] }, "lb_subset_config": { "fallback_policy": "ANY_ENDPOINT", "subset_selectors": { "keys": [ "x" ] }, "locality_weight_aware": "true" }, "common_lb_config": { "healthy_panic_threshold": { "value": 0.8 }, "locality_weighted_lb_config": { } } } ] }, "admin": { "access_log_path": "/dev/null", "address": { "socket_address": { "address": "1.2.3.4", "port_value": 5678 } } } } )EOF"; auto bootstrap = Upstream::parseBootstrapFromV3Json(json); MainImpl config; EXPECT_THROW_WITH_MESSAGE( config.initialize(bootstrap, server_, cluster_manager_factory_), EnvoyException, "The sum of weights of all localities at the same priority exceeds 4294967295"); } TEST_F(ConfigurationImplTest, KillTimeoutWithoutSkew) { const std::string json = R"EOF( { "watchdog": { "kill_timeout": "1.0s", }, })EOF"; envoy::config::bootstrap::v3::Bootstrap bootstrap; TestUtility::loadFromJson(json, bootstrap); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(std::chrono::milliseconds(1000), config.wdKillTimeout()); } TEST_F(ConfigurationImplTest, CanSkewsKillTimeout) { const std::string json = R"EOF( { "watchdog": { "kill_timeout": "1.0s", "max_kill_timeout_jitter": "0.5s" }, })EOF"; envoy::config::bootstrap::v3::Bootstrap bootstrap; TestUtility::loadFromJson(json, bootstrap); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_LT(std::chrono::milliseconds(1000), config.wdKillTimeout()); EXPECT_GE(std::chrono::milliseconds(1500), config.wdKillTimeout()); } TEST_F(ConfigurationImplTest, DoesNotSkewIfKillTimeoutDisabled) { const std::string json = R"EOF( { "watchdog": { "max_kill_timeout_jitter": "0.5s" }, })EOF"; envoy::config::bootstrap::v3::Bootstrap bootstrap; TestUtility::loadFromJson(json, bootstrap); MainImpl config; config.initialize(bootstrap, server_, cluster_manager_factory_); EXPECT_EQ(std::chrono::milliseconds(0), config.wdKillTimeout()); } } // namespace } // namespace Configuration } // namespace Server } // namespace Envoy
27.581731
116
0.570551
YaronKoller
c8b32db2214557c7968800ecd0841a8c62861db0
817
hpp
C++
medusa.hpp
rolandnyamo/combat_tournament
7123942dfc432c401404bd89fe0bd77f9938af1d
[ "MIT" ]
null
null
null
medusa.hpp
rolandnyamo/combat_tournament
7123942dfc432c401404bd89fe0bd77f9938af1d
[ "MIT" ]
null
null
null
medusa.hpp
rolandnyamo/combat_tournament
7123942dfc432c401404bd89fe0bd77f9938af1d
[ "MIT" ]
null
null
null
#ifndef MEDUSA_HPP #define MEDUSA_HPP #include "character.hpp" class Medusa: public Character { private: Dice *attack_dice[2];//pointer to the character's attack dice(s). Dice *defense_dice;//pointer to the character's defense dice(s). public: Medusa(); virtual int calcDamage(int);//calculates the damage inflicted to this character virtual int attack(Character *); virtual int defend();//defends, then subtracts from the strength virtual bool isDead();//returns true when Medusa dies virtual void won();//to be called when this character won the game virtual int getStrength(); virtual void setName(std::string); virtual std::string getName(); virtual std::string getType(); virtual void recover(); virtual void setTeam(std::string); ~Medusa(); }; #endif
31.423077
83
0.709914
rolandnyamo
c8b4c59d0792330989ee35df4c5ee738d0327fa0
2,738
hpp
C++
include/transcript_align.hpp
GWW/scsnv
7332ad7cec482a9c249707255e68977e4dae52e9
[ "MIT" ]
6
2020-07-12T19:33:41.000Z
2021-07-06T05:29:33.000Z
include/transcript_align.hpp
GWW/scsnv
7332ad7cec482a9c249707255e68977e4dae52e9
[ "MIT" ]
6
2021-05-12T21:08:55.000Z
2022-03-15T00:49:53.000Z
include/transcript_align.hpp
GWW/scsnv
7332ad7cec482a9c249707255e68977e4dae52e9
[ "MIT" ]
null
null
null
#pragma once /* Copyright (c) 2018-2020 Gavin W. Wilson 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 "align_aux.hpp" #include "index.hpp" #include "genome_align.hpp" #include "bwamem.h" namespace gwsc { class TranscriptAlign{ TranscriptAlign( const TranscriptAlign& ) = delete; TranscriptAlign& operator=(const TranscriptAlign&) = delete; public: TranscriptAlign(const TXIndex & index, StrandMode smode) : idx_(index), smode_(smode) { } ~TranscriptAlign(){ if(bidx_ != nullptr) bwa_idx_destroy(bidx_); if(args_ != nullptr) free(args_); } void unload(){ if(bidx_ != nullptr) bwa_idx_destroy(bidx_); if(args_ != nullptr) free(args_); bidx_ = nullptr; args_ = nullptr; } void load(const std::string & prefix, unsigned int min_overhang); void set_gidx(const GenomeAlign * gidx) { gidx_ = gidx; } void align(AlignGroup & ad, const std::string & seq, unsigned int len) const; void get(AlignGroup & ad, size_t i, const std::string & seq, unsigned int len) const; void project(AlignData & a, CigarString & tc) const; AlignScore ascore; private: void make_align_(AlignGroup & ad, mem_aln_t & a) const; void trim_splices_(AlignData & a) const; const TXIndex & idx_; bwaidx_t * bidx_ = nullptr; const GenomeAlign * gidx_ = nullptr; mem_opt_t * args_ = nullptr; unsigned int min_overhang_; StrandMode smode_; }; }
34.225
95
0.645362
GWW
c8b856fa57e708ca331cb46a75d831b036f90fc0
311
cpp
C++
glean/lang/clang/tests/regression/codemarkup/var1/test.cpp
phlalx/Glean
f26b48216bf5ae25a40e867cad3ebfe586466e5a
[ "BSD-3-Clause" ]
null
null
null
glean/lang/clang/tests/regression/codemarkup/var1/test.cpp
phlalx/Glean
f26b48216bf5ae25a40e867cad3ebfe586466e5a
[ "BSD-3-Clause" ]
null
null
null
glean/lang/clang/tests/regression/codemarkup/var1/test.cpp
phlalx/Glean
f26b48216bf5ae25a40e867cad3ebfe586466e5a
[ "BSD-3-Clause" ]
null
null
null
extern int v1; int v2; static int v3; inline int v4; constexpr int v5 = 4; struct T { static int m1; inline static int m2; constexpr static int m3 = 4; static void f() { m1; m2; m3; } }; void g(int x1) { v1; v2; v3; v4; v5; T::m1; T::m2; T::m3; int x2; x1; x2; }
9.424242
30
0.527331
phlalx
c8b930379a946a2d31d7856e8c42af2af8826319
1,954
cc
C++
cc/playground/sum_store-dir/sum_store.cc
KeyurRamoliya/FASTER
bf3a426266fd47ac97c660d365ee8e2d4317c3e0
[ "MIT" ]
3,190
2018-08-16T01:06:12.000Z
2019-05-04T17:04:07.000Z
cc/playground/sum_store-dir/sum_store.cc
KeyurRamoliya/FASTER
bf3a426266fd47ac97c660d365ee8e2d4317c3e0
[ "MIT" ]
82
2018-08-17T19:45:28.000Z
2019-04-28T00:59:25.000Z
cc/playground/sum_store-dir/sum_store.cc
KeyurRamoliya/FASTER
bf3a426266fd47ac97c660d365ee8e2d4317c3e0
[ "MIT" ]
220
2018-08-17T19:03:53.000Z
2019-05-06T06:46:42.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <cstdint> #include <cstdio> #include <cstdlib> #include <string> #include "concurrent_recovery_test.h" #include "sum_store.h" #include "single_threaded_recovery_test.h" int main(int argc, char* argv[]) { if(argc < 3) { printf("Usage: sum_store.exe single <operation>\n"); printf("Where <operation> is one of \"populate\", \"recover <token>\", or " "\"continue <token>\".\n"); exit(0); } std::experimental::filesystem::create_directory("sum_storage"); static constexpr uint64_t kKeySpace = (1L << 15); sum_store::store_t store{ kKeySpace, 17179869184, "sum_storage" }; std::string type{ argv[1] }; if(type == "single") { sum_store::SingleThreadedRecoveryTest test{ store }; std::string task{ argv[2] }; if(task == "populate") { test.Populate(); } else if(task == "recover") { if(argc != 4) { printf("Must specify token to recover to.\n"); exit(1); } Guid token = Guid::Parse(argv[3]); test.RecoverAndTest(token, token); } } else if(type == "concurrent") { if(argc < 4) { printf("Must specify number of threads to execute concurrently.\n"); exit(1); } size_t num_threads = std::atoi(argv[2]); sum_store::ConcurrentRecoveryTest test{ store, num_threads }; std::string task{ argv[3] }; if(task == "populate") { test.Populate(); } else if(task == "recover") { if(argc != 5) { printf("Must specify token to recover to.\n"); exit(1); } Guid token = Guid::Parse(argv[4]); test.RecoverAndTest(token, token); } else if(task == "continue") { if(argc != 5) { printf("Must specify version to continue from.\n"); exit(1); } Guid token = Guid::Parse(argv[4]); test.Continue(token, token); } } return 0; }
25.051282
79
0.596725
KeyurRamoliya
c8b9515318fbceebe8f98c2b730816092c6bf7ab
7,784
cc
C++
src/box/engine.cc
rtsisyk/tarantool-archive
b001ff969cd9a87e0393f01fa3d6edc6c00dd1f6
[ "BSD-2-Clause" ]
null
null
null
src/box/engine.cc
rtsisyk/tarantool-archive
b001ff969cd9a87e0393f01fa3d6edc6c00dd1f6
[ "BSD-2-Clause" ]
1
2017-08-22T11:04:34.000Z
2017-08-22T11:04:34.000Z
src/box/engine.cc
rtsisyk/tarantool-archive
b001ff969cd9a87e0393f01fa3d6edc6c00dd1f6
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "engine.h" #include "tuple.h" #include "txn.h" #include "port.h" #include "space.h" #include "exception.h" #include "schema.h" #include "small/rlist.h" #include "scoped_guard.h" #include "vclock.h" #include <stdlib.h> #include <string.h> #include <errinj.h> RLIST_HEAD(engines); Engine::Engine(const char *engine_name, struct tuple_format_vtab *format_arg) :name(engine_name), id(-1), flags(0), link(RLIST_HEAD_INITIALIZER(link)), format(format_arg) {} void Engine::init() {} void Engine::begin(struct txn *) {} void Engine::beginStatement(struct txn *) {} void Engine::prepare(struct txn *) {} void Engine::commit(struct txn *, int64_t) {} void Engine::rollback(struct txn *) {} void Engine::rollbackStatement(struct txn *, struct txn_stmt *) {} void Engine::bootstrap() {} void Engine::beginInitialRecovery(struct vclock *vclock) { (void) vclock; } void Engine::beginFinalRecovery() {} void Engine::endRecovery() {} void Engine::initSystemSpace(struct space * /* space */) { panic("not implemented"); } void Engine::addPrimaryKey(struct space * /* space */) { } void Engine::dropPrimaryKey(struct space * /* space */) { } void Engine::buildSecondaryKey(struct space *, struct space *, Index *) { tnt_raise(ClientError, ER_UNSUPPORTED, this->name, "buildSecondaryKey"); } int Engine::beginCheckpoint() { return 0; } int Engine::prepareWaitCheckpoint(struct vclock *vclock) { (void) vclock; return 0; } int Engine::waitCheckpoint(struct vclock *vclock) { (void) vclock; return 0; } void Engine::commitCheckpoint(struct vclock *vclock) { (void) vclock; } void Engine::abortCheckpoint() { } void Engine::collectGarbage(int64_t lsn) { (void) lsn; } int Engine::backup(struct vclock *vclock, engine_backup_cb cb, void *cb_arg) { (void) vclock; (void) cb; (void) cb_arg; return 0; } void Engine::join(struct vclock *vclock, struct xstream *stream) { (void) vclock; (void) stream; } void Engine::checkIndexDef(struct space *space, struct index_def *index_def) { (void) space; (void) index_def; /* * Don't bother checking index_def to match the view requirements. * Index::initIterator() must check key on each call. */ } Handler::Handler(Engine *f) :engine(f) { } void Handler::applyInitialJoinRow(struct space *, struct request *) { tnt_raise(ClientError, ER_UNSUPPORTED, engine->name, "applySnapshotRow"); } struct tuple * Handler::executeReplace(struct txn *, struct space *, struct request *) { tnt_raise(ClientError, ER_UNSUPPORTED, engine->name, "replace"); } struct tuple * Handler::executeDelete(struct txn*, struct space *, struct request *) { tnt_raise(ClientError, ER_UNSUPPORTED, engine->name, "delete"); } struct tuple * Handler::executeUpdate(struct txn*, struct space *, struct request *) { tnt_raise(ClientError, ER_UNSUPPORTED, engine->name, "update"); } void Handler::executeUpsert(struct txn *, struct space *, struct request *) { tnt_raise(ClientError, ER_UNSUPPORTED, engine->name, "upsert"); } void Handler::prepareAlterSpace(struct space *, struct space *) { } void Handler::commitAlterSpace(struct space *, struct space *) { } void Handler::executeSelect(struct txn *, struct space *space, uint32_t index_id, uint32_t iterator, uint32_t offset, uint32_t limit, const char *key, const char * /* key_end */, struct port *port) { Index *index = index_find_xc(space, index_id); uint32_t found = 0; if (iterator >= iterator_type_MAX) tnt_raise(IllegalParams, "Invalid iterator type"); enum iterator_type type = (enum iterator_type) iterator; uint32_t part_count = key ? mp_decode_array(&key) : 0; if (key_validate(index->index_def, type, key, part_count)) diag_raise(); struct iterator *it = index->allocIterator(); IteratorGuard guard(it); index->initIterator(it, type, key, part_count); struct tuple *tuple; while ((tuple = it->next(it)) != NULL) { if (offset > 0) { offset--; continue; } if (limit == found++) break; port_add_tuple(port, tuple); } } /** Register engine instance. */ void engine_register(Engine *engine) { static int n_engines; rlist_add_tail_entry(&engines, engine, link); engine->id = n_engines++; } /** Find engine by name. */ Engine * engine_find(const char *name) { Engine *e; engine_foreach(e) { if (strcmp(e->name, name) == 0) return e; } tnt_raise(LoggedError, ER_NO_SUCH_ENGINE, name); } /** Shutdown all engine factories. */ void engine_shutdown() { Engine *e, *tmp; rlist_foreach_entry_safe(e, &engines, link, tmp) { delete e; } } void engine_bootstrap() { Engine *engine; engine_foreach(engine) { engine->bootstrap(); } } void engine_begin_initial_recovery(struct vclock *vclock) { /* recover engine snapshot */ Engine *engine; engine_foreach(engine) { engine->beginInitialRecovery(vclock); } } void engine_begin_final_recovery() { Engine *engine; engine_foreach(engine) engine->beginFinalRecovery(); } void engine_end_recovery() { /* * For all new spaces created after recovery is complete, * when the primary key is added, enable all keys. */ Engine *engine; engine_foreach(engine) engine->endRecovery(); } int engine_begin_checkpoint() { /* create engine snapshot */ Engine *engine; engine_foreach(engine) { if (engine->beginCheckpoint() < 0) return -1; } return 0; } int engine_commit_checkpoint(struct vclock *vclock) { Engine *engine; /* prepare to wait */ engine_foreach(engine) { if (engine->prepareWaitCheckpoint(vclock) < 0) return -1; } /* wait for engine snapshot completion */ engine_foreach(engine) { if (engine->waitCheckpoint(vclock) < 0) return -1; } /* remove previous snapshot reference */ engine_foreach(engine) { engine->commitCheckpoint(vclock); } return 0; } void engine_abort_checkpoint() { Engine *engine; /* rollback snapshot creation */ engine_foreach(engine) engine->abortCheckpoint(); } void engine_collect_garbage(int64_t lsn) { Engine *engine; engine_foreach(engine) engine->collectGarbage(lsn); } int engine_backup(struct vclock *vclock, engine_backup_cb cb, void *cb_arg) { Engine *engine; engine_foreach(engine) { if (engine->backup(vclock, cb, cb_arg) < 0) return -1; } return 0; } void engine_join(struct vclock *vclock, struct xstream *stream) { Engine *engine; engine_foreach(engine) { engine->join(vclock, stream); } }
19.756345
77
0.711588
rtsisyk
c8ba8ddcaa093183ccd721dfeabf8b9ee6bf4cc2
40,077
cpp
C++
sw/src/xaxivdma.cpp
DoubleGithub/HOG_Zedboard
6fc55c37ee210d7fc8bca919213e96bfc5c9d811
[ "MIT" ]
29
2018-07-09T10:12:47.000Z
2022-01-14T18:57:52.000Z
sw/src/xaxivdma.cpp
DoubleGithub/HOG_Zedboard
6fc55c37ee210d7fc8bca919213e96bfc5c9d811
[ "MIT" ]
10
2018-10-30T10:38:12.000Z
2021-04-14T00:43:29.000Z
sw/src/xaxivdma.cpp
DoubleGithub/HOG_Zedboard
6fc55c37ee210d7fc8bca919213e96bfc5c9d811
[ "MIT" ]
10
2019-07-04T07:39:38.000Z
2021-05-11T13:54:07.000Z
/****************************************************************************** * * Copyright (C) 2012 - 2015 Xilinx, Inc. All rights reserved. * * 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. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * 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 * XILINX 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. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /*****************************************************************************/ /** * * @file xaxivdma.c * @addtogroup axivdma_v6_0 * @{ * * Implementation of the driver API functions for the AXI Video DMA engine. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ------------------------------------------------------- * 1.00a jz 08/16/10 First release * 2.00a jz 12/10/10 Added support for direct register access mode, v3 core * 2.01a jz 01/19/11 Added ability to re-assign BD addresses * rkv 03/28/11 Added support for frame store register. * 3.00a srt 08/26/11 Added support for Flush on Frame Sync and dynamic * programming of Line Buffer Thresholds and added API * XAxiVdma_SetLineBufThreshold. * 4.00a srt 11/21/11 - XAxiVdma_CfgInitialize API is modified to use the * EffectiveAddr. * - Added APIs: * XAxiVdma_FsyncSrcSelect() * XAxiVdma_GenLockSourceSelect() * 4.01a srt 06/13/12 - Added APIs: * XAxiVdma_GetDmaChannelErrors() * XAxiVdma_ClearDmaChannelErrors() * 4.02a srt 09/25/12 - Fixed CR 678734 * XAxiVdma_SetFrmStore function changed to remove * Reset logic after setting number of frame stores. * 4.03a srt 01/18/13 - Updated logic of GenLockSourceSelect() & FsyncSrcSelect() * APIs for newer versions of IP (CR: 691052). * - Modified CfgInitialize() API to initialize * StreamWidth parameters. (CR 691866) * 4.04a srt 03/03/13 - Support for *_ENABLE_DEBUG_INFO_* debug configuration * parameters (CR: 703738) * 6.1 sk 11/10/15 Used UINTPTR instead of u32 for Baseaddress CR# 867425. * Changed the prototype of XAxiVdma_CfgInitialize API. * * </pre> * ******************************************************************************/ /***************************** Include Files *********************************/ #include "xaxivdma.h" #include "xaxivdma_i.h" /************************** Constant Definitions *****************************/ /* The polling upon starting the hardware * * We have the assumption that reset is fast upon hardware start */ #define INITIALIZATION_POLLING 100000 /*****************************************************************************/ /** * Get a channel * * @param InstancePtr is the DMA engine to work on * @param Direction is the direction for the channel to get * * @return * The pointer to the channel. Upon error, return NULL. * * @note * Since this function is internally used, we assume Direction is valid *****************************************************************************/ XAxiVdma_Channel *XAxiVdma_GetChannel(XAxiVdma *InstancePtr, u16 Direction) { if (Direction == XAXIVDMA_READ) { return &(InstancePtr->ReadChannel); } else if (Direction == XAXIVDMA_WRITE) { return &(InstancePtr->WriteChannel); } else { xdbg_printf(XDBG_DEBUG_ERROR, "Invalid direction %x\r\n", Direction); return NULL; } } static int XAxiVdma_Major(XAxiVdma *InstancePtr) { u32 Reg; Reg = XAxiVdma_ReadReg(InstancePtr->BaseAddr, XAXIVDMA_VERSION_OFFSET); return (int)((Reg & XAXIVDMA_VERSION_MAJOR_MASK) >> XAXIVDMA_VERSION_MAJOR_SHIFT); } /*****************************************************************************/ /** * Initialize the driver with hardware configuration * * @param InstancePtr is the pointer to the DMA engine to work on * @param CfgPtr is the pointer to the hardware configuration structure * @param EffectiveAddr is the virtual address map for the device * * @return * - XST_SUCCESS if everything goes fine * - XST_FAILURE if reset the hardware failed, need system reset to recover * * @note * If channel fails reset, then it will be set as invalid *****************************************************************************/ int XAxiVdma_CfgInitialize(XAxiVdma *InstancePtr, XAxiVdma_Config *CfgPtr, UINTPTR EffectiveAddr) { XAxiVdma_Channel *RdChannel; XAxiVdma_Channel *WrChannel; int Polls; /* Validate parameters */ Xil_AssertNonvoid(InstancePtr != NULL); Xil_AssertNonvoid(CfgPtr != NULL); /* Initially, no interrupt callback functions */ InstancePtr->ReadCallBack.CompletionCallBack = 0x0; InstancePtr->ReadCallBack.ErrCallBack = 0x0; InstancePtr->WriteCallBack.CompletionCallBack = 0x0; InstancePtr->WriteCallBack.ErrCallBack = 0x0; InstancePtr->BaseAddr = EffectiveAddr; InstancePtr->MaxNumFrames = CfgPtr->MaxFrameStoreNum; InstancePtr->HasMm2S = CfgPtr->HasMm2S; InstancePtr->HasS2Mm = CfgPtr->HasS2Mm; InstancePtr->UseFsync = CfgPtr->UseFsync; InstancePtr->InternalGenLock = CfgPtr->InternalGenLock; InstancePtr->AddrWidth = CfgPtr->AddrWidth; if (XAxiVdma_Major(InstancePtr) < 3) { InstancePtr->HasSG = 1; } else { InstancePtr->HasSG = CfgPtr->HasSG; } /* The channels are not valid until being initialized */ RdChannel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_READ); RdChannel->IsValid = 0; WrChannel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_WRITE); WrChannel->IsValid = 0; if (InstancePtr->HasMm2S) { RdChannel->direction = XAXIVDMA_READ; RdChannel->ChanBase = InstancePtr->BaseAddr + XAXIVDMA_TX_OFFSET; RdChannel->InstanceBase = InstancePtr->BaseAddr; RdChannel->HasSG = InstancePtr->HasSG; RdChannel->IsRead = 1; RdChannel->StartAddrBase = InstancePtr->BaseAddr + XAXIVDMA_MM2S_ADDR_OFFSET; RdChannel->NumFrames = CfgPtr->MaxFrameStoreNum; /* Flush on Sync */ RdChannel->FlushonFsync = CfgPtr->FlushonFsync; /* Dynamic Line Buffers Depth */ RdChannel->LineBufDepth = CfgPtr->Mm2SBufDepth; if(RdChannel->LineBufDepth > 0) { RdChannel->LineBufThreshold = XAxiVdma_ReadReg(RdChannel->ChanBase, XAXIVDMA_BUFTHRES_OFFSET); xdbg_printf(XDBG_DEBUG_GENERAL, "Read Channel Buffer Threshold %d bytes\n\r", RdChannel->LineBufThreshold); } RdChannel->HasDRE = CfgPtr->HasMm2SDRE; RdChannel->WordLength = CfgPtr->Mm2SWordLen >> 3; RdChannel->StreamWidth = CfgPtr->Mm2SStreamWidth >> 3; RdChannel->AddrWidth = InstancePtr->AddrWidth; /* Internal GenLock */ RdChannel->GenLock = CfgPtr->Mm2SGenLock; /* Debug Info Parameter flags */ if (!CfgPtr->EnableAllDbgFeatures) { if (CfgPtr->Mm2SThresRegEn) { RdChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_THRESHOLD_REG; } if (CfgPtr->Mm2SFrmStoreRegEn) { RdChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_FRMSTORE_REG; } if (CfgPtr->Mm2SDlyCntrEn) { RdChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_DLY_CNTR; } if (CfgPtr->Mm2SFrmCntrEn) { RdChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_FRM_CNTR; } } else { RdChannel->DbgFeatureFlags = XAXIVDMA_ENABLE_DBG_ALL_FEATURES; } XAxiVdma_ChannelInit(RdChannel); XAxiVdma_ChannelReset(RdChannel); /* At time of initialization, no transfers are going on, * reset is expected to be quick */ Polls = INITIALIZATION_POLLING; while (Polls && XAxiVdma_ChannelResetNotDone(RdChannel)) { Polls -= 1; } if (!Polls) { xdbg_printf(XDBG_DEBUG_ERROR, "Read channel reset failed %x\n\r", (unsigned int)XAxiVdma_ChannelGetStatus(RdChannel)); return XST_FAILURE; } } if (InstancePtr->HasS2Mm) { WrChannel->direction = XAXIVDMA_WRITE; WrChannel->ChanBase = InstancePtr->BaseAddr + XAXIVDMA_RX_OFFSET; WrChannel->InstanceBase = InstancePtr->BaseAddr; WrChannel->HasSG = InstancePtr->HasSG; WrChannel->IsRead = 0; WrChannel->StartAddrBase = InstancePtr->BaseAddr + XAXIVDMA_S2MM_ADDR_OFFSET; WrChannel->NumFrames = CfgPtr->MaxFrameStoreNum; WrChannel->AddrWidth = InstancePtr->AddrWidth; /* Flush on Sync */ WrChannel->FlushonFsync = CfgPtr->FlushonFsync; /* Dynamic Line Buffers Depth */ WrChannel->LineBufDepth = CfgPtr->S2MmBufDepth; if(WrChannel->LineBufDepth > 0) { WrChannel->LineBufThreshold = XAxiVdma_ReadReg(WrChannel->ChanBase, XAXIVDMA_BUFTHRES_OFFSET); xdbg_printf(XDBG_DEBUG_GENERAL, "Write Channel Buffer Threshold %d bytes\n\r", WrChannel->LineBufThreshold); } WrChannel->HasDRE = CfgPtr->HasS2MmDRE; WrChannel->WordLength = CfgPtr->S2MmWordLen >> 3; WrChannel->StreamWidth = CfgPtr->S2MmStreamWidth >> 3; /* Internal GenLock */ WrChannel->GenLock = CfgPtr->S2MmGenLock; /* Frame Sync Source Selection*/ WrChannel->S2MmSOF = CfgPtr->S2MmSOF; /* Debug Info Parameter flags */ if (!CfgPtr->EnableAllDbgFeatures) { if (CfgPtr->S2MmThresRegEn) { WrChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_THRESHOLD_REG; } if (CfgPtr->S2MmFrmStoreRegEn) { WrChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_FRMSTORE_REG; } if (CfgPtr->S2MmDlyCntrEn) { WrChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_DLY_CNTR; } if (CfgPtr->S2MmFrmCntrEn) { WrChannel->DbgFeatureFlags |= XAXIVDMA_ENABLE_DBG_FRM_CNTR; } } else { WrChannel->DbgFeatureFlags = XAXIVDMA_ENABLE_DBG_ALL_FEATURES; } XAxiVdma_ChannelInit(WrChannel); XAxiVdma_ChannelReset(WrChannel); /* At time of initialization, no transfers are going on, * reset is expected to be quick */ Polls = INITIALIZATION_POLLING; while (Polls && XAxiVdma_ChannelResetNotDone(WrChannel)) { Polls -= 1; } if (!Polls) { xdbg_printf(XDBG_DEBUG_ERROR, "Write channel reset failed %x\n\r", (unsigned int)XAxiVdma_ChannelGetStatus(WrChannel)); return XST_FAILURE; } } InstancePtr->IsReady = XAXIVDMA_DEVICE_READY; return XST_SUCCESS; } /*****************************************************************************/ /** * This function resets one DMA channel * * The registers will be default values after the reset * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * None * * @note * Due to undeterminism of system delays, check the reset status through * XAxiVdma_ResetNotDone(). If direction is invalid, do nothing. *****************************************************************************/ void XAxiVdma_Reset(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return; } if (Channel->IsValid) { XAxiVdma_ChannelReset(Channel); return; } } /*****************************************************************************/ /** * This function checks one DMA channel for reset completion * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * - 0 if reset is done * - 1 if reset is ongoing * * @note * We do not check for channel validity, because channel is marked as invalid * before reset is done *****************************************************************************/ int XAxiVdma_ResetNotDone(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); /* If dirction is invalid, reset is never done */ if (!Channel) { return 1; } return XAxiVdma_ChannelResetNotDone(Channel); } /*****************************************************************************/ /** * Check whether a DMA channel is busy * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * - Non-zero if the channel is busy * - Zero if the channel is idle * *****************************************************************************/ int XAxiVdma_IsBusy(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return 0; } if (Channel->IsValid) { return XAxiVdma_ChannelIsBusy(Channel); } else { /* An invalid channel is never busy */ return 0; } } /*****************************************************************************/ /** * Get the current frame that hardware is working on * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * The current frame that the hardware is working on * * @note * If returned frame number is out of range, then the channel is invalid *****************************************************************************/ u32 XAxiVdma_CurrFrameStore(XAxiVdma *InstancePtr, u16 Direction) { u32 Rc; Rc = XAxiVdma_ReadReg(InstancePtr->BaseAddr, XAXIVDMA_PARKPTR_OFFSET); if (Direction == XAXIVDMA_READ) { Rc &= XAXIVDMA_PARKPTR_READSTR_MASK; return (Rc >> XAXIVDMA_READSTR_SHIFT); } else if (Direction == XAXIVDMA_WRITE) { Rc &= XAXIVDMA_PARKPTR_WRTSTR_MASK; return (Rc >> XAXIVDMA_WRTSTR_SHIFT); } else { return 0xFFFFFFFF; } } /*****************************************************************************/ /** * Get the version of the hardware * * @param InstancePtr is the pointer to the DMA engine to work on * * @return * The version of the hardware * *****************************************************************************/ u32 XAxiVdma_GetVersion(XAxiVdma *InstancePtr) { return XAxiVdma_ReadReg(InstancePtr->BaseAddr, XAXIVDMA_VERSION_OFFSET); } /*****************************************************************************/ /** * Get the status of a channel * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * The status of the channel * * @note * An invalid return value indicates that channel is invalid *****************************************************************************/ u32 XAxiVdma_GetStatus(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return 0xFFFFFFFF; } if (Channel->IsValid) { return XAxiVdma_ChannelGetStatus(Channel); } else { return 0xFFFFFFFF; } } /*****************************************************************************/ /** * Configure Line Buffer Threshold * * @param InstancePtr is the pointer to the DMA engine to work on * @param LineBufThreshold is the value to set threshold * @param Direction is the DMA channel to work on * * @return * - XST_SUCCESS if successful * - XST_FAILURE otherwise * - XST_NO_FEATURE if access to Threshold register is disabled *****************************************************************************/ int XAxiVdma_SetLineBufThreshold(XAxiVdma *InstancePtr, int LineBufThreshold, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!(Channel->DbgFeatureFlags & XAXIVDMA_ENABLE_DBG_THRESHOLD_REG)) { xdbg_printf(XDBG_DEBUG_ERROR, "Threshold Register is disabled\n\r"); return XST_NO_FEATURE; } if(Channel->LineBufThreshold) { if((LineBufThreshold < Channel->LineBufDepth) && (LineBufThreshold % Channel->StreamWidth == 0)) { XAxiVdma_WriteReg(Channel->ChanBase, XAXIVDMA_BUFTHRES_OFFSET, LineBufThreshold); xdbg_printf(XDBG_DEBUG_GENERAL, "Line Buffer Threshold set to %x\n\r", XAxiVdma_ReadReg(Channel->ChanBase, XAXIVDMA_BUFTHRES_OFFSET)); } else { xdbg_printf(XDBG_DEBUG_ERROR, "Invalid Line Buffer Threshold\n\r"); return XST_FAILURE; } } else { xdbg_printf(XDBG_DEBUG_ERROR, "Failed to set Threshold\n\r"); return XST_FAILURE; } return XST_SUCCESS; } /*****************************************************************************/ /** * Configure Frame Sync Source and valid only when C_USE_FSYNC is enabled. * * @param InstancePtr is the pointer to the DMA engine to work on * @param Source is the value to set the source of Frame Sync * @param Direction is the DMA channel to work on * * @return * - XST_SUCCESS if successful * - XST_FAILURE if C_USE_FSYNC is disabled. * *****************************************************************************/ int XAxiVdma_FsyncSrcSelect(XAxiVdma *InstancePtr, u32 Source, u16 Direction) { XAxiVdma_Channel *Channel; u32 CrBits; u32 UseFsync; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (Direction == XAXIVDMA_WRITE) { UseFsync = ((InstancePtr->UseFsync == 1) || (InstancePtr->UseFsync == 3)) ? 1 : 0; } else { UseFsync = ((InstancePtr->UseFsync == 1) || (InstancePtr->UseFsync == 2)) ? 1 : 0; } if (UseFsync) { CrBits = XAxiVdma_ReadReg(Channel->ChanBase, XAXIVDMA_CR_OFFSET); switch (Source) { case XAXIVDMA_CHAN_FSYNC: /* Same Channel Frame Sync */ CrBits &= ~(XAXIVDMA_CR_FSYNC_SRC_MASK); break; case XAXIVDMA_CHAN_OTHER_FSYNC: /* The other Channel Frame Sync */ CrBits |= (XAXIVDMA_CR_FSYNC_SRC_MASK & ~(1 << 6)); break; case XAXIVDMA_S2MM_TUSER_FSYNC: /* S2MM TUser Sync */ if (Channel->S2MmSOF) { CrBits |= (XAXIVDMA_CR_FSYNC_SRC_MASK & ~(1 << 5)); } else return XST_FAILURE; break; } XAxiVdma_WriteReg(Channel->ChanBase, XAXIVDMA_CR_OFFSET, CrBits); return XST_SUCCESS; } xdbg_printf(XDBG_DEBUG_ERROR, "This bit is not valid for this configuration\n\r"); return XST_FAILURE; } /*****************************************************************************/ /** * Configure Gen Lock Source * * @param InstancePtr is the pointer to the DMA engine to work on * @param Source is the value to set the source of Gen Lock * @param Direction is the DMA channel to work on * * @return * - XST_SUCCESS if successful * - XST_FAILURE if the channel is in GenLock Master Mode. * if C_INCLUDE_INTERNAL_GENLOCK is disabled. * *****************************************************************************/ int XAxiVdma_GenLockSourceSelect(XAxiVdma *InstancePtr, u32 Source, u16 Direction) { XAxiVdma_Channel *Channel, *XChannel; u32 CrBits; if (InstancePtr->HasMm2S && InstancePtr->HasS2Mm && InstancePtr->InternalGenLock) { if (Direction == XAXIVDMA_WRITE) { Channel = XAxiVdma_GetChannel(InstancePtr, Direction); XChannel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_READ); } else { Channel = XAxiVdma_GetChannel(InstancePtr, Direction); XChannel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_WRITE); } if ((Channel->GenLock == XAXIVDMA_GENLOCK_MASTER && XChannel->GenLock == XAXIVDMA_GENLOCK_SLAVE) || (Channel->GenLock == XAXIVDMA_GENLOCK_SLAVE && XChannel->GenLock == XAXIVDMA_GENLOCK_MASTER) || (Channel->GenLock == XAXIVDMA_DYN_GENLOCK_MASTER && XChannel->GenLock == XAXIVDMA_DYN_GENLOCK_SLAVE) || (Channel->GenLock == XAXIVDMA_DYN_GENLOCK_SLAVE && XChannel->GenLock == XAXIVDMA_DYN_GENLOCK_MASTER)) { CrBits = XAxiVdma_ReadReg(Channel->ChanBase, XAXIVDMA_CR_OFFSET); if (Source == XAXIVDMA_INTERNAL_GENLOCK) CrBits |= XAXIVDMA_CR_GENLCK_SRC_MASK; else if (Source == XAXIVDMA_EXTERNAL_GENLOCK) CrBits &= ~XAXIVDMA_CR_GENLCK_SRC_MASK; else { xdbg_printf(XDBG_DEBUG_ERROR, "Invalid argument\n\r"); return XST_FAILURE; } XAxiVdma_WriteReg(Channel->ChanBase, XAXIVDMA_CR_OFFSET, CrBits); return XST_SUCCESS; } } xdbg_printf(XDBG_DEBUG_ERROR, "This bit is not valid for this configuration\n\r"); return XST_FAILURE; } /*****************************************************************************/ /** * Start parking mode on a certain frame * * @param InstancePtr is the pointer to the DMA engine to work on * @param FrameIndex is the frame to park on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * - XST_SUCCESS if everything is fine * - XST_INVALID_PARAM if * . channel is invalid * . FrameIndex is invalid * . Direction is invalid *****************************************************************************/ int XAxiVdma_StartParking(XAxiVdma *InstancePtr, int FrameIndex, u16 Direction) { XAxiVdma_Channel *Channel; u32 FrmBits; u32 RegValue; int Status; if (FrameIndex > XAXIVDMA_FRM_MAX) { xdbg_printf(XDBG_DEBUG_ERROR, "Invalid frame to park on %d\r\n", FrameIndex); return XST_INVALID_PARAM; } if (Direction == XAXIVDMA_READ) { FrmBits = FrameIndex & XAXIVDMA_PARKPTR_READREF_MASK; RegValue = XAxiVdma_ReadReg(InstancePtr->BaseAddr, XAXIVDMA_PARKPTR_OFFSET); RegValue &= ~XAXIVDMA_PARKPTR_READREF_MASK; RegValue |= FrmBits; XAxiVdma_WriteReg(InstancePtr->BaseAddr, XAXIVDMA_PARKPTR_OFFSET, RegValue); } else if (Direction == XAXIVDMA_WRITE) { FrmBits = FrameIndex << XAXIVDMA_WRTREF_SHIFT; FrmBits &= XAXIVDMA_PARKPTR_WRTREF_MASK; RegValue = XAxiVdma_ReadReg(InstancePtr->BaseAddr, XAXIVDMA_PARKPTR_OFFSET); RegValue &= ~XAXIVDMA_PARKPTR_WRTREF_MASK; RegValue |= FrmBits; XAxiVdma_WriteReg(InstancePtr->BaseAddr, XAXIVDMA_PARKPTR_OFFSET, RegValue); } else { /* Invalid direction, do nothing */ return XST_INVALID_PARAM; } Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (Channel->IsValid) { Status = XAxiVdma_ChannelStartParking(Channel); if (Status != XST_SUCCESS) { xdbg_printf(XDBG_DEBUG_ERROR, "Failed to start channel %x\r\n", (unsigned int)Channel); return XST_FAILURE; } } return XST_SUCCESS; } /*****************************************************************************/ /** * Exit parking mode, the channel will return to circular buffer mode * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * None * * @note * If channel is invalid, then do nothing *****************************************************************************/ void XAxiVdma_StopParking(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return; } if (Channel->IsValid) { XAxiVdma_ChannelStopParking(Channel); } return; } /*****************************************************************************/ /** * Start frame count enable on one channel * * This is needed to start limiting the number of frames to transfer so that * software can check the data etc after hardware stops transfer. * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return * None * *****************************************************************************/ void XAxiVdma_StartFrmCntEnable(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (Channel->IsValid) { XAxiVdma_ChannelStartFrmCntEnable(Channel); } } /*****************************************************************************/ /** * Set BD addresses to be different. * * In some systems, it is convenient to put BDs into a certain region of the * memory. This function enables that. * * @param InstancePtr is the pointer to the DMA engine to work on * @param BdAddrPhys is the physical starting address for BDs * @param BdAddrVirt is the Virtual starting address for BDs. For systems that * do not use MMU, then virtual address is the same as physical address * @param NumBds is the number of BDs to setup with. This is required to be * the same as the number of frame stores for that channel * @param Direction is the channel direction * * @return * - XST_SUCCESS for a successful setup * - XST_DEVICE_BUSY if the DMA channel is not idle, BDs are still being used * - XST_INVALID_PARAM if parameters not valid * - XST_DEVICE_NOT_FOUND if the channel is invalid * * @notes * We assume that the memory region starting from BdAddrPhys and BdAddrVirt are * large enough to hold all the BDs. *****************************************************************************/ int XAxiVdma_SetBdAddrs(XAxiVdma *InstancePtr, u32 BdAddrPhys, u32 BdAddrVirt, int NumBds, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (Channel->IsValid) { if (NumBds != Channel->AllCnt) { return XST_INVALID_PARAM; } if (BdAddrPhys & (XAXIVDMA_BD_MINIMUM_ALIGNMENT - 1)) { return XST_INVALID_PARAM; } if (BdAddrVirt & (XAXIVDMA_BD_MINIMUM_ALIGNMENT - 1)) { return XST_INVALID_PARAM; } return XAxiVdma_ChannelSetBdAddrs(Channel, BdAddrPhys, BdAddrVirt); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Start a write operation * * Write corresponds to send data from device to memory * * @param InstancePtr is the pointer to the DMA engine to work on * @param DmaConfigPtr is the pointer to the setup structure * * @return * - XST_SUCCESS for a successful submission * - XST_DEVICE_BUSY if the DMA channel is not idle, BDs are still being used * - XST_INVAID_PARAM if parameters in config structure not valid * - XST_DEVICE_NOT_FOUND if the channel is invalid * *****************************************************************************/ int XAxiVdma_StartWriteFrame(XAxiVdma *InstancePtr, XAxiVdma_DmaSetup *DmaConfigPtr) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_WRITE); if (Channel->IsValid) { return XAxiVdma_ChannelStartTransfer(Channel, (XAxiVdma_ChannelSetup *)DmaConfigPtr); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Start a read operation * * Read corresponds to send data from memory to device * * @param InstancePtr is the pointer to the DMA engine to work on * @param DmaConfigPtr is the pointer to the setup structure * * @return * - XST_SUCCESS for a successful submission * - XST_DEVICE_BUSY if the DMA channel is not idle, BDs are still being used * - XST_INVAID_PARAM if parameters in config structure not valid * - XST_DEVICE_NOT_FOUND if the channel is invalid * *****************************************************************************/ int XAxiVdma_StartReadFrame(XAxiVdma *InstancePtr, XAxiVdma_DmaSetup *DmaConfigPtr) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_READ); if (Channel->IsValid) { return XAxiVdma_ChannelStartTransfer(Channel, (XAxiVdma_ChannelSetup *)DmaConfigPtr); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Configure one DMA channel using the configuration structure * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the DMA channel to work on * @param DmaConfigPtr is the pointer to the setup structure * * @return * - XST_SUCCESS if successful * - XST_DEVICE_BUSY if the DMA channel is not idle, BDs are still being used * - XST_INVAID_PARAM if buffer address not valid, for example, unaligned * address with no DRE built in the hardware, or Direction invalid * - XST_DEVICE_NOT_FOUND if the channel is invalid * *****************************************************************************/ int XAxiVdma_DmaConfig(XAxiVdma *InstancePtr, u16 Direction, XAxiVdma_DmaSetup *DmaConfigPtr) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_INVALID_PARAM; } if (Channel->IsValid) { return XAxiVdma_ChannelConfig(Channel, (XAxiVdma_ChannelSetup *)DmaConfigPtr); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Configure buffer addresses for one DMA channel * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the DMA channel to work on * @param BufferAddrSet is the set of addresses for the transfers * * @return * - XST_SUCCESS if successful * - XST_DEVICE_BUSY if the DMA channel is not idle, BDs are still being used * - XST_INVAID_PARAM if buffer address not valid, for example, unaligned * address with no DRE built in the hardware, or Direction invalid * - XST_DEVICE_NOT_FOUND if the channel is invalid * *****************************************************************************/ int XAxiVdma_DmaSetBufferAddr(XAxiVdma *InstancePtr, u16 Direction, UINTPTR *BufferAddrSet) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_INVALID_PARAM; } if (Channel->IsValid) { return XAxiVdma_ChannelSetBufferAddr(Channel, BufferAddrSet, Channel->NumFrames); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Start one DMA channel * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the DMA channel to work on * * @return * - XST_SUCCESS if channel started successfully * - XST_FAILURE otherwise * - XST_DEVICE_NOT_FOUND if the channel is invalid * - XST_INVALID_PARAM if Direction invalid * *****************************************************************************/ int XAxiVdma_DmaStart(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_INVALID_PARAM; } if (Channel->IsValid) { return XAxiVdma_ChannelStart(Channel); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Stop one DMA channel * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the DMA channel to work on * * @return * None * * @note * If channel is invalid, then do nothing on that channel *****************************************************************************/ void XAxiVdma_DmaStop(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return; } if (Channel->IsValid) { XAxiVdma_ChannelStop(Channel); } return; } /*****************************************************************************/ /** * Dump registers of one DMA channel * * @param InstancePtr is the pointer to the DMA engine to work on * @param Direction is the DMA channel to work on * * @return * None * * @note * If channel is invalid, then do nothing on that channel *****************************************************************************/ void XAxiVdma_DmaRegisterDump(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return; } if (Channel->IsValid) { XAxiVdma_ChannelRegisterDump(Channel); } return; } /*****************************************************************************/ /** * Set the frame counter and delay counter for both channels * * @param InstancePtr is the pointer to the DMA engine to work on * @param CfgPtr is the pointer to the configuration structure * * @return * - XST_SUCCESS if setup finishes successfully * - XST_INVALID_PARAM if the configuration structure has invalid values * - Others if setting channel frame counter fails * * @note * If channel is invalid, then do nothing on that channel *****************************************************************************/ int XAxiVdma_SetFrameCounter(XAxiVdma *InstancePtr, XAxiVdma_FrameCounter *CfgPtr) { int Status; XAxiVdma_Channel *Channel; /* Validate parameters */ Xil_AssertNonvoid(InstancePtr != NULL); Xil_AssertNonvoid(InstancePtr->IsReady == XAXIVDMA_DEVICE_READY); Xil_AssertNonvoid(CfgPtr != NULL); if ((CfgPtr->ReadFrameCount == 0) || (CfgPtr->WriteFrameCount == 0)) { return XST_INVALID_PARAM; } Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_READ); if (Channel->IsValid) { Status = XAxiVdma_ChannelSetFrmCnt(Channel, CfgPtr->ReadFrameCount, CfgPtr->ReadDelayTimerCount); if (Status != XST_SUCCESS) { xdbg_printf(XDBG_DEBUG_ERROR, "Setting read channel frame counter " "failed with %d\r\n", Status); return Status; } } Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_WRITE); if (Channel->IsValid) { Status = XAxiVdma_ChannelSetFrmCnt(Channel, CfgPtr->WriteFrameCount, CfgPtr->WriteDelayTimerCount); if (Status != XST_SUCCESS) { xdbg_printf(XDBG_DEBUG_ERROR, "Setting write channel frame counter " "failed with %d\r\n", Status); return Status; } } return XST_SUCCESS; } /*****************************************************************************/ /** * Get the frame counter and delay counter for both channels * * @param InstancePtr is the pointer to the DMA engine to work on * @param CfgPtr is the configuration structure to contain return values * * @return * None * * @note * If returned frame counter value is 0, then the channel is not valid *****************************************************************************/ void XAxiVdma_GetFrameCounter(XAxiVdma *InstancePtr, XAxiVdma_FrameCounter *CfgPtr) { XAxiVdma_Channel *Channel; u8 FrmCnt; u8 DlyCnt; /* Validate parameters */ Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XAXIVDMA_DEVICE_READY); Xil_AssertVoid(CfgPtr != NULL); /* Use a zero frame counter value to indicate failure */ FrmCnt = 0; Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_READ); if (Channel->IsValid) { XAxiVdma_ChannelGetFrmCnt(Channel, &FrmCnt, &DlyCnt); } CfgPtr->ReadFrameCount = FrmCnt; CfgPtr->ReadDelayTimerCount = DlyCnt; /* Use a zero frame counter value to indicate failure */ FrmCnt = 0; Channel = XAxiVdma_GetChannel(InstancePtr, XAXIVDMA_WRITE); if (Channel->IsValid) { XAxiVdma_ChannelGetFrmCnt(Channel, &FrmCnt, &DlyCnt); } CfgPtr->WriteFrameCount = FrmCnt; CfgPtr->WriteDelayTimerCount = DlyCnt; return; } #include <stdio.h> /*****************************************************************************/ /** * Set the number of frame store buffers to use. * * @param InstancePtr is the XAxiVdma instance to operate on * @param FrmStoreNum is the number of frame store buffers to use. * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return - XST_SUCCESS if operation is successful * - XST_FAILURE if operation fails. * - XST_NO_FEATURE if access to FrameStore register is disabled * @note None * *****************************************************************************/ int XAxiVdma_SetFrmStore(XAxiVdma *InstancePtr, u8 FrmStoreNum, u16 Direction) { XAxiVdma_Channel *Channel; if(FrmStoreNum > InstancePtr->MaxNumFrames) { return XST_FAILURE; } Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_FAILURE; } if(XAxiVdma_ChannelIsRunning(Channel)) { xdbg_printf(XDBG_DEBUG_ERROR, "Cannot set frame store..." "channel is running\r\n"); return XST_FAILURE; } printf( "feature flags %u\n", Channel->DbgFeatureFlags ); if (!(Channel->DbgFeatureFlags & XAXIVDMA_ENABLE_DBG_FRMSTORE_REG)) { xdbg_printf(XDBG_DEBUG_ERROR, "Frame Store Register is disabled\n\r"); return XST_NO_FEATURE; } XAxiVdma_WriteReg(Channel->ChanBase, XAXIVDMA_FRMSTORE_OFFSET, FrmStoreNum & XAXIVDMA_FRMSTORE_MASK); Channel->NumFrames = FrmStoreNum; XAxiVdma_ChannelInit(Channel); return XST_SUCCESS; } /*****************************************************************************/ /** * Get the number of frame store buffers to use. * * @param InstancePtr is the XAxiVdma instance to operate on * @param FrmStoreNum is the number of frame store buffers to use. * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return None * * @note None * *****************************************************************************/ void XAxiVdma_GetFrmStore(XAxiVdma *InstancePtr, u8 *FrmStoreNum, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return; } if (Channel->DbgFeatureFlags & XAXIVDMA_ENABLE_DBG_FRMSTORE_REG) { *FrmStoreNum = (XAxiVdma_ReadReg(Channel->ChanBase, XAXIVDMA_FRMSTORE_OFFSET)) & XAXIVDMA_FRMSTORE_MASK; } else { xdbg_printf(XDBG_DEBUG_ERROR, "Frame Store Register is disabled\n\r"); } } /*****************************************************************************/ /** * Check for DMA Channel Errors. * * @param InstancePtr is the XAxiVdma instance to operate on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * * @return - Errors seen on the channel * - XST_INVALID_PARAM, when channel pointer is invalid. * - XST_DEVICE_NOT_FOUND, when the channel is not valid. * * @note None * *****************************************************************************/ int XAxiVdma_GetDmaChannelErrors(XAxiVdma *InstancePtr, u16 Direction) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_INVALID_PARAM; } if (Channel->IsValid) { return XAxiVdma_ChannelErrors(Channel); } else { return XST_DEVICE_NOT_FOUND; } } /*****************************************************************************/ /** * Clear DMA Channel Errors. * * @param InstancePtr is the XAxiVdma instance to operate on * @param Direction is the channel to work on, use XAXIVDMA_READ/WRITE * @param ErrorMask is the mask of error bits to clear * * @return - XST_SUCCESS, when error bits are cleared. * - XST_INVALID_PARAM, when channel pointer is invalid. * - XST_DEVICE_NOT_FOUND, when the channel is not valid. * * @note None * *****************************************************************************/ int XAxiVdma_ClearDmaChannelErrors(XAxiVdma *InstancePtr, u16 Direction, u32 ErrorMask) { XAxiVdma_Channel *Channel; Channel = XAxiVdma_GetChannel(InstancePtr, Direction); if (!Channel) { return XST_INVALID_PARAM; } if (Channel->IsValid) { XAxiVdma_ClearChannelErrors(Channel, ErrorMask); return XST_SUCCESS; } else { return XST_DEVICE_NOT_FOUND; } } /** @} */
28.646891
81
0.636026
DoubleGithub
c8bd23cdd24d30466f369da83dd9eeec976964bd
8,836
cpp
C++
Arduino/snapshots/20140120-r2454-V0p2-Arduino-KU-beta-13/V0p2_Main/RTC_Support.cpp
opentrv/opentrv-OpenTRV-Arduino-V0p2
746753c88ed426c35ee91fa8933264e8bf2529b5
[ "Apache-2.0" ]
2
2016-11-05T09:59:06.000Z
2018-12-10T17:33:32.000Z
Arduino/snapshots/20140120-r2454-V0p2-Arduino-KU-beta-13/V0p2_Main/RTC_Support.cpp
opentrv/opentrv-OpenTRV-Arduino-V0p2
746753c88ed426c35ee91fa8933264e8bf2529b5
[ "Apache-2.0" ]
2
2017-01-12T14:48:13.000Z
2017-03-13T19:21:49.000Z
Arduino/snapshots/20140120-r2454-V0p2-Arduino-KU-beta-13/V0p2_Main/RTC_Support.cpp
opentrv/opentrv-OpenTRV-Arduino-V0p2
746753c88ed426c35ee91fa8933264e8bf2529b5
[ "Apache-2.0" ]
11
2016-08-15T10:23:09.000Z
2021-09-10T12:48:31.000Z
/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2013 */ #include <util/atomic.h> #include "RTC_Support.h" #include "EEPROM_Utils.h" // Seconds for local time (and assumed UTC) in range [0,59]. // Volatile to allow for async update. // Maintained locally or shadowed from external RTC. // Read and write accesses assumed effectively atomic. // NOT FOR DIRECT ACCESS OUTSIDE RTC ROUTINES. volatile uint_fast8_t _secondsLT; // Minutes since midnight for local time in range [0,1439]. // Must be accessed with interrupts disabled and as if volatile. // Maintained locally or shadowed from external RTC. // NOT FOR DIRECT ACCESS OUTSIDE RTC ROUTINES. volatile uint_least16_t _minutesSinceMidnightLT; // Whole days since the start of 2000/01/01 (ie the midnight between 1999 and 2000), local time. // Must be accessed with interrupts disabled and as if volatile. // This will roll in about 2179. // NOT FOR DIRECT ACCESS OUTSIDE RTC ROUTINES. volatile uint_least16_t _daysSince1999LT; // The encoding for the persisted HH:MM value is as follows. // The top 5 bits are the hour in the range [0,23]. // The bottom 3 bits inidicate the quarter hour as follows: // 111 => :00, 110 => :15, 100 => :30, 000 => :45. // Invalid values (in particular, 0xff, for an erased byte) are ignored. // On the hour the full byte is erased and written written, including the lsbits at 1. // At each quarter hour one of the lsbits is written to zero (no erase is needed). // Thus an hour causes 1 erase and 4 writes (3 of which only affect one bit each). // The AVR EEPROM is rated for 100k cycles per byte (or page, not clear from docs), // where a cycle would normally be 1 erase and 1 write. // At worst, providing that no redundant writes are done, // this causes 35k operations per year for ~3 years of continuous operation. // If changing the bits is the stressful part that wears the EEPROM, // and given that each bit only sees one erase and (at most) one subsequent write to 0 each hour, // it may be reasonable to hope for upwards of 12 years of operation, // in which time the Flash program and other EEPROM contents may have evaporated anyway. // It is best to keep this byte in an EEPROM page without any other critical data // and/or that is subject to significant erase/write cycles of its own, // and where bytes may not be truely independent for wear purposes. // Persist software RTC information to non-volatile (EEPROM) store. // This does not attempt to store full precision of time down to seconds, // but enough to help avoid the clock slipping too much during (say) a battery change. // There is no point calling this more than (say) once per minute, // though it will simply return relatively quickly from redundant calls. // The RTC data is stored so as not to wear out AVR EEPROM for at least several years. // IMPLEMENTATION OF THIS AND THE eeprom_smart_xxx_byte() ROUTINES IS CRITICAL TO PERFORMANCE AND LONGEVITY. void persistRTC() { ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { uint8_t quarterHours = (_minutesSinceMidnightLT / 15); uint8_t targetByte = (quarterHours << 1) & ~7U; // Bit pattern now hhhhh000 where hhhhh is whole hours [0,23]. switch(quarterHours & 3) { case 0: targetByte |= 7; break; case 1: targetByte |= 3; break; case 2: targetByte |= 1; break; } // Update if target HH:MM not already correct. const uint8_t persistedValue = eeprom_read_byte((uint8_t*)EE_START_RTC_HHMM_PERSIST); if(persistedValue != targetByte) { // Where it is not possible to get the target value just by setting bits to 0, // eg for a new hour (ie completely different hour to that in EEPROM and on roll to new hour), // then do a full erase/write... //if((0 == quarterHours) || ((persistedValue & 0xf8) != (targetByte & 0xf8))) if(targetByte != (persistedValue & targetByte)) { eeprom_write_byte((uint8_t*)EE_START_RTC_HHMM_PERSIST, targetByte); } // Else do a write without erase, typically clearing the quarter bits one at a time... else { eeprom_smart_clear_bits((uint8_t*)EE_START_RTC_HHMM_PERSIST, targetByte); } // Also persist the current days if not up to date. const uint16_t days = eeprom_read_word((uint16_t*)EE_START_RTC_DAY_PERSIST); if(days != _daysSince1999LT) { eeprom_write_word((uint16_t*)EE_START_RTC_DAY_PERSIST, _daysSince1999LT); } } } } // Restore software RTC information from non-volatile (EEPROM) store, if possible. // Returns true if the persisted data seemed valid and was restored, in full or part. // To void on average using 15/2 minutes at each reset/restart, // this starts the internal time a little over half way into the restored 15-minute slot. bool restoreRTC() { uint8_t persistedValue; ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { // Restore the persisted days, though ignore if apparently unset (all 1s). const uint16_t days = eeprom_read_word((uint16_t*)EE_START_RTC_DAY_PERSIST); if(days != (uint16_t)~0U) { _daysSince1999LT = days; } // Now recover persisted HH:MM value. persistedValue = eeprom_read_byte((uint8_t*)EE_START_RTC_HHMM_PERSIST); } // Abort if value clearly invalid, eg likely an unprogrammed (0xff) byte. if(persistedValue >= (24 << 3)) { return(false); } uint_least16_t minutesSinceMidnight = (persistedValue >> 3) * 60; minutesSinceMidnight += 8; // Start just over half-way into one quantum to minimise average time lost on restart. const uint8_t lowBits = persistedValue & 7; // Extract quarter-hour bits. switch(lowBits) { case 0: minutesSinceMidnight += 45; break; case 1: minutesSinceMidnight += 30; break; case 3: minutesSinceMidnight += 15; break; case 7: break; // Nothing to add, but a valid 0-quarter bit pattern. default: return(false); // Invalid bit pattern: abort. } // Set the hours and minutes (atomically). // Deliberately leave the seconds unset to avoid units becoming too synchronised with one another, increasing TX collisions, etc. ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { _minutesSinceMidnightLT = minutesSinceMidnight; } return(true); } // Get local time seconds from RTC [0,59]. // Is as fast as reasonably practical. // Returns a consistent atomic snapshot. // Note that if TWO_S_TICK_RTC_SUPPORT is defined then only even seconds will be seen. #ifndef getSecondsLT uint_fast8_t getSecondsLT() { return(_secondsLT); } // Assumed atomic. #endif // Get minutes since midnight local time [0,1439]. // Useful to fetch time atomically for scheduling purposes. // Preserves interrupt state. uint_least16_t getMinutesSinceMidnightLT() { uint_least16_t result; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { result = _minutesSinceMidnightLT; } return(result); } // Get local time minutes from RTC [0,59]. uint_least8_t getMinutesLT() { return(getMinutesSinceMidnightLT() % 60); } // Get local time hours from RTC [0,23]. uint_least8_t getHoursLT() { return(getMinutesSinceMidnightLT() / 60); } // Get whole days since the start of 2000/01/01 (ie the midnight between 1999 and 2000), local time. // This will roll in about 2179, by which time I will not care. uint_least16_t getDaysSince1999LT() { uint_least16_t result; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { result = _daysSince1999LT; } return(result); } // Set time as hours [0,23] and minutes [0,59]. // Will ignore attempts to set bad values and return false in that case. // Returns true if all OK and the time has been set. // Does not attempt to set seconds. // Thread/interrupt safe, but do not call this from an ISR. // Will persist time to survive reset as neceessary. bool setHoursMinutesLT(int hours, int minutes) { if((hours < 0) || (hours > 23) || (minutes < 0) || (minutes > 59)) { return(false); } // Invalid time. const uint_least16_t computedMinutesSinceMidnightLT = (uint_least16_t) ((60 * hours) + minutes); ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if(computedMinutesSinceMidnightLT != _minutesSinceMidnightLT) { // If time has changed then store it locally and persist it if need be. _minutesSinceMidnightLT = computedMinutesSinceMidnightLT; persistRTC(); } } return(true); // Assume set and persisted OK. }
41.28972
131
0.728837
opentrv
c8bdc88175c14901033cdf982783ac9858047894
3,433
cc
C++
src/session.cc
scylla-zpp-blas/scylla_modern_cpp_driver
a9ea3ca5b2d2921af497164994d64ddf09e52fd9
[ "Apache-2.0" ]
1
2021-07-25T06:59:40.000Z
2021-07-25T06:59:40.000Z
src/session.cc
scylla-zpp-blas/scylla_modern_cpp_driver
a9ea3ca5b2d2921af497164994d64ddf09e52fd9
[ "Apache-2.0" ]
7
2020-12-25T10:17:24.000Z
2021-03-04T20:19:58.000Z
src/session.cc
scylla-zpp-blas/scylla_modern_cpp_driver
a9ea3ca5b2d2921af497164994d64ddf09e52fd9
[ "Apache-2.0" ]
null
null
null
#include "cassandra.h" #include "session.hh" #include "future.hh" #include "exceptions.hh" namespace scmd { session::session(const std::string &address, const std::string &port) { _cluster = cass_cluster_new(); _session = cass_session_new(); cass_cluster_set_contact_points(_cluster, address.c_str()); if (!port.empty()) { cass_cluster_set_port(_cluster, std::stoi(port)); } cass_cluster_set_protocol_version(_cluster, CASS_PROTOCOL_VERSION_V4); CassFuture *connect_future = cass_session_connect(_session, _cluster); auto cleanup = [=]() { cass_future_free(connect_future); }; scmd_internal::throw_on_cass_error(cass_future_error_code(connect_future), cleanup); cleanup(); } session::session(session &&other) noexcept : _cluster(std::exchange(other._cluster, nullptr)), _session(std::exchange(other._session, nullptr)) {} session &session::operator=(session &&other) noexcept { std::swap(_cluster, other._cluster); std::swap(_session, other._session); return *this; } session::~session() { if(this->_session) { cass_session_free(_session); } if(this->_cluster) { cass_cluster_free(_cluster); } } prepared_query session::prepare(const std::string& query) { scmd::future future(cass_session_prepare(_session, query.c_str())); return future.get_prepared(); } const CassPrepared *session::prepare_raw(const std::string &query) { scmd::future future(cass_session_prepare(_session, query.c_str())); return future.get_prepared_raw(); } future session::execute_async(const statement &statement) { return future(cass_session_execute(_session, statement.get_statement())); } future session::execute_async(statement &&statement) { return future(cass_session_execute(_session, statement.get_statement())); } future session::execute_async(const std::string &query) { return execute_async(statement(query)); } future session::execute_async(std::string &&query) { return execute_async(statement(std::move(query))); } future session::execute_async(const batch_query &query) { return future(cass_session_execute_batch(_session, query.get_query())); } future session::execute_async(batch_query &&query) { return future(cass_session_execute_batch(_session, query.get_query())); } future session::execute_async(const prepared_query &query) { return execute_async(query.get_statement()); } future session::execute_async(prepared_query &&query) { return execute_async(query.get_statement()); } query_result session::execute(const statement &statement) { return execute_async(statement).get_result(); } query_result session::execute(statement &&statement) { return execute_async(std::move(statement)).get_result(); } query_result session::execute(const std::string &query) { return execute_async(query).get_result(); } query_result session::execute(std::string &&query) { return execute_async(std::move(query)).get_result(); } query_result session::execute(const batch_query &query) { return execute_async(query).get_result(); } query_result session::execute(batch_query &&query) { return execute_async(std::move(query)).get_result(); } query_result session::execute(const prepared_query &query) { return execute(query.get_statement()); } query_result session::execute(prepared_query &&query) { return execute(query.get_statement()); } } // namespace scmd
30.114035
107
0.736091
scylla-zpp-blas
c8c0b6db9571fb033014899ba237c032507b36f1
6,044
hpp
C++
components/nif/node.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/nif/node.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/nif/node.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef OPENMW_COMPONENTS_NIF_NODE_HPP #define OPENMW_COMPONENTS_NIF_NODE_HPP #include <OgreMatrix4.h> #include "controlled.hpp" #include "extra.hpp" #include "data.hpp" #include "property.hpp" #include "niftypes.hpp" #include "controller.hpp" #include "base.hpp" namespace Nif { class NiNode; /** A Node is an object that's part of the main NIF tree. It has parent node (unless it's the root), and transformation (location and rotation) relative to it's parent. */ class Node : public Named { public: // Node flags. Interpretation depends somewhat on the type of node. int flags; Transformation trafo; Ogre::Vector3 velocity; // Unused? Might be a run-time game state PropertyList props; // Bounding box info bool hasBounds; Ogre::Vector3 boundPos; Ogre::Matrix3 boundRot; Ogre::Vector3 boundXYZ; // Box size void read(NIFStream *nif) { Named::read(nif); flags = nif->getUShort(); trafo = nif->getTrafo(); velocity = nif->getVector3(); props.read(nif); hasBounds = !!nif->getInt(); if(hasBounds) { nif->getInt(); // always 1 boundPos = nif->getVector3(); boundRot = nif->getMatrix3(); boundXYZ = nif->getVector3(); } parent = NULL; boneTrafo = NULL; boneIndex = -1; } void post(NIFFile *nif) { Named::post(nif); props.post(nif); } // Parent node, or NULL for the root node. As far as I'm aware, only // NiNodes (or types derived from NiNodes) can be parents. NiNode *parent; // Bone transformation. If set, node is a part of a skeleton. const NiSkinData::BoneTrafo *boneTrafo; // Bone weight info, from NiSkinData const NiSkinData::BoneInfo *boneInfo; // Bone index. If -1, this node is either not a bone, or if // boneTrafo is set it is the root bone in the skeleton. short boneIndex; void makeRootBone(const NiSkinData::BoneTrafo *tr) { boneTrafo = tr; boneIndex = -1; } void makeBone(short ind, const NiSkinData::BoneInfo &bi) { boneInfo = &bi; boneTrafo = &bi.trafo; boneIndex = ind; } void getProperties(const Nif::NiTexturingProperty *&texprop, const Nif::NiMaterialProperty *&matprop, const Nif::NiAlphaProperty *&alphaprop, const Nif::NiVertexColorProperty *&vertprop, const Nif::NiZBufferProperty *&zprop, const Nif::NiSpecularProperty *&specprop, const Nif::NiWireframeProperty *&wireprop) const; Ogre::Matrix4 getLocalTransform() const; Ogre::Matrix4 getWorldTransform() const; }; struct NiNode : Node { NodeList children; NodeList effects; enum Flags { Flag_Hidden = 0x0001, Flag_MeshCollision = 0x0002, Flag_BBoxCollision = 0x0004 }; enum BSAnimFlags { AnimFlag_AutoPlay = 0x0020 }; enum BSParticleFlags { ParticleFlag_AutoPlay = 0x0020, ParticleFlag_LocalSpace = 0x0080 }; enum ControllerFlags { ControllerFlag_Active = 0x8 }; void read(NIFStream *nif) { Node::read(nif); children.read(nif); effects.read(nif); // Discard tranformations for the root node, otherwise some meshes // occasionally get wrong orientation. Only for NiNode-s for now, but // can be expanded if needed. if (0 == recIndex) { static_cast<Nif::Node*>(this)->trafo = Nif::Transformation::getIdentity(); } } void post(NIFFile *nif) { Node::post(nif); children.post(nif); effects.post(nif); for(size_t i = 0;i < children.length();i++) { // Why would a unique list of children contain empty refs? if(!children[i].empty()) children[i]->parent = this; } } }; struct NiTriShape : Node { /* Possible flags: 0x40 - mesh has no vertex normals ? Only flags included in 0x47 (ie. 0x01, 0x02, 0x04 and 0x40) have been observed so far. */ NiTriShapeDataPtr data; NiSkinInstancePtr skin; void read(NIFStream *nif) { Node::read(nif); data.read(nif); skin.read(nif); } void post(NIFFile *nif) { Node::post(nif); data.post(nif); skin.post(nif); } }; struct NiCamera : Node { struct Camera { // Camera frustrum float left, right, top, bottom, nearDist, farDist; // Viewport float vleft, vright, vtop, vbottom; // Level of detail modifier float LOD; void read(NIFStream *nif) { left = nif->getFloat(); right = nif->getFloat(); top = nif->getFloat(); bottom = nif->getFloat(); nearDist = nif->getFloat(); farDist = nif->getFloat(); vleft = nif->getFloat(); vright = nif->getFloat(); vtop = nif->getFloat(); vbottom = nif->getFloat(); LOD = nif->getFloat(); } }; Camera cam; void read(NIFStream *nif) { Node::read(nif); cam.read(nif); nif->getInt(); // -1 nif->getInt(); // 0 } }; struct NiAutoNormalParticles : Node { NiAutoNormalParticlesDataPtr data; void read(NIFStream *nif) { Node::read(nif); data.read(nif); nif->getInt(); // -1 } void post(NIFFile *nif) { Node::post(nif); data.post(nif); } }; struct NiRotatingParticles : Node { NiRotatingParticlesDataPtr data; void read(NIFStream *nif) { Node::read(nif); data.read(nif); nif->getInt(); // -1 } void post(NIFFile *nif) { Node::post(nif); data.post(nif); } }; } // Namespace #endif
22.721805
86
0.564527
Bodillium
c8c6f5f989b781f85909b8ad4036810e6e1269d3
26,774
cc
C++
modules/rtp_rtcp/source/rtp_format_h264.cc
na-g/webrtc-tracking
6b33e602138812e6dfd01d29a9373535316fc6a0
[ "BSD-3-Clause" ]
2
2019-09-01T23:36:33.000Z
2020-04-13T11:40:13.000Z
modules/rtp_rtcp/source/rtp_format_h264.cc
na-g/webrtc-tracking
6b33e602138812e6dfd01d29a9373535316fc6a0
[ "BSD-3-Clause" ]
2
2019-04-26T04:57:02.000Z
2019-06-11T17:55:16.000Z
modules/rtp_rtcp/source/rtp_format_h264.cc
caffeinetv/webrtc
2e79d2b398b430348845e5d5deccb66bca78f1a1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/rtp_rtcp/source/rtp_format_h264.h" #include <string.h> #include <memory> #include <utility> #include <vector> #include "common_video/h264/h264_common.h" #include "common_video/h264/pps_parser.h" #include "common_video/h264/sps_parser.h" #include "common_video/h264/sps_vui_rewriter.h" #include "modules/include/module_common_types.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/system/fallthrough.h" #include "system_wrappers/include/metrics.h" namespace webrtc { namespace { static const size_t kNalHeaderSize = 1; static const size_t kFuAHeaderSize = 2; static const size_t kLengthFieldSize = 2; static const size_t kStapAHeaderSize = kNalHeaderSize + kLengthFieldSize; static const char* kSpsValidHistogramName = "WebRTC.Video.H264.SpsValid"; enum SpsValidEvent { kReceivedSpsPocOk = 0, kReceivedSpsVuiOk = 1, kReceivedSpsRewritten = 2, kReceivedSpsParseFailure = 3, kSentSpsPocOk = 4, kSentSpsVuiOk = 5, kSentSpsRewritten = 6, kSentSpsParseFailure = 7, kSpsRewrittenMax = 8 }; // Bit masks for FU (A and B) indicators. enum NalDefs : uint8_t { kFBit = 0x80, kNriMask = 0x60, kTypeMask = 0x1F }; // Bit masks for FU (A and B) headers. enum FuDefs : uint8_t { kSBit = 0x80, kEBit = 0x40, kRBit = 0x20 }; // TODO(pbos): Avoid parsing this here as well as inside the jitter buffer. bool ParseStapAStartOffsets(const uint8_t* nalu_ptr, size_t length_remaining, std::vector<size_t>* offsets) { size_t offset = 0; while (length_remaining > 0) { // Buffer doesn't contain room for additional nalu length. if (length_remaining < sizeof(uint16_t)) return false; uint16_t nalu_size = ByteReader<uint16_t>::ReadBigEndian(nalu_ptr); nalu_ptr += sizeof(uint16_t); length_remaining -= sizeof(uint16_t); if (nalu_size > length_remaining) return false; nalu_ptr += nalu_size; length_remaining -= nalu_size; offsets->push_back(offset + kStapAHeaderSize); offset += kLengthFieldSize + nalu_size; } return true; } } // namespace RtpPacketizerH264::RtpPacketizerH264(size_t max_payload_len, size_t last_packet_reduction_len, H264PacketizationMode packetization_mode) : max_payload_len_(max_payload_len), last_packet_reduction_len_(last_packet_reduction_len), num_packets_left_(0), packetization_mode_(packetization_mode) { // Guard against uninitialized memory in packetization_mode. RTC_CHECK(packetization_mode == H264PacketizationMode::NonInterleaved || packetization_mode == H264PacketizationMode::SingleNalUnit); RTC_CHECK_GT(max_payload_len, last_packet_reduction_len); } RtpPacketizerH264::~RtpPacketizerH264() {} RtpPacketizerH264::Fragment::~Fragment() = default; RtpPacketizerH264::Fragment::Fragment(const uint8_t* buffer, size_t length) : buffer(buffer), length(length) {} RtpPacketizerH264::Fragment::Fragment(const Fragment& fragment) : buffer(fragment.buffer), length(fragment.length) {} size_t RtpPacketizerH264::SetPayloadData( const uint8_t* payload_data, size_t payload_size, const RTPFragmentationHeader* fragmentation) { RTC_DCHECK(packets_.empty()); RTC_DCHECK(input_fragments_.empty()); RTC_DCHECK(fragmentation); for (int i = 0; i < fragmentation->fragmentationVectorSize; ++i) { const uint8_t* buffer = &payload_data[fragmentation->fragmentationOffset[i]]; size_t length = fragmentation->fragmentationLength[i]; bool updated_sps = false; H264::NaluType nalu_type = H264::ParseNaluType(buffer[0]); if (nalu_type == H264::NaluType::kSps) { // Check if stream uses picture order count type 0, and if so rewrite it // to enable faster decoding. Streams in that format incur additional // delay because it allows decode order to differ from render order. // The mechanism used is to rewrite (edit or add) the SPS's VUI to contain // restrictions on the maximum number of reordered pictures. This reduces // latency significantly, though it still adds about a frame of latency to // decoding. // Note that we do this rewriting both here (send side, in order to // protect legacy receive clients) and below in // RtpDepacketizerH264::ParseSingleNalu (receive side, in orderer to // protect us from unknown or legacy send clients). absl::optional<SpsParser::SpsState> sps; std::unique_ptr<rtc::Buffer> output_buffer(new rtc::Buffer()); // Add the type header to the output buffer first, so that the rewriter // can append modified payload on top of that. output_buffer->AppendData(buffer[0]); SpsVuiRewriter::ParseResult result = SpsVuiRewriter::ParseAndRewriteSps( buffer + H264::kNaluTypeSize, length - H264::kNaluTypeSize, &sps, output_buffer.get()); switch (result) { case SpsVuiRewriter::ParseResult::kVuiRewritten: input_fragments_.push_back( Fragment(output_buffer->data(), output_buffer->size())); input_fragments_.rbegin()->tmp_buffer = std::move(output_buffer); updated_sps = true; RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kSentSpsRewritten, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kPocOk: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kSentSpsPocOk, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kVuiOk: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kSentSpsVuiOk, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kFailure: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kSentSpsParseFailure, SpsValidEvent::kSpsRewrittenMax); break; } } if (!updated_sps) input_fragments_.push_back(Fragment(buffer, length)); } if (!GeneratePackets()) { // If failed to generate all the packets, discard already generated // packets in case the caller would ignore return value and still try to // call NextPacket(). num_packets_left_ = 0; while (!packets_.empty()) { packets_.pop(); } return 0; } return num_packets_left_; } bool RtpPacketizerH264::GeneratePackets() { for (size_t i = 0; i < input_fragments_.size();) { switch (packetization_mode_) { case H264PacketizationMode::SingleNalUnit: if (!PacketizeSingleNalu(i)) return false; ++i; break; case H264PacketizationMode::NonInterleaved: size_t fragment_len = input_fragments_[i].length; if (i + 1 == input_fragments_.size()) { // Pretend that last fragment is larger instead of making last packet // smaller. fragment_len += last_packet_reduction_len_; } if (fragment_len > max_payload_len_) { PacketizeFuA(i); ++i; } else { i = PacketizeStapA(i); } break; } } return true; } void RtpPacketizerH264::PacketizeFuA(size_t fragment_index) { // Fragment payload into packets (FU-A). // Strip out the original header and leave room for the FU-A header. const Fragment& fragment = input_fragments_[fragment_index]; bool is_last_fragment = fragment_index + 1 == input_fragments_.size(); size_t payload_left = fragment.length - kNalHeaderSize; size_t offset = kNalHeaderSize; size_t per_packet_capacity = max_payload_len_ - kFuAHeaderSize; // Instead of making the last packet smaller we pretend that all packets are // of the same size but we write additional virtual payload to the last // packet. size_t extra_len = is_last_fragment ? last_packet_reduction_len_ : 0; // Integer divisions with rounding up. Minimal number of packets to fit all // payload and virtual payload. size_t num_packets = (payload_left + extra_len + (per_packet_capacity - 1)) / per_packet_capacity; // Bytes per packet. Average rounded down. size_t payload_per_packet = (payload_left + extra_len) / num_packets; // We make several first packets to be 1 bytes smaller than the rest. // i.e 14 bytes splitted in 4 packets would be 3+3+4+4. size_t num_larger_packets = (payload_left + extra_len) % num_packets; num_packets_left_ += num_packets; while (payload_left > 0) { // Increase payload per packet at the right time. if (num_packets == num_larger_packets) ++payload_per_packet; size_t packet_length = payload_per_packet; if (payload_left <= packet_length) { // Last portion of the payload packet_length = payload_left; // One additional packet may be used for extensions in the last packet. // Together with last payload packet there may be at most 2 of them. RTC_DCHECK_LE(num_packets, 2); if (num_packets == 2) { // Whole payload fits in the first num_packets-1 packets but extra // packet is used for virtual payload. Leave at least one byte of data // for the last packet. --packet_length; } } RTC_CHECK_GT(packet_length, 0); packets_.push(PacketUnit(Fragment(fragment.buffer + offset, packet_length), offset - kNalHeaderSize == 0, payload_left == packet_length, false, fragment.buffer[0])); offset += packet_length; payload_left -= packet_length; --num_packets; } RTC_CHECK_EQ(0, payload_left); } size_t RtpPacketizerH264::PacketizeStapA(size_t fragment_index) { // Aggregate fragments into one packet (STAP-A). size_t payload_size_left = max_payload_len_; int aggregated_fragments = 0; size_t fragment_headers_length = 0; const Fragment* fragment = &input_fragments_[fragment_index]; RTC_CHECK_GE(payload_size_left, fragment->length); ++num_packets_left_; while (payload_size_left >= fragment->length + fragment_headers_length && (fragment_index + 1 < input_fragments_.size() || payload_size_left >= fragment->length + fragment_headers_length + last_packet_reduction_len_)) { RTC_CHECK_GT(fragment->length, 0); packets_.push(PacketUnit(*fragment, aggregated_fragments == 0, false, true, fragment->buffer[0])); payload_size_left -= fragment->length; payload_size_left -= fragment_headers_length; fragment_headers_length = kLengthFieldSize; // If we are going to try to aggregate more fragments into this packet // we need to add the STAP-A NALU header and a length field for the first // NALU of this packet. if (aggregated_fragments == 0) fragment_headers_length += kNalHeaderSize + kLengthFieldSize; ++aggregated_fragments; // Next fragment. ++fragment_index; if (fragment_index == input_fragments_.size()) break; fragment = &input_fragments_[fragment_index]; } RTC_CHECK_GT(aggregated_fragments, 0); packets_.back().last_fragment = true; return fragment_index; } bool RtpPacketizerH264::PacketizeSingleNalu(size_t fragment_index) { // Add a single NALU to the queue, no aggregation. size_t payload_size_left = max_payload_len_; if (fragment_index + 1 == input_fragments_.size()) payload_size_left -= last_packet_reduction_len_; const Fragment* fragment = &input_fragments_[fragment_index]; if (payload_size_left < fragment->length) { RTC_LOG(LS_ERROR) << "Failed to fit a fragment to packet in SingleNalu " "packetization mode. Payload size left " << payload_size_left << ", fragment length " << fragment->length << ", packet capacity " << max_payload_len_; return false; } RTC_CHECK_GT(fragment->length, 0u); packets_.push(PacketUnit(*fragment, true /* first */, true /* last */, false /* aggregated */, fragment->buffer[0])); ++num_packets_left_; return true; } bool RtpPacketizerH264::NextPacket(RtpPacketToSend* rtp_packet) { RTC_DCHECK(rtp_packet); if (packets_.empty()) { return false; } PacketUnit packet = packets_.front(); if (packet.first_fragment && packet.last_fragment) { // Single NAL unit packet. size_t bytes_to_send = packet.source_fragment.length; uint8_t* buffer = rtp_packet->AllocatePayload(bytes_to_send); memcpy(buffer, packet.source_fragment.buffer, bytes_to_send); packets_.pop(); input_fragments_.pop_front(); } else if (packet.aggregated) { RTC_CHECK(H264PacketizationMode::NonInterleaved == packetization_mode_); bool is_last_packet = num_packets_left_ == 1; NextAggregatePacket(rtp_packet, is_last_packet); } else { RTC_CHECK(H264PacketizationMode::NonInterleaved == packetization_mode_); NextFragmentPacket(rtp_packet); } RTC_DCHECK_LE(rtp_packet->payload_size(), max_payload_len_); if (packets_.empty()) { RTC_DCHECK_LE(rtp_packet->payload_size(), max_payload_len_ - last_packet_reduction_len_); } rtp_packet->SetMarker(packets_.empty()); --num_packets_left_; return true; } void RtpPacketizerH264::NextAggregatePacket(RtpPacketToSend* rtp_packet, bool last) { uint8_t* buffer = rtp_packet->AllocatePayload( last ? max_payload_len_ - last_packet_reduction_len_ : max_payload_len_); RTC_DCHECK(buffer); PacketUnit* packet = &packets_.front(); RTC_CHECK(packet->first_fragment); // STAP-A NALU header. buffer[0] = (packet->header & (kFBit | kNriMask)) | H264::NaluType::kStapA; size_t index = kNalHeaderSize; bool is_last_fragment = packet->last_fragment; while (packet->aggregated) { const Fragment& fragment = packet->source_fragment; // Add NAL unit length field. ByteWriter<uint16_t>::WriteBigEndian(&buffer[index], fragment.length); index += kLengthFieldSize; // Add NAL unit. memcpy(&buffer[index], fragment.buffer, fragment.length); index += fragment.length; packets_.pop(); input_fragments_.pop_front(); if (is_last_fragment) break; packet = &packets_.front(); is_last_fragment = packet->last_fragment; } RTC_CHECK(is_last_fragment); rtp_packet->SetPayloadSize(index); } void RtpPacketizerH264::NextFragmentPacket(RtpPacketToSend* rtp_packet) { PacketUnit* packet = &packets_.front(); // NAL unit fragmented over multiple packets (FU-A). // We do not send original NALU header, so it will be replaced by the // FU indicator header of the first packet. uint8_t fu_indicator = (packet->header & (kFBit | kNriMask)) | H264::NaluType::kFuA; uint8_t fu_header = 0; // S | E | R | 5 bit type. fu_header |= (packet->first_fragment ? kSBit : 0); fu_header |= (packet->last_fragment ? kEBit : 0); uint8_t type = packet->header & kTypeMask; fu_header |= type; const Fragment& fragment = packet->source_fragment; uint8_t* buffer = rtp_packet->AllocatePayload(kFuAHeaderSize + fragment.length); buffer[0] = fu_indicator; buffer[1] = fu_header; memcpy(buffer + kFuAHeaderSize, fragment.buffer, fragment.length); if (packet->last_fragment) input_fragments_.pop_front(); packets_.pop(); } std::string RtpPacketizerH264::ToString() { return "RtpPacketizerH264"; } RtpDepacketizerH264::RtpDepacketizerH264() : offset_(0), length_(0) {} RtpDepacketizerH264::~RtpDepacketizerH264() {} bool RtpDepacketizerH264::Parse(ParsedPayload* parsed_payload, const uint8_t* payload_data, size_t payload_data_length) { RTC_CHECK(parsed_payload != nullptr); if (payload_data_length == 0) { RTC_LOG(LS_ERROR) << "Empty payload."; return false; } offset_ = 0; length_ = payload_data_length; modified_buffer_.reset(); uint8_t nal_type = payload_data[0] & kTypeMask; parsed_payload->type.Video.codecHeader.H264.nalus_length = 0; if (nal_type == H264::NaluType::kFuA) { // Fragmented NAL units (FU-A). if (!ParseFuaNalu(parsed_payload, payload_data)) return false; } else { // We handle STAP-A and single NALU's the same way here. The jitter buffer // will depacketize the STAP-A into NAL units later. // TODO(sprang): Parse STAP-A offsets here and store in fragmentation vec. if (!ProcessStapAOrSingleNalu(parsed_payload, payload_data)) return false; } const uint8_t* payload = modified_buffer_ ? modified_buffer_->data() : payload_data; parsed_payload->payload = payload + offset_; parsed_payload->payload_length = length_; return true; } bool RtpDepacketizerH264::ProcessStapAOrSingleNalu( ParsedPayload* parsed_payload, const uint8_t* payload_data) { parsed_payload->type.Video.width = 0; parsed_payload->type.Video.height = 0; parsed_payload->type.Video.codec = kVideoCodecH264; parsed_payload->type.Video.simulcastIdx = 0; parsed_payload->type.Video.is_first_packet_in_frame = true; RTPVideoHeaderH264* h264_header = &parsed_payload->type.Video.codecHeader.H264; const uint8_t* nalu_start = payload_data + kNalHeaderSize; const size_t nalu_length = length_ - kNalHeaderSize; uint8_t nal_type = payload_data[0] & kTypeMask; std::vector<size_t> nalu_start_offsets; if (nal_type == H264::NaluType::kStapA) { // Skip the StapA header (StapA NAL type + length). if (length_ <= kStapAHeaderSize) { RTC_LOG(LS_ERROR) << "StapA header truncated."; return false; } if (!ParseStapAStartOffsets(nalu_start, nalu_length, &nalu_start_offsets)) { RTC_LOG(LS_ERROR) << "StapA packet with incorrect NALU packet lengths."; return false; } h264_header->packetization_type = kH264StapA; nal_type = payload_data[kStapAHeaderSize] & kTypeMask; } else { h264_header->packetization_type = kH264SingleNalu; nalu_start_offsets.push_back(0); } h264_header->nalu_type = nal_type; parsed_payload->frame_type = kVideoFrameDelta; nalu_start_offsets.push_back(length_ + kLengthFieldSize); // End offset. for (size_t i = 0; i < nalu_start_offsets.size() - 1; ++i) { size_t start_offset = nalu_start_offsets[i]; // End offset is actually start offset for next unit, excluding length field // so remove that from this units length. size_t end_offset = nalu_start_offsets[i + 1] - kLengthFieldSize; if (end_offset - start_offset < H264::kNaluTypeSize) { RTC_LOG(LS_ERROR) << "STAP-A packet too short"; return false; } NaluInfo nalu; nalu.type = payload_data[start_offset] & kTypeMask; nalu.sps_id = -1; nalu.pps_id = -1; start_offset += H264::kNaluTypeSize; switch (nalu.type) { case H264::NaluType::kSps: { // Check if VUI is present in SPS and if it needs to be modified to // avoid // excessive decoder latency. // Copy any previous data first (likely just the first header). std::unique_ptr<rtc::Buffer> output_buffer(new rtc::Buffer()); if (start_offset) output_buffer->AppendData(payload_data, start_offset); absl::optional<SpsParser::SpsState> sps; SpsVuiRewriter::ParseResult result = SpsVuiRewriter::ParseAndRewriteSps( &payload_data[start_offset], end_offset - start_offset, &sps, output_buffer.get()); switch (result) { case SpsVuiRewriter::ParseResult::kVuiRewritten: if (modified_buffer_) { RTC_LOG(LS_WARNING) << "More than one H264 SPS NAL units needing " "rewriting found within a single STAP-A packet. " "Keeping the first and rewriting the last."; } // Rewrite length field to new SPS size. if (h264_header->packetization_type == kH264StapA) { size_t length_field_offset = start_offset - (H264::kNaluTypeSize + kLengthFieldSize); // Stap-A Length includes payload data and type header. size_t rewritten_size = output_buffer->size() - start_offset + H264::kNaluTypeSize; ByteWriter<uint16_t>::WriteBigEndian( &(*output_buffer)[length_field_offset], rewritten_size); } // Append rest of packet. output_buffer->AppendData( &payload_data[end_offset], nalu_length + kNalHeaderSize - end_offset); modified_buffer_ = std::move(output_buffer); length_ = modified_buffer_->size(); RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kReceivedSpsRewritten, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kPocOk: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kReceivedSpsPocOk, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kVuiOk: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kReceivedSpsVuiOk, SpsValidEvent::kSpsRewrittenMax); break; case SpsVuiRewriter::ParseResult::kFailure: RTC_HISTOGRAM_ENUMERATION(kSpsValidHistogramName, SpsValidEvent::kReceivedSpsParseFailure, SpsValidEvent::kSpsRewrittenMax); break; } if (sps) { parsed_payload->type.Video.width = sps->width; parsed_payload->type.Video.height = sps->height; nalu.sps_id = sps->id; } else { RTC_LOG(LS_WARNING) << "Failed to parse SPS id from SPS slice."; } parsed_payload->frame_type = kVideoFrameKey; break; } case H264::NaluType::kPps: { uint32_t pps_id; uint32_t sps_id; if (PpsParser::ParsePpsIds(&payload_data[start_offset], end_offset - start_offset, &pps_id, &sps_id)) { nalu.pps_id = pps_id; nalu.sps_id = sps_id; } else { RTC_LOG(LS_WARNING) << "Failed to parse PPS id and SPS id from PPS slice."; } break; } case H264::NaluType::kIdr: parsed_payload->frame_type = kVideoFrameKey; RTC_FALLTHROUGH(); case H264::NaluType::kSlice: { absl::optional<uint32_t> pps_id = PpsParser::ParsePpsIdFromSlice( &payload_data[start_offset], end_offset - start_offset); if (pps_id) { nalu.pps_id = *pps_id; } else { RTC_LOG(LS_WARNING) << "Failed to parse PPS id from slice of type: " << static_cast<int>(nalu.type); } break; } // Slices below don't contain SPS or PPS ids. case H264::NaluType::kAud: case H264::NaluType::kEndOfSequence: case H264::NaluType::kEndOfStream: case H264::NaluType::kFiller: case H264::NaluType::kSei: break; case H264::NaluType::kStapA: case H264::NaluType::kFuA: RTC_LOG(LS_WARNING) << "Unexpected STAP-A or FU-A received."; return false; } RTPVideoHeaderH264* h264 = &parsed_payload->type.Video.codecHeader.H264; if (h264->nalus_length == kMaxNalusPerPacket) { RTC_LOG(LS_WARNING) << "Received packet containing more than " << kMaxNalusPerPacket << " NAL units. Will not keep track sps and pps ids for all of them."; } else { h264->nalus[h264->nalus_length++] = nalu; } } return true; } bool RtpDepacketizerH264::ParseFuaNalu( RtpDepacketizer::ParsedPayload* parsed_payload, const uint8_t* payload_data) { if (length_ < kFuAHeaderSize) { RTC_LOG(LS_ERROR) << "FU-A NAL units truncated."; return false; } uint8_t fnri = payload_data[0] & (kFBit | kNriMask); uint8_t original_nal_type = payload_data[1] & kTypeMask; bool first_fragment = (payload_data[1] & kSBit) > 0; NaluInfo nalu; nalu.type = original_nal_type; nalu.sps_id = -1; nalu.pps_id = -1; if (first_fragment) { offset_ = 0; length_ -= kNalHeaderSize; absl::optional<uint32_t> pps_id = PpsParser::ParsePpsIdFromSlice( payload_data + 2 * kNalHeaderSize, length_ - kNalHeaderSize); if (pps_id) { nalu.pps_id = *pps_id; } else { RTC_LOG(LS_WARNING) << "Failed to parse PPS from first fragment of FU-A NAL " "unit with original type: " << static_cast<int>(nalu.type); } uint8_t original_nal_header = fnri | original_nal_type; modified_buffer_.reset(new rtc::Buffer()); modified_buffer_->AppendData(payload_data + kNalHeaderSize, length_); (*modified_buffer_)[0] = original_nal_header; } else { offset_ = kFuAHeaderSize; length_ -= kFuAHeaderSize; } if (original_nal_type == H264::NaluType::kIdr) { parsed_payload->frame_type = kVideoFrameKey; } else { parsed_payload->frame_type = kVideoFrameDelta; } parsed_payload->type.Video.width = 0; parsed_payload->type.Video.height = 0; parsed_payload->type.Video.codec = kVideoCodecH264; parsed_payload->type.Video.simulcastIdx = 0; parsed_payload->type.Video.is_first_packet_in_frame = first_fragment; RTPVideoHeaderH264* h264 = &parsed_payload->type.Video.codecHeader.H264; h264->packetization_type = kH264FuA; h264->nalu_type = original_nal_type; if (first_fragment) { h264->nalus[h264->nalus_length] = nalu; h264->nalus_length = 1; } return true; } } // namespace webrtc
38.746744
80
0.664339
na-g
c8cbe5f1daa67b1a83c250dc0ae095b642a18eb1
2,087
cpp
C++
src/DotExporter.cpp
vdodev/maplang
5e37bb9adf3e7bddfdde18979a55ca998d33dede
[ "Apache-2.0" ]
1
2021-11-05T15:49:51.000Z
2021-11-05T15:49:51.000Z
src/DotExporter.cpp
vdodev/maplang
5e37bb9adf3e7bddfdde18979a55ca998d33dede
[ "Apache-2.0" ]
null
null
null
src/DotExporter.cpp
vdodev/maplang
5e37bb9adf3e7bddfdde18979a55ca998d33dede
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 VDO Dev Inc <support@maplang.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "maplang/DotExporter.h" #include <sstream> namespace maplang { std::string DotExporter::ExportGraph( DataGraph* graph, const std::string& graphName) { std::vector<std::shared_ptr<GraphNode>> elements; std::ostringstream out; std::unordered_map<std::shared_ptr<GraphNode>, std::string> nodeToNameMap; size_t nodeIndex = 0; graph->visitNodes([&nodeToNameMap, &nodeIndex, &out]( const std::shared_ptr<GraphNode>& element) { nodeToNameMap[element] = element->name; nodeIndex++; // out << " <node id=\"" << elementName << "\"/>\n"; }); // out << std::endl; out << "strict digraph " << graphName << " {" << std::endl; for (const auto& elementNamePair : nodeToNameMap) { const std::shared_ptr<GraphNode>& element = elementNamePair.first; const std::string& name = elementNamePair.second; for (const auto& edgePair : element->forwardEdges) { const std::string& channel = edgePair.first; const std::vector<GraphEdge>& channelEdges = edgePair.second; for (const auto& edge : channelEdges) { const auto otherElementName = nodeToNameMap[edge.next]; out << " \"" << name << "\" -> \"" << otherElementName << "\""; if (!edge.channel.empty()) { out << " [label=\"" << edge.channel << "\"]"; } out << std::endl; } } } out << "}" << std::endl; return out.str(); } } // namespace maplang
29.394366
76
0.635841
vdodev
c8cc3d2d1183ec6d3765a799f338c032459ad047
3,940
cc
C++
shell/platform/android/android_surface_gl.cc
climbzb4192/flutter-engine
65ac8be350adf276b2b9606375ecc641ab17c149
[ "BSD-3-Clause" ]
4
2020-06-14T03:05:51.000Z
2022-02-11T22:26:55.000Z
shell/platform/android/android_surface_gl.cc
shoryukenn/engine
0dc86cda19d55aba8b719231c11306eeaca4b798
[ "BSD-3-Clause" ]
2
2019-10-24T01:29:37.000Z
2020-07-16T09:52:12.000Z
shell/platform/android/android_surface_gl.cc
shoryukenn/engine
0dc86cda19d55aba8b719231c11306eeaca4b798
[ "BSD-3-Clause" ]
1
2021-07-21T13:47:26.000Z
2021-07-21T13:47:26.000Z
// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_surface_gl.h" #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/shell/platform/android/android_shell_holder.h" namespace flutter { AndroidSurfaceGL::AndroidSurfaceGL( std::shared_ptr<AndroidContext> android_context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, const AndroidSurface::Factory& surface_factory) : external_view_embedder_( std::make_unique<AndroidExternalViewEmbedder>(android_context, jni_facade, surface_factory)), android_context_( std::static_pointer_cast<AndroidContextGL>(android_context)), native_window_(nullptr), onscreen_surface_(nullptr), offscreen_surface_(nullptr) { // Acquire the offscreen surface. offscreen_surface_ = android_context_->CreateOffscreenSurface(); if (!offscreen_surface_->IsValid()) { offscreen_surface_ = nullptr; } } AndroidSurfaceGL::~AndroidSurfaceGL() = default; void AndroidSurfaceGL::TeardownOnScreenContext() { android_context_->ClearCurrent(); } bool AndroidSurfaceGL::IsValid() const { return offscreen_surface_ && android_context_->IsValid(); } std::unique_ptr<Surface> AndroidSurfaceGL::CreateGPUSurface( GrContext* gr_context) { if (gr_context) { return std::make_unique<GPUSurfaceGL>(sk_ref_sp(gr_context), this, true); } return std::make_unique<GPUSurfaceGL>(this, true); } bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); FML_DCHECK(native_window_); if (size == onscreen_surface_->GetSize()) { return true; } android_context_->ClearCurrent(); // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; onscreen_surface_ = android_context_->CreateOnscreenSurface(native_window_); if (!onscreen_surface_->IsValid()) { FML_LOG(ERROR) << "Unable to create EGL window surface on resize."; return false; } onscreen_surface_->MakeCurrent(); return true; } bool AndroidSurfaceGL::ResourceContextMakeCurrent() { FML_DCHECK(IsValid()); return offscreen_surface_->MakeCurrent(); } bool AndroidSurfaceGL::ResourceContextClearCurrent() { FML_DCHECK(IsValid()); return android_context_->ClearCurrent(); } bool AndroidSurfaceGL::SetNativeWindow( fml::RefPtr<AndroidNativeWindow> window) { FML_DCHECK(IsValid()); FML_DCHECK(window); native_window_ = window; // Create the onscreen surface. onscreen_surface_ = android_context_->CreateOnscreenSurface(window); if (!onscreen_surface_->IsValid()) { return false; } return true; } std::unique_ptr<GLContextResult> AndroidSurfaceGL::GLContextMakeCurrent() { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); auto default_context_result = std::make_unique<GLContextDefaultResult>( onscreen_surface_->MakeCurrent()); return std::move(default_context_result); } bool AndroidSurfaceGL::GLContextClearCurrent() { FML_DCHECK(IsValid()); return android_context_->ClearCurrent(); } bool AndroidSurfaceGL::GLContextPresent() { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); return onscreen_surface_->SwapBuffers(); } intptr_t AndroidSurfaceGL::GLContextFBO() const { FML_DCHECK(IsValid()); // The default window bound framebuffer on Android. return 0; } // |GPUSurfaceGLDelegate| ExternalViewEmbedder* AndroidSurfaceGL::GetExternalViewEmbedder() { if (!AndroidShellHolder::use_embedded_view) { return nullptr; } return external_view_embedder_.get(); } } // namespace flutter
29.62406
78
0.734772
climbzb4192
c8ce7f8dda775ecaaff66bd84568a16290b400ba
3,975
cxx
C++
external/source/vncdll/rdr/ZlibOutStream.cxx
metasploit/framework3
8670817a938c74837be073e4c7ab610068d42cfd
[ "OpenSSL", "Unlicense" ]
8
2015-04-22T05:30:34.000Z
2021-01-21T19:10:57.000Z
external/source/vncdll/rdr/ZlibOutStream.cxx
metasploit/framework3
8670817a938c74837be073e4c7ab610068d42cfd
[ "OpenSSL", "Unlicense" ]
null
null
null
external/source/vncdll/rdr/ZlibOutStream.cxx
metasploit/framework3
8670817a938c74837be073e4c7ab610068d42cfd
[ "OpenSSL", "Unlicense" ]
3
2015-04-22T05:30:56.000Z
2019-08-08T06:52:00.000Z
// // Copyright (C) 2002 RealVNC Ltd. All Rights Reserved. // // This 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 software 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 software; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. #include <rdr/ZlibOutStream.h> #include <rdr/Exception.h> #include <zlib.h> using namespace rdr; enum { DEFAULT_BUF_SIZE = 16384 }; ZlibOutStream::ZlibOutStream(OutStream* os, int bufSize_) : underlying(os), bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) { zs = new z_stream; zs->zalloc = Z_NULL; zs->zfree = Z_NULL; zs->opaque = Z_NULL; if (deflateInit(zs, Z_DEFAULT_COMPRESSION) != Z_OK) { delete zs; throw Exception("ZlibOutStream: deflateInit failed"); } ptr = start = new U8[bufSize]; end = start + bufSize; } ZlibOutStream::~ZlibOutStream() { try { flush(); } catch (Exception&) { } delete [] start; deflateEnd(zs); delete zs; } void ZlibOutStream::setUnderlying(OutStream* os) { underlying = os; } int ZlibOutStream::length() { return offset + ptr - start; } void ZlibOutStream::flush() { zs->next_in = start; zs->avail_in = ptr - start; // fprintf(stderr,"zos flush: avail_in %d\n",zs->avail_in); while (zs->avail_in != 0) { do { underlying->check(1); zs->next_out = underlying->getptr(); zs->avail_out = underlying->getend() - underlying->getptr(); // fprintf(stderr,"zos flush: calling deflate, avail_in %d, avail_out %d\n", // zs->avail_in,zs->avail_out); int rc = deflate(zs, Z_SYNC_FLUSH); if (rc != Z_OK) throw Exception("ZlibOutStream: deflate failed"); // fprintf(stderr,"zos flush: after deflate: %d bytes\n", // zs->next_out-underlying->getptr()); underlying->setptr(zs->next_out); } while (zs->avail_out == 0); } offset += ptr - start; ptr = start; } int ZlibOutStream::overrun(int itemSize, int nItems) { // fprintf(stderr,"ZlibOutStream overrun\n"); if (itemSize > bufSize) throw Exception("ZlibOutStream overrun: max itemSize exceeded"); while (end - ptr < itemSize) { zs->next_in = start; zs->avail_in = ptr - start; do { underlying->check(1); zs->next_out = underlying->getptr(); zs->avail_out = underlying->getend() - underlying->getptr(); // fprintf(stderr,"zos overrun: calling deflate, avail_in %d, avail_out %d\n", // zs->avail_in,zs->avail_out); int rc = deflate(zs, 0); if (rc != Z_OK) throw Exception("ZlibOutStream: deflate failed"); // fprintf(stderr,"zos overrun: after deflate: %d bytes\n", // zs->next_out-underlying->getptr()); underlying->setptr(zs->next_out); } while (zs->avail_out == 0); // output buffer not full if (zs->avail_in == 0) { offset += ptr - start; ptr = start; } else { // but didn't consume all the data? try shifting what's left to the // start of the buffer. fprintf(stderr,"z out buf not full, but in data not consumed\n"); memmove(start, zs->next_in, ptr - zs->next_in); offset += zs->next_in - start; ptr -= zs->next_in - start; } } if (itemSize * nItems > end - ptr) nItems = (end - ptr) / itemSize; return nItems; }
28.191489
86
0.615094
metasploit
c8d33e39f939cb4a468323f4c40414527c45bd36
2,776
cpp
C++
source/common/MTLShader.cpp
Zainrax/COSC342-OpenGL
223c45c763a82e543c62e3bc3b22e1220e20fe7d
[ "MIT" ]
null
null
null
source/common/MTLShader.cpp
Zainrax/COSC342-OpenGL
223c45c763a82e543c62e3bc3b22e1220e20fe7d
[ "MIT" ]
null
null
null
source/common/MTLShader.cpp
Zainrax/COSC342-OpenGL
223c45c763a82e543c62e3bc3b22e1220e20fe7d
[ "MIT" ]
null
null
null
#include "MTLShader.hpp" // complete the setters with the appropriate method for passing information to the shaders MTLShader::MTLShader(){ } // version of constructor that allows for vertex and fragment shader with differnt names MTLShader::MTLShader(std::string vertexshaderName, std::string fragmentshaderName): Shader(vertexshaderName, fragmentshaderName){ setUpShaderParameters(); } // version of constructor that assumes that vertex and fragment shader have same name MTLShader::MTLShader(std::string shaderName): Shader(shaderName){ setUpShaderParameters(); } MTLShader::~MTLShader(){ glDeleteTextures(1, &m_TextureID); } void MTLShader::setUpShaderParameters(){ m_diffuseColor = glm::vec4(1.0); GLint diffusecolorID = glGetUniformLocation(programID, "diffuseColor"); glProgramUniform4fv(programID,diffusecolorID,1, &m_diffuseColor[0]); m_texture =NULL; } void MTLShader::setTexture(Texture* texture){ m_texture = texture; // Get a handle for our "myTextureSampler" uniform m_TextureID = glGetUniformLocation(programID, "myTextureSampler"); } void MTLShader::setLightPos(glm::vec3 lightPos){ m_lightPos= lightPos; } void MTLShader::setDiffuse(glm::vec3 diffuse){ m_diffuseColor= glm::vec4(diffuse[0],diffuse[1],diffuse[2],1.0);; GLint diffusecolorID = glGetUniformLocation(programID, "diffuseColor"); glProgramUniform4fv(programID,diffusecolorID,1, &m_diffuseColor[0]); } void MTLShader::setAmbient(glm::vec3 ambient){ m_ambientColor= glm::vec4(ambient[0],ambient[1],ambient[2],1.0); GLint ambientcolorID = glGetUniformLocation(programID, "ambientColor"); glProgramUniform4fv(programID,ambientcolorID,1, &m_diffuseColor[0]); } void MTLShader::setSpecular(glm::vec3 specular){ m_specularColor= glm::vec4(specular[0],specular[1],specular[2],1.0); GLint specularcolorID = glGetUniformLocation(programID, "specularColor"); glProgramUniform4fv(programID,specularcolorID,1, &m_specularColor[0]); } void MTLShader::setOpacity(float opacity){ m_opacity= opacity; GLint opacityID = glGetUniformLocation(programID, "opacity"); glProgramUniform1f(programID,opacityID, m_opacity); } void MTLShader::setRenderMode(float renderMode){ m_renderMode= renderMode; GLint renderModeID = glGetUniformLocation(programID, "renderMode"); glProgramUniform1f(programID,renderModeID,m_renderMode); } void MTLShader::bind(){ // Use our shader glUseProgram(programID); // Bind our texture in Texture Unit 0 if(m_texture!=NULL){ m_texture->bindTexture(); // Set our "myTextureSampler" sampler to user Texture Unit 0 using glUniform1i glUniform1i(m_TextureID,0); } }
27.76
129
0.731268
Zainrax
c8d44f177f1005eac9a1c0019a7db74145815f10
2,473
cpp
C++
source/Logic/generator.cpp
KidomMoc/YahahaEngine
15a097aa5b8f130d19dbc019d444c9c317b337e8
[ "MIT" ]
null
null
null
source/Logic/generator.cpp
KidomMoc/YahahaEngine
15a097aa5b8f130d19dbc019d444c9c317b337e8
[ "MIT" ]
null
null
null
source/Logic/generator.cpp
KidomMoc/YahahaEngine
15a097aa5b8f130d19dbc019d444c9c317b337e8
[ "MIT" ]
null
null
null
#include "generator.hpp" #include "Core/Asset/AssetTypes.hpp" #include "Core/Asset/AssetManager.hpp" #include <stdio.h> #include <libpng/png.h> namespace KFTG { void generateData () { Image *background; u32 size_background = readImg ("background.png", background); Image *img1; u32 size_img1 = readImg ("img.png", img1); Image *img2; u32 size_img2 = readImg ("img.png", img2); Image *img3; u32 size_img3 = readImg ("img.png", img3); u32 size_ani1 = sizeof (Animation) + 2 * sizeof (Animation::Clip); Animation *ani1 = (Animation*) new char[size_ani1]; ani1->len = 2; ani1->ani[0].img = img1; ani1->ani[0].time = 400; ani1->ani[1].img = img2; ani1->ani[1].time = 400; u32 size_ani2 = sizeof (Animation) + 2 * sizeof (Animation::Clip); Animation *ani2 = (Animation*) new char[size_ani2]; ani1->len = 2; ani1->ani[0].img = img1; ani1->ani[0].time = 250; ani1->ani[1].img = img3; ani1->ani[1].time = 250; u32 size_ani3 = sizeof (Animation) + 1 * sizeof (Animation::Clip); Animation *ani3 = (Animation*) new char[size_ani3]; ani1->len = 1; ani1->ani[0].img = img3; ani1->ani[0].time = 1000; } u32 readImg (const char *path, Image *img) { char header[8]; png_structp png_ptr; png_infop info_ptr; u32 width, height; png_bytep *row_pointers; png_byte color_type; FILE *fp = fopen (path, "rb"); fread (header, 1, 8, fp); png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); info_ptr = png_create_info_struct (png_ptr); png_init_io (png_ptr, fp); png_set_sig_bytes (png_ptr, 8); png_read_info (png_ptr, info_ptr); color_type = png_get_color_type (png_ptr, info_ptr); width = png_get_image_width (png_ptr, info_ptr); height = png_get_image_height (png_ptr, info_ptr); img = (Image*) new char[sizeof (Image) + width * height * sizeof (Color)]; img->width = width; img->height = height; row_pointers = (png_bytep*) new char[sizeof (png_bytep) * height]; for (u16 i = 0; i < height; ++i) row_pointers[i] = (png_byte*) new char [png_get_rowbytes (png_ptr, info_ptr)]; png_read_image (png_ptr, row_pointers); for (u16 i = 0; i < height; ++i) for (u16 j = 0; j < width; ++j) img->image[i * height + j] = Color (row_pointers[i][j * 4], row_pointers[i][j * 4 + 1], row_pointers[i][j * 4 + 2], color_type == PNG_COLOR_TYPE_RGBA ? row_pointers[i][j * 4 + 0] : 255); for (u16 i = 0; i < height; ++i) delete[] row_pointers[i]; delete[] row_pointers; fclose (fp); return sizeof (Color) * width * height; } }
32.539474
189
0.675698
KidomMoc
c8d60c20026ed6da818acc5591ecaf4ce0801a7b
5,032
hxx
C++
Modules/Segmentation/MeanShift/include/otbMeanShiftSegmentationFilter.hxx
heralex/OTB
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
[ "Apache-2.0" ]
317
2015-01-19T08:40:58.000Z
2022-03-17T11:55:48.000Z
Modules/Segmentation/MeanShift/include/otbMeanShiftSegmentationFilter.hxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
18
2015-07-29T14:13:45.000Z
2021-03-29T12:36:24.000Z
Modules/Segmentation/MeanShift/include/otbMeanShiftSegmentationFilter.hxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
132
2015-02-21T23:57:25.000Z
2022-03-25T16:03:16.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbMeanShiftSegmentationFilter_hxx #define otbMeanShiftSegmentationFilter_hxx #include "otbMeanShiftSegmentationFilter.h" namespace otb { template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::MeanShiftSegmentationFilter() { m_MeanShiftFilter = MeanShiftFilterType::New(); m_RegionMergingFilter = RegionMergingFilterType::New(); m_RegionPruningFilter = RegionPruningFilterType::New(); m_RelabelFilter = RelabelComponentFilterType::New(); this->SetMinRegionSize(100); this->SetNumberOfRequiredOutputs(2); this->SetNthOutput(0, TOutputLabelImage::New()); this->SetNthOutput(1, TOutputClusteredImage::New()); // default set MeanShiftFilter mode search to true because Merging and Pruning use LabelOutput m_MeanShiftFilter->SetModeSearch(true); } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::~MeanShiftSegmentationFilter() { } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> TOutputLabelImage* MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::GetLabelOutput() { return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0)); } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> const TOutputLabelImage* MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::GetLabelOutput() const { return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0)); } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> typename MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::OutputClusteredImageType* MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::GetClusteredOutput() { return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1)); } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> const typename MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::OutputClusteredImageType* MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::GetClusteredOutput() const { return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1)); } template <class TInputImage, class TOutputLabelImage, class TOutputClusteredImage, class TKernel> void MeanShiftSegmentationFilter<TInputImage, TOutputLabelImage, TOutputClusteredImage, TKernel>::GenerateData() { this->m_MeanShiftFilter->SetInput(this->GetInput()); // Relabel output to avoid same label assigned to discontinuous areas m_RelabelFilter->SetInput(this->m_MeanShiftFilter->GetLabelOutput()); this->m_RegionMergingFilter->SetInputLabelImage(this->m_RelabelFilter->GetOutput()); this->m_RegionMergingFilter->SetInputSpectralImage(this->m_MeanShiftFilter->GetRangeOutput()); this->m_RegionMergingFilter->SetRangeBandwidth(this->GetRangeBandwidth()); if (this->GetMinRegionSize() == 0) { m_RegionMergingFilter->GraftNthOutput(0, this->GetLabelOutput()); m_RegionMergingFilter->GraftNthOutput(1, this->GetClusteredOutput()); this->m_RegionMergingFilter->Update(); this->GraftNthOutput(0, m_RegionMergingFilter->GetLabelOutput()); this->GraftNthOutput(1, m_RegionMergingFilter->GetClusteredOutput()); } else { this->m_RegionPruningFilter->SetInputLabelImage(this->m_RegionMergingFilter->GetLabelOutput()); this->m_RegionPruningFilter->SetInputSpectralImage(this->m_RegionMergingFilter->GetClusteredOutput()); m_RegionPruningFilter->GraftNthOutput(0, this->GetLabelOutput()); m_RegionPruningFilter->GraftNthOutput(1, this->GetClusteredOutput()); this->m_RegionPruningFilter->Update(); this->GraftNthOutput(0, m_RegionPruningFilter->GetLabelOutput()); this->GraftNthOutput(1, m_RegionPruningFilter->GetClusteredOutput()); } } } // end namespace otb #endif
44.928571
140
0.801471
heralex
c8d7535f6bc96d7bce13dcd5343a71bc7696658d
3,194
cpp
C++
clients/tests/test_global_matrix.cpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
1
2020-04-15T18:26:58.000Z
2020-04-15T18:26:58.000Z
clients/tests/test_global_matrix.cpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
null
null
null
clients/tests/test_global_matrix.cpp
pruthvistony/rocALUTION
2a5c602f41194f7730f59b4f0ce8c5cfff77fa07
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2018 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #include "testing_global_matrix.hpp" #include "utility.hpp" #include <gtest/gtest.h> /* typedef std::tuple<int, int, int, int, bool, int, bool> backend_tuple; int backend_rank[] = {-1, 0, 13}; int backend_dev_node[] = {-1, 0, 13}; int backend_dev[] = {-1, 0, 13}; int backend_omp_threads[] = {-1, 0, 8}; bool backend_affinity[] = {true, false}; int backend_omp_threshold[] = {-1, 0, 20000}; bool backend_disable_acc[] = {true, false}; class parameterized_backend : public testing::TestWithParam<backend_tuple> { protected: parameterized_backend() {} virtual ~parameterized_backend() {} virtual void SetUp() {} virtual void TearDown() {} }; Arguments setup_backend_arguments(backend_tuple tup) { Arguments arg; arg.rank = std::get<0>(tup); arg.dev_per_node = std::get<1>(tup); arg.dev = std::get<2>(tup); arg.omp_nthreads = std::get<3>(tup); arg.omp_affinity = std::get<4>(tup); arg.omp_threshold = std::get<5>(tup); arg.use_acc = std::get<6>(tup); return arg; } */ TEST(global_matrix_bad_args, global_matrix) { testing_global_matrix_bad_args<float>(); } /* TEST_P(parameterized_backend, backend) { Arguments arg = setup_backend_arguments(GetParam()); testing_backend(arg); } INSTANTIATE_TEST_CASE_P(backend, parameterized_backend, testing::Combine(testing::ValuesIn(backend_rank), testing::ValuesIn(backend_dev_node), testing::ValuesIn(backend_dev), testing::ValuesIn(backend_omp_threads), testing::ValuesIn(backend_affinity), testing::ValuesIn(backend_omp_threshold), testing::ValuesIn(backend_disable_acc))); */
38.95122
82
0.623356
pruthvistony
c8d7823b0a659dcb1bd30e89b153f9dabd8d9720
811
cc
C++
Chapter01/pra/t19_handle.cc
geometryolife/CppPrimer
1159cd9dab50a112fa2f70b0507cae2a67614d4a
[ "MIT" ]
null
null
null
Chapter01/pra/t19_handle.cc
geometryolife/CppPrimer
1159cd9dab50a112fa2f70b0507cae2a67614d4a
[ "MIT" ]
null
null
null
Chapter01/pra/t19_handle.cc
geometryolife/CppPrimer
1159cd9dab50a112fa2f70b0507cae2a67614d4a
[ "MIT" ]
null
null
null
// 练习1.19: 修改你为1.4.1节练习1.11(第11页)所编写的程序(打印一个范围 // 内的数),使其能处理用户输入的第一个数比第二个数小的情况。 #include <iostream> int main() { int start = 0, end = 0; std::cout << "Please enter the atart and end ranges:" << std::endl; std::cin >> start >> end; if (start < end) { while (start <= end) { std::cout << start << " "; start++; } } else { while (start >= end) { std::cout << start << " "; start--; } } std::cout << std::endl; return 0; } /* >>> Execution Result: Please enter the atart and end ranges: 1 12 1 2 3 4 5 6 7 8 9 10 11 12 Please enter the atart and end ranges: -3 5 -3 -2 -1 0 1 2 3 4 5 Please enter the atart and end ranges: 10 5 10 9 8 7 6 5 Please enter the atart and end ranges: 5 -5 5 4 3 2 1 0 -1 -2 -3 -4 -5 */
18.431818
69
0.54254
geometryolife
c8e01b967e7f667ce64bb0fe3df573a3fcc664e5
6,649
cc
C++
tensorflow/compiler/xla/service/mlir_gpu/mlir_irgen_test_base.cc
minai2020/tensorflow
a6b4474186c906c09cd29b1a7d4d0af714c261e4
[ "Apache-2.0" ]
57
2017-09-03T07:08:31.000Z
2022-02-28T04:33:42.000Z
tensorflow/compiler/xla/service/mlir_gpu/mlir_irgen_test_base.cc
minai2020/tensorflow
a6b4474186c906c09cd29b1a7d4d0af714c261e4
[ "Apache-2.0" ]
8
2019-03-13T23:13:47.000Z
2020-01-31T21:08:21.000Z
tensorflow/compiler/xla/service/mlir_gpu/mlir_irgen_test_base.cc
minai2020/tensorflow
a6b4474186c906c09cd29b1a7d4d0af714c261e4
[ "Apache-2.0" ]
28
2017-03-25T13:48:09.000Z
2021-10-14T00:10:50.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/mlir_gpu/mlir_irgen_test_base.h" #include <functional> #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/Module.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "tensorflow/compiler/xla/service/hlo_module_config.h" #include "tensorflow/compiler/xla/service/mlir_gpu/failover_compiler.h" #include "tensorflow/compiler/xla/service/mlir_gpu/inject_errors_pass.h" #include "tensorflow/compiler/xla/service/mlir_gpu/mlir_compiler.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/tests/filecheck.h" #include "tensorflow/compiler/xla/tests/verified_hlo_module.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/resource_loader.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace mlir_gpu { void MlirIrGenTestBase::CompileIr(std::unique_ptr<HloModule> hlo_module, const MlirCompiler::IRHook& ir_hook) { MlirCompiler* compiler = GetMLIRCompiler(); compiler->SetModuleHook(ir_hook); Status status = CompileToExecutable(std::move(hlo_module)).status(); compiler->RemoveModuleHook(); TF_ASSERT_OK(status); } void MlirIrGenTestBase::PatternMatch(const std::string& str, const std::string& pattern_file) { StatusOr<bool> filecheck_result = RunFileCheckWithPatternFile(str, pattern_file); TF_ASSERT_OK(filecheck_result.status()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } string MlirIrGenTestBase::CompileIr( std::unique_ptr<HloModule> hlo_module, MlirCompiler::IRHook::LoweringStage printing_stage) { std::string ir; CompileIr(std::move(hlo_module), {[&ir](mlir::ModuleOp module) -> Status { std::string buffer_string; llvm::raw_string_ostream ostream(buffer_string); module.print(ostream); ostream.flush(); ir = buffer_string; return Status::OK(); }, printing_stage}); return ir; } void MlirIrGenTestBase::CompileAndVerifyIr( std::unique_ptr<HloModule> hlo_module, const std::string& pattern_file, LoweringStage printing_stage) { std::string ir = CompileIr(std::move(hlo_module), printing_stage); PatternMatch(ir, pattern_file); } void MlirIrGenTestBase::CompileAndVerifyIr(const std::string& hlo_text_filename, LoweringStage printing_stage) { std::string hlo_text_absolute_filename = tensorflow::GetDataDependencyFilepath(hlo_text_filename); TF_ASSERT_OK_AND_ASSIGN(auto module, GetVerifiedHloModule(hlo_text_absolute_filename)); CompileAndVerifyIr(std::move(module), /*pattern_file=*/hlo_text_absolute_filename, printing_stage); } MlirCompiler::IRHook MlirIrGenTestBase::getIRHookBreakingLoweringStage( LoweringStage breaking_stage) { return {[](mlir::ModuleOp module) -> Status { mlir::PassManager pm(module.getContext()); pm.addPass(::mlir::createInjectErrorsForTestingPass()); if (failed(pm.run(module))) { return InternalError("InjectErrorsForTestingPass failed."); } return Status::OK(); }, breaking_stage}; } StatusOr<string> MlirIrGenTestBase::CompileAndInjectErrors( std::unique_ptr<HloModule> hlo_module, LoweringStage breaking_stage) { std::string errors; auto error_handler = [&errors](const EmissionContext::ErrorMap& error_map, HloModule* hlo_module) { errors = "ERRORS FOUND: "; for (auto& err : error_map) { errors += "[" + err.first->ToString() + ": " + absl::StrJoin(err.second, "; ") + "]"; } }; MlirCompiler* compiler = GetMLIRCompiler(); compiler->SetModuleHook(getIRHookBreakingLoweringStage(breaking_stage)); compiler->SetErrorHandler(error_handler); Status status = CompileToExecutable(std::move(hlo_module)).status(); compiler->RemoveModuleHook(); compiler->RemoveErrorHandler(); if (status.ok()) { return errors; } return status; } void MlirIrGenTestBase::CompileAndVerifyErrors( const std::string& hlo_text_filename, LoweringStage breaking_stage) { std::string test_srcdir = tensorflow::testing::TensorFlowSrcRoot(); std::string hlo_text_absolute_filename = tensorflow::GetDataDependencyFilepath(hlo_text_filename); TF_ASSERT_OK_AND_ASSIGN(auto module, GetVerifiedHloModule(hlo_text_absolute_filename)); TF_ASSERT_OK_AND_ASSIGN( std::string errors, CompileAndInjectErrors(std::move(module), breaking_stage)); PatternMatch(errors, /*pattern_file=*/hlo_text_absolute_filename); } StatusOr<std::unique_ptr<VerifiedHloModule>> MlirIrGenTestBase::GetVerifiedHloModule(const std::string& hlo_text_filename) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); auto module = absl::make_unique<VerifiedHloModule>( "Module", config, /*verifier_layout_sensitive=*/true, /*allow_mixed_precision_in_hlo_verifier=*/false, /*shape_size_function=*/ShapeUtil::ByteSizeOfElements); std::string hlo_text; TF_RETURN_IF_ERROR(tensorflow::ReadFileToString( tensorflow::Env::Default(), hlo_text_filename, &hlo_text)); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } MlirCompiler* MlirIrGenTestBase::GetMLIRCompiler() { // TODO(b/137624192): Remove failover once no longer in place. auto* failover = static_cast<FailoverCompiler*>(backend().compiler()); return static_cast<MlirCompiler*>(failover->GetPrimary()); } } // namespace mlir_gpu } // namespace xla
39.343195
80
0.708076
minai2020
c8e1ea97ad52b119a70fa1c2c838774e9ac275db
92,436
inl
C++
external/vulkancts/framework/vulkan/vkFunctionPointerTypes.inl
akeley98NV/VK-GL-CTS
21d9f01031515737435ccf091cc4c7caf77a661a
[ "Apache-2.0" ]
1
2021-07-15T23:37:39.000Z
2021-07-15T23:37:39.000Z
external/vulkancts/framework/vulkan/vkFunctionPointerTypes.inl
akeley98NV/VK-GL-CTS
21d9f01031515737435ccf091cc4c7caf77a661a
[ "Apache-2.0" ]
null
null
null
external/vulkancts/framework/vulkan/vkFunctionPointerTypes.inl
akeley98NV/VK-GL-CTS
21d9f01031515737435ccf091cc4c7caf77a661a
[ "Apache-2.0" ]
null
null
null
/* WARNING: This is auto-generated file. Do not modify, since changes will * be lost! Modify the generating script instead. */ typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateInstanceFunc) (const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkInstance* pInstance); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyInstanceFunc) (VkInstance instance, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumeratePhysicalDevicesFunc) (VkInstance instance, deUint32* pPhysicalDeviceCount, VkPhysicalDevice* pPhysicalDevices); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFeaturesFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFormatPropertiesFunc) (VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceImageFormatPropertiesFunc) (VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDevicePropertiesFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceQueueFamilyPropertiesFunc) (VkPhysicalDevice physicalDevice, deUint32* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceMemoryPropertiesFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties* pMemoryProperties); typedef VKAPI_ATTR PFN_vkVoidFunction (VKAPI_CALL* GetInstanceProcAddrFunc) (VkInstance instance, const char* pName); typedef VKAPI_ATTR PFN_vkVoidFunction (VKAPI_CALL* GetDeviceProcAddrFunc) (VkDevice device, const char* pName); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDeviceFunc) (VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDevice* pDevice); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDeviceFunc) (VkDevice device, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumerateInstanceExtensionPropertiesFunc) (const char* pLayerName, deUint32* pPropertyCount, VkExtensionProperties* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumerateDeviceExtensionPropertiesFunc) (VkPhysicalDevice physicalDevice, const char* pLayerName, deUint32* pPropertyCount, VkExtensionProperties* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumerateInstanceLayerPropertiesFunc) (deUint32* pPropertyCount, VkLayerProperties* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumerateDeviceLayerPropertiesFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkLayerProperties* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceQueueFunc) (VkDevice device, deUint32 queueFamilyIndex, deUint32 queueIndex, VkQueue* pQueue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueueSubmitFunc) (VkQueue queue, deUint32 submitCount, const VkSubmitInfo* pSubmits, VkFence fence); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueueWaitIdleFunc) (VkQueue queue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* DeviceWaitIdleFunc) (VkDevice device); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AllocateMemoryFunc) (VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo, const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory); typedef VKAPI_ATTR void (VKAPI_CALL* FreeMemoryFunc) (VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* MapMemoryFunc) (VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void** ppData); typedef VKAPI_ATTR void (VKAPI_CALL* UnmapMemoryFunc) (VkDevice device, VkDeviceMemory memory); typedef VKAPI_ATTR VkResult (VKAPI_CALL* FlushMappedMemoryRangesFunc) (VkDevice device, deUint32 memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges); typedef VKAPI_ATTR VkResult (VKAPI_CALL* InvalidateMappedMemoryRangesFunc) (VkDevice device, deUint32 memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceMemoryCommitmentFunc) (VkDevice device, VkDeviceMemory memory, VkDeviceSize* pCommittedMemoryInBytes); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindBufferMemoryFunc) (VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize memoryOffset); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindImageMemoryFunc) (VkDevice device, VkImage image, VkDeviceMemory memory, VkDeviceSize memoryOffset); typedef VKAPI_ATTR void (VKAPI_CALL* GetBufferMemoryRequirementsFunc) (VkDevice device, VkBuffer buffer, VkMemoryRequirements* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageMemoryRequirementsFunc) (VkDevice device, VkImage image, VkMemoryRequirements* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageSparseMemoryRequirementsFunc) (VkDevice device, VkImage image, deUint32* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements* pSparseMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceSparseImageFormatPropertiesFunc) (VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageTiling tiling, deUint32* pPropertyCount, VkSparseImageFormatProperties* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueueBindSparseFunc) (VkQueue queue, deUint32 bindInfoCount, const VkBindSparseInfo* pBindInfo, VkFence fence); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateFenceFunc) (VkDevice device, const VkFenceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyFenceFunc) (VkDevice device, VkFence fence, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ResetFencesFunc) (VkDevice device, deUint32 fenceCount, const VkFence* pFences); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetFenceStatusFunc) (VkDevice device, VkFence fence); typedef VKAPI_ATTR VkResult (VKAPI_CALL* WaitForFencesFunc) (VkDevice device, deUint32 fenceCount, const VkFence* pFences, VkBool32 waitAll, deUint64 timeout); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSemaphoreFunc) (VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySemaphoreFunc) (VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateEventFunc) (VkDevice device, const VkEventCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkEvent* pEvent); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyEventFunc) (VkDevice device, VkEvent event, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetEventStatusFunc) (VkDevice device, VkEvent event); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SetEventFunc) (VkDevice device, VkEvent event); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ResetEventFunc) (VkDevice device, VkEvent event); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateQueryPoolFunc) (VkDevice device, const VkQueryPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkQueryPool* pQueryPool); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyQueryPoolFunc) (VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetQueryPoolResultsFunc) (VkDevice device, VkQueryPool queryPool, deUint32 firstQuery, deUint32 queryCount, deUintptr dataSize, void* pData, VkDeviceSize stride, VkQueryResultFlags flags); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateBufferFunc) (VkDevice device, const VkBufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyBufferFunc) (VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateBufferViewFunc) (VkDevice device, const VkBufferViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBufferView* pView); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyBufferViewFunc) (VkDevice device, VkBufferView bufferView, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateImageFunc) (VkDevice device, const VkImageCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImage* pImage); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyImageFunc) (VkDevice device, VkImage image, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageSubresourceLayoutFunc) (VkDevice device, VkImage image, const VkImageSubresource* pSubresource, VkSubresourceLayout* pLayout); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateImageViewFunc) (VkDevice device, const VkImageViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImageView* pView); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyImageViewFunc) (VkDevice device, VkImageView imageView, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateShaderModuleFunc) (VkDevice device, const VkShaderModuleCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkShaderModule* pShaderModule); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyShaderModuleFunc) (VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreatePipelineCacheFunc) (VkDevice device, const VkPipelineCacheCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineCache* pPipelineCache); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyPipelineCacheFunc) (VkDevice device, VkPipelineCache pipelineCache, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPipelineCacheDataFunc) (VkDevice device, VkPipelineCache pipelineCache, deUintptr* pDataSize, void* pData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* MergePipelineCachesFunc) (VkDevice device, VkPipelineCache dstCache, deUint32 srcCacheCount, const VkPipelineCache* pSrcCaches); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateGraphicsPipelinesFunc) (VkDevice device, VkPipelineCache pipelineCache, deUint32 createInfoCount, const VkGraphicsPipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateComputePipelinesFunc) (VkDevice device, VkPipelineCache pipelineCache, deUint32 createInfoCount, const VkComputePipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyPipelineFunc) (VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreatePipelineLayoutFunc) (VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineLayout* pPipelineLayout); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyPipelineLayoutFunc) (VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSamplerFunc) (VkDevice device, const VkSamplerCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSampler* pSampler); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySamplerFunc) (VkDevice device, VkSampler sampler, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDescriptorSetLayoutFunc) (VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorSetLayout* pSetLayout); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDescriptorSetLayoutFunc) (VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDescriptorPoolFunc) (VkDevice device, const VkDescriptorPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorPool* pDescriptorPool); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDescriptorPoolFunc) (VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ResetDescriptorPoolFunc) (VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AllocateDescriptorSetsFunc) (VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo, VkDescriptorSet* pDescriptorSets); typedef VKAPI_ATTR VkResult (VKAPI_CALL* FreeDescriptorSetsFunc) (VkDevice device, VkDescriptorPool descriptorPool, deUint32 descriptorSetCount, const VkDescriptorSet* pDescriptorSets); typedef VKAPI_ATTR void (VKAPI_CALL* UpdateDescriptorSetsFunc) (VkDevice device, deUint32 descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites, deUint32 descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateFramebufferFunc) (VkDevice device, const VkFramebufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyFramebufferFunc) (VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateRenderPassFunc) (VkDevice device, const VkRenderPassCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyRenderPassFunc) (VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* GetRenderAreaGranularityFunc) (VkDevice device, VkRenderPass renderPass, VkExtent2D* pGranularity); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateCommandPoolFunc) (VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyCommandPoolFunc) (VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ResetCommandPoolFunc) (VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AllocateCommandBuffersFunc) (VkDevice device, const VkCommandBufferAllocateInfo* pAllocateInfo, VkCommandBuffer* pCommandBuffers); typedef VKAPI_ATTR void (VKAPI_CALL* FreeCommandBuffersFunc) (VkDevice device, VkCommandPool commandPool, deUint32 commandBufferCount, const VkCommandBuffer* pCommandBuffers); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BeginCommandBufferFunc) (VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EndCommandBufferFunc) (VkCommandBuffer commandBuffer); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ResetCommandBufferFunc) (VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindPipelineFunc) (VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetViewportFunc) (VkCommandBuffer commandBuffer, deUint32 firstViewport, deUint32 viewportCount, const VkViewport* pViewports); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetScissorFunc) (VkCommandBuffer commandBuffer, deUint32 firstScissor, deUint32 scissorCount, const VkRect2D* pScissors); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetLineWidthFunc) (VkCommandBuffer commandBuffer, float lineWidth); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthBiasFunc) (VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetBlendConstantsFunc) (VkCommandBuffer commandBuffer, const float blendConstants[4]); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthBoundsFunc) (VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetStencilCompareMaskFunc) (VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, deUint32 compareMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetStencilWriteMaskFunc) (VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, deUint32 writeMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetStencilReferenceFunc) (VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, deUint32 reference); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindDescriptorSetsFunc) (VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, deUint32 firstSet, deUint32 descriptorSetCount, const VkDescriptorSet* pDescriptorSets, deUint32 dynamicOffsetCount, const deUint32* pDynamicOffsets); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindIndexBufferFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindVertexBuffersFunc) (VkCommandBuffer commandBuffer, deUint32 firstBinding, deUint32 bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawFunc) (VkCommandBuffer commandBuffer, deUint32 vertexCount, deUint32 instanceCount, deUint32 firstVertex, deUint32 firstInstance); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndexedFunc) (VkCommandBuffer commandBuffer, deUint32 indexCount, deUint32 instanceCount, deUint32 firstIndex, deInt32 vertexOffset, deUint32 firstInstance); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndirectFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, deUint32 drawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndexedIndirectFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, deUint32 drawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDispatchFunc) (VkCommandBuffer commandBuffer, deUint32 groupCountX, deUint32 groupCountY, deUint32 groupCountZ); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDispatchIndirectFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyBufferFunc) (VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, deUint32 regionCount, const VkBufferCopy* pRegions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyImageFunc) (VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, deUint32 regionCount, const VkImageCopy* pRegions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBlitImageFunc) (VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, deUint32 regionCount, const VkImageBlit* pRegions, VkFilter filter); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyBufferToImageFunc) (VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, deUint32 regionCount, const VkBufferImageCopy* pRegions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyImageToBufferFunc) (VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, deUint32 regionCount, const VkBufferImageCopy* pRegions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdUpdateBufferFunc) (VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdFillBufferFunc) (VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, deUint32 data); typedef VKAPI_ATTR void (VKAPI_CALL* CmdClearColorImageFunc) (VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue* pColor, deUint32 rangeCount, const VkImageSubresourceRange* pRanges); typedef VKAPI_ATTR void (VKAPI_CALL* CmdClearDepthStencilImageFunc) (VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue* pDepthStencil, deUint32 rangeCount, const VkImageSubresourceRange* pRanges); typedef VKAPI_ATTR void (VKAPI_CALL* CmdClearAttachmentsFunc) (VkCommandBuffer commandBuffer, deUint32 attachmentCount, const VkClearAttachment* pAttachments, deUint32 rectCount, const VkClearRect* pRects); typedef VKAPI_ATTR void (VKAPI_CALL* CmdResolveImageFunc) (VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, deUint32 regionCount, const VkImageResolve* pRegions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetEventFunc) (VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdResetEventFunc) (VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWaitEventsFunc) (VkCommandBuffer commandBuffer, deUint32 eventCount, const VkEvent* pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, deUint32 memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, deUint32 bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, deUint32 imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPipelineBarrierFunc) (VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, deUint32 memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, deUint32 bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, deUint32 imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginQueryFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 query, VkQueryControlFlags flags); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndQueryFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 query); typedef VKAPI_ATTR void (VKAPI_CALL* CmdResetQueryPoolFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 firstQuery, deUint32 queryCount); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteTimestampFunc) (VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, deUint32 query); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyQueryPoolResultsFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 firstQuery, deUint32 queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPushConstantsFunc) (VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, deUint32 offset, deUint32 size, const void* pValues); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginRenderPassFunc) (VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, VkSubpassContents contents); typedef VKAPI_ATTR void (VKAPI_CALL* CmdNextSubpassFunc) (VkCommandBuffer commandBuffer, VkSubpassContents contents); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndRenderPassFunc) (VkCommandBuffer commandBuffer); typedef VKAPI_ATTR void (VKAPI_CALL* CmdExecuteCommandsFunc) (VkCommandBuffer commandBuffer, deUint32 commandBufferCount, const VkCommandBuffer* pCommandBuffers); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumerateInstanceVersionFunc) (deUint32* pApiVersion); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindBufferMemory2Func) (VkDevice device, deUint32 bindInfoCount, const VkBindBufferMemoryInfo* pBindInfos); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindImageMemory2Func) (VkDevice device, deUint32 bindInfoCount, const VkBindImageMemoryInfo* pBindInfos); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceGroupPeerMemoryFeaturesFunc) (VkDevice device, deUint32 heapIndex, deUint32 localDeviceIndex, deUint32 remoteDeviceIndex, VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDeviceMaskFunc) (VkCommandBuffer commandBuffer, deUint32 deviceMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDispatchBaseFunc) (VkCommandBuffer commandBuffer, deUint32 baseGroupX, deUint32 baseGroupY, deUint32 baseGroupZ, deUint32 groupCountX, deUint32 groupCountY, deUint32 groupCountZ); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumeratePhysicalDeviceGroupsFunc) (VkInstance instance, deUint32* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageMemoryRequirements2Func) (VkDevice device, const VkImageMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetBufferMemoryRequirements2Func) (VkDevice device, const VkBufferMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageSparseMemoryRequirements2Func) (VkDevice device, const VkImageSparseMemoryRequirementsInfo2* pInfo, deUint32* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFeatures2Func) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceProperties2Func) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFormatProperties2Func) (VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2* pFormatProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceImageFormatProperties2Func) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, VkImageFormatProperties2* pImageFormatProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceQueueFamilyProperties2Func) (VkPhysicalDevice physicalDevice, deUint32* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceMemoryProperties2Func) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2* pMemoryProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceSparseImageFormatProperties2Func) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, deUint32* pPropertyCount, VkSparseImageFormatProperties2* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* TrimCommandPoolFunc) (VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlags flags); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceQueue2Func) (VkDevice device, const VkDeviceQueueInfo2* pQueueInfo, VkQueue* pQueue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSamplerYcbcrConversionFunc) (VkDevice device, const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversion* pYcbcrConversion); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySamplerYcbcrConversionFunc) (VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDescriptorUpdateTemplateFunc) (VkDevice device, const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDescriptorUpdateTemplateFunc) (VkDevice device, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* UpdateDescriptorSetWithTemplateFunc) (VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void* pData); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalBufferPropertiesFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalFencePropertiesFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalSemaphorePropertiesFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetDescriptorSetLayoutSupportFunc) (VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupport* pSupport); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndirectCountFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndexedIndirectCountFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateRenderPass2Func) (VkDevice device, const VkRenderPassCreateInfo2* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginRenderPass2Func) (VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, const VkSubpassBeginInfo* pSubpassBeginInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdNextSubpass2Func) (VkCommandBuffer commandBuffer, const VkSubpassBeginInfo* pSubpassBeginInfo, const VkSubpassEndInfo* pSubpassEndInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndRenderPass2Func) (VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo); typedef VKAPI_ATTR void (VKAPI_CALL* ResetQueryPoolFunc) (VkDevice device, VkQueryPool queryPool, deUint32 firstQuery, deUint32 queryCount); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSemaphoreCounterValueFunc) (VkDevice device, VkSemaphore semaphore, deUint64* pValue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* WaitSemaphoresFunc) (VkDevice device, const VkSemaphoreWaitInfo* pWaitInfo, deUint64 timeout); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SignalSemaphoreFunc) (VkDevice device, const VkSemaphoreSignalInfo* pSignalInfo); typedef VKAPI_ATTR VkDeviceAddress (VKAPI_CALL* GetBufferDeviceAddressFunc) (VkDevice device, const VkBufferDeviceAddressInfo* pInfo); typedef VKAPI_ATTR uint64_t (VKAPI_CALL* GetBufferOpaqueCaptureAddressFunc) (VkDevice device, const VkBufferDeviceAddressInfo* pInfo); typedef VKAPI_ATTR uint64_t (VKAPI_CALL* GetDeviceMemoryOpaqueCaptureAddressFunc) (VkDevice device, const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySurfaceKHRFunc) (VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceSupportKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex, VkSurfaceKHR surface, VkBool32* pSupported); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceCapabilitiesKHRFunc) (VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR* pSurfaceCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceFormatsKHRFunc) (VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, deUint32* pSurfaceFormatCount, VkSurfaceFormatKHR* pSurfaceFormats); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfacePresentModesKHRFunc) (VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, deUint32* pPresentModeCount, VkPresentModeKHR* pPresentModes); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSwapchainKHRFunc) (VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySwapchainKHRFunc) (VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSwapchainImagesKHRFunc) (VkDevice device, VkSwapchainKHR swapchain, deUint32* pSwapchainImageCount, VkImage* pSwapchainImages); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireNextImageKHRFunc) (VkDevice device, VkSwapchainKHR swapchain, deUint64 timeout, VkSemaphore semaphore, VkFence fence, deUint32* pImageIndex); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueuePresentKHRFunc) (VkQueue queue, const VkPresentInfoKHR* pPresentInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDeviceGroupPresentCapabilitiesKHRFunc) (VkDevice device, VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDeviceGroupSurfacePresentModesKHRFunc) (VkDevice device, VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHR* pModes); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDevicePresentRectanglesKHRFunc) (VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, deUint32* pRectCount, VkRect2D* pRects); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireNextImage2KHRFunc) (VkDevice device, const VkAcquireNextImageInfoKHR* pAcquireInfo, deUint32* pImageIndex); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceDisplayPropertiesKHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkDisplayPropertiesKHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceDisplayPlanePropertiesKHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkDisplayPlanePropertiesKHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDisplayPlaneSupportedDisplaysKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 planeIndex, deUint32* pDisplayCount, VkDisplayKHR* pDisplays); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDisplayModePropertiesKHRFunc) (VkPhysicalDevice physicalDevice, VkDisplayKHR display, deUint32* pPropertyCount, VkDisplayModePropertiesKHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDisplayModeKHRFunc) (VkPhysicalDevice physicalDevice, VkDisplayKHR display, const VkDisplayModeCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDisplayModeKHR* pMode); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDisplayPlaneCapabilitiesKHRFunc) (VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode, deUint32 planeIndex, VkDisplayPlaneCapabilitiesKHR* pCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDisplayPlaneSurfaceKHRFunc) (VkInstance instance, const VkDisplaySurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSharedSwapchainsKHRFunc) (VkDevice device, deUint32 swapchainCount, const VkSwapchainCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchains); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFeatures2KHRFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceProperties2KHRFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceFormatProperties2KHRFunc) (VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2* pFormatProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceImageFormatProperties2KHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, VkImageFormatProperties2* pImageFormatProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceQueueFamilyProperties2KHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceMemoryProperties2KHRFunc) (VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2* pMemoryProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceSparseImageFormatProperties2KHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, deUint32* pPropertyCount, VkSparseImageFormatProperties2* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceGroupPeerMemoryFeaturesKHRFunc) (VkDevice device, deUint32 heapIndex, deUint32 localDeviceIndex, deUint32 remoteDeviceIndex, VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDeviceMaskKHRFunc) (VkCommandBuffer commandBuffer, deUint32 deviceMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDispatchBaseKHRFunc) (VkCommandBuffer commandBuffer, deUint32 baseGroupX, deUint32 baseGroupY, deUint32 baseGroupZ, deUint32 groupCountX, deUint32 groupCountY, deUint32 groupCountZ); typedef VKAPI_ATTR void (VKAPI_CALL* TrimCommandPoolKHRFunc) (VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlags flags); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumeratePhysicalDeviceGroupsKHRFunc) (VkInstance instance, deUint32* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalBufferPropertiesKHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryFdKHRFunc) (VkDevice device, const VkMemoryGetFdInfoKHR* pGetFdInfo, int* pFd); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryFdPropertiesKHRFunc) (VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, int fd, VkMemoryFdPropertiesKHR* pMemoryFdProperties); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalSemaphorePropertiesKHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ImportSemaphoreFdKHRFunc) (VkDevice device, const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSemaphoreFdKHRFunc) (VkDevice device, const VkSemaphoreGetFdInfoKHR* pGetFdInfo, int* pFd); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPushDescriptorSetKHRFunc) (VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, deUint32 set, deUint32 descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPushDescriptorSetWithTemplateKHRFunc) (VkCommandBuffer commandBuffer, VkDescriptorUpdateTemplate descriptorUpdateTemplate, VkPipelineLayout layout, deUint32 set, const void* pData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDescriptorUpdateTemplateKHRFunc) (VkDevice device, const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDescriptorUpdateTemplateKHRFunc) (VkDevice device, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* UpdateDescriptorSetWithTemplateKHRFunc) (VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void* pData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateRenderPass2KHRFunc) (VkDevice device, const VkRenderPassCreateInfo2* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginRenderPass2KHRFunc) (VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, const VkSubpassBeginInfo* pSubpassBeginInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdNextSubpass2KHRFunc) (VkCommandBuffer commandBuffer, const VkSubpassBeginInfo* pSubpassBeginInfo, const VkSubpassEndInfo* pSubpassEndInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndRenderPass2KHRFunc) (VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSwapchainStatusKHRFunc) (VkDevice device, VkSwapchainKHR swapchain); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceExternalFencePropertiesKHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ImportFenceFdKHRFunc) (VkDevice device, const VkImportFenceFdInfoKHR* pImportFenceFdInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetFenceFdKHRFunc) (VkDevice device, const VkFenceGetFdInfoKHR* pGetFdInfo, int* pFd); typedef VKAPI_ATTR VkResult (VKAPI_CALL* EnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex, deUint32* pCounterCount, VkPerformanceCounterKHR* pCounters, VkPerformanceCounterDescriptionKHR* pCounterDescriptions); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHRFunc) (VkPhysicalDevice physicalDevice, const VkQueryPoolPerformanceCreateInfoKHR* pPerformanceQueryCreateInfo, deUint32* pNumPasses); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireProfilingLockKHRFunc) (VkDevice device, const VkAcquireProfilingLockInfoKHR* pInfo); typedef VKAPI_ATTR void (VKAPI_CALL* ReleaseProfilingLockKHRFunc) (VkDevice device); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceCapabilities2KHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceFormats2KHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, deUint32* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceDisplayProperties2KHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkDisplayProperties2KHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceDisplayPlaneProperties2KHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkDisplayPlaneProperties2KHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDisplayModeProperties2KHRFunc) (VkPhysicalDevice physicalDevice, VkDisplayKHR display, deUint32* pPropertyCount, VkDisplayModeProperties2KHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDisplayPlaneCapabilities2KHRFunc) (VkPhysicalDevice physicalDevice, const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo, VkDisplayPlaneCapabilities2KHR* pCapabilities); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageMemoryRequirements2KHRFunc) (VkDevice device, const VkImageMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetBufferMemoryRequirements2KHRFunc) (VkDevice device, const VkBufferMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* GetImageSparseMemoryRequirements2KHRFunc) (VkDevice device, const VkImageSparseMemoryRequirementsInfo2* pInfo, deUint32* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateSamplerYcbcrConversionKHRFunc) (VkDevice device, const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversion* pYcbcrConversion); typedef VKAPI_ATTR void (VKAPI_CALL* DestroySamplerYcbcrConversionKHRFunc) (VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindBufferMemory2KHRFunc) (VkDevice device, deUint32 bindInfoCount, const VkBindBufferMemoryInfo* pBindInfos); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindImageMemory2KHRFunc) (VkDevice device, deUint32 bindInfoCount, const VkBindImageMemoryInfo* pBindInfos); typedef VKAPI_ATTR void (VKAPI_CALL* GetDescriptorSetLayoutSupportKHRFunc) (VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupport* pSupport); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndirectCountKHRFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndexedIndirectCountKHRFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSemaphoreCounterValueKHRFunc) (VkDevice device, VkSemaphore semaphore, deUint64* pValue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* WaitSemaphoresKHRFunc) (VkDevice device, const VkSemaphoreWaitInfo* pWaitInfo, deUint64 timeout); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SignalSemaphoreKHRFunc) (VkDevice device, const VkSemaphoreSignalInfo* pSignalInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceFragmentShadingRatesKHRFunc) (VkPhysicalDevice physicalDevice, deUint32* pFragmentShadingRateCount, VkPhysicalDeviceFragmentShadingRateKHR* pFragmentShadingRates); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetFragmentShadingRateKHRFunc) (VkCommandBuffer commandBuffer, const VkExtent2D* pFragmentSize, const VkFragmentShadingRateCombinerOpKHR combinerOps[2]); typedef VKAPI_ATTR VkDeviceAddress (VKAPI_CALL* GetBufferDeviceAddressKHRFunc) (VkDevice device, const VkBufferDeviceAddressInfo* pInfo); typedef VKAPI_ATTR uint64_t (VKAPI_CALL* GetBufferOpaqueCaptureAddressKHRFunc) (VkDevice device, const VkBufferDeviceAddressInfo* pInfo); typedef VKAPI_ATTR uint64_t (VKAPI_CALL* GetDeviceMemoryOpaqueCaptureAddressKHRFunc) (VkDevice device, const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDeferredOperationKHRFunc) (VkDevice device, const VkAllocationCallbacks* pAllocator, VkDeferredOperationKHR* pDeferredOperation); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDeferredOperationKHRFunc) (VkDevice device, VkDeferredOperationKHR operation, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR uint32_t (VKAPI_CALL* GetDeferredOperationMaxConcurrencyKHRFunc) (VkDevice device, VkDeferredOperationKHR operation); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDeferredOperationResultKHRFunc) (VkDevice device, VkDeferredOperationKHR operation); typedef VKAPI_ATTR VkResult (VKAPI_CALL* DeferredOperationJoinKHRFunc) (VkDevice device, VkDeferredOperationKHR operation); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPipelineExecutablePropertiesKHRFunc) (VkDevice device, const VkPipelineInfoKHR* pPipelineInfo, deUint32* pExecutableCount, VkPipelineExecutablePropertiesKHR* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPipelineExecutableStatisticsKHRFunc) (VkDevice device, const VkPipelineExecutableInfoKHR* pExecutableInfo, deUint32* pStatisticCount, VkPipelineExecutableStatisticKHR* pStatistics); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPipelineExecutableInternalRepresentationsKHRFunc) (VkDevice device, const VkPipelineExecutableInfoKHR* pExecutableInfo, deUint32* pInternalRepresentationCount, VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetEvent2KHRFunc) (VkCommandBuffer commandBuffer, VkEvent event, const VkDependencyInfoKHR* pDependencyInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdResetEvent2KHRFunc) (VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2KHR stageMask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWaitEvents2KHRFunc) (VkCommandBuffer commandBuffer, deUint32 eventCount, const VkEvent* pEvents, const VkDependencyInfoKHR* pDependencyInfos); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPipelineBarrier2KHRFunc) (VkCommandBuffer commandBuffer, const VkDependencyInfoKHR* pDependencyInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteTimestamp2KHRFunc) (VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkQueryPool queryPool, deUint32 query); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueueSubmit2KHRFunc) (VkQueue queue, deUint32 submitCount, const VkSubmitInfo2KHR* pSubmits, VkFence fence); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteBufferMarker2AMDFunc) (VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkBuffer dstBuffer, VkDeviceSize dstOffset, deUint32 marker); typedef VKAPI_ATTR void (VKAPI_CALL* GetQueueCheckpointData2NVFunc) (VkQueue queue, deUint32* pCheckpointDataCount, VkCheckpointData2NV* pCheckpointData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyBuffer2KHRFunc) (VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR* pCopyBufferInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyImage2KHRFunc) (VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR* pCopyImageInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyBufferToImage2KHRFunc) (VkCommandBuffer commandBuffer, const VkCopyBufferToImageInfo2KHR* pCopyBufferToImageInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyImageToBuffer2KHRFunc) (VkCommandBuffer commandBuffer, const VkCopyImageToBufferInfo2KHR* pCopyImageToBufferInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBlitImage2KHRFunc) (VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR* pBlitImageInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdResolveImage2KHRFunc) (VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR* pResolveImageInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDebugReportCallbackEXTFunc) (VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDebugReportCallbackEXTFunc) (VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* DebugReportMessageEXTFunc) (VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, deUint64 object, deUintptr location, deInt32 messageCode, const char* pLayerPrefix, const char* pMessage); typedef VKAPI_ATTR VkResult (VKAPI_CALL* DebugMarkerSetObjectTagEXTFunc) (VkDevice device, const VkDebugMarkerObjectTagInfoEXT* pTagInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* DebugMarkerSetObjectNameEXTFunc) (VkDevice device, const VkDebugMarkerObjectNameInfoEXT* pNameInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDebugMarkerBeginEXTFunc) (VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDebugMarkerEndEXTFunc) (VkCommandBuffer commandBuffer); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDebugMarkerInsertEXTFunc) (VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindTransformFeedbackBuffersEXTFunc) (VkCommandBuffer commandBuffer, deUint32 firstBinding, deUint32 bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets, const VkDeviceSize* pSizes); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginTransformFeedbackEXTFunc) (VkCommandBuffer commandBuffer, deUint32 firstCounterBuffer, deUint32 counterBufferCount, const VkBuffer* pCounterBuffers, const VkDeviceSize* pCounterBufferOffsets); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndTransformFeedbackEXTFunc) (VkCommandBuffer commandBuffer, deUint32 firstCounterBuffer, deUint32 counterBufferCount, const VkBuffer* pCounterBuffers, const VkDeviceSize* pCounterBufferOffsets); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginQueryIndexedEXTFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 query, VkQueryControlFlags flags, deUint32 index); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndQueryIndexedEXTFunc) (VkCommandBuffer commandBuffer, VkQueryPool queryPool, deUint32 query, deUint32 index); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndirectByteCountEXTFunc) (VkCommandBuffer commandBuffer, deUint32 instanceCount, deUint32 firstInstance, VkBuffer counterBuffer, VkDeviceSize counterBufferOffset, deUint32 counterOffset, deUint32 vertexStride); typedef VKAPI_ATTR uint32_t (VKAPI_CALL* GetImageViewHandleNVXFunc) (VkDevice device, const VkImageViewHandleInfoNVX* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetImageViewAddressNVXFunc) (VkDevice device, VkImageView imageView, VkImageViewAddressPropertiesNVX* pProperties); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndirectCountAMDFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawIndexedIndirectCountAMDFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetShaderInfoAMDFunc) (VkDevice device, VkPipeline pipeline, VkShaderStageFlagBits shaderStage, VkShaderInfoTypeAMD infoType, deUintptr* pInfoSize, void* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceExternalImageFormatPropertiesNVFunc) (VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkExternalMemoryHandleTypeFlagsNV externalHandleType, VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginConditionalRenderingEXTFunc) (VkCommandBuffer commandBuffer, const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndConditionalRenderingEXTFunc) (VkCommandBuffer commandBuffer); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetViewportWScalingNVFunc) (VkCommandBuffer commandBuffer, deUint32 firstViewport, deUint32 viewportCount, const VkViewportWScalingNV* pViewportWScalings); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ReleaseDisplayEXTFunc) (VkPhysicalDevice physicalDevice, VkDisplayKHR display); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfaceCapabilities2EXTFunc) (VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilities2EXT* pSurfaceCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* DisplayPowerControlEXTFunc) (VkDevice device, VkDisplayKHR display, const VkDisplayPowerInfoEXT* pDisplayPowerInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* RegisterDeviceEventEXTFunc) (VkDevice device, const VkDeviceEventInfoEXT* pDeviceEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); typedef VKAPI_ATTR VkResult (VKAPI_CALL* RegisterDisplayEventEXTFunc) (VkDevice device, VkDisplayKHR display, const VkDisplayEventInfoEXT* pDisplayEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSwapchainCounterEXTFunc) (VkDevice device, VkSwapchainKHR swapchain, VkSurfaceCounterFlagBitsEXT counter, deUint64* pCounterValue); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetRefreshCycleDurationGOOGLEFunc) (VkDevice device, VkSwapchainKHR swapchain, VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPastPresentationTimingGOOGLEFunc) (VkDevice device, VkSwapchainKHR swapchain, deUint32* pPresentationTimingCount, VkPastPresentationTimingGOOGLE* pPresentationTimings); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDiscardRectangleEXTFunc) (VkCommandBuffer commandBuffer, deUint32 firstDiscardRectangle, deUint32 discardRectangleCount, const VkRect2D* pDiscardRectangles); typedef VKAPI_ATTR void (VKAPI_CALL* SetHdrMetadataEXTFunc) (VkDevice device, deUint32 swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pMetadata); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SetDebugUtilsObjectNameEXTFunc) (VkDevice device, const VkDebugUtilsObjectNameInfoEXT* pNameInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SetDebugUtilsObjectTagEXTFunc) (VkDevice device, const VkDebugUtilsObjectTagInfoEXT* pTagInfo); typedef VKAPI_ATTR void (VKAPI_CALL* QueueBeginDebugUtilsLabelEXTFunc) (VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo); typedef VKAPI_ATTR void (VKAPI_CALL* QueueEndDebugUtilsLabelEXTFunc) (VkQueue queue); typedef VKAPI_ATTR void (VKAPI_CALL* QueueInsertDebugUtilsLabelEXTFunc) (VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginDebugUtilsLabelEXTFunc) (VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndDebugUtilsLabelEXTFunc) (VkCommandBuffer commandBuffer); typedef VKAPI_ATTR void (VKAPI_CALL* CmdInsertDebugUtilsLabelEXTFunc) (VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateDebugUtilsMessengerEXTFunc) (VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pMessenger); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyDebugUtilsMessengerEXTFunc) (VkInstance instance, VkDebugUtilsMessengerEXT messenger, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* SubmitDebugUtilsMessageEXTFunc) (VkInstance instance, VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetSampleLocationsEXTFunc) (VkCommandBuffer commandBuffer, const VkSampleLocationsInfoEXT* pSampleLocationsInfo); typedef VKAPI_ATTR void (VKAPI_CALL* GetPhysicalDeviceMultisamplePropertiesEXTFunc) (VkPhysicalDevice physicalDevice, VkSampleCountFlagBits samples, VkMultisamplePropertiesEXT* pMultisampleProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetImageDrmFormatModifierPropertiesEXTFunc) (VkDevice device, VkImage image, VkImageDrmFormatModifierPropertiesEXT* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateValidationCacheEXTFunc) (VkDevice device, const VkValidationCacheCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkValidationCacheEXT* pValidationCache); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyValidationCacheEXTFunc) (VkDevice device, VkValidationCacheEXT validationCache, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* MergeValidationCachesEXTFunc) (VkDevice device, VkValidationCacheEXT dstCache, deUint32 srcCacheCount, const VkValidationCacheEXT* pSrcCaches); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetValidationCacheDataEXTFunc) (VkDevice device, VkValidationCacheEXT validationCache, deUintptr* pDataSize, void* pData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindShadingRateImageNVFunc) (VkCommandBuffer commandBuffer, VkImageView imageView, VkImageLayout imageLayout); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetViewportShadingRatePaletteNVFunc) (VkCommandBuffer commandBuffer, deUint32 firstViewport, deUint32 viewportCount, const VkShadingRatePaletteNV* pShadingRatePalettes); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetCoarseSampleOrderNVFunc) (VkCommandBuffer commandBuffer, VkCoarseSampleOrderTypeNV sampleOrderType, deUint32 customSampleOrderCount, const VkCoarseSampleOrderCustomNV* pCustomSampleOrders); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateAccelerationStructureNVFunc) (VkDevice device, const VkAccelerationStructureCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureNV* pAccelerationStructure); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyAccelerationStructureNVFunc) (VkDevice device, VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* GetAccelerationStructureMemoryRequirementsNVFunc) (VkDevice device, const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindAccelerationStructureMemoryNVFunc) (VkDevice device, deUint32 bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBuildAccelerationStructureNVFunc) (VkCommandBuffer commandBuffer, const VkAccelerationStructureInfoNV* pInfo, VkBuffer instanceData, VkDeviceSize instanceOffset, VkBool32 update, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkBuffer scratch, VkDeviceSize scratchOffset); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyAccelerationStructureNVFunc) (VkCommandBuffer commandBuffer, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkCopyAccelerationStructureModeKHR mode); typedef VKAPI_ATTR void (VKAPI_CALL* CmdTraceRaysNVFunc) (VkCommandBuffer commandBuffer, VkBuffer raygenShaderBindingTableBuffer, VkDeviceSize raygenShaderBindingOffset, VkBuffer missShaderBindingTableBuffer, VkDeviceSize missShaderBindingOffset, VkDeviceSize missShaderBindingStride, VkBuffer hitShaderBindingTableBuffer, VkDeviceSize hitShaderBindingOffset, VkDeviceSize hitShaderBindingStride, VkBuffer callableShaderBindingTableBuffer, VkDeviceSize callableShaderBindingOffset, VkDeviceSize callableShaderBindingStride, deUint32 width, deUint32 height, deUint32 depth); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateRayTracingPipelinesNVFunc) (VkDevice device, VkPipelineCache pipelineCache, deUint32 createInfoCount, const VkRayTracingPipelineCreateInfoNV* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetRayTracingShaderGroupHandlesKHRFunc) (VkDevice device, VkPipeline pipeline, deUint32 firstGroup, deUint32 groupCount, deUintptr dataSize, void* pData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetRayTracingShaderGroupHandlesNVFunc) (VkDevice device, VkPipeline pipeline, deUint32 firstGroup, deUint32 groupCount, deUintptr dataSize, void* pData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetAccelerationStructureHandleNVFunc) (VkDevice device, VkAccelerationStructureNV accelerationStructure, deUintptr dataSize, void* pData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteAccelerationStructuresPropertiesNVFunc) (VkCommandBuffer commandBuffer, deUint32 accelerationStructureCount, const VkAccelerationStructureNV* pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, deUint32 firstQuery); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CompileDeferredNVFunc) (VkDevice device, VkPipeline pipeline, deUint32 shader); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryHostPointerPropertiesEXTFunc) (VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, const void* pHostPointer, VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteBufferMarkerAMDFunc) (VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkBuffer dstBuffer, VkDeviceSize dstOffset, deUint32 marker); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceCalibrateableTimeDomainsEXTFunc) (VkPhysicalDevice physicalDevice, deUint32* pTimeDomainCount, VkTimeDomainEXT* pTimeDomains); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetCalibratedTimestampsEXTFunc) (VkDevice device, deUint32 timestampCount, const VkCalibratedTimestampInfoEXT* pTimestampInfos, deUint64* pTimestamps, deUint64* pMaxDeviation); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawMeshTasksNVFunc) (VkCommandBuffer commandBuffer, deUint32 taskCount, deUint32 firstTask); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawMeshTasksIndirectNVFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, deUint32 drawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDrawMeshTasksIndirectCountNVFunc) (VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, deUint32 maxDrawCount, deUint32 stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetExclusiveScissorNVFunc) (VkCommandBuffer commandBuffer, deUint32 firstExclusiveScissor, deUint32 exclusiveScissorCount, const VkRect2D* pExclusiveScissors); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetCheckpointNVFunc) (VkCommandBuffer commandBuffer, const void* pCheckpointMarker); typedef VKAPI_ATTR void (VKAPI_CALL* GetQueueCheckpointDataNVFunc) (VkQueue queue, deUint32* pCheckpointDataCount, VkCheckpointDataNV* pCheckpointData); typedef VKAPI_ATTR VkResult (VKAPI_CALL* InitializePerformanceApiINTELFunc) (VkDevice device, const VkInitializePerformanceApiInfoINTEL* pInitializeInfo); typedef VKAPI_ATTR void (VKAPI_CALL* UninitializePerformanceApiINTELFunc) (VkDevice device); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CmdSetPerformanceMarkerINTELFunc) (VkCommandBuffer commandBuffer, const VkPerformanceMarkerInfoINTEL* pMarkerInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CmdSetPerformanceStreamMarkerINTELFunc) (VkCommandBuffer commandBuffer, const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CmdSetPerformanceOverrideINTELFunc) (VkCommandBuffer commandBuffer, const VkPerformanceOverrideInfoINTEL* pOverrideInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquirePerformanceConfigurationINTELFunc) (VkDevice device, const VkPerformanceConfigurationAcquireInfoINTEL* pAcquireInfo, VkPerformanceConfigurationINTEL* pConfiguration); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ReleasePerformanceConfigurationINTELFunc) (VkDevice device, VkPerformanceConfigurationINTEL configuration); typedef VKAPI_ATTR VkResult (VKAPI_CALL* QueueSetPerformanceConfigurationINTELFunc) (VkQueue queue, VkPerformanceConfigurationINTEL configuration); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPerformanceParameterINTELFunc) (VkDevice device, VkPerformanceParameterTypeINTEL parameter, VkPerformanceValueINTEL* pValue); typedef VKAPI_ATTR void (VKAPI_CALL* SetLocalDimmingAMDFunc) (VkDevice device, VkSwapchainKHR swapChain, VkBool32 localDimmingEnable); typedef VKAPI_ATTR VkDeviceAddress (VKAPI_CALL* GetBufferDeviceAddressEXTFunc) (VkDevice device, const VkBufferDeviceAddressInfo* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceToolPropertiesEXTFunc) (VkPhysicalDevice physicalDevice, deUint32* pToolCount, VkPhysicalDeviceToolPropertiesEXT* pToolProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceCooperativeMatrixPropertiesNVFunc) (VkPhysicalDevice physicalDevice, deUint32* pPropertyCount, VkCooperativeMatrixPropertiesNV* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVFunc) (VkPhysicalDevice physicalDevice, deUint32* pCombinationCount, VkFramebufferMixedSamplesCombinationNV* pCombinations); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateHeadlessSurfaceEXTFunc) (VkInstance instance, const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetLineStippleEXTFunc) (VkCommandBuffer commandBuffer, deUint32 lineStippleFactor, deUint16 lineStipplePattern); typedef VKAPI_ATTR void (VKAPI_CALL* ResetQueryPoolEXTFunc) (VkDevice device, VkQueryPool queryPool, deUint32 firstQuery, deUint32 queryCount); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetCullModeEXTFunc) (VkCommandBuffer commandBuffer, VkCullModeFlags cullMode); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetFrontFaceEXTFunc) (VkCommandBuffer commandBuffer, VkFrontFace frontFace); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetPrimitiveTopologyEXTFunc) (VkCommandBuffer commandBuffer, VkPrimitiveTopology primitiveTopology); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetViewportWithCountEXTFunc) (VkCommandBuffer commandBuffer, deUint32 viewportCount, const VkViewport* pViewports); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetScissorWithCountEXTFunc) (VkCommandBuffer commandBuffer, deUint32 scissorCount, const VkRect2D* pScissors); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindVertexBuffers2EXTFunc) (VkCommandBuffer commandBuffer, deUint32 firstBinding, deUint32 bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets, const VkDeviceSize* pSizes, const VkDeviceSize* pStrides); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthTestEnableEXTFunc) (VkCommandBuffer commandBuffer, VkBool32 depthTestEnable); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthWriteEnableEXTFunc) (VkCommandBuffer commandBuffer, VkBool32 depthWriteEnable); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthCompareOpEXTFunc) (VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetDepthBoundsTestEnableEXTFunc) (VkCommandBuffer commandBuffer, VkBool32 depthBoundsTestEnable); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetStencilTestEnableEXTFunc) (VkCommandBuffer commandBuffer, VkBool32 stencilTestEnable); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetStencilOpEXTFunc) (VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp); typedef VKAPI_ATTR void (VKAPI_CALL* GetGeneratedCommandsMemoryRequirementsNVFunc) (VkDevice device, const VkGeneratedCommandsMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2* pMemoryRequirements); typedef VKAPI_ATTR void (VKAPI_CALL* CmdPreprocessGeneratedCommandsNVFunc) (VkCommandBuffer commandBuffer, const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdExecuteGeneratedCommandsNVFunc) (VkCommandBuffer commandBuffer, VkBool32 isPreprocessed, const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBindPipelineShaderGroupNVFunc) (VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline, deUint32 groupIndex); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateIndirectCommandsLayoutNVFunc) (VkDevice device, const VkIndirectCommandsLayoutCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkIndirectCommandsLayoutNV* pIndirectCommandsLayout); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyIndirectCommandsLayoutNVFunc) (VkDevice device, VkIndirectCommandsLayoutNV indirectCommandsLayout, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreatePrivateDataSlotEXTFunc) (VkDevice device, const VkPrivateDataSlotCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPrivateDataSlotEXT* pPrivateDataSlot); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyPrivateDataSlotEXTFunc) (VkDevice device, VkPrivateDataSlotEXT privateDataSlot, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* SetPrivateDataEXTFunc) (VkDevice device, VkObjectType objectType, deUint64 objectHandle, VkPrivateDataSlotEXT privateDataSlot, deUint64 data); typedef VKAPI_ATTR void (VKAPI_CALL* GetPrivateDataEXTFunc) (VkDevice device, VkObjectType objectType, deUint64 objectHandle, VkPrivateDataSlotEXT privateDataSlot, deUint64* pData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetFragmentShadingRateEnumNVFunc) (VkCommandBuffer commandBuffer, VkFragmentShadingRateNV shadingRate, const VkFragmentShadingRateCombinerOpKHR combinerOps[2]); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireWinrtDisplayNVFunc) (VkPhysicalDevice physicalDevice, VkDisplayKHR display); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetWinrtDisplayNVFunc) (VkPhysicalDevice physicalDevice, deUint32 deviceRelativeId, VkDisplayKHR* pDisplay); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetVertexInputEXTFunc) (VkCommandBuffer commandBuffer, deUint32 vertexBindingDescriptionCount, const VkVertexInputBindingDescription2EXT* pVertexBindingDescriptions, deUint32 vertexAttributeDescriptionCount, const VkVertexInputAttributeDescription2EXT* pVertexAttributeDescriptions); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetColorWriteEnableEXTFunc) (VkCommandBuffer commandBuffer, deUint32 attachmentCount, const VkBool32* pColorWriteEnables); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateAccelerationStructureKHRFunc) (VkDevice device, const VkAccelerationStructureCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureKHR* pAccelerationStructure); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyAccelerationStructureKHRFunc) (VkDevice device, VkAccelerationStructureKHR accelerationStructure, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBuildAccelerationStructuresKHRFunc) (VkCommandBuffer commandBuffer, deUint32 infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBuildAccelerationStructuresIndirectKHRFunc) (VkCommandBuffer commandBuffer, deUint32 infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkDeviceAddress* pIndirectDeviceAddresses, const deUint32* pIndirectStrides, const deUint32* const* ppMaxPrimitiveCounts); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BuildAccelerationStructuresKHRFunc) (VkDevice device, VkDeferredOperationKHR deferredOperation, deUint32 infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CopyAccelerationStructureKHRFunc) (VkDevice device, VkDeferredOperationKHR deferredOperation, const VkCopyAccelerationStructureInfoKHR* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CopyAccelerationStructureToMemoryKHRFunc) (VkDevice device, VkDeferredOperationKHR deferredOperation, const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CopyMemoryToAccelerationStructureKHRFunc) (VkDevice device, VkDeferredOperationKHR deferredOperation, const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* WriteAccelerationStructuresPropertiesKHRFunc) (VkDevice device, deUint32 accelerationStructureCount, const VkAccelerationStructureKHR* pAccelerationStructures, VkQueryType queryType, deUintptr dataSize, void* pData, deUintptr stride); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyAccelerationStructureKHRFunc) (VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureInfoKHR* pInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyAccelerationStructureToMemoryKHRFunc) (VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdCopyMemoryToAccelerationStructureKHRFunc) (VkCommandBuffer commandBuffer, const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo); typedef VKAPI_ATTR VkDeviceAddress (VKAPI_CALL* GetAccelerationStructureDeviceAddressKHRFunc) (VkDevice device, const VkAccelerationStructureDeviceAddressInfoKHR* pInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdWriteAccelerationStructuresPropertiesKHRFunc) (VkCommandBuffer commandBuffer, deUint32 accelerationStructureCount, const VkAccelerationStructureKHR* pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, deUint32 firstQuery); typedef VKAPI_ATTR void (VKAPI_CALL* GetDeviceAccelerationStructureCompatibilityKHRFunc) (VkDevice device, const VkAccelerationStructureVersionInfoKHR* pVersionInfo, VkAccelerationStructureCompatibilityKHR* pCompatibility); typedef VKAPI_ATTR void (VKAPI_CALL* GetAccelerationStructureBuildSizesKHRFunc) (VkDevice device, VkAccelerationStructureBuildTypeKHR buildType, const VkAccelerationStructureBuildGeometryInfoKHR* pBuildInfo, const deUint32* pMaxPrimitiveCounts, VkAccelerationStructureBuildSizesInfoKHR* pSizeInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdTraceRaysKHRFunc) (VkCommandBuffer commandBuffer, const VkStridedDeviceAddressRegionKHR* pRaygenShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pMissShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pHitShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pCallableShaderBindingTable, deUint32 width, deUint32 height, deUint32 depth); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateRayTracingPipelinesKHRFunc) (VkDevice device, VkDeferredOperationKHR deferredOperation, VkPipelineCache pipelineCache, deUint32 createInfoCount, const VkRayTracingPipelineCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetRayTracingCaptureReplayShaderGroupHandlesKHRFunc) (VkDevice device, VkPipeline pipeline, deUint32 firstGroup, deUint32 groupCount, deUintptr dataSize, void* pData); typedef VKAPI_ATTR void (VKAPI_CALL* CmdTraceRaysIndirectKHRFunc) (VkCommandBuffer commandBuffer, const VkStridedDeviceAddressRegionKHR* pRaygenShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pMissShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pHitShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pCallableShaderBindingTable, VkDeviceAddress indirectDeviceAddress); typedef VKAPI_ATTR VkDeviceSize (VKAPI_CALL* GetRayTracingShaderGroupStackSizeKHRFunc) (VkDevice device, VkPipeline pipeline, deUint32 group, VkShaderGroupShaderKHR groupShader); typedef VKAPI_ATTR void (VKAPI_CALL* CmdSetRayTracingPipelineStackSizeKHRFunc) (VkCommandBuffer commandBuffer, deUint32 pipelineStackSize); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateAndroidSurfaceKHRFunc) (VkInstance instance, const VkAndroidSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetAndroidHardwareBufferPropertiesANDROIDFunc) (VkDevice device, const struct pt::AndroidHardwareBufferPtr buffer, VkAndroidHardwareBufferPropertiesANDROID* pProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryAndroidHardwareBufferANDROIDFunc) (VkDevice device, const VkMemoryGetAndroidHardwareBufferInfoANDROID* pInfo, struct pt::AndroidHardwareBufferPtr* pBuffer); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceVideoCapabilitiesKHRFunc) (VkPhysicalDevice physicalDevice, const VkVideoProfileKHR* pVideoProfile, VkVideoCapabilitiesKHR* pCapabilities); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceVideoFormatPropertiesKHRFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceVideoFormatInfoKHR* pVideoFormatInfo, deUint32* pVideoFormatPropertyCount, VkVideoFormatPropertiesKHR* pVideoFormatProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateVideoSessionKHRFunc) (VkDevice device, const VkVideoSessionCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkVideoSessionKHR* pVideoSession); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyVideoSessionKHRFunc) (VkDevice device, VkVideoSessionKHR videoSession, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetVideoSessionMemoryRequirementsKHRFunc) (VkDevice device, VkVideoSessionKHR videoSession, deUint32* pVideoSessionMemoryRequirementsCount, VkVideoGetMemoryPropertiesKHR* pVideoSessionMemoryRequirements); typedef VKAPI_ATTR VkResult (VKAPI_CALL* BindVideoSessionMemoryKHRFunc) (VkDevice device, VkVideoSessionKHR videoSession, deUint32 videoSessionBindMemoryCount, const VkVideoBindMemoryKHR* pVideoSessionBindMemories); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateVideoSessionParametersKHRFunc) (VkDevice device, const VkVideoSessionParametersCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkVideoSessionParametersKHR* pVideoSessionParameters); typedef VKAPI_ATTR VkResult (VKAPI_CALL* UpdateVideoSessionParametersKHRFunc) (VkDevice device, VkVideoSessionParametersKHR videoSessionParameters, const VkVideoSessionParametersUpdateInfoKHR* pUpdateInfo); typedef VKAPI_ATTR void (VKAPI_CALL* DestroyVideoSessionParametersKHRFunc) (VkDevice device, VkVideoSessionParametersKHR videoSessionParameters, const VkAllocationCallbacks* pAllocator); typedef VKAPI_ATTR void (VKAPI_CALL* CmdBeginVideoCodingKHRFunc) (VkCommandBuffer commandBuffer, const VkVideoBeginCodingInfoKHR* pBeginInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEndVideoCodingKHRFunc) (VkCommandBuffer commandBuffer, const VkVideoEndCodingInfoKHR* pEndCodingInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdControlVideoCodingKHRFunc) (VkCommandBuffer commandBuffer, const VkVideoCodingControlInfoKHR* pCodingControlInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdDecodeVideoKHRFunc) (VkCommandBuffer commandBuffer, const VkVideoDecodeInfoKHR* pFrameInfo); typedef VKAPI_ATTR void (VKAPI_CALL* CmdEncodeVideoKHRFunc) (VkCommandBuffer commandBuffer, const VkVideoEncodeInfoKHR* pEncodeInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateImagePipeSurfaceFUCHSIAFunc) (VkInstance instance, const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryZirconHandleFUCHSIAFunc) (VkDevice device, const VkMemoryGetZirconHandleInfoFUCHSIA* pGetZirconHandleInfo, pt::zx_handle_t* pZirconHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryZirconHandlePropertiesFUCHSIAFunc) (VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, pt::zx_handle_t zirconHandle, VkMemoryZirconHandlePropertiesFUCHSIA* pMemoryZirconHandleProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ImportSemaphoreZirconHandleFUCHSIAFunc) (VkDevice device, const VkImportSemaphoreZirconHandleInfoFUCHSIA* pImportSemaphoreZirconHandleInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSemaphoreZirconHandleFUCHSIAFunc) (VkDevice device, const VkSemaphoreGetZirconHandleInfoFUCHSIA* pGetZirconHandleInfo, pt::zx_handle_t* pZirconHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateStreamDescriptorSurfaceGGPFunc) (VkInstance instance, const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateIOSSurfaceMVKFunc) (VkInstance instance, const VkIOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateMacOSSurfaceMVKFunc) (VkInstance instance, const VkMacOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateMetalSurfaceEXTFunc) (VkInstance instance, const VkMetalSurfaceCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateViSurfaceNNFunc) (VkInstance instance, const VkViSurfaceCreateInfoNN* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateWaylandSurfaceKHRFunc) (VkInstance instance, const VkWaylandSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkBool32 (VKAPI_CALL* GetPhysicalDeviceWaylandPresentationSupportKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex, pt::WaylandDisplayPtr display); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateWin32SurfaceKHRFunc) (VkInstance instance, const VkWin32SurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkBool32 (VKAPI_CALL* GetPhysicalDeviceWin32PresentationSupportKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryWin32HandleKHRFunc) (VkDevice device, const VkMemoryGetWin32HandleInfoKHR* pGetWin32HandleInfo, pt::Win32Handle* pHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryWin32HandlePropertiesKHRFunc) (VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, pt::Win32Handle handle, VkMemoryWin32HandlePropertiesKHR* pMemoryWin32HandleProperties); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ImportSemaphoreWin32HandleKHRFunc) (VkDevice device, const VkImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetSemaphoreWin32HandleKHRFunc) (VkDevice device, const VkSemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo, pt::Win32Handle* pHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ImportFenceWin32HandleKHRFunc) (VkDevice device, const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetFenceWin32HandleKHRFunc) (VkDevice device, const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo, pt::Win32Handle* pHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetMemoryWin32HandleNVFunc) (VkDevice device, VkDeviceMemory memory, VkExternalMemoryHandleTypeFlagsNV handleType, pt::Win32Handle* pHandle); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetPhysicalDeviceSurfacePresentModes2EXTFunc) (VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, deUint32* pPresentModeCount, VkPresentModeKHR* pPresentModes); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireFullScreenExclusiveModeEXTFunc) (VkDevice device, VkSwapchainKHR swapchain); typedef VKAPI_ATTR VkResult (VKAPI_CALL* ReleaseFullScreenExclusiveModeEXTFunc) (VkDevice device, VkSwapchainKHR swapchain); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetDeviceGroupSurfacePresentModes2EXTFunc) (VkDevice device, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkDeviceGroupPresentModeFlagsKHR* pModes); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateXcbSurfaceKHRFunc) (VkInstance instance, const VkXcbSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkBool32 (VKAPI_CALL* GetPhysicalDeviceXcbPresentationSupportKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex, pt::XcbConnectionPtr connection, pt::XcbVisualid visual_id); typedef VKAPI_ATTR VkResult (VKAPI_CALL* CreateXlibSurfaceKHRFunc) (VkInstance instance, const VkXlibSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); typedef VKAPI_ATTR VkBool32 (VKAPI_CALL* GetPhysicalDeviceXlibPresentationSupportKHRFunc) (VkPhysicalDevice physicalDevice, deUint32 queueFamilyIndex, pt::XlibDisplayPtr dpy, pt::XlibVisualID visualID); typedef VKAPI_ATTR VkResult (VKAPI_CALL* AcquireXlibDisplayEXTFunc) (VkPhysicalDevice physicalDevice, pt::XlibDisplayPtr dpy, VkDisplayKHR display); typedef VKAPI_ATTR VkResult (VKAPI_CALL* GetRandROutputDisplayEXTFunc) (VkPhysicalDevice physicalDevice, pt::XlibDisplayPtr dpy, pt::RROutput rrOutput, VkDisplayKHR* pDisplay);
194.193277
589
0.816089
akeley98NV
c8e2df1fae16bebf4efbcbc582a0f8b6c1e172e5
2,029
cpp
C++
RVAF-GUI/teechart/walls.cpp
YangQun1/RVAF-GUI
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
[ "BSD-2-Clause" ]
4
2018-03-31T10:45:19.000Z
2021-10-09T02:57:13.000Z
RVAF-GUI/teechart/walls.cpp
P-Chao/RVAF-GUI
3bbeed7d2ffa400f754f095e7c08400f701813d4
[ "BSD-2-Clause" ]
1
2018-04-22T05:12:36.000Z
2018-04-22T05:12:36.000Z
RVAF-GUI/teechart/walls.cpp
YangQun1/RVAF-GUI
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
[ "BSD-2-Clause" ]
5
2018-01-13T15:57:14.000Z
2019-11-12T03:23:18.000Z
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "walls.h" // Dispatch interfaces referenced by this interface #include "Wall.h" ///////////////////////////////////////////////////////////////////////////// // CWalls properties ///////////////////////////////////////////////////////////////////////////// // CWalls operations CWall CWalls::GetBottom() { LPDISPATCH pDispatch; InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CWall(pDispatch); } CWall CWalls::GetLeft() { LPDISPATCH pDispatch; InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CWall(pDispatch); } BOOL CWalls::GetVisible() { BOOL result; InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CWalls::SetVisible(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } unsigned long CWalls::GetBackColor() { unsigned long result; InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CWalls::SetBackColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CWall CWalls::GetBack() { LPDISPATCH pDispatch; InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CWall(pDispatch); } CWall CWalls::GetRight() { LPDISPATCH pDispatch; InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CWall(pDispatch); } void CWalls::SetSize(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xc9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); }
23.870588
83
0.659438
YangQun1
c8e3e10871208834479e18da04ca66b13991df83
4,653
cpp
C++
src/armnnDeserializer/test/DeserializeCast.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
1
2021-07-03T23:46:08.000Z
2021-07-03T23:46:08.000Z
src/armnnDeserializer/test/DeserializeCast.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
null
null
null
src/armnnDeserializer/test/DeserializeCast.cpp
tuanhe/armnn
8a4bd6671d0106dfb788b8c9019f2f9646770f8d
[ "MIT" ]
null
null
null
// // Copyright © 2021 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "ParserFlatbuffersSerializeFixture.hpp" #include <armnnDeserializer/IDeserializer.hpp> #include <QuantizeHelper.hpp> #include <ResolveType.hpp> #include <boost/test/unit_test.hpp> #include <string> BOOST_AUTO_TEST_SUITE(Deserializer) struct CastFixture : public ParserFlatbuffersSerializeFixture { explicit CastFixture(const std::string& inputShape, const std::string& outputShape, const std::string& inputDataType, const std::string& outputDataType) { m_JsonString = R"( { inputIds: [0], outputIds: [2], layers: [ { layer_type: "InputLayer", layer: { base: { layerBindingId: 0, base: { index: 0, layerName: "inputTensor", layerType: "Input", inputSlots: [{ index: 0, connection: { sourceLayerIndex:0, outputSlotIndex:0 }, }], outputSlots: [{ index: 0, tensorInfo: { dimensions: )" + inputShape + R"(, dataType: )" + inputDataType + R"( } }] } } } }, { layer_type: "CastLayer", layer: { base: { index:1, layerName: "CastLayer", layerType: "Cast", inputSlots: [{ index: 0, connection: { sourceLayerIndex:0, outputSlotIndex:0 }, }], outputSlots: [{ index: 0, tensorInfo: { dimensions: )" + outputShape + R"(, dataType: )" + outputDataType + R"( }, }], }, }, }, { layer_type: "OutputLayer", layer: { base:{ layerBindingId: 2, base: { index: 2, layerName: "outputTensor", layerType: "Output", inputSlots: [{ index: 0, connection: { sourceLayerIndex:1, outputSlotIndex:0 }, }], outputSlots: [{ index: 0, tensorInfo: { dimensions: )" + outputShape + R"(, dataType: )" + outputDataType + R"( }, }], } } }, } ] } )"; Setup(); } }; struct SimpleCastFixture : CastFixture { SimpleCastFixture() : CastFixture("[ 1, 6 ]", "[ 1, 6 ]", "Signed32", "Float32") {} }; BOOST_FIXTURE_TEST_CASE(SimpleCast, SimpleCastFixture) { RunTest<2, armnn::DataType::Signed32 , armnn::DataType::Float32>( 0, {{"inputTensor", { 0, -1, 5, -100, 200, -255 }}}, {{"outputTensor", { 0.0f, -1.0f, 5.0f, -100.0f, 200.0f, -255.0f }}}); } BOOST_AUTO_TEST_SUITE_END()
37.524194
94
0.300666
tuanhe
c8e499f49dcbb730379d3fd59fada0a3c40dcff1
2,698
hpp
C++
include/mettle/suite/compiled_suite.hpp
Hamled/mettle
11e0979c2d84027f4ac941ff922a4278994a8f09
[ "BSD-3-Clause" ]
10
2017-08-11T20:02:26.000Z
2022-01-01T09:50:19.000Z
BowlingTests.Mettle/mettle/suite/compiled_suite.hpp
dhelper/CppUnitTestingAndMockingComparison
4f1049709c2480b0c1435607cdc932b45c209898
[ "MIT" ]
null
null
null
BowlingTests.Mettle/mettle/suite/compiled_suite.hpp
dhelper/CppUnitTestingAndMockingComparison
4f1049709c2480b0c1435607cdc932b45c209898
[ "MIT" ]
null
null
null
#ifndef INC_METTLE_SUITE_COMPILED_SUITE_HPP #define INC_METTLE_SUITE_COMPILED_SUITE_HPP #include <functional> #include <string> #include <vector> #include "attributes.hpp" #include "../test_uid.hpp" #include "../detail/forward_if.hpp" namespace mettle { struct test_result { bool passed; std::string message; }; template<typename Function> struct basic_test_info { using function_type = std::function<Function>; basic_test_info(std::string name, function_type function, attributes attrs) : name(std::move(name)), function(std::move(function)), attrs(std::move(attrs)), id(detail::make_test_uid()) {} std::string name; function_type function; attributes attrs; test_uid id; }; template<typename Function> class compiled_suite { template<typename> friend class compiled_suite; public: using test_info = basic_test_info<Function>; using iterator = typename std::vector<test_info>::const_iterator; template<typename String, typename Tests, typename Subsuites, typename Compile> compiled_suite( String &&name, Tests &&tests, Subsuites &&subsuites, const attributes &attrs, Compile &&compile ) : name_(std::forward<String>(name)) { using detail::forward_if; for(auto &&test : tests) { tests_.emplace_back( forward_if<Tests>(test.name), compile(forward_if<Tests>(test.function)), unite(forward_if<Tests>(test.attrs), attrs) ); } for(auto &&ss : subsuites) subsuites_.emplace_back(forward_if<Subsuites>(ss), attrs, compile); } template<typename Function2, typename Compile> compiled_suite(const compiled_suite<Function2> &suite, const attributes &attrs, Compile &&compile) : compiled_suite(suite.name_, suite.tests_, suite.subsuites_, attrs, std::forward<Compile>(compile)) {} template<typename Function2, typename Compile> compiled_suite(compiled_suite<Function2> &&suite, const attributes &attrs, Compile &&compile) : compiled_suite(std::move(suite.name_), std::move(suite.tests_), std::move(suite.subsuites_), attrs, std::forward<Compile>(compile)) {} const std::string & name() const { return name_; } const std::vector<test_info> & tests() const { return tests_; } const std::vector<compiled_suite> & subsuites() const { return subsuites_; } private: std::string name_; std::vector<test_info> tests_; std::vector<compiled_suite> subsuites_; }; using runnable_suite = compiled_suite<test_result()>; using suites_list = std::vector<runnable_suite>; using test_info = runnable_suite::test_info; } // namespace mettle #endif
27.814433
77
0.69533
Hamled
c8e5c307adebed16a23012c8230f1c4a7e49c80b
1,572
hpp
C++
src/Enzo/enzo_EnzoMethodHeat.hpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
src/Enzo/enzo_EnzoMethodHeat.hpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
src/Enzo/enzo_EnzoMethodHeat.hpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
// See LICENSE_CELLO file for license and copyright information /// @file enzo_EnzoMethodHeat.hpp /// @author James Bordner (jobordner@ucsd.edu) /// @date Thu Apr 1 16:14:38 PDT 2010 /// @brief [\ref Enzo] Declaration of EnzoMethodHeat /// forward Euler solver for the heat equation #ifndef ENZO_ENZO_METHOD_HEAT_HPP #define ENZO_ENZO_METHOD_HEAT_HPP class EnzoMethodHeat : public Method { /// @class EnzoMethodHeat /// @ingroup Enzo /// /// @brief [\ref Enzo] Demonstration method to solve heat equation /// using forward Euler method public: // interface /// Create a new EnzoMethodHeat object EnzoMethodHeat(double alpha, double courant); EnzoMethodHeat() : Method(), alpha_(0.0), courant_(0.0) { } /// Charm++ PUP::able declarations PUPable_decl(EnzoMethodHeat); /// Charm++ PUP::able migration constructor EnzoMethodHeat (CkMigrateMessage *m) : Method (m), alpha_(0.0), courant_(0.0) { } /// CHARM++ Pack / Unpack function void pup (PUP::er &p) ; /// Apply the method to advance a block one timestep virtual void compute( Block * block) throw(); virtual std::string name () throw () { return "heat"; } /// Compute maximum timestep for this method virtual double timestep ( Block * block) throw(); protected: // methods void compute_ (Block * block, enzo_float * Unew ) throw(); protected: // attributes /// Thermal diffusivity double alpha_; /// Courant safety number double courant_; }; #endif /* ENZO_ENZO_METHOD_HEAT_HPP */
23.462687
68
0.668575
TrevorMcCrary
c8e6b8319dcc87d496b56573af098b775f79c6cf
8,149
cc
C++
src/testing/test/gmock_output_test_.cc
zzilla/gbreakpad
02fd5a078bda4eb2fd7ee881c8d301bea2bf87fe
[ "BSD-3-Clause" ]
321
2018-06-17T03:52:46.000Z
2022-03-18T02:34:52.000Z
TestFramework/gmock-1.6.0/test/gmock_output_test_.cc
blackberry-webworks/Ripple-Framework
c3126aa0669068f5ee102b65231fdaebdcdfa9ff
[ "Apache-2.0" ]
72
2015-02-05T11:42:13.000Z
2015-12-09T22:18:41.000Z
TestFramework/gmock-1.6.0/test/gmock_output_test_.cc
blackberry-webworks/Ripple-Framework
c3126aa0669068f5ee102b65231fdaebdcdfa9ff
[ "Apache-2.0" ]
58
2018-06-21T10:43:03.000Z
2022-03-29T12:42:11.000Z
// Copyright 2008, 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. // // Author: wan@google.com (Zhanyong Wan) // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. #include "gmock/gmock.h" #include <stdio.h> #include <string> #include "gtest/gtest.h" using testing::_; using testing::AnyNumber; using testing::Ge; using testing::InSequence; using testing::Ref; using testing::Return; using testing::Sequence; class MockFoo { public: MockFoo() {} MOCK_METHOD3(Bar, char(const std::string& s, int i, double x)); MOCK_METHOD2(Bar2, bool(int x, int y)); MOCK_METHOD2(Bar3, void(int x, int y)); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); }; class GMockOutputTest : public testing::Test { protected: MockFoo foo_; }; TEST_F(GMockOutputTest, ExpectedCall) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { testing::GMOCK_FLAG(verbose) = "info"; EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call testing::GMOCK_FLAG(verbose) = "warning"; } TEST_F(GMockOutputTest, ExplicitActionsRunOut) { EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, UnexpectedCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(1, 0); // Unexpected call foo_.Bar2(0, 0); // Expected call } TEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(1, 0); // Unexpected call foo_.Bar3(0, 0); // Expected call } TEST_F(GMockOutputTest, ExcessiveCall) { EXPECT_CALL(foo_, Bar2(0, _)); foo_.Bar2(0, 0); // Expected call foo_.Bar2(0, 1); // Excessive call } TEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) { EXPECT_CALL(foo_, Bar3(0, _)); foo_.Bar3(0, 0); // Expected call foo_.Bar3(0, 1); // Excessive call } TEST_F(GMockOutputTest, UninterestingCall) { foo_.Bar2(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { foo_.Bar3(0, 1); // Uninteresting call } TEST_F(GMockOutputTest, RetiredExpectation) { EXPECT_CALL(foo_, Bar2(_, _)) .RetiresOnSaturation(); EXPECT_CALL(foo_, Bar2(0, 0)); foo_.Bar2(1, 1); foo_.Bar2(1, 1); // Matches a retired expectation foo_.Bar2(0, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { { InSequence s; EXPECT_CALL(foo_, Bar(_, 0, _)); EXPECT_CALL(foo_, Bar2(0, 0)); EXPECT_CALL(foo_, Bar2(1, _)); } foo_.Bar2(1, 0); // Has one immediate unsatisfied pre-requisite foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { Sequence s1, s2; EXPECT_CALL(foo_, Bar(_, 0, _)) .InSequence(s1); EXPECT_CALL(foo_, Bar2(0, 0)) .InSequence(s2); EXPECT_CALL(foo_, Bar2(1, _)) .InSequence(s1, s2); foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar("Hi", 0, 0); foo_.Bar2(0, 0); foo_.Bar2(1, 0); } TEST_F(GMockOutputTest, UnsatisfiedWith) { EXPECT_CALL(foo_, Bar2(_, _)).With(Ge()); } TEST_F(GMockOutputTest, UnsatisfiedExpectation) { EXPECT_CALL(foo_, Bar(_, _, _)); EXPECT_CALL(foo_, Bar2(0, _)) .Times(2); foo_.Bar2(0, 1); } TEST_F(GMockOutputTest, MismatchArguments) { const std::string s = "Hi"; EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0))); foo_.Bar("Ho", 0, -0.1); // Mismatch arguments foo_.Bar(s, 0, 0); } TEST_F(GMockOutputTest, MismatchWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) .With(Ge()); foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); foo_.Bar2(1, 0); // Unexpected call, takes default action #2. foo_.Bar2(0, 0); // Unexpected call, takes default action #1. foo_.Bar2(2, 2); // Expected call. } TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(1, 1)); foo_.Bar2(2, 2); // Expected call. foo_.Bar2(2, 2); // Excessive call, takes default action #1. foo_.Bar2(1, 1); // Expected call. foo_.Bar2(1, 1); // Excessive call, takes default action #2. } TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)) .WillByDefault(Return(false)); // Default action #2 foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. } TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { ON_CALL(foo_, Bar2(_, _)) .WillByDefault(Return(true)); // Default action #1 EXPECT_CALL(foo_, Bar2(_, _)) .Times(2) .WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } TEST_F(GMockOutputTest, CatchesLeakedMocks) { MockFoo* foo1 = new MockFoo; MockFoo* foo2 = new MockFoo; // Invokes ON_CALL on foo1. ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a')); // Invokes EXPECT_CALL on foo2. EXPECT_CALL(*foo2, Bar2(_, _)); EXPECT_CALL(*foo2, Bar2(1, _)); EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber()); foo2->Bar2(2, 1); foo2->Bar2(1, 1); // Both foo1 and foo2 are deliberately leaked. } void TestCatchesLeakedMocksInAdHocTests() { MockFoo* foo = new MockFoo; // Invokes EXPECT_CALL on foo. EXPECT_CALL(*foo, Bar2(_, _)); foo->Bar2(2, 1); // foo is deliberately leaked. } int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; testing::GMOCK_FLAG(verbose) = "warning"; TestCatchesLeakedMocksInAdHocTests(); return RUN_ALL_TESTS(); }
28.003436
73
0.689901
zzilla
c8e73290272494ac25b7673fa73e1603ef000cdd
3,304
cpp
C++
Project_7_Solution/Source/ModuleParticles.cpp
eriik1212/Efective
82fa3d069b116a9e0c3a1a5cb6e16262bc955da2
[ "MIT" ]
3
2021-02-24T15:47:41.000Z
2021-03-08T17:06:26.000Z
Project_7_Solution/Source/ModuleParticles.cpp
eriik1212/Effective
82fa3d069b116a9e0c3a1a5cb6e16262bc955da2
[ "MIT" ]
null
null
null
Project_7_Solution/Source/ModuleParticles.cpp
eriik1212/Effective
82fa3d069b116a9e0c3a1a5cb6e16262bc955da2
[ "MIT" ]
null
null
null
#include "ModuleParticles.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleCollisions.h" #include "SDL/include/SDL_timer.h" ModuleParticles::ModuleParticles(bool enabled) : Module(enabled) { for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) particles[i] = nullptr; } ModuleParticles::~ModuleParticles() { } bool ModuleParticles::Start() { LOG("Loading particles"); texture = App->textures->Load("Assets/Enemies/White_enemy.png"); // Explosion particle explosion.anim.PushBack({274, 296, 33, 30}); explosion.anim.PushBack({313, 296, 33, 30}); explosion.anim.PushBack({346, 296, 33, 30}); explosion.anim.PushBack({382, 296, 33, 30}); explosion.anim.PushBack({419, 296, 33, 30}); explosion.anim.PushBack({457, 296, 33, 30}); explosion.anim.loop = false; explosion.anim.speed = 0.3f; suriken.anim.PushBack({ 34, 1129, 29, 15 }); surikenBreak.anim.PushBack({ 34, 1129, 29, 15 }); surikenBreak.anim.PushBack({ 34, 1129, 29, 15 }); surikenBreak.anim.PushBack({ 34, 1129, 29, 15 }); surikenBreak.anim.PushBack({ 34, 1129, 29, 15 }); surikenBreak.anim.PushBack({ 34, 1129, 29, 15 }); suriken.speed.x = -5; suriken.lifetime = 180; return true; } bool ModuleParticles::CleanUp() { LOG("Unloading particles"); // Delete all remaining active particles on application exit for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if(particles[i] != nullptr) { delete particles[i]; particles[i] = nullptr; } } return true; } void ModuleParticles::OnCollision(Collider* c1, Collider* c2) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { // Always destroy particles that collide if (particles[i] != nullptr && particles[i]->collider == c1) { delete particles[i]; particles[i] = nullptr; break; } } } update_status ModuleParticles::Update() { for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { Particle* particle = particles[i]; if(particle == nullptr) continue; // Call particle Update. If it has reached its lifetime, destroy it if(particle->Update() == false) { delete particle; particles[i] = nullptr; } } return update_status::UPDATE_CONTINUE; } update_status ModuleParticles::PostUpdate() { //Iterating all particle array and drawing any active particles for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { Particle* particle = particles[i]; if (particle != nullptr && particle->isAlive) { App->render->Blit(texture, particle->position.x, particle->position.y, &(particle->anim.GetCurrentFrame())); } } return update_status::UPDATE_CONTINUE; } void ModuleParticles::AddParticle(const Particle& particle, int x, int y, Collider::Type colliderType, uint delay) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { //Finding an empty slot for a new particle if (particles[i] == nullptr) { Particle* p = new Particle(particle); p->frameCount = -(int)delay; // We start the frameCount as the negative delay p->position.x = x; // so when frameCount reaches 0 the particle will be activated p->position.y = y; //Adding the particle's collider if (colliderType != Collider::Type::NONE) p->collider = App->collisions->AddCollider(p->anim.GetCurrentFrame(), colliderType, this); particles[i] = p; break; } } }
23.432624
114
0.68069
eriik1212
c8ea429d4031e280a0c582797d7055eaca3adad0
24,271
cpp
C++
source/App/TAppDecoder/TAppDecTop.cpp
GregDobby/16.4pgr
d6a3e413477ab82377a3469602a529fd24525a78
[ "BSD-3-Clause" ]
1
2015-06-12T01:49:19.000Z
2015-06-12T01:49:19.000Z
source/App/TAppDecoder/TAppDecTop.cpp
GregDobby/16.4pgr
d6a3e413477ab82377a3469602a529fd24525a78
[ "BSD-3-Clause" ]
null
null
null
source/App/TAppDecoder/TAppDecTop.cpp
GregDobby/16.4pgr
d6a3e413477ab82377a3469602a529fd24525a78
[ "BSD-3-Clause" ]
1
2022-02-22T06:19:14.000Z
2022-02-22T06:19:14.000Z
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2015, ITU/ISO/IEC * 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 ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file TAppDecTop.cpp \brief Decoder application class */ #include <list> #include <vector> #include <stdio.h> #include <fcntl.h> #include <assert.h> #include "TAppDecTop.h" #include "TLibDecoder/AnnexBread.h" #include "TLibDecoder/NALread.h" #if RExt__DECODER_DEBUG_BIT_STATISTICS #include "TLibCommon/TComCodingStatistics.h" #endif //! \ingroup TAppDecoder //! \{ // ==================================================================================================================== // Constructor / destructor / initialization / destroy // ==================================================================================================================== TAppDecTop::TAppDecTop() : m_iPOCLastDisplay(-MAX_INT) { } Void TAppDecTop::create() { } Void TAppDecTop::destroy() { if (m_pchBitstreamFile) { free (m_pchBitstreamFile); m_pchBitstreamFile = NULL; } if (m_pchReconFile) { free (m_pchReconFile); m_pchReconFile = NULL; } } // ==================================================================================================================== // Public member functions // ==================================================================================================================== /** - create internal class - initialize internal class - until the end of the bitstream, call decoding function in TDecTop class - delete allocated buffers - destroy internal class . */ Void TAppDecTop::decode() { Int poc; TComList<TComPic*>* pcListPic = NULL; ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary); if (!bitstreamFile) { fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile); exit(EXIT_FAILURE); } InputByteStream bytestream(bitstreamFile); if (!m_outputDecodedSEIMessagesFilename.empty() && m_outputDecodedSEIMessagesFilename!="-") { m_seiMessageFileStream.open(m_outputDecodedSEIMessagesFilename.c_str(), std::ios::out); if (!m_seiMessageFileStream.is_open() || !m_seiMessageFileStream.good()) { fprintf(stderr, "\nUnable to open file `%s' for writing decoded SEI messages\n", m_outputDecodedSEIMessagesFilename.c_str()); exit(EXIT_FAILURE); } } // create & initialize internal classes xCreateDecLib(); xInitDecLib (); m_iPOCLastDisplay += m_iSkipFrame; // set the last displayed POC correctly for skip forward. // main decoder loop Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen) Bool loopFiltered = false; while (!!bitstreamFile) { /* location serves to work around a design fault in the decoder, whereby * the process of reading a new slice that is the first slice of a new frame * requires the TDecTop::decode() method to be called again with the same * nal unit. */ #if RExt__DECODER_DEBUG_BIT_STATISTICS TComCodingStatistics::TComCodingStatisticsData backupStats(TComCodingStatistics::GetStatistics()); streampos location = bitstreamFile.tellg() - streampos(bytestream.GetNumBufferedBytes()); #else streampos location = bitstreamFile.tellg(); #endif AnnexBStats stats = AnnexBStats(); vector<uint8_t> nalUnit; InputNALUnit nalu; byteStreamNALUnit(bytestream, nalUnit, stats); // call actual decoding function Bool bNewPicture = false; if (nalUnit.empty()) { /* this can happen if the following occur: * - empty input file * - two back-to-back start_code_prefixes * - start_code_prefix immediately followed by EOF */ fprintf(stderr, "Warning: Attempt to decode an empty NAL unit\n"); } else { read(nalu, nalUnit); if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu) ) { bNewPicture = false; } else { bNewPicture = m_cTDecTop.decode(nalu, m_iSkipFrame, m_iPOCLastDisplay); if (bNewPicture) { bitstreamFile.clear(); /* location points to the current nalunit payload[1] due to the * need for the annexB parser to read three extra bytes. * [1] except for the first NAL unit in the file * (but bNewPicture doesn't happen then) */ #if RExt__DECODER_DEBUG_BIT_STATISTICS bitstreamFile.seekg(location); bytestream.reset(); TComCodingStatistics::SetStatistics(backupStats); #else bitstreamFile.seekg(location-streamoff(3)); bytestream.reset(); #endif } } } if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS) && !m_cTDecTop.getFirstSliceInSequence () ) { if (!loopFiltered || bitstreamFile) { m_cTDecTop.executeLoopFilters(poc, pcListPic); } loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS); if (nalu.m_nalUnitType == NAL_UNIT_EOS) { m_cTDecTop.setFirstSliceInSequence(true); } } else if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS ) && m_cTDecTop.getFirstSliceInSequence () ) { m_cTDecTop.setFirstSliceInPicture (true); } if( pcListPic ) { if ( m_pchReconFile && !openedReconFile ) { const BitDepths &bitDepths=pcListPic->front()->getPicSym()->getSPS().getBitDepths(); // use bit depths of first reconstructed picture. for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++) { if (m_outputBitDepth[channelType] == 0) { m_outputBitDepth[channelType] = bitDepths.recon[channelType]; } } m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon ); // write mode openedReconFile = true; } // write reconstruction to file if( bNewPicture ) { xWriteOutput( pcListPic, nalu.m_temporalId ); } if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_cTDecTop.getNoOutputPriorPicsFlag() ) { m_cTDecTop.checkNoOutputPriorPics( pcListPic ); m_cTDecTop.setNoOutputPriorPicsFlag (false); } if ( bNewPicture && ( nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP ) ) { xFlushOutput( pcListPic ); } if (nalu.m_nalUnitType == NAL_UNIT_EOS) { xWriteOutput( pcListPic, nalu.m_temporalId ); m_cTDecTop.setFirstSliceInPicture (false); } // write reconstruction to file -- for additional bumping as defined in C.5.2.3 if(!bNewPicture && nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_TRAIL_N && nalu.m_nalUnitType <= NAL_UNIT_RESERVED_VCL31) { xWriteOutput( pcListPic, nalu.m_temporalId ); } } } xFlushOutput( pcListPic ); // delete buffers m_cTDecTop.deletePicBuffer(); // destroy internal classes xDestroyDecLib(); } // ==================================================================================================================== // Protected member functions // ==================================================================================================================== Void TAppDecTop::xCreateDecLib() { // create decoder class m_cTDecTop.create(); } Void TAppDecTop::xDestroyDecLib() { if ( m_pchReconFile ) { m_cTVideoIOYuvReconFile. close(); } // destroy decoder class m_cTDecTop.destroy(); } Void TAppDecTop::xInitDecLib() { // initialize decoder class m_cTDecTop.init(); m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled); #if O0043_BEST_EFFORT_DECODING m_cTDecTop.setForceDecodeBitDepth(m_forceDecodeBitDepth); #endif if (!m_outputDecodedSEIMessagesFilename.empty()) { std::ostream &os=m_seiMessageFileStream.is_open() ? m_seiMessageFileStream : std::cout; m_cTDecTop.setDecodedSEIMessageOutputStream(&os); } } /** \param pcListPic list of pictures to be written to file \param tId temporal sub-layer ID \todo DYN_REF_FREE should be revised */ Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt tId ) { if (pcListPic->empty()) { return; } TComList<TComPic*>::iterator iterPic = pcListPic->begin(); Int numPicsNotYetDisplayed = 0; Int dpbFullness = 0; const TComSPS* activeSPS = &(pcListPic->front()->getPicSym()->getSPS()); UInt numReorderPicsHighestTid; UInt maxDecPicBufferingHighestTid; UInt maxNrSublayers = activeSPS->getMaxTLayers(); if(m_iMaxTemporalLayer == -1 || m_iMaxTemporalLayer >= maxNrSublayers) { numReorderPicsHighestTid = activeSPS->getNumReorderPics(maxNrSublayers-1); maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering(maxNrSublayers-1); } else { numReorderPicsHighestTid = activeSPS->getNumReorderPics(m_iMaxTemporalLayer); maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering(m_iMaxTemporalLayer); } while (iterPic != pcListPic->end()) { TComPic* pcPic = *(iterPic); if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay) { numPicsNotYetDisplayed++; dpbFullness++; } else if(pcPic->getSlice( 0 )->isReferenced()) { dpbFullness++; } iterPic++; } iterPic = pcListPic->begin(); if (numPicsNotYetDisplayed>2) { iterPic++; } TComPic* pcPic = *(iterPic); if (numPicsNotYetDisplayed>2 && pcPic->isField()) //Field Decoding { TComList<TComPic*>::iterator endPic = pcListPic->end(); endPic--; iterPic = pcListPic->begin(); while (iterPic != endPic) { TComPic* pcPicTop = *(iterPic); iterPic++; TComPic* pcPicBottom = *(iterPic); if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed > numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) && (!(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1) && (pcPicTop->getPOC() == m_iPOCLastDisplay+1 || m_iPOCLastDisplay < 0)) { // write to file numPicsNotYetDisplayed = numPicsNotYetDisplayed-2; if ( m_pchReconFile ) { const Window &conf = pcPicTop->getConformanceWindow(); const Window defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window(); const Bool isTff = pcPicTop->isTopField(); Bool display = true; if( m_decodedNoDisplaySEIEnabled ) { SEIMessages noDisplay = getSeisByType(pcPic->getSEIs(), SEI::NO_DISPLAY ); const SEINoDisplay *nd = ( noDisplay.size() > 0 ) ? (SEINoDisplay*) *(noDisplay.begin()) : NULL; if( (nd != NULL) && nd->m_noDisplay ) { display = false; } } if (display) { m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(), m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff ); } } // update POC of display order m_iPOCLastDisplay = pcPicBottom->getPOC(); // erase non-referenced picture in the reference picture list after display if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true ) { #if !DYN_REF_FREE pcPicTop->setReconMark(false); // mark it should be extended later pcPicTop->getPicYuvRec()->setBorderExtension( false ); #else pcPicTop->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true ) { #if !DYN_REF_FREE pcPicBottom->setReconMark(false); // mark it should be extended later pcPicBottom->getPicYuvRec()->setBorderExtension( false ); #else pcPicBottom->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } pcPicTop->setOutputMark(false); pcPicBottom->setOutputMark(false); } } } else if (!pcPic->isField()) //Frame Decoding { iterPic = pcListPic->begin(); while (iterPic != pcListPic->end()) { pcPic = *(iterPic); if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay && (numPicsNotYetDisplayed > numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid)) { // write to file numPicsNotYetDisplayed--; if(pcPic->getSlice(0)->isReferenced() == false) { dpbFullness--; } if ( m_pchReconFile ) { const Window &conf = pcPic->getConformanceWindow(); const Window defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window(); #if PGR_ENABLE //pcPic->getPicYuvRec()->resample(MAX_CU_SIZE,MAX_CU_SIZE,true); #endif const BitDepths &bitDepths = pcListPic->front()->getPicSym()->getSPS().getBitDepths(); #if PGR_ENABLE if (pcPic->getSlice(0)->getSliceType() == I_SLICE) pcPic->getPicYuvRec()->resample(pcPic->getPicSym()->getSPS().getMaxCUWidth(), pcPic->getPicSym()->getSPS().getMaxCUHeight(), true); #endif m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() ); //TVideoIOYuv resi, abresi, pred; //resi.open("dec_resi.yuv", true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon); // write mode //abresi.open("dec_abresi.yuv", true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon); // write mode //pred.open("dec_pred.yuv", true, m_outputBitDepth, m_outputBitDepth, bitDepths.recon); // write mode //resi.write(g_pcYuvResi, m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset()); //abresi.write(g_pcYuvAbnormalResi, m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset()); //pred.write(g_pcYuvPred, m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset()); //resi.close(); //abresi.close(); //pred.close(); } // update POC of display order m_iPOCLastDisplay = pcPic->getPOC(); // erase non-referenced picture in the reference picture list after display if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true ) { #if !DYN_REF_FREE pcPic->setReconMark(false); // mark it should be extended later pcPic->getPicYuvRec()->setBorderExtension( false ); #else pcPic->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } pcPic->setOutputMark(false); } iterPic++; } } } /** \param pcListPic list of pictures to be written to file \todo DYN_REF_FREE should be revised */ Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic ) { if(!pcListPic || pcListPic->empty()) { return; } TComList<TComPic*>::iterator iterPic = pcListPic->begin(); iterPic = pcListPic->begin(); TComPic* pcPic = *(iterPic); if (pcPic->isField()) //Field Decoding { TComList<TComPic*>::iterator endPic = pcListPic->end(); endPic--; TComPic *pcPicTop, *pcPicBottom = NULL; while (iterPic != endPic) { pcPicTop = *(iterPic); iterPic++; pcPicBottom = *(iterPic); if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && !(pcPicTop->getPOC()%2) && (pcPicBottom->getPOC() == pcPicTop->getPOC()+1) ) { // write to file if ( m_pchReconFile ) { const Window &conf = pcPicTop->getConformanceWindow(); const Window defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window(); const Bool isTff = pcPicTop->isTopField(); m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(), m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff ); } // update POC of display order m_iPOCLastDisplay = pcPicBottom->getPOC(); // erase non-referenced picture in the reference picture list after display if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true ) { #if !DYN_REF_FREE pcPicTop->setReconMark(false); // mark it should be extended later pcPicTop->getPicYuvRec()->setBorderExtension( false ); #else pcPicTop->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true ) { #if !DYN_REF_FREE pcPicBottom->setReconMark(false); // mark it should be extended later pcPicBottom->getPicYuvRec()->setBorderExtension( false ); #else pcPicBottom->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } pcPicTop->setOutputMark(false); pcPicBottom->setOutputMark(false); #if !DYN_REF_FREE if(pcPicTop) { pcPicTop->destroy(); delete pcPicTop; pcPicTop = NULL; } #endif } } if(pcPicBottom) { pcPicBottom->destroy(); delete pcPicBottom; pcPicBottom = NULL; } } else //Frame decoding { while (iterPic != pcListPic->end()) { pcPic = *(iterPic); if ( pcPic->getOutputMark() ) { // write to file if ( m_pchReconFile ) { const Window &conf = pcPic->getConformanceWindow(); const Window defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window(); m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert, conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(), conf.getWindowRightOffset() + defDisp.getWindowRightOffset(), conf.getWindowTopOffset() + defDisp.getWindowTopOffset(), conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() ); } // update POC of display order m_iPOCLastDisplay = pcPic->getPOC(); // erase non-referenced picture in the reference picture list after display if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true ) { #if !DYN_REF_FREE pcPic->setReconMark(false); // mark it should be extended later pcPic->getPicYuvRec()->setBorderExtension( false ); #else pcPic->destroy(); pcListPic->erase( iterPic ); iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised! continue; #endif } pcPic->setOutputMark(false); } #if !DYN_REF_FREE if(pcPic != NULL) { pcPic->destroy(); delete pcPic; pcPic = NULL; } #endif iterPic++; } } pcListPic->clear(); m_iPOCLastDisplay = -MAX_INT; } /** \param nalu Input nalu to check whether its LayerId is within targetDecLayerIdSet */ Bool TAppDecTop::isNaluWithinTargetDecLayerIdSet( InputNALUnit* nalu ) { if ( m_targetDecLayerIdSet.size() == 0 ) // By default, the set is empty, meaning all LayerIds are allowed { return true; } for (std::vector<Int>::iterator it = m_targetDecLayerIdSet.begin(); it != m_targetDecLayerIdSet.end(); it++) { if ( nalu->m_nuhLayerId == (*it) ) { return true; } } return false; } //! \}
35.483918
312
0.620823
GregDobby
c8ef2e5f7d61f445ce78039ac50d8ff7f74e0f38
1,296
hpp
C++
include/doll/Script/Scripting.hpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
1
2021-07-19T14:40:15.000Z
2021-07-19T14:40:15.000Z
include/doll/Script/Scripting.hpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
null
null
null
include/doll/Script/Scripting.hpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
null
null
null
#pragma once #include "../Core/Defs.hpp" namespace doll { // Script compiler class RCompiler; // Create a new script compiler DOLL_FUNC RCompiler *DOLL_API sc_new(); // Destroy a script compiler DOLL_FUNC NullPtr DOLL_API sc_delete( RCompiler *compiler ); // Open a source file in the compiler DOLL_FUNC Bool DOLL_API sc_openSource( RCompiler *compiler, const Str &filename ); // Close the current source and move to the next source DOLL_FUNC Bool DOLL_API sc_nextSource( RCompiler *compiler ); // Check whether a source file is open DOLL_FUNC Bool DOLL_API sc_isOpen( const RCompiler *compiler ); // Set a filename to use for the current source file, for diagnostic purposes DOLL_FUNC Bool DOLL_API sc_setSourceName( RCompiler *compiler, const Str &filename ); // Retrieve the filename of the current source DOLL_FUNC Bool DOLL_API sc_getSourceName( const RCompiler *compiler, Str &dstFilename ); inline Str DOLL_API sc_getSourceName( const RCompiler *compiler ) { Str src; (Void)sc_getSourceName( compiler, src ); return src; } // Perform internal testing on the currently active source, using specially // written "test comments" written in that source DOLL_FUNC Bool DOLL_API sc_testCurrentSource( RCompiler *compiler ); }
36
90
0.746142
axia-sw
c8f14dd8336575e8c4236e120c931e9dabd37246
1,406
cpp
C++
all/native/packagemanager/handlers/RoutingPackageHandler.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
1
2019-11-04T08:40:40.000Z
2019-11-04T08:40:40.000Z
all/native/packagemanager/handlers/RoutingPackageHandler.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
null
null
null
all/native/packagemanager/handlers/RoutingPackageHandler.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
null
null
null
#if defined(_CARTO_ROUTING_SUPPORT) && defined(_CARTO_PACKAGEMANAGER_SUPPORT) #include "RoutingPackageHandler.h" #include "packagemanager/PackageTileMask.h" #include "utils/Log.h" namespace carto { RoutingPackageHandler::RoutingPackageHandler(const std::string& fileName) : PackageHandler(fileName), _graphFile() { } RoutingPackageHandler::~RoutingPackageHandler() { } std::shared_ptr<std::ifstream> RoutingPackageHandler::getGraphFile() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (!_graphFile) { try { _graphFile = std::make_shared<std::ifstream>(); _graphFile->exceptions(std::ifstream::failbit | std::ifstream::badbit); _graphFile->rdbuf()->pubsetbuf(0, 0); _graphFile->open(_fileName, std::ios::binary); } catch (const std::exception& ex) { Log::Errorf("RoutingPackageHandler::getGraphFile: Failed to open graph file %s", _fileName.c_str()); _graphFile.reset(); } } return _graphFile; } void RoutingPackageHandler::onImportPackage() { } void RoutingPackageHandler::onDeletePackage() { } std::shared_ptr<PackageTileMask> RoutingPackageHandler::calculateTileMask() const { return std::shared_ptr<PackageTileMask>(); } } #endif
28.693878
116
0.631579
JianYT
c8fa1117f2635a2a71e365c1f2f58baa9752e8de
2,202
cpp
C++
src/Wektor.cpp
bsierp/ZadanieUkladyRownan
a28beafbec3d23ea0144e218e71f5908a3732c06
[ "MIT" ]
null
null
null
src/Wektor.cpp
bsierp/ZadanieUkladyRownan
a28beafbec3d23ea0144e218e71f5908a3732c06
[ "MIT" ]
null
null
null
src/Wektor.cpp
bsierp/ZadanieUkladyRownan
a28beafbec3d23ea0144e218e71f5908a3732c06
[ "MIT" ]
null
null
null
#include "Wektor.hh" Wektor::Wektor(){ for(int i=0;i<ROZMIAR;i++){ tab[i]=0; } } Wektor::Wektor(double xx, double yy, double zz){ tab[0]=xx; tab[1]=yy; tab[2]=zz; } const double & Wektor::operator [](int index) const{ if(index<0||index>ROZMIAR){ cerr<<"Skladowa wektora pozaś zakresem"<<endl; exit(1); } return this->tab[index]; } double & Wektor::operator [](int index){ if(index<0||index>ROZMIAR){ cerr<<"Skladowa wektora poza zakresem"<<endl; exit(1); } return this->tab[index]; } Wektor Wektor::operator +(const Wektor & skl) const{ Wektor wynik; for(int i=0;i<ROZMIAR;i++){ wynik[i]=this->tab[i]+skl[i]; } return wynik; } Wektor Wektor::operator - (const Wektor & skl) const{ Wektor wynik; for(int i=0;i<ROZMIAR;i++){ wynik[i]=this->tab[i]-skl[i]; } return wynik; } double Wektor::operator *(const Wektor & skl) const{ double wynik,czesciowa; for(int i=0;i<ROZMIAR;i++){ czesciowa=this->tab[i]*skl[i]; wynik+=czesciowa; } return wynik; } Wektor Wektor::operator *(double skl) const{ Wektor wynik; for(int i=0;i<ROZMIAR;i++){ wynik[i]=this->tab[i]*skl; } return wynik; } double Wektor::dlugosc() const{ double wynik,czesciowa; for(int i=0;i<ROZMIAR;i++){ czesciowa=this->tab[i]*this->tab[i]; wynik+=czesciowa; } return sqrt(wynik); } bool Wektor::operator == (const Wektor & skl) const{ double epsilon=0.00000000000001; for(int i=0;i<ROZMIAR;i++){ if(abs(this->tab[i]-skl[i])<epsilon) continue; else { return false; } } return true; } bool Wektor::operator != (const Wektor & skl) const{ return !(*this==skl); } std::istream & operator >> (std::istream &strm, Wektor &Wek){ for(int i=0;i<ROZMIAR;i++){ strm>>Wek[i]; } return strm; } std::ostream & operator << (std::ostream &strm, const Wektor &Wek){ for(int i=0;i<ROZMIAR;i++){ strm<<Wek[i]<<' '; } }
24.197802
67
0.536331
bsierp
7407c27f1d09a8e43ca297572c91f0538ba64cfc
972
cc
C++
GeeksForGeeks/Easy/ArrayPairs.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
GeeksForGeeks/Easy/ArrayPairs.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
GeeksForGeeks/Easy/ArrayPairs.cc
ChakreshSinghUC/CPPCodes
d82a3f467303566afbfcc927b660b0f7bf7c0432
[ "MIT" ]
null
null
null
// 12-23-2016 // Author: Chakresh Singh /* Given an array of integers arr[0..n-1], count all pairs (arr[i], arr[j]) in the such that i*arr[i] > j*arr[j], 0 =< i < j < n. Examples: Input : arr[] = {5 , 0, 10, 2, 4, 1, 6} Output: 5 Pairs which hold condition i*arr[i] > j*arr[j] are (10, 2) (10, 4) (10, 1) (2, 1) (4, 1) Input : arr[] = {8, 4, 2, 1} Output : 2 */ #include <iostream> using namespace std; void BAD_findPairsFunc(int A[], int n) { //Time complexity - O(n^2) int count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (i * A[i] > j * A[j]) { count++; cout << A[i] << " " << A[j] << endl; } cout << "Count of such pairs = " << count; } int main() { int A[] = {5, 0, 10, 2, 4, 1, 6}; int n = sizeof(A) / sizeof(A[0]); cout << "The pairs that satisfy the condition - i*arr[i] > j*arr[j], 0 =< i " "< j < n, are: " << endl; BAD_findPairsFunc(A, n); return -1; }
22.090909
79
0.496914
ChakreshSinghUC
740f56ac305257e09eefcfc459170ebc4a1a75a5
17
cpp
C++
Tools/Ptr.cpp
Jacobious52/CPPLab
bc8778018b544e6271cfd7d9b35388c0e6149c68
[ "MIT" ]
null
null
null
Tools/Ptr.cpp
Jacobious52/CPPLab
bc8778018b544e6271cfd7d9b35388c0e6149c68
[ "MIT" ]
null
null
null
Tools/Ptr.cpp
Jacobious52/CPPLab
bc8778018b544e6271cfd7d9b35388c0e6149c68
[ "MIT" ]
1
2022-01-12T09:07:37.000Z
2022-01-12T09:07:37.000Z
#include "Ptr.h"
8.5
16
0.647059
Jacobious52
740f646e85767c3543021e891021588a3414b913
3,172
cpp
C++
src/jled_base.cpp
geekmystique/jled
3568a043e551bcc31b7e1e5b7bfaf6ff0f90e413
[ "MIT" ]
235
2017-06-19T16:48:13.000Z
2022-03-29T15:08:47.000Z
src/jled_base.cpp
geekmystique/jled
3568a043e551bcc31b7e1e5b7bfaf6ff0f90e413
[ "MIT" ]
90
2017-12-07T06:36:57.000Z
2022-03-29T20:38:18.000Z
src/jled_base.cpp
geekmystique/jled
3568a043e551bcc31b7e1e5b7bfaf6ff0f90e413
[ "MIT" ]
55
2017-08-20T16:47:35.000Z
2022-01-13T07:28:33.000Z
// Copyright (c) 2017 Jan Delgado <jdelgado[at]gmx.net> // https://github.com/jandelgado/jled // // 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 "jled_base.h" // NOLINT namespace jled { // pre-calculated fade-on function. This table samples the function // y(x) = exp(sin((t - period / 2.) * PI / period)) - 0.36787944) // * 108. // at x={0,32,...,256}. In FadeOnFunc() we us linear interpolation // to // approximate the original function (so we do not need fp-ops). // fade-off and breath functions are all derived from fade-on, see // below. static constexpr uint8_t kFadeOnTable[] = {0, 3, 13, 33, 68, 118, 179, 232, 255}; // https://www.wolframalpha.com/input/?i=plot+(exp(sin((x-100%2F2.)*PI%2F100))-0.36787944)*108.0++x%3D0+to+100 // The fade-on func is an approximation of // y(x) = exp(sin((t-period/2.) * PI / period)) - 0.36787944) * 108.) uint8_t fadeon_func(uint32_t t, uint16_t period) { if (t + 1 >= period) return 255; // kFullBrightness; // approximate by linear interpolation. // scale t according to period to 0..255 t = ((t << 8) / period) & 0xff; const auto i = (t >> 5); // -> i will be in range 0 .. 7 const auto y0 = kFadeOnTable[i]; const auto y1 = kFadeOnTable[i + 1]; const auto x0 = i << 5; // *32 // y(t) = mt+b, with m = dy/dx = (y1-y0)/32 = (y1-y0) >> 5 return (((t - x0) * (y1 - y0)) >> 5) + y0; } static uint32_t rand_ = 0; void rand_seed(uint32_t seed) { rand_ = seed; } uint8_t rand8() { if (rand_ & 1) { rand_ = (rand_ >> 1); } else { rand_ = (rand_ >> 1) ^ 0x7FFFF159; } return (uint8_t)rand_; } // scale a byte by a factor, where only the lower 5 bits of factor are used. // i.e. the scaling factor is in the range [0,31]. scale5 has the following // properties: // scale5(x, f) = x*f / 32 for all x and f=0..30 // scale5(x, 31) = x for all x uint8_t scale5(uint8_t val, uint8_t factor) { if (factor == 31) return val; // optimize for most common case (full brightness) return ((uint16_t)val * factor) >> 5; } }; // namespace jled
39.160494
110
0.6529
geekmystique
7410132719f7b4930f6986bf7b66767ce5024154
663
cpp
C++
Iniciante/1-generic.cpp
hugotannus/URI-Online-Judge---Solutions
83f1279dd435aef1d911d1490712357baa9fd4dc
[ "MIT" ]
null
null
null
Iniciante/1-generic.cpp
hugotannus/URI-Online-Judge---Solutions
83f1279dd435aef1d911d1490712357baa9fd4dc
[ "MIT" ]
null
null
null
Iniciante/1-generic.cpp
hugotannus/URI-Online-Judge---Solutions
83f1279dd435aef1d911d1490712357baa9fd4dc
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <string> #include <algorithm> #include <cmath> #include <cstdio> #include <climits> #include <vector> #include <stack> using namespace std; #define MAX 21 #define sp setprecision #define pb push_back #define INF 0x3f3f3f3f int gcd(int a, int b) { while(b) { a = a%b; swap(a,b); } return a; } int main() { ios_base::sync_with_stdio(false); cout << setprecision(2) << fixed; //~ int N, mark, pos, cor; for(int i=0; i<5; i++) { for(int j=0; j<5; j++) { cout << "\t"; if(i+j < 5) cout << i*0.25 << " , " << j*0.25; else cout << "---- , ----"; } cout << endl; } return 0; }
15.068182
38
0.573152
hugotannus
7416ef728049c35ba41d61cf503eca1d6503d7d9
1,094
cpp
C++
Season 2/11_Fib.cpp
dreamerlee9489/Algorithms-Cpp
9253e4a5246630e71932c136898efad3e1278298
[ "MIT" ]
null
null
null
Season 2/11_Fib.cpp
dreamerlee9489/Algorithms-Cpp
9253e4a5246630e71932c136898efad3e1278298
[ "MIT" ]
null
null
null
Season 2/11_Fib.cpp
dreamerlee9489/Algorithms-Cpp
9253e4a5246630e71932c136898efad3e1278298
[ "MIT" ]
null
null
null
#include <ctime> #include <iostream> using namespace std; int fib0(int n) { if (n <= 2) return 1; return fib0(n - 1) + fib0(n - 2); } int fib1(int n) { if (n <= 2) return 1; int array[2] = {1, 1}; for (size_t i = 3; i <= n; i++) array[i & 1] = array[(i - 1) & 1] + array[(i - 2) & 1]; return array[n & 1]; } int fib2(int n) { if (n <= 2) return 1; int first = 0, second = 1; for (size_t i = 0; i < n - 1; i++) { int sum = first + second; first = second; second = sum; } return second; } int main(int argc, char const *argv[]) { clock_t start, end0, end1, end2; start = clock(); fib0(48); end0 = clock(); cout << "fib0耗时: " << double(end0 - start) / CLOCKS_PER_SEC << "s" << endl; fib1(48); end1 = clock(); cout << "fib1耗时: " << double(end1 - end0) / CLOCKS_PER_SEC << "s" << endl; fib2(48); end2 = clock(); cout << "fib2耗时: " << double(end2 - end1) / CLOCKS_PER_SEC << "s" << endl; return 0; } /* fib0耗时: 6.829s fib1耗时: 0s fib2耗时: 0s */
19.192982
79
0.492687
dreamerlee9489
741d59184c7d53d54c878dcf53c9a0498a2db77f
194,491
cpp
C++
ExternalLib/ExternalLib/Source/DirectXTexConvert.cpp
Jin02/SOCEngine
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
[ "MIT" ]
14
2015-12-24T03:08:59.000Z
2021-12-13T13:29:07.000Z
ExternalLib/ExternalLib/Source/DirectXTexConvert.cpp
Jin02/SOCEngine
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
[ "MIT" ]
106
2015-08-16T10:32:47.000Z
2018-10-08T19:01:44.000Z
ExternalLib/ExternalLib/Source/DirectXTexConvert.cpp
Jin02/SOCEngine
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
[ "MIT" ]
2
2018-03-02T06:17:08.000Z
2020-02-11T11:19:41.000Z
//------------------------------------------------------------------------------------- // DirectXTexConvert.cpp // // DirectX Texture Library - Image conversion // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248926 //------------------------------------------------------------------------------------- #include "directxtexp.h" using namespace DirectX::PackedVector; using Microsoft::WRL::ComPtr; namespace { #if DIRECTX_MATH_VERSION < 306 inline float round_to_nearest( float x ) { // Round to nearest (even) float i = floorf(x); x -= i; if(x < 0.5f) return i; if(x > 0.5f) return i + 1.f; float int_part; modff( i / 2.f, &int_part ); if ( (2.f*int_part) == i ) { return i; } return i + 1.f; } #endif inline uint32_t FloatTo7e3(float Value) { uint32_t IValue = reinterpret_cast<uint32_t *>(&Value)[0]; if ( IValue & 0x80000000U ) { // Positive only return 0; } else if (IValue > 0x41FF73FFU) { // The number is too large to be represented as a 7e3. Saturate. return 0x3FFU; } else { if (IValue < 0x3E800000U) { // The number is too small to be represented as a normalized 7e3. // Convert it to a denormalized value. uint32_t Shift = 125U - (IValue >> 23U); IValue = (0x800000U | (IValue & 0x7FFFFFU)) >> Shift; } else { // Rebias the exponent to represent the value as a normalized 7e3. IValue += 0xC2000000U; } return ((IValue + 0x7FFFU + ((IValue >> 16U) & 1U)) >> 16U)&0x3FFU; } } inline float FloatFrom7e3( uint32_t Value ) { uint32_t Mantissa = (uint32_t)(Value & 0x7F); uint32_t Exponent = (Value & 0x380); if (Exponent != 0) // The value is normalized { Exponent = (uint32_t)((Value >> 7) & 0x7); } else if (Mantissa != 0) // The value is denormalized { // Normalize the value in the resulting float Exponent = 1; do { Exponent--; Mantissa <<= 1; } while ((Mantissa & 0x80) == 0); Mantissa &= 0x7F; } else // The value is zero { Exponent = (uint32_t)-124; } uint32_t Result = ((Exponent + 124) << 23) | // Exponent (Mantissa << 16); // Mantissa return reinterpret_cast<float*>(&Result)[0]; } inline uint32_t FloatTo6e4(float Value) { uint32_t IValue = reinterpret_cast<uint32_t *>(&Value)[0]; if ( IValue & 0x80000000U ) { // Positive only return 0; } else if (IValue > 0x43FEFFFFU) { // The number is too large to be represented as a 6e4. Saturate. return 0x3FFU; } else { if (IValue < 0x3C800000U) { // The number is too small to be represented as a normalized 6e4. // Convert it to a denormalized value. uint32_t Shift = 121U - (IValue >> 23U); IValue = (0x800000U | (IValue & 0x7FFFFFU)) >> Shift; } else { // Rebias the exponent to represent the value as a normalized 6e4. IValue += 0xC4000000U; } return ((IValue + 0xFFFFU + ((IValue >> 17U) & 1U)) >> 17U)&0x3FFU; } } inline float FloatFrom6e4( uint32_t Value ) { uint32_t Mantissa = (uint32_t)(Value & 0x3F); uint32_t Exponent = (Value & 0x3C0); if (Exponent != 0) // The value is normalized { Exponent = (uint32_t)((Value >> 6) & 0xF); } else if (Mantissa != 0) // The value is denormalized { // Normalize the value in the resulting float Exponent = 1; do { Exponent--; Mantissa <<= 1; } while ((Mantissa & 0x40) == 0); Mantissa &= 0x3F; } else // The value is zero { Exponent = (uint32_t)-120; } uint32_t Result = ((Exponent + 120) << 23) | // Exponent (Mantissa << 17); // Mantissa return reinterpret_cast<float*>(&Result)[0]; } }; namespace DirectX { static const XMVECTORF32 g_Grayscale = { 0.2125f, 0.7154f, 0.0721f, 0.0f }; static const XMVECTORF32 g_HalfMin = { -65504.f, -65504.f, -65504.f, -65504.f }; static const XMVECTORF32 g_HalfMax = { 65504.f, 65504.f, 65504.f, 65504.f }; static const XMVECTORF32 g_8BitBias = { 0.5f/255.f, 0.5f/255.f, 0.5f/255.f, 0.5f/255.f }; //------------------------------------------------------------------------------------- // Copies an image row with optional clearing of alpha value to 1.0 // (can be used in place as well) otherwise copies the image row unmodified. //------------------------------------------------------------------------------------- void _CopyScanline(_When_(pDestination == pSource, _Inout_updates_bytes_(outSize)) _When_(pDestination != pSource, _Out_writes_bytes_(outSize)) LPVOID pDestination, _In_ size_t outSize, _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize, _In_ DXGI_FORMAT format, _In_ DWORD flags) { assert( pDestination && outSize > 0 ); assert( pSource && inSize > 0 ); assert( IsValid(format) && !IsPalettized(format) ); if ( flags & TEXP_SCANLINE_SETALPHA ) { switch( static_cast<int>(format) ) { //----------------------------------------------------------------------------- case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: if ( inSize >= 16 && outSize >= 16 ) { uint32_t alpha; if ( format == DXGI_FORMAT_R32G32B32A32_FLOAT ) alpha = 0x3f800000; else if ( format == DXGI_FORMAT_R32G32B32A32_SINT ) alpha = 0x7fffffff; else alpha = 0xffffffff; if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*> (pDestination); for( size_t count = 0; count < ( outSize - 15 ); count += 16 ) { dPtr += 3; *(dPtr++) = alpha; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 15 ); count += 16 ) { *(dPtr++) = *(sPtr++); *(dPtr++) = *(sPtr++); *(dPtr++) = *(sPtr++); *(dPtr++) = alpha; ++sPtr; } } } return; //----------------------------------------------------------------------------- case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: case DXGI_FORMAT_Y416: if ( inSize >= 8 && outSize >= 8 ) { uint16_t alpha; if ( format == DXGI_FORMAT_R16G16B16A16_FLOAT ) alpha = 0x3c00; else if ( format == DXGI_FORMAT_R16G16B16A16_SNORM || format == DXGI_FORMAT_R16G16B16A16_SINT ) alpha = 0x7fff; else alpha = 0xffff; if ( pDestination == pSource ) { uint16_t *dPtr = reinterpret_cast<uint16_t*>(pDestination); for( size_t count = 0; count < ( outSize - 7 ); count += 8 ) { dPtr += 3; *(dPtr++) = alpha; } } else { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 7 ); count += 8 ) { *(dPtr++) = *(sPtr++); *(dPtr++) = *(sPtr++); *(dPtr++) = *(sPtr++); *(dPtr++) = alpha; ++sPtr; } } } return; //----------------------------------------------------------------------------- case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: case DXGI_FORMAT_Y410: case XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT: case XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT: case XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: if ( inSize >= 4 && outSize >= 4 ) { if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t count = 0; count < ( outSize - 3 ); count += 4 ) { *dPtr |= 0xC0000000; ++dPtr; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 3 ); count += 4 ) { *(dPtr++) = *(sPtr++) | 0xC0000000; } } } return; //----------------------------------------------------------------------------- case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_AYUV: if ( inSize >= 4 && outSize >= 4 ) { const uint32_t alpha = ( format == DXGI_FORMAT_R8G8B8A8_SNORM || format == DXGI_FORMAT_R8G8B8A8_SINT ) ? 0x7f000000 : 0xff000000; if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t count = 0; count < ( outSize - 3 ); count += 4 ) { uint32_t t = *dPtr & 0xFFFFFF; t |= alpha; *(dPtr++) = t; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 3 ); count += 4 ) { uint32_t t = *(sPtr++) & 0xFFFFFF; t |= alpha; *(dPtr++) = t; } } } return; //----------------------------------------------------------------------------- case DXGI_FORMAT_B5G5R5A1_UNORM: if ( inSize >= 2 && outSize >= 2 ) { if ( pDestination == pSource ) { uint16_t *dPtr = reinterpret_cast<uint16_t*>(pDestination); for( size_t count = 0; count < ( outSize - 1 ); count += 2 ) { *(dPtr++) |= 0x8000; } } else { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 1 ); count += 2 ) { *(dPtr++) = *(sPtr++) | 0x8000; } } } return; //----------------------------------------------------------------------------- case DXGI_FORMAT_A8_UNORM: memset( pDestination, 0xff, outSize ); return; //----------------------------------------------------------------------------- case DXGI_FORMAT_B4G4R4A4_UNORM: if ( inSize >= 2 && outSize >= 2 ) { if ( pDestination == pSource ) { uint16_t *dPtr = reinterpret_cast<uint16_t*>(pDestination); for( size_t count = 0; count < ( outSize - 1 ); count += 2 ) { *(dPtr++) |= 0xF000; } } else { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 1 ); count += 2 ) { *(dPtr++) = *(sPtr++) | 0xF000; } } } return; } } // Fall-through case is to just use memcpy (assuming this is not an in-place operation) if ( pDestination == pSource ) return; size_t size = std::min<size_t>( outSize, inSize ); memcpy_s( pDestination, outSize, pSource, size ); } //------------------------------------------------------------------------------------- // Swizzles (RGB <-> BGR) an image row with optional clearing of alpha value to 1.0 // (can be used in place as well) otherwise copies the image row unmodified. //------------------------------------------------------------------------------------- _Use_decl_annotations_ void _SwizzleScanline( LPVOID pDestination, size_t outSize, LPCVOID pSource, size_t inSize, DXGI_FORMAT format, DWORD flags ) { assert( pDestination && outSize > 0 ); assert( pSource && inSize > 0 ); assert( IsValid(format) && !IsPlanar(format) && !IsPalettized(format) ); switch( static_cast<int>(format) ) { //--------------------------------------------------------------------------------- case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: case XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: if ( inSize >= 4 && outSize >= 4 ) { if ( flags & TEXP_SCANLINE_LEGACY ) { // Swap Red (R) and Blue (B) channel (used for D3DFMT_A2R10G10B10 legacy sources) if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t count = 0; count < ( outSize - 3 ); count += 4 ) { uint32_t t = *dPtr; uint32_t t1 = (t & 0x3ff00000) >> 20; uint32_t t2 = (t & 0x000003ff) << 20; uint32_t t3 = (t & 0x000ffc00); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xC0000000 : (t & 0xC0000000); *(dPtr++) = t1 | t2 | t3 | ta; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 3 ); count += 4 ) { uint32_t t = *(sPtr++); uint32_t t1 = (t & 0x3ff00000) >> 20; uint32_t t2 = (t & 0x000003ff) << 20; uint32_t t3 = (t & 0x000ffc00); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xC0000000 : (t & 0xC0000000); *(dPtr++) = t1 | t2 | t3 | ta; } } return; } } break; //--------------------------------------------------------------------------------- case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: if ( inSize >= 4 && outSize >= 4 ) { // Swap Red (R) and Blue (B) channels (used to convert from DXGI 1.1 BGR formats to DXGI 1.0 RGB) if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t count = 0; count < ( outSize - 3 ); count += 4 ) { uint32_t t = *dPtr; uint32_t t1 = (t & 0x00ff0000) >> 16; uint32_t t2 = (t & 0x000000ff) << 16; uint32_t t3 = (t & 0x0000ff00); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : (t & 0xFF000000); *(dPtr++) = t1 | t2 | t3 | ta; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 3 ); count += 4 ) { uint32_t t = *(sPtr++); uint32_t t1 = (t & 0x00ff0000) >> 16; uint32_t t2 = (t & 0x000000ff) << 16; uint32_t t3 = (t & 0x0000ff00); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : (t & 0xFF000000); *(dPtr++) = t1 | t2 | t3 | ta; } } return; } break; //--------------------------------------------------------------------------------- case DXGI_FORMAT_YUY2: if ( inSize >= 4 && outSize >= 4 ) { if ( flags & TEXP_SCANLINE_LEGACY ) { // Reorder YUV components (used to convert legacy UYVY -> YUY2) if ( pDestination == pSource ) { uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t count = 0; count < ( outSize - 3 ); count += 4 ) { uint32_t t = *dPtr; uint32_t t1 = (t & 0x000000ff) << 8; uint32_t t2 = (t & 0x0000ff00) >> 8; uint32_t t3 = (t & 0x00ff0000) << 8; uint32_t t4 = (t & 0xff000000) >> 8; *(dPtr++) = t1 | t2 | t3 | t4; } } else { const uint32_t * __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); size_t size = std::min<size_t>( outSize, inSize ); for( size_t count = 0; count < ( size - 3 ); count += 4 ) { uint32_t t = *(sPtr++); uint32_t t1 = (t & 0x000000ff) << 8; uint32_t t2 = (t & 0x0000ff00) >> 8; uint32_t t3 = (t & 0x00ff0000) << 8; uint32_t t4 = (t & 0xff000000) >> 8; *(dPtr++) = t1 | t2 | t3 | t4; } } return; } } break; } // Fall-through case is to just use memcpy (assuming this is not an in-place operation) if ( pDestination == pSource ) return; size_t size = std::min<size_t>( outSize, inSize ); memcpy_s( pDestination, outSize, pSource, size ); } //------------------------------------------------------------------------------------- // Converts an image row with optional clearing of alpha value to 1.0 // Returns true if supported, false if expansion case not supported //------------------------------------------------------------------------------------- _Use_decl_annotations_ bool _ExpandScanline( LPVOID pDestination, size_t outSize, DXGI_FORMAT outFormat, LPCVOID pSource, size_t inSize, DXGI_FORMAT inFormat, DWORD flags ) { assert( pDestination && outSize > 0 ); assert( pSource && inSize > 0 ); assert( IsValid(outFormat) && !IsPlanar(outFormat) && !IsPalettized(outFormat) ); assert( IsValid(inFormat) && !IsPlanar(inFormat) && !IsPalettized(inFormat) ); switch( inFormat ) { case DXGI_FORMAT_B5G6R5_UNORM: if ( outFormat != DXGI_FORMAT_R8G8B8A8_UNORM ) return false; // DXGI_FORMAT_B5G6R5_UNORM -> DXGI_FORMAT_R8G8B8A8_UNORM if ( inSize >= 2 && outSize >= 4 ) { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t ocount = 0, icount = 0; ( ( icount < ( inSize - 1 ) ) && ( ocount < ( outSize - 3 ) ) ); icount += 2, ocount += 4 ) { uint16_t t = *(sPtr++); uint32_t t1 = ((t & 0xf800) >> 8) | ((t & 0xe000) >> 13); uint32_t t2 = ((t & 0x07e0) << 5) | ((t & 0x0600) >> 5); uint32_t t3 = ((t & 0x001f) << 19) | ((t & 0x001c) << 14); *(dPtr++) = t1 | t2 | t3 | 0xff000000; } return true; } return false; case DXGI_FORMAT_B5G5R5A1_UNORM: if ( outFormat != DXGI_FORMAT_R8G8B8A8_UNORM ) return false; // DXGI_FORMAT_B5G5R5A1_UNORM -> DXGI_FORMAT_R8G8B8A8_UNORM if ( inSize >= 2 && outSize >= 4 ) { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t ocount = 0, icount = 0; ( ( icount < ( inSize - 1 ) ) && ( ocount < ( outSize - 3 ) ) ); icount += 2, ocount += 4 ) { uint16_t t = *(sPtr++); uint32_t t1 = ((t & 0x7c00) >> 7) | ((t & 0x7000) >> 12); uint32_t t2 = ((t & 0x03e0) << 6) | ((t & 0x0380) << 1); uint32_t t3 = ((t & 0x001f) << 19) | ((t & 0x001c) << 14); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : ((t & 0x8000) ? 0xff000000 : 0); *(dPtr++) = t1 | t2 | t3 | ta; } return true; } return false; case DXGI_FORMAT_B4G4R4A4_UNORM: if ( outFormat != DXGI_FORMAT_R8G8B8A8_UNORM ) return false; // DXGI_FORMAT_B4G4R4A4_UNORM -> DXGI_FORMAT_R8G8B8A8_UNORM if ( inSize >= 2 && outSize >= 4 ) { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t ocount = 0, icount = 0; ( ( icount < ( inSize - 1 ) ) && ( ocount < ( outSize - 3 ) ) ); icount += 2, ocount += 4 ) { uint16_t t = *(sPtr++); uint32_t t1 = ((t & 0x0f00) >> 4) | ((t & 0x0f00) >> 8); uint32_t t2 = ((t & 0x00f0) << 8) | ((t & 0x00f0) << 4); uint32_t t3 = ((t & 0x000f) << 20) | ((t & 0x000f) << 16); uint32_t ta = ( flags & TEXP_SCANLINE_SETALPHA ) ? 0xff000000 : (((t & 0xf000) << 16) | ((t & 0xf000) << 12)); *(dPtr++) = t1 | t2 | t3 | ta; } return true; } return false; } return false; } //------------------------------------------------------------------------------------- // Loads an image row into standard RGBA XMVECTOR (aligned) array //------------------------------------------------------------------------------------- #define LOAD_SCANLINE( type, func )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = func( sPtr++ );\ }\ return true;\ }\ return false; #define LOAD_SCANLINE3( type, func, defvec )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ XMVECTOR v = func( sPtr++ );\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = XMVectorSelect( defvec, v, g_XMSelect1110 );\ }\ return true;\ }\ return false; #define LOAD_SCANLINE2( type, func, defvec )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ XMVECTOR v = func( sPtr++ );\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = XMVectorSelect( defvec, v, g_XMSelect1100 );\ }\ return true;\ }\ return false; #pragma warning(suppress: 6101) _Use_decl_annotations_ bool _LoadScanline( XMVECTOR* pDestination, size_t count, LPCVOID pSource, size_t size, DXGI_FORMAT format ) { assert( pDestination && count > 0 && (((uintptr_t)pDestination & 0xF) == 0) ); assert( pSource && size > 0 ); assert( IsValid(format) && !IsTypeless(format, false) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format) ); XMVECTOR* __restrict dPtr = pDestination; if ( !dPtr ) return false; const XMVECTOR* ePtr = pDestination + count; switch( static_cast<int>(format) ) { case DXGI_FORMAT_R32G32B32A32_FLOAT: { size_t msize = (size > (sizeof(XMVECTOR)*count)) ? (sizeof(XMVECTOR)*count) : size; memcpy_s( dPtr, sizeof(XMVECTOR)*count, pSource, msize ); } return true; case DXGI_FORMAT_R32G32B32A32_UINT: LOAD_SCANLINE( XMUINT4, XMLoadUInt4 ) case DXGI_FORMAT_R32G32B32A32_SINT: LOAD_SCANLINE( XMINT4, XMLoadSInt4 ) case DXGI_FORMAT_R32G32B32_FLOAT: LOAD_SCANLINE3( XMFLOAT3, XMLoadFloat3, g_XMIdentityR3 ) case DXGI_FORMAT_R32G32B32_UINT: LOAD_SCANLINE3( XMUINT3, XMLoadUInt3, g_XMIdentityR3 ) case DXGI_FORMAT_R32G32B32_SINT: LOAD_SCANLINE3( XMINT3, XMLoadSInt3, g_XMIdentityR3 ) case DXGI_FORMAT_R16G16B16A16_FLOAT: LOAD_SCANLINE( XMHALF4, XMLoadHalf4 ) case DXGI_FORMAT_R16G16B16A16_UNORM: LOAD_SCANLINE( XMUSHORTN4, XMLoadUShortN4 ) case DXGI_FORMAT_R16G16B16A16_UINT: LOAD_SCANLINE( XMUSHORT4, XMLoadUShort4 ) case DXGI_FORMAT_R16G16B16A16_SNORM: LOAD_SCANLINE( XMSHORTN4, XMLoadShortN4 ) case DXGI_FORMAT_R16G16B16A16_SINT: LOAD_SCANLINE( XMSHORT4, XMLoadShort4 ) case DXGI_FORMAT_R32G32_FLOAT: LOAD_SCANLINE2( XMFLOAT2, XMLoadFloat2, g_XMIdentityR3 ) case DXGI_FORMAT_R32G32_UINT: LOAD_SCANLINE2( XMUINT2, XMLoadUInt2, g_XMIdentityR3 ) case DXGI_FORMAT_R32G32_SINT: LOAD_SCANLINE2( XMINT2, XMLoadSInt2, g_XMIdentityR3 ) case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: { const size_t psize = sizeof(float)+sizeof(uint32_t); if ( size >= psize ) { const float * sPtr = reinterpret_cast<const float*>(pSource); for( size_t icount = 0; icount < ( size - psize + 1 ); icount += psize ) { const uint8_t* ps8 = reinterpret_cast<const uint8_t*>( &sPtr[1] ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( sPtr[0], static_cast<float>( *ps8 ), 0.f, 1.f ); sPtr += 2; } return true; } } return false; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: { const size_t psize = sizeof(float)+sizeof(uint32_t); if ( size >= psize ) { const float * sPtr = reinterpret_cast<const float*>(pSource); for( size_t icount = 0; icount < ( size - psize + 1 ); icount += psize ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( sPtr[0], 0.f /* typeless component assumed zero */, 0.f, 1.f ); sPtr += 2; } return true; } } return false; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: { const size_t psize = sizeof(float)+sizeof(uint32_t); if ( size >= psize ) { const float * sPtr = reinterpret_cast<const float*>(pSource); for( size_t icount = 0; icount < ( size - psize + 1 ); icount += psize ) { const uint8_t* pg8 = reinterpret_cast<const uint8_t*>( &sPtr[1] ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( 0.f /* typeless component assumed zero */, static_cast<float>( *pg8 ), 0.f, 1.f ); sPtr += 2; } return true; } } return false; case DXGI_FORMAT_R10G10B10A2_UNORM: LOAD_SCANLINE( XMUDECN4, XMLoadUDecN4 ); case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: #if DIRECTX_MATH_VERSION >= 306 LOAD_SCANLINE( XMUDECN4, XMLoadUDecN4_XR ); #else if ( size >= sizeof(XMUDECN4) ) { const XMUDECN4 * __restrict sPtr = reinterpret_cast<const XMUDECN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( dPtr >= ePtr ) break; int32_t ElementX = sPtr->v & 0x3FF; int32_t ElementY = (sPtr->v >> 10) & 0x3FF; int32_t ElementZ = (sPtr->v >> 20) & 0x3FF; XMVECTORF32 vResult = { (float)(ElementX - 0x180) / 510.0f, (float)(ElementY - 0x180) / 510.0f, (float)(ElementZ - 0x180) / 510.0f, (float)(sPtr->v >> 30) / 3.0f }; ++sPtr; *(dPtr++) = vResult.v; } return true; } return false; #endif case DXGI_FORMAT_R10G10B10A2_UINT: LOAD_SCANLINE( XMUDEC4, XMLoadUDec4 ); case DXGI_FORMAT_R11G11B10_FLOAT: LOAD_SCANLINE3( XMFLOAT3PK, XMLoadFloat3PK, g_XMIdentityR3 ); case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: LOAD_SCANLINE( XMUBYTEN4, XMLoadUByteN4 ) case DXGI_FORMAT_R8G8B8A8_UINT: LOAD_SCANLINE( XMUBYTE4, XMLoadUByte4 ) case DXGI_FORMAT_R8G8B8A8_SNORM: LOAD_SCANLINE( XMBYTEN4, XMLoadByteN4 ) case DXGI_FORMAT_R8G8B8A8_SINT: LOAD_SCANLINE( XMBYTE4, XMLoadByte4 ) case DXGI_FORMAT_R16G16_FLOAT: LOAD_SCANLINE2( XMHALF2, XMLoadHalf2, g_XMIdentityR3 ) case DXGI_FORMAT_R16G16_UNORM: LOAD_SCANLINE2( XMUSHORTN2, XMLoadUShortN2, g_XMIdentityR3 ) case DXGI_FORMAT_R16G16_UINT: LOAD_SCANLINE2( XMUSHORT2, XMLoadUShort2, g_XMIdentityR3 ) case DXGI_FORMAT_R16G16_SNORM: LOAD_SCANLINE2( XMSHORTN2, XMLoadShortN2, g_XMIdentityR3 ) case DXGI_FORMAT_R16G16_SINT: LOAD_SCANLINE2( XMSHORT2, XMLoadShort2, g_XMIdentityR3 ) case DXGI_FORMAT_D32_FLOAT: case DXGI_FORMAT_R32_FLOAT: if ( size >= sizeof(float) ) { const float* __restrict sPtr = reinterpret_cast<const float*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(float) + 1 ); icount += sizeof(float) ) { XMVECTOR v = XMLoadFloat( sPtr++ ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1000 ); } return true; } return false; case DXGI_FORMAT_R32_UINT: if ( size >= sizeof(uint32_t) ) { const uint32_t* __restrict sPtr = reinterpret_cast<const uint32_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { XMVECTOR v = XMLoadInt( sPtr++ ); v = XMConvertVectorUIntToFloat( v, 0 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1000 ); } return true; } return false; case DXGI_FORMAT_R32_SINT: if ( size >= sizeof(int32_t) ) { const int32_t * __restrict sPtr = reinterpret_cast<const int32_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(int32_t) + 1 ); icount += sizeof(int32_t) ) { XMVECTOR v = XMLoadInt( reinterpret_cast<const uint32_t*> (sPtr++) ); v = XMConvertVectorIntToFloat( v, 0 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1000 ); } return true; } return false; case DXGI_FORMAT_D24_UNORM_S8_UINT: if ( size >= sizeof(uint32_t) ) { const uint32_t * sPtr = reinterpret_cast<const uint32_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { float d = static_cast<float>( *sPtr & 0xFFFFFF ) / 16777215.f; float s = static_cast<float>( ( *sPtr & 0xFF000000 ) >> 24 ); ++sPtr; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( d, s, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: if ( size >= sizeof(uint32_t) ) { const uint32_t * sPtr = reinterpret_cast<const uint32_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { float r = static_cast<float>( *sPtr & 0xFFFFFF ) / 16777215.f; ++sPtr; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( r, 0.f /* typeless component assumed zero */, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: if ( size >= sizeof(uint32_t) ) { const uint32_t * sPtr = reinterpret_cast<const uint32_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { float g = static_cast<float>( ( *sPtr & 0xFF000000 ) >> 24 ); ++sPtr; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( 0.f /* typeless component assumed zero */, g, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R8G8_UNORM: LOAD_SCANLINE2( XMUBYTEN2, XMLoadUByteN2, g_XMIdentityR3 ) case DXGI_FORMAT_R8G8_UINT: LOAD_SCANLINE2( XMUBYTE2, XMLoadUByte2, g_XMIdentityR3 ) case DXGI_FORMAT_R8G8_SNORM: LOAD_SCANLINE2( XMBYTEN2, XMLoadByteN2, g_XMIdentityR3 ) case DXGI_FORMAT_R8G8_SINT: LOAD_SCANLINE2( XMBYTE2, XMLoadByte2, g_XMIdentityR3 ) case DXGI_FORMAT_R16_FLOAT: if ( size >= sizeof(HALF) ) { const HALF * __restrict sPtr = reinterpret_cast<const HALF*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(HALF) + 1 ); icount += sizeof(HALF) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( XMConvertHalfToFloat(*sPtr++), 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: if ( size >= sizeof(uint16_t) ) { const uint16_t* __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint16_t) + 1 ); icount += sizeof(uint16_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++) / 65535.f, 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R16_UINT: if ( size >= sizeof(uint16_t) ) { const uint16_t * __restrict sPtr = reinterpret_cast<const uint16_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint16_t) + 1 ); icount += sizeof(uint16_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++), 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R16_SNORM: if ( size >= sizeof(int16_t) ) { const int16_t * __restrict sPtr = reinterpret_cast<const int16_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(int16_t) + 1 ); icount += sizeof(int16_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++) / 32767.f, 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R16_SINT: if ( size >= sizeof(int16_t) ) { const int16_t * __restrict sPtr = reinterpret_cast<const int16_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(int16_t) + 1 ); icount += sizeof(int16_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++), 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R8_UNORM: if ( size >= sizeof(uint8_t) ) { const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++) / 255.f, 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R8_UINT: if ( size >= sizeof(uint8_t) ) { const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++), 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R8_SNORM: if ( size >= sizeof(int8_t) ) { const int8_t * __restrict sPtr = reinterpret_cast<const int8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(int8_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++) / 127.f, 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_R8_SINT: if ( size >= sizeof(int8_t) ) { const int8_t * __restrict sPtr = reinterpret_cast<const int8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(int8_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( static_cast<float>(*sPtr++), 0.f, 0.f, 1.f ); } return true; } return false; case DXGI_FORMAT_A8_UNORM: if ( size >= sizeof(uint8_t) ) { const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( 0.f, 0.f, 0.f, static_cast<float>(*sPtr++) / 255.f ); } return true; } return false; case DXGI_FORMAT_R1_UNORM: if ( size >= sizeof(uint8_t) ) { const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { for( size_t bcount = 8; bcount > 0; --bcount ) { if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( (((*sPtr >> (bcount-1)) & 0x1) ? 1.f : 0.f), 0.f, 0.f, 1.f ); } ++sPtr; } return true; } return false; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: #if DIRECTX_MATH_VERSION >= 306 LOAD_SCANLINE3( XMFLOAT3SE, XMLoadFloat3SE, g_XMIdentityR3 ) #else if ( size >= sizeof(XMFLOAT3SE) ) { const XMFLOAT3SE * __restrict sPtr = reinterpret_cast<const XMFLOAT3SE*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMFLOAT3SE) + 1 ); icount += sizeof(XMFLOAT3SE) ) { union { float f; int32_t i; } fi; fi.i = 0x33800000 + (sPtr->e << 23); float Scale = fi.f; XMVECTORF32 v = { Scale * float( sPtr->xm ), Scale * float( sPtr->ym ), Scale * float( sPtr->zm ), 1.0f }; if ( dPtr >= ePtr ) break; *(dPtr++) = v; } return true; } return false; #endif case DXGI_FORMAT_R8G8_B8G8_UNORM: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { XMVECTOR v = XMLoadUByteN4( sPtr++ ); XMVECTOR v1 = XMVectorSwizzle<0, 3, 2, 1>( v ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1110 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v1, g_XMSelect1110 ); } return true; } return false; case DXGI_FORMAT_G8R8_G8B8_UNORM: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { XMVECTOR v = XMLoadUByteN4( sPtr++ ); XMVECTOR v0 = XMVectorSwizzle<1, 0, 3, 2>( v ); XMVECTOR v1 = XMVectorSwizzle<1, 2, 3, 0>( v ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v0, g_XMSelect1110 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v1, g_XMSelect1110 ); } return true; } return false; case DXGI_FORMAT_B5G6R5_UNORM: if ( size >= sizeof(XMU565) ) { static const XMVECTORF32 s_Scale = { 1.f/31.f, 1.f/63.f, 1.f/31.f, 1.f }; const XMU565 * __restrict sPtr = reinterpret_cast<const XMU565*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMU565) + 1 ); icount += sizeof(XMU565) ) { XMVECTOR v = XMLoadU565( sPtr++ ); v = XMVectorMultiply( v, s_Scale ); v = XMVectorSwizzle<2, 1, 0, 3>( v ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1110 ); } return true; } return false; case DXGI_FORMAT_B5G5R5A1_UNORM: if ( size >= sizeof(XMU555) ) { static const XMVECTORF32 s_Scale = { 1.f/31.f, 1.f/31.f, 1.f/31.f, 1.f }; const XMU555 * __restrict sPtr = reinterpret_cast<const XMU555*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMU555) + 1 ); icount += sizeof(XMU555) ) { XMVECTOR v = XMLoadU555( sPtr++ ); v = XMVectorMultiply( v, s_Scale ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSwizzle<2, 1, 0, 3>( v ); } return true; } return false; case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { XMVECTOR v = XMLoadUByteN4( sPtr++ ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSwizzle<2, 1, 0, 3>( v ); } return true; } return false; case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { XMVECTOR v = XMLoadUByteN4( sPtr++ ); v = XMVectorSwizzle<2, 1, 0, 3>( v ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1110 ); } return true; } return false; case DXGI_FORMAT_AYUV: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { int v = int(sPtr->x) - 128; int u = int(sPtr->y) - 128; int y = int(sPtr->z) - 16; unsigned int a = sPtr->w; ++sPtr; // http://msdn.microsoft.com/en-us/library/windows/desktop/dd206750.aspx // Y? = Y - 16 // Cb?= Cb - 128 // Cr?= Cr - 128 // R = 1.1644Y?+ 1.5960Cr? // G = 1.1644Y?- 0.3917Cb?- 0.8128Cr? // B = 1.1644Y?+ 2.0172Cb? int r = (298 * y + 409 * v + 128) >> 8; int g = (298 * y - 100 * u - 208 * v + 128) >> 8; int b = (298 * y + 516 * u + 128) >> 8; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( g, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( b, 0 ), 255 ) ) / 255.f, float( a / 255.f ) ); } return true; } return false; case DXGI_FORMAT_Y410: if ( size >= sizeof(XMUDECN4) ) { const XMUDECN4 * __restrict sPtr = reinterpret_cast<const XMUDECN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { int64_t u = int(sPtr->x) - 512; int64_t y = int(sPtr->y) - 64; int64_t v = int(sPtr->z) - 512; unsigned int a = sPtr->w; ++sPtr; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb970578.aspx // Y? = Y - 64 // Cb?= Cb - 512 // Cr?= Cr - 512 // R = 1.1678Y?+ 1.6007Cr? // G = 1.1678Y?- 0.3929Cb?- 0.8152Cr? // B = 1.1678Y?+ 2.0232Cb? int r = static_cast<int>( (76533 * y + 104905 * v + 32768) >> 16 ); int g = static_cast<int>( (76533 * y - 25747 * u - 53425 * v + 32768) >> 16 ); int b = static_cast<int>( (76533 * y + 132590 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( g, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( b, 0 ), 1023 ) ) / 1023.f, float( a / 3.f ) ); } return true; } return false; case DXGI_FORMAT_Y416: if ( size >= sizeof(XMUSHORTN4) ) { const XMUSHORTN4 * __restrict sPtr = reinterpret_cast<const XMUSHORTN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { int64_t u = int64_t(sPtr->x) - 32768; int64_t y = int64_t(sPtr->y) - 4096; int64_t v = int64_t(sPtr->z) - 32768; unsigned int a = sPtr->w; ++sPtr; // http://msdn.microsoft.com/en-us/library/windows/desktop/bb970578.aspx // Y? = Y - 4096 // Cb?= Cb - 32768 // Cr?= Cr - 32768 // R = 1.1689Y?+ 1.6023Cr? // G = 1.1689Y?- 0.3933Cb?- 0.8160Cr? // B = 1.1689Y? 2.0251Cb? int r = static_cast<int>( (76607 * y + 105006 * v + 32768) >> 16 ); int g = static_cast<int>( (76607 * y - 25772 * u - 53477 * v + 32768) >> 16 ); int b = static_cast<int>( (76607 * y + 132718 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( g, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( b, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( a, 0 ), 65535 ) ) / 65535.f ); } return true; } return false; case DXGI_FORMAT_YUY2: if ( size >= sizeof(XMUBYTEN4) ) { const XMUBYTEN4 * __restrict sPtr = reinterpret_cast<const XMUBYTEN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { int y0 = int(sPtr->x) - 16; int u = int(sPtr->y) - 128; int y1 = int(sPtr->z) - 16; int v = int(sPtr->w) - 128; ++sPtr; // See AYUV int r = (298 * y0 + 409 * v + 128) >> 8; int g = (298 * y0 - 100 * u - 208 * v + 128) >> 8; int b = (298 * y0 + 516 * u + 128) >> 8; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( g, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( b, 0 ), 255 ) ) / 255.f, 1.f ); r = (298 * y1 + 409 * v + 128) >> 8; g = (298 * y1 - 100 * u - 208 * v + 128) >> 8; b = (298 * y1 + 516 * u + 128) >> 8; if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( g, 0 ), 255 ) ) / 255.f, float( std::min<int>( std::max<int>( b, 0 ), 255 ) ) / 255.f, 1.f ); } return true; } return false; case DXGI_FORMAT_Y210: // Same as Y216 with least significant 6 bits set to zero if ( size >= sizeof(XMUSHORTN4) ) { const XMUSHORTN4 * __restrict sPtr = reinterpret_cast<const XMUSHORTN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { int64_t y0 = int64_t(sPtr->x >> 6) - 64; int64_t u = int64_t(sPtr->y >> 6) - 512; int64_t y1 = int64_t(sPtr->z >> 6) - 64; int64_t v = int64_t(sPtr->w >> 6) - 512; ++sPtr; // See Y410 int r = static_cast<int>( (76533 * y0 + 104905 * v + 32768) >> 16 ); int g = static_cast<int>( (76533 * y0 - 25747 * u - 53425 * v + 32768) >> 16 ); int b = static_cast<int>( (76533 * y0 + 132590 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( g, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( b, 0 ), 1023 ) ) / 1023.f, 1.f ); r = static_cast<int>( (76533 * y1 + 104905 * v + 32768) >> 16 ); g = static_cast<int>( (76533 * y1 - 25747 * u - 53425 * v + 32768) >> 16 ); b = static_cast<int>( (76533 * y1 + 132590 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( g, 0 ), 1023 ) ) / 1023.f, float( std::min<int>( std::max<int>( b, 0 ), 1023 ) ) / 1023.f, 1.f ); } return true; } return false; case DXGI_FORMAT_Y216: if ( size >= sizeof(XMUSHORTN4) ) { const XMUSHORTN4 * __restrict sPtr = reinterpret_cast<const XMUSHORTN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { int64_t y0 = int64_t(sPtr->x) - 4096; int64_t u = int64_t(sPtr->y) - 32768; int64_t y1 = int64_t(sPtr->z) - 4096; int64_t v = int64_t(sPtr->w) - 32768; ++sPtr; // See Y416 int r = static_cast<int>( (76607 * y0 + 105006 * v + 32768) >> 16 ); int g = static_cast<int>( (76607 * y0 - 25772 * u - 53477 * v + 32768) >> 16 ); int b = static_cast<int>( (76607 * y0 + 132718 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( g, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( b, 0 ), 65535 ) ) / 65535.f, 1.f ); r = static_cast<int>( (76607 * y1 + 105006 * v + 32768) >> 16 ); g = static_cast<int>( (76607 * y1 - 25772 * u - 53477 * v + 32768) >> 16 ); b = static_cast<int>( (76607 * y1 + 132718 * u + 32768) >> 16 ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSet( float( std::min<int>( std::max<int>( r, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( g, 0 ), 65535 ) ) / 65535.f, float( std::min<int>( std::max<int>( b, 0 ), 65535 ) ) / 65535.f, 1.f ); } return true; } return false; case DXGI_FORMAT_B4G4R4A4_UNORM: if ( size >= sizeof(XMUNIBBLE4) ) { static const XMVECTORF32 s_Scale = { 1.f/15.f, 1.f/15.f, 1.f/15.f, 1.f/15.f }; const XMUNIBBLE4 * __restrict sPtr = reinterpret_cast<const XMUNIBBLE4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUNIBBLE4) + 1 ); icount += sizeof(XMUNIBBLE4) ) { XMVECTOR v = XMLoadUNibble4( sPtr++ ); v = XMVectorMultiply( v, s_Scale ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSwizzle<2, 1, 0, 3>( v ); } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT: // Xbox One specific 7e3 format if ( size >= sizeof(XMUDECN4) ) { const XMUDECN4 * __restrict sPtr = reinterpret_cast<const XMUDECN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( dPtr >= ePtr ) break; XMVECTORF32 vResult = { FloatFrom7e3(sPtr->x), FloatFrom7e3(sPtr->y), FloatFrom7e3(sPtr->z), (float)(sPtr->v >> 30) / 3.0f }; ++sPtr; *(dPtr++) = vResult.v; } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT: // Xbox One specific 6e4 format if ( size >= sizeof(XMUDECN4) ) { const XMUDECN4 * __restrict sPtr = reinterpret_cast<const XMUDECN4*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( dPtr >= ePtr ) break; XMVECTORF32 vResult = { FloatFrom6e4(sPtr->x), FloatFrom6e4(sPtr->y), FloatFrom6e4(sPtr->z), (float)(sPtr->v >> 30) / 3.0f }; ++sPtr; *(dPtr++) = vResult.v; } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: // Xbox One specific format LOAD_SCANLINE( XMXDECN4, XMLoadXDecN4 ); case XBOX_DXGI_FORMAT_R4G4_UNORM: // Xbox One specific format if ( size >= sizeof(uint8_t) ) { static const XMVECTORF32 s_Scale = { 1.f/15.f, 1.f/15.f, 0.f, 0.f }; const uint8_t * __restrict sPtr = reinterpret_cast<const uint8_t*>(pSource); for( size_t icount = 0; icount < ( size - sizeof(uint8_t) + 1 ); icount += sizeof(uint8_t) ) { XMUNIBBLE4 nibble; nibble.v = static_cast<uint16_t>( *sPtr++ ); XMVECTOR v = XMLoadUNibble4( &nibble ); v = XMVectorMultiply( v, s_Scale ); if ( dPtr >= ePtr ) break; *(dPtr++) = XMVectorSelect( g_XMIdentityR3, v, g_XMSelect1100 ); } return true; } return false; // We don't support the planar or palettized formats default: return false; } } #undef LOAD_SCANLINE #undef LOAD_SCANLINE3 #undef LOAD_SCANLINE2 //------------------------------------------------------------------------------------- // Stores an image row from standard RGBA XMVECTOR (aligned) array //------------------------------------------------------------------------------------- #define STORE_SCANLINE( type, func )\ if ( size >= sizeof(type) )\ {\ type * __restrict dPtr = reinterpret_cast<type*>(pDestination);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ if ( sPtr >= ePtr ) break;\ func( dPtr++, *sPtr++ );\ }\ return true; \ }\ return false; _Use_decl_annotations_ bool _StoreScanline( LPVOID pDestination, size_t size, DXGI_FORMAT format, const XMVECTOR* pSource, size_t count, float threshold ) { assert( pDestination && size > 0 ); assert( pSource && count > 0 && (((uintptr_t)pSource & 0xF) == 0) ); assert( IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format) ); const XMVECTOR* __restrict sPtr = pSource; if ( !sPtr ) return false; const XMVECTOR* ePtr = pSource + count; switch( static_cast<int>(format) ) { case DXGI_FORMAT_R32G32B32A32_FLOAT: STORE_SCANLINE( XMFLOAT4, XMStoreFloat4 ) case DXGI_FORMAT_R32G32B32A32_UINT: STORE_SCANLINE( XMUINT4, XMStoreUInt4 ) case DXGI_FORMAT_R32G32B32A32_SINT: STORE_SCANLINE( XMINT4, XMStoreSInt4 ) case DXGI_FORMAT_R32G32B32_FLOAT: STORE_SCANLINE( XMFLOAT3, XMStoreFloat3 ) case DXGI_FORMAT_R32G32B32_UINT: STORE_SCANLINE( XMUINT3, XMStoreUInt3 ) case DXGI_FORMAT_R32G32B32_SINT: STORE_SCANLINE( XMINT3, XMStoreSInt3 ) case DXGI_FORMAT_R16G16B16A16_FLOAT: if ( size >= sizeof(XMHALF4) ) { XMHALF4* __restrict dPtr = reinterpret_cast<XMHALF4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMHALF4) + 1 ); icount += sizeof(XMHALF4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = *sPtr++; v = XMVectorClamp( v, g_HalfMin, g_HalfMax ); XMStoreHalf4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_R16G16B16A16_UNORM: STORE_SCANLINE( XMUSHORTN4, XMStoreUShortN4 ) case DXGI_FORMAT_R16G16B16A16_UINT: STORE_SCANLINE( XMUSHORT4, XMStoreUShort4 ) case DXGI_FORMAT_R16G16B16A16_SNORM: STORE_SCANLINE( XMSHORTN4, XMStoreShortN4 ) case DXGI_FORMAT_R16G16B16A16_SINT: STORE_SCANLINE( XMSHORT4, XMStoreShort4 ) case DXGI_FORMAT_R32G32_FLOAT: STORE_SCANLINE( XMFLOAT2, XMStoreFloat2 ) case DXGI_FORMAT_R32G32_UINT: STORE_SCANLINE( XMUINT2, XMStoreUInt2 ) case DXGI_FORMAT_R32G32_SINT: STORE_SCANLINE( XMINT2, XMStoreSInt2 ) case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: { const size_t psize = sizeof(float)+sizeof(uint32_t); if ( size >= psize ) { float *dPtr = reinterpret_cast<float*>(pDestination); for( size_t icount = 0; icount < ( size - psize + 1 ); icount += psize ) { if ( sPtr >= ePtr ) break; XMFLOAT4 f; XMStoreFloat4( &f, *sPtr++ ); dPtr[0] = f.x; uint8_t* ps8 = reinterpret_cast<uint8_t*>( &dPtr[1] ); ps8[0] = static_cast<uint8_t>( std::min<float>( 255.f, std::max<float>( 0.f, f.y ) ) ); ps8[1] = ps8[2] = ps8[3] = 0; dPtr += 2; } return true; } } return false; case DXGI_FORMAT_R10G10B10A2_UNORM: STORE_SCANLINE( XMUDECN4, XMStoreUDecN4 ); case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: #if DIRECTX_MATH_VERSION >= 306 STORE_SCANLINE( XMUDECN4, XMStoreUDecN4_XR ); #else if ( size >= sizeof(XMUDECN4) ) { static const XMVECTORF32 Scale = { 510.0f, 510.0f, 510.0f, 3.0f }; static const XMVECTORF32 Bias = { 384.0f, 384.0f, 384.0f, 0.0f }; static const XMVECTORF32 C = { 1023.f, 1023.f, 1023.f, 3.f }; XMUDECN4 * __restrict dPtr = reinterpret_cast<XMUDECN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR N = XMVectorMultiplyAdd( *sPtr++, Scale, Bias ); N = XMVectorClamp( N, g_XMZero, C ); XMFLOAT4A tmp; XMStoreFloat4A(&tmp, N ); dPtr->v = ((uint32_t)tmp.w << 30) | (((uint32_t)tmp.z & 0x3FF) << 20) | (((uint32_t)tmp.y & 0x3FF) << 10) | (((uint32_t)tmp.x & 0x3FF)); ++dPtr; } return true; } return false; #endif case DXGI_FORMAT_R10G10B10A2_UINT: STORE_SCANLINE( XMUDEC4, XMStoreUDec4 ); case DXGI_FORMAT_R11G11B10_FLOAT: STORE_SCANLINE( XMFLOAT3PK, XMStoreFloat3PK ); case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorAdd( *sPtr++, g_8BitBias ); XMStoreUByteN4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_R8G8B8A8_UINT: STORE_SCANLINE( XMUBYTE4, XMStoreUByte4 ) case DXGI_FORMAT_R8G8B8A8_SNORM: STORE_SCANLINE( XMBYTEN4, XMStoreByteN4 ) case DXGI_FORMAT_R8G8B8A8_SINT: STORE_SCANLINE( XMBYTE4, XMStoreByte4 ) case DXGI_FORMAT_R16G16_FLOAT: if ( size >= sizeof(XMHALF2) ) { XMHALF2* __restrict dPtr = reinterpret_cast<XMHALF2*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMHALF2) + 1 ); icount += sizeof(XMHALF2) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = *sPtr++; v = XMVectorClamp( v, g_HalfMin, g_HalfMax ); XMStoreHalf2( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_R16G16_UNORM: STORE_SCANLINE( XMUSHORTN2, XMStoreUShortN2 ) case DXGI_FORMAT_R16G16_UINT: STORE_SCANLINE( XMUSHORT2, XMStoreUShort2 ) case DXGI_FORMAT_R16G16_SNORM: STORE_SCANLINE( XMSHORTN2, XMStoreShortN2 ) case DXGI_FORMAT_R16G16_SINT: STORE_SCANLINE( XMSHORT2, XMStoreShort2 ) case DXGI_FORMAT_D32_FLOAT: case DXGI_FORMAT_R32_FLOAT: if ( size >= sizeof(float) ) { float * __restrict dPtr = reinterpret_cast<float*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(float) + 1 ); icount += sizeof(float) ) { if ( sPtr >= ePtr ) break; XMStoreFloat( dPtr++, *(sPtr++) ); } return true; } return false; case DXGI_FORMAT_R32_UINT: if ( size >= sizeof(uint32_t) ) { uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMConvertVectorFloatToUInt( *(sPtr++), 0 ); XMStoreInt( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_R32_SINT: if ( size >= sizeof(int32_t) ) { uint32_t * __restrict dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(int32_t) + 1 ); icount += sizeof(int32_t) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMConvertVectorFloatToInt( *(sPtr++), 0 ); XMStoreInt( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_D24_UNORM_S8_UINT: if ( size >= sizeof(uint32_t) ) { static const XMVECTORF32 clamp = { 1.f, 255.f, 0.f, 0.f }; XMVECTOR zero = XMVectorZero(); uint32_t *dPtr = reinterpret_cast<uint32_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(uint32_t) + 1 ); icount += sizeof(uint32_t) ) { if ( sPtr >= ePtr ) break; XMFLOAT4 f; XMStoreFloat4( &f, XMVectorClamp( *sPtr++, zero, clamp ) ); *dPtr++ = (static_cast<uint32_t>( f.x * 16777215.f ) & 0xFFFFFF) | ((static_cast<uint32_t>( f.y ) & 0xFF) << 24); } return true; } return false; case DXGI_FORMAT_R8G8_UNORM: STORE_SCANLINE( XMUBYTEN2, XMStoreUByteN2 ) case DXGI_FORMAT_R8G8_UINT: STORE_SCANLINE( XMUBYTE2, XMStoreUByte2 ) case DXGI_FORMAT_R8G8_SNORM: STORE_SCANLINE( XMBYTEN2, XMStoreByteN2 ) case DXGI_FORMAT_R8G8_SINT: STORE_SCANLINE( XMBYTE2, XMStoreByte2 ) case DXGI_FORMAT_R16_FLOAT: if ( size >= sizeof(HALF) ) { HALF * __restrict dPtr = reinterpret_cast<HALF*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(HALF) + 1 ); icount += sizeof(HALF) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 65504.f ), -65504.f ); *(dPtr++) = XMConvertFloatToHalf(v); } return true; } return false; case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: if ( size >= sizeof(uint16_t) ) { uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(uint16_t) + 1 ); icount += sizeof(uint16_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 1.f ), 0.f ); *(dPtr++) = static_cast<uint16_t>( v*65535.f + 0.5f ); } return true; } return false; case DXGI_FORMAT_R16_UINT: if ( size >= sizeof(uint16_t) ) { uint16_t * __restrict dPtr = reinterpret_cast<uint16_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(uint16_t) + 1 ); icount += sizeof(uint16_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 65535.f ), 0.f ); *(dPtr++) = static_cast<uint16_t>(v); } return true; } return false; case DXGI_FORMAT_R16_SNORM: if ( size >= sizeof(int16_t) ) { int16_t * __restrict dPtr = reinterpret_cast<int16_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(int16_t) + 1 ); icount += sizeof(int16_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 1.f ), -1.f ); *(dPtr++) = static_cast<int16_t>( v * 32767.f ); } return true; } return false; case DXGI_FORMAT_R16_SINT: if ( size >= sizeof(int16_t) ) { int16_t * __restrict dPtr = reinterpret_cast<int16_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(int16_t) + 1 ); icount += sizeof(int16_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 32767.f ), -32767.f ); *(dPtr++) = static_cast<int16_t>(v); } return true; } return false; case DXGI_FORMAT_R8_UNORM: if ( size >= sizeof(uint8_t) ) { uint8_t * __restrict dPtr = reinterpret_cast<uint8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 1.f ), 0.f ); *(dPtr++) = static_cast<uint8_t>( v * 255.f ); } return true; } return false; case DXGI_FORMAT_R8_UINT: if ( size >= sizeof(uint8_t) ) { uint8_t * __restrict dPtr = reinterpret_cast<uint8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 255.f ), 0.f ); *(dPtr++) = static_cast<uint8_t>(v); } return true; } return false; case DXGI_FORMAT_R8_SNORM: if ( size >= sizeof(int8_t) ) { int8_t * __restrict dPtr = reinterpret_cast<int8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(int8_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 1.f ), -1.f ); *(dPtr++) = static_cast<int8_t>( v * 127.f ); } return true; } return false; case DXGI_FORMAT_R8_SINT: if ( size >= sizeof(int8_t) ) { int8_t * __restrict dPtr = reinterpret_cast<int8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(int8_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); v = std::max<float>( std::min<float>( v, 127.f ), -127.f ); *(dPtr++) = static_cast<int8_t>( v ); } return true; } return false; case DXGI_FORMAT_A8_UNORM: if ( size >= sizeof(uint8_t) ) { uint8_t * __restrict dPtr = reinterpret_cast<uint8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetW( *sPtr++ ); v = std::max<float>( std::min<float>( v, 1.f ), 0.f ); *(dPtr++) = static_cast<uint8_t>( v * 255.f); } return true; } return false; case DXGI_FORMAT_R1_UNORM: if ( size >= sizeof(uint8_t) ) { uint8_t * __restrict dPtr = reinterpret_cast<uint8_t*>(pDestination); for( size_t icount = 0; icount < size; icount += sizeof(uint8_t) ) { uint8_t pixels = 0; for( size_t bcount = 8; bcount > 0; --bcount ) { if ( sPtr >= ePtr ) break; float v = XMVectorGetX( *sPtr++ ); // Absolute thresholding generally doesn't give good results for all images // Picking the 'right' threshold automatically requires whole-image analysis if ( v > 0.25f ) pixels |= 1 << (bcount-1); } *(dPtr++) = pixels; } return true; } return false; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: #if DIRECTX_MATH_VERSION >= 306 STORE_SCANLINE( XMFLOAT3SE, XMStoreFloat3SE ) #else if ( size >= sizeof(XMFLOAT3SE) ) { static const float maxf9 = float(0x1FF << 7); static const float minf9 = float(1.f / (1 << 16)); XMFLOAT3SE * __restrict dPtr = reinterpret_cast<XMFLOAT3SE*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMFLOAT3SE) + 1 ); icount += sizeof(XMFLOAT3SE) ) { if ( sPtr >= ePtr ) break; XMFLOAT3 rgb; XMStoreFloat3( &rgb, *(sPtr++) ); float r = (rgb.x >= 0.f) ? ( (rgb.x > maxf9) ? maxf9 : rgb.x ) : 0.f; float g = (rgb.y >= 0.f) ? ( (rgb.y > maxf9) ? maxf9 : rgb.y ) : 0.f; float b = (rgb.z >= 0.f) ? ( (rgb.z > maxf9) ? maxf9 : rgb.z ) : 0.f; const float max_rg = (r > g) ? r : g; const float max_rgb = (max_rg > b) ? max_rg : b; const float maxColor = (max_rgb > minf9) ? max_rgb : minf9; union { float f; INT32 i; } fi; fi.f = maxColor; fi.i &= 0xFF800000; // cut off fraction dPtr->e = (fi.i - 0x37800000) >> 23; fi.i = 0x83000000 - fi.i; float ScaleR = fi.f; dPtr->xm = static_cast<uint32_t>( round_to_nearest(r * ScaleR) ); dPtr->ym = static_cast<uint32_t>( round_to_nearest(g * ScaleR) ); dPtr->zm = static_cast<uint32_t>( round_to_nearest(b * ScaleR) ); ++dPtr; } return true; } return false; #endif case DXGI_FORMAT_R8G8_B8G8_UNORM: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v0 = *sPtr++; XMVECTOR v1 = (sPtr < ePtr) ? XMVectorSplatY( *sPtr++ ) : XMVectorZero(); XMVECTOR v = XMVectorSelect( v1, v0, g_XMSelect1110 ); v = XMVectorAdd( v, g_8BitBias ); XMStoreUByteN4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_G8R8_G8B8_UNORM: if ( size >= sizeof(XMUBYTEN4) ) { static XMVECTORU32 select1101 = {XM_SELECT_1, XM_SELECT_1, XM_SELECT_0, XM_SELECT_1}; XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v0 = XMVectorSwizzle<1, 0, 3, 2>( *sPtr++ ); XMVECTOR v1 = (sPtr < ePtr) ? XMVectorSplatY( *sPtr++ ) : XMVectorZero(); XMVECTOR v = XMVectorSelect( v1, v0, select1101 ); v = XMVectorAdd( v, g_8BitBias ); XMStoreUByteN4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_B5G6R5_UNORM: if ( size >= sizeof(XMU565) ) { static const XMVECTORF32 s_Scale = { 31.f, 63.f, 31.f, 1.f }; XMU565 * __restrict dPtr = reinterpret_cast<XMU565*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMU565) + 1 ); icount += sizeof(XMU565) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( *sPtr++ ); v = XMVectorMultiply( v, s_Scale ); XMStoreU565( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_B5G5R5A1_UNORM: if ( size >= sizeof(XMU555) ) { static const XMVECTORF32 s_Scale = { 31.f, 31.f, 31.f, 1.f }; XMU555 * __restrict dPtr = reinterpret_cast<XMU555*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMU555) + 1 ); icount += sizeof(XMU555) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( *sPtr++ ); v = XMVectorMultiply( v, s_Scale ); XMStoreU555( dPtr, v ); dPtr->w = ( XMVectorGetW( v ) > threshold ) ? 1 : 0; ++dPtr; } return true; } return false; case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( *sPtr++ ); v = XMVectorAdd( v, g_8BitBias ); XMStoreUByteN4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorPermute<2, 1, 0, 7>( *sPtr++, g_XMIdentityR3 ); v = XMVectorAdd( v, g_8BitBias ); XMStoreUByteN4( dPtr++, v ); } return true; } return false; case DXGI_FORMAT_AYUV: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMUBYTEN4 rgba; XMStoreUByteN4( &rgba, *sPtr++ ); // http://msdn.microsoft.com/en-us/library/windows/desktop/dd206750.aspx // Y = 0.2568R + 0.5041G + 0.1001B + 16 // Cb = -0.1482R - 0.2910G + 0.4392B + 128 // Cr = 0.4392R - 0.3678G - 0.0714B + 128 int y = ( ( 66 * rgba.x + 129 * rgba.y + 25 * rgba.z + 128) >> 8) + 16; int u = ( ( -38 * rgba.x - 74 * rgba.y + 112 * rgba.z + 128) >> 8) + 128; int v = ( ( 112 * rgba.x - 94 * rgba.y - 18 * rgba.z + 128) >> 8) + 128; dPtr->x = static_cast<uint8_t>( std::min<int>( std::max<int>( v, 0 ), 255 ) ); dPtr->y = static_cast<uint8_t>( std::min<int>( std::max<int>( u, 0 ), 255 ) ); dPtr->z = static_cast<uint8_t>( std::min<int>( std::max<int>( y, 0 ), 255 ) ); dPtr->w = rgba.w; ++dPtr; } return true; } return false; case DXGI_FORMAT_Y410: if ( size >= sizeof(XMUDECN4) ) { XMUDECN4 * __restrict dPtr = reinterpret_cast<XMUDECN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( sPtr >= ePtr ) break; XMUDECN4 rgba; XMStoreUDecN4( &rgba, *sPtr++ ); // http://msdn.microsoft.com/en-us/library/windows/desktop/bb970578.aspx // Y = 0.2560R + 0.5027G + 0.0998B + 64 // Cb = -0.1478R - 0.2902G + 0.4379B + 512 // Cr = 0.4379R - 0.3667G - 0.0712B + 512 int64_t r = rgba.x; int64_t g = rgba.y; int64_t b = rgba.z; int y = static_cast<int>( ( 16780 * r + 32942 * g + 6544 * b + 32768) >> 16) + 64; int u = static_cast<int>( ( -9683 * r - 19017 * g + 28700 * b + 32768) >> 16) + 512; int v = static_cast<int>( ( 28700 * r - 24033 * g - 4667 * b + 32768) >> 16) + 512; dPtr->x = static_cast<uint32_t>( std::min<int>( std::max<int>( u, 0 ), 1023 ) ); dPtr->y = static_cast<uint32_t>( std::min<int>( std::max<int>( y, 0 ), 1023 ) ); dPtr->z = static_cast<uint32_t>( std::min<int>( std::max<int>( v, 0 ), 1023 ) ); dPtr->w = rgba.w; ++dPtr; } return true; } return false; case DXGI_FORMAT_Y416: if ( size >= sizeof(XMUSHORTN4) ) { XMUSHORTN4 * __restrict dPtr = reinterpret_cast<XMUSHORTN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { if ( sPtr >= ePtr ) break; XMUSHORTN4 rgba; XMStoreUShortN4( &rgba, *sPtr++ ); // http://msdn.microsoft.com/en-us/library/windows/desktop/bb970578.aspx // Y = 0.2558R + 0.5022G + 0.0998B + 4096 // Cb = -0.1476R - 0.2899G + 0.4375B + 32768 // Cr = 0.4375R - 0.3664G - 0.0711B + 32768 int64_t r = int64_t(rgba.x); int64_t g = int64_t(rgba.y); int64_t b = int64_t(rgba.z); int y = static_cast<int>( ( 16763 * r + 32910 * g + 6537 * b + 32768) >> 16) + 4096; int u = static_cast<int>( ( -9674 * r - 18998 * g + 28672 * b + 32768) >> 16) + 32768; int v = static_cast<int>( ( 28672 * r - 24010 * g - 4662 * b + 32768) >> 16) + 32768; dPtr->x = static_cast<uint16_t>( std::min<int>( std::max<int>( u, 0 ), 65535 ) ); dPtr->y = static_cast<uint16_t>( std::min<int>( std::max<int>( y, 0 ), 65535 ) ); dPtr->z = static_cast<uint16_t>( std::min<int>( std::max<int>( v, 0 ), 65535 ) ); dPtr->w = rgba.w; ++dPtr; } return true; } return false; case DXGI_FORMAT_YUY2: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUBYTEN4) + 1 ); icount += sizeof(XMUBYTEN4) ) { if ( sPtr >= ePtr ) break; XMUBYTEN4 rgb1; XMStoreUByteN4( &rgb1, *sPtr++ ); // See AYUV int y0 = ( ( 66 * rgb1.x + 129 * rgb1.y + 25 * rgb1.z + 128) >> 8) + 16; int u0 = ( ( -38 * rgb1.x - 74 * rgb1.y + 112 * rgb1.z + 128) >> 8) + 128; int v0 = ( ( 112 * rgb1.x - 94 * rgb1.y - 18 * rgb1.z + 128) >> 8) + 128; XMUBYTEN4 rgb2; if(sPtr < ePtr) { XMStoreUByteN4( &rgb2, *sPtr++ ); } else { rgb2.x = rgb2.y = rgb2.z = rgb2.w = 0; } int y1 = ( ( 66 * rgb2.x + 129 * rgb2.y + 25 * rgb2.z + 128) >> 8) + 16; int u1 = ( ( -38 * rgb2.x - 74 * rgb2.y + 112 * rgb2.z + 128) >> 8) + 128; int v1 = ( ( 112 * rgb2.x - 94 * rgb2.y - 18 * rgb2.z + 128) >> 8) + 128; dPtr->x = static_cast<uint8_t>( std::min<int>( std::max<int>( y0, 0 ), 255 ) ); dPtr->y = static_cast<uint8_t>( std::min<int>( std::max<int>( (u0 + u1) >> 1, 0 ), 255 ) ); dPtr->z = static_cast<uint8_t>( std::min<int>( std::max<int>( y1, 0 ), 255 ) ); dPtr->w = static_cast<uint8_t>( std::min<int>( std::max<int>( (v0 + v1) >> 1, 0 ), 255 ) ); ++dPtr; } return true; } return false; case DXGI_FORMAT_Y210: // Same as Y216 with least significant 6 bits set to zero if ( size >= sizeof(XMUSHORTN4) ) { XMUSHORTN4 * __restrict dPtr = reinterpret_cast<XMUSHORTN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { if ( sPtr >= ePtr ) break; XMUDECN4 rgb1; XMStoreUDecN4( &rgb1, *sPtr++ ); // See Y410 int64_t r = rgb1.x; int64_t g = rgb1.y; int64_t b = rgb1.z; int y0 = static_cast<int>( ( 16780 * r + 32942 * g + 6544 * b + 32768) >> 16) + 64; int u0 = static_cast<int>( ( -9683 * r - 19017 * g + 28700 * b + 32768) >> 16) + 512; int v0 = static_cast<int>( ( 28700 * r - 24033 * g - 4667 * b + 32768) >> 16) + 512; XMUDECN4 rgb2; if(sPtr < ePtr) { XMStoreUDecN4( &rgb2, *sPtr++ ); } else { rgb2.x = rgb2.y = rgb2.z = rgb2.w = 0; } r = rgb2.x; g = rgb2.y; b = rgb2.z; int y1 = static_cast<int>( ( 16780 * r + 32942 * g + 6544 * b + 32768) >> 16) + 64; int u1 = static_cast<int>( ( -9683 * r - 19017 * g + 28700 * b + 32768) >> 16) + 512; int v1 = static_cast<int>( ( 28700 * r - 24033 * g - 4667 * b + 32768) >> 16) + 512; dPtr->x = static_cast<uint16_t>( std::min<int>( std::max<int>( y0, 0 ), 1023 ) << 6 ); dPtr->y = static_cast<uint16_t>( std::min<int>( std::max<int>( (u0 + u1) >> 1, 0 ), 1023 ) << 6 ); dPtr->z = static_cast<uint16_t>( std::min<int>( std::max<int>( y1, 0 ), 1023 ) << 6 ); dPtr->w = static_cast<uint16_t>( std::min<int>( std::max<int>( (v0 + v1) >> 1, 0 ), 1023 ) << 6 ); ++dPtr; } return true; } return false; case DXGI_FORMAT_Y216: if ( size >= sizeof(XMUSHORTN4) ) { XMUSHORTN4 * __restrict dPtr = reinterpret_cast<XMUSHORTN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUSHORTN4) + 1 ); icount += sizeof(XMUSHORTN4) ) { if ( sPtr >= ePtr ) break; XMUSHORTN4 rgb1; XMStoreUShortN4( &rgb1, *sPtr++ ); // See Y416 int64_t r = int64_t(rgb1.x); int64_t g = int64_t(rgb1.y); int64_t b = int64_t(rgb1.z); int y0 = static_cast<int>( ( 16763 * r + 32910 * g + 6537 * b + 32768) >> 16) + 4096; int u0 = static_cast<int>( (-9674 * r - 18998 * g + 28672 * b + 32768) >> 16) + 32768; int v0 = static_cast<int>( ( 28672 * r - 24010 * g - 4662 * b + 32768) >> 16) + 32768; XMUSHORTN4 rgb2; if(sPtr < ePtr) { XMStoreUShortN4( &rgb2, *sPtr++ ); } else { rgb2.x = rgb2.y = rgb2.z = rgb2.w = 0; } r = int64_t(rgb2.x); g = int64_t(rgb2.y); b = int64_t(rgb2.z); int y1 = static_cast<int>( ( 16763 * r + 32910 * g + 6537 * b + 32768) >> 16) + 4096; int u1 = static_cast<int>( (-9674 * r - 18998 * g + 28672 * b + 32768) >> 16) + 32768; int v1 = static_cast<int>( ( 28672 * r - 24010 * g - 4662 * b + 32768) >> 16) + 32768; dPtr->x = static_cast<uint16_t>( std::min<int>( std::max<int>( y0, 0 ), 65535 ) ); dPtr->y = static_cast<uint16_t>( std::min<int>( std::max<int>( (u0 + u1) >> 1, 0 ), 65535 ) ); dPtr->z = static_cast<uint16_t>( std::min<int>( std::max<int>( y1, 0 ), 65535 ) ); dPtr->w = static_cast<uint16_t>( std::min<int>( std::max<int>( (v0 + v1) >> 1, 0 ), 65535 ) ); ++dPtr; } return true; } return false; case DXGI_FORMAT_B4G4R4A4_UNORM: if ( size >= sizeof(XMUNIBBLE4) ) { static const XMVECTORF32 s_Scale = { 15.f, 15.f, 15.f, 15.f }; XMUNIBBLE4 * __restrict dPtr = reinterpret_cast<XMUNIBBLE4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUNIBBLE4) + 1 ); icount += sizeof(XMUNIBBLE4) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( *sPtr++ ); v = XMVectorMultiply( v, s_Scale ); XMStoreUNibble4( dPtr++, v ); } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT: // Xbox One specific 7e3 format with alpha if ( size >= sizeof(XMUDECN4) ) { static const XMVECTORF32 Scale = { 1.0f, 1.0f, 1.0f, 3.0f }; static const XMVECTORF32 C = { 31.875f, 31.875f, 31.875f, 3.f }; XMUDECN4 * __restrict dPtr = reinterpret_cast<XMUDECN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR V = XMVectorMultiply( *sPtr++, Scale ); V = XMVectorClamp( V, g_XMZero, C ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, V ); dPtr->x = FloatTo7e3( tmp.x ); dPtr->y = FloatTo7e3( tmp.y ); dPtr->z = FloatTo7e3( tmp.z ); dPtr->w = (uint32_t)tmp.w; ++dPtr; } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT: // Xbox One specific 6e4 format with alpha if ( size >= sizeof(XMUDECN4) ) { static const XMVECTORF32 Scale = { 1.0f, 1.0f, 1.0f, 3.0f }; static const XMVECTORF32 C = { 508.f, 508.f, 508.f, 3.f }; XMUDECN4 * __restrict dPtr = reinterpret_cast<XMUDECN4*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(XMUDECN4) + 1 ); icount += sizeof(XMUDECN4) ) { if ( sPtr >= ePtr ) break; XMVECTOR V = XMVectorMultiply( *sPtr++, Scale ); V = XMVectorClamp( V, g_XMZero, C ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, V ); dPtr->x = FloatTo6e4( tmp.x ); dPtr->y = FloatTo6e4( tmp.y ); dPtr->z = FloatTo6e4( tmp.z ); dPtr->w = (uint32_t)tmp.w; ++dPtr; } return true; } return false; case XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: // Xbox One specific format STORE_SCANLINE( XMXDECN4, XMStoreXDecN4 ); case XBOX_DXGI_FORMAT_R4G4_UNORM: // Xbox One specific format if ( size >= sizeof(uint8_t) ) { static const XMVECTORF32 s_Scale = { 15.f, 15.f, 0.f, 0.f }; uint8_t * __restrict dPtr = reinterpret_cast<uint8_t*>(pDestination); for( size_t icount = 0; icount < ( size - sizeof(uint8_t) + 1 ); icount += sizeof(uint8_t) ) { if ( sPtr >= ePtr ) break; XMVECTOR v = XMVectorMultiply( *sPtr++, s_Scale ); XMUNIBBLE4 nibble; XMStoreUNibble4( &nibble, v ); *dPtr = static_cast<uint8_t>( nibble.v ); ++dPtr; } return true; } return false; // We don't support the planar or palettized formats default: return false; } } #undef STORE_SCANLINE //------------------------------------------------------------------------------------- // Convert DXGI image to/from GUID_WICPixelFormat128bppRGBAFloat (no range conversions) //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT _ConvertToR32G32B32A32( const Image& srcImage, ScratchImage& image ) { if ( !srcImage.pixels ) return E_POINTER; HRESULT hr = image.Initialize2D( DXGI_FORMAT_R32G32B32A32_FLOAT, srcImage.width, srcImage.height, 1, 1 ); if ( FAILED(hr) ) return hr; const Image *img = image.GetImage( 0, 0, 0 ); if ( !img ) { image.Release(); return E_POINTER; } uint8_t* pDest = img->pixels; if ( !pDest ) { image.Release(); return E_POINTER; } const uint8_t *pSrc = srcImage.pixels; for( size_t h = 0; h < srcImage.height; ++h ) { if ( !_LoadScanline( reinterpret_cast<XMVECTOR*>(pDest), srcImage.width, pSrc, srcImage.rowPitch, srcImage.format ) ) { image.Release(); return E_FAIL; } pSrc += srcImage.rowPitch; pDest += img->rowPitch; } return S_OK; } _Use_decl_annotations_ HRESULT _ConvertFromR32G32B32A32( const Image& srcImage, const Image& destImage ) { assert( srcImage.format == DXGI_FORMAT_R32G32B32A32_FLOAT ); if ( !srcImage.pixels || !destImage.pixels ) return E_POINTER; if ( srcImage.width != destImage.width || srcImage.height != destImage.height ) return E_FAIL; const uint8_t *pSrc = srcImage.pixels; uint8_t* pDest = destImage.pixels; for( size_t h = 0; h < srcImage.height; ++h ) { if ( !_StoreScanline( pDest, destImage.rowPitch, destImage.format, reinterpret_cast<const XMVECTOR*>(pSrc), srcImage.width ) ) return E_FAIL; pSrc += srcImage.rowPitch; pDest += destImage.rowPitch; } return S_OK; } _Use_decl_annotations_ HRESULT _ConvertFromR32G32B32A32( const Image& srcImage, DXGI_FORMAT format, ScratchImage& image ) { if ( !srcImage.pixels ) return E_POINTER; HRESULT hr = image.Initialize2D( format, srcImage.width, srcImage.height, 1, 1 ); if ( FAILED(hr) ) return hr; const Image *img = image.GetImage( 0, 0, 0 ); if ( !img ) { image.Release(); return E_POINTER; } hr = _ConvertFromR32G32B32A32( srcImage, *img ); if ( FAILED(hr) ) { image.Release(); return hr; } return S_OK; } _Use_decl_annotations_ HRESULT _ConvertFromR32G32B32A32( const Image* srcImages, size_t nimages, const TexMetadata& metadata, DXGI_FORMAT format, ScratchImage& result ) { if ( !srcImages ) return E_POINTER; result.Release(); assert( metadata.format == DXGI_FORMAT_R32G32B32A32_FLOAT ); TexMetadata mdata2 = metadata; mdata2.format = format; HRESULT hr = result.Initialize( mdata2 ); if ( FAILED(hr) ) return hr; if ( nimages != result.GetImageCount() ) { result.Release(); return E_FAIL; } const Image* dest = result.GetImages(); if ( !dest ) { result.Release(); return E_POINTER; } for( size_t index=0; index < nimages; ++index ) { const Image& src = srcImages[ index ]; const Image& dst = dest[ index ]; assert( src.format == DXGI_FORMAT_R32G32B32A32_FLOAT ); assert( dst.format == format ); if ( src.width != dst.width || src.height != dst.height ) { result.Release(); return E_FAIL; } const uint8_t* pSrc = src.pixels; uint8_t* pDest = dst.pixels; if ( !pSrc || !pDest ) { result.Release(); return E_POINTER; } for( size_t h=0; h < src.height; ++h ) { if ( !_StoreScanline( pDest, dst.rowPitch, format, reinterpret_cast<const XMVECTOR*>(pSrc), src.width ) ) { result.Release(); return E_FAIL; } pSrc += src.rowPitch; pDest += dst.rowPitch; } } return S_OK; } //------------------------------------------------------------------------------------- // Convert from Linear RGB to sRGB // // if C_linear <= 0.0031308 -> C_srgb = 12.92 * C_linear // if C_linear > 0.0031308 -> C_srgb = ( 1 + a ) * pow( C_Linear, 1 / 2.4 ) - a // where a = 0.055 //------------------------------------------------------------------------------------- #if DIRECTX_MATH_VERSION < 306 static inline XMVECTOR XMColorRGBToSRGB( FXMVECTOR rgb ) { static const XMVECTORF32 Cutoff = { 0.0031308f, 0.0031308f, 0.0031308f, 1.f }; static const XMVECTORF32 Linear = { 12.92f, 12.92f, 12.92f, 1.f }; static const XMVECTORF32 Scale = { 1.055f, 1.055f, 1.055f, 1.f }; static const XMVECTORF32 Bias = { 0.055f, 0.055f, 0.055f, 0.f }; static const XMVECTORF32 InvGamma = { 1.0f/2.4f, 1.0f/2.4f, 1.0f/2.4f, 1.f }; XMVECTOR V = XMVectorSaturate(rgb); XMVECTOR V0 = XMVectorMultiply( V, Linear ); XMVECTOR V1 = Scale * XMVectorPow( V, InvGamma ) - Bias; XMVECTOR select = XMVectorLess( V, Cutoff ); V = XMVectorSelect( V1, V0, select ); return XMVectorSelect( rgb, V, g_XMSelect1110 ); } #endif _Use_decl_annotations_ bool _StoreScanlineLinear( LPVOID pDestination, size_t size, DXGI_FORMAT format, XMVECTOR* pSource, size_t count, DWORD flags, float threshold ) { assert( pDestination && size > 0 ); assert( pSource && count > 0 && (((uintptr_t)pSource & 0xF) == 0) ); assert( IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format) ); switch ( format ) { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: flags |= TEX_FILTER_SRGB; break; case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: break; default: // can't treat A8, XR, Depth, SNORM, UINT, or SINT as sRGB flags &= ~TEX_FILTER_SRGB; break; } // sRGB output processing (Linear RGB -> sRGB) if ( flags & TEX_FILTER_SRGB_OUT ) { // To avoid the need for another temporary scanline buffer, we allow this function to overwrite the source buffer in-place // Given the intended usage in the filtering routines, this is not a problem. XMVECTOR* ptr = pSource; for( size_t i=0; i < count; ++i, ++ptr ) { *ptr = XMColorRGBToSRGB( *ptr ); } } return _StoreScanline( pDestination, size, format, pSource, count, threshold ); } //------------------------------------------------------------------------------------- // Convert from sRGB to Linear RGB // // if C_srgb <= 0.04045 -> C_linear = C_srgb / 12.92 // if C_srgb > 0.04045 -> C_linear = pow( ( C_srgb + a ) / ( 1 + a ), 2.4 ) // where a = 0.055 //------------------------------------------------------------------------------------- #if DIRECTX_MATH_VERSION < 306 static inline XMVECTOR XMColorSRGBToRGB( FXMVECTOR srgb ) { static const XMVECTORF32 Cutoff = { 0.04045f, 0.04045f, 0.04045f, 1.f }; static const XMVECTORF32 ILinear = { 1.f/12.92f, 1.f/12.92f, 1.f/12.92f, 1.f }; static const XMVECTORF32 Scale = { 1.f/1.055f, 1.f/1.055f, 1.f/1.055f, 1.f }; static const XMVECTORF32 Bias = { 0.055f, 0.055f, 0.055f, 0.f }; static const XMVECTORF32 Gamma = { 2.4f, 2.4f, 2.4f, 1.f }; XMVECTOR V = XMVectorSaturate(srgb); XMVECTOR V0 = XMVectorMultiply( V, ILinear ); XMVECTOR V1 = XMVectorPow( (V + Bias) * Scale, Gamma ); XMVECTOR select = XMVectorGreater( V, Cutoff ); V = XMVectorSelect( V0, V1, select ); return XMVectorSelect( srgb, V, g_XMSelect1110 ); } #endif _Use_decl_annotations_ bool _LoadScanlineLinear( XMVECTOR* pDestination, size_t count, LPCVOID pSource, size_t size, DXGI_FORMAT format, DWORD flags ) { assert( pDestination && count > 0 && (((uintptr_t)pDestination & 0xF) == 0) ); assert( pSource && size > 0 ); assert( IsValid(format) && !IsTypeless(format,false) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format) ); switch ( format ) { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: flags |= TEX_FILTER_SRGB; break; case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: break; default: // can't treat A8, XR, Depth, SNORM, UINT, or SINT as sRGB flags &= ~TEX_FILTER_SRGB; break; } if ( _LoadScanline( pDestination, count, pSource, size, format ) ) { // sRGB input processing (sRGB -> Linear RGB) if ( flags & TEX_FILTER_SRGB_IN ) { XMVECTOR* ptr = pDestination; for( size_t i=0; i < count; ++i, ++ptr ) { *ptr = XMColorSRGBToRGB( *ptr ); } } return true; } return false; } //------------------------------------------------------------------------------------- // Convert scanline based on source/target formats //------------------------------------------------------------------------------------- struct ConvertData { DXGI_FORMAT format; size_t datasize; DWORD flags; }; static const ConvertData g_ConvertTable[] = { { DXGI_FORMAT_R32G32B32A32_FLOAT, 32, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R32G32B32A32_UINT, 32, CONVF_UINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R32G32B32A32_SINT, 32, CONVF_SINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R32G32B32_FLOAT, 32, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R32G32B32_UINT, 32, CONVF_UINT | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R32G32B32_SINT, 32, CONVF_SINT | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R16G16B16A16_FLOAT, 16, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R16G16B16A16_UNORM, 16, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R16G16B16A16_UINT, 16, CONVF_UINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R16G16B16A16_SNORM, 16, CONVF_SNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R16G16B16A16_SINT, 16, CONVF_SINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R32G32_FLOAT, 32, CONVF_FLOAT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R32G32_UINT, 32, CONVF_UINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R32G32_SINT, 32, CONVF_SINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_D32_FLOAT_S8X24_UINT, 32, CONVF_FLOAT | CONVF_DEPTH | CONVF_STENCIL }, { DXGI_FORMAT_R10G10B10A2_UNORM, 10, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R10G10B10A2_UINT, 10, CONVF_UINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R11G11B10_FLOAT, 10, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R8G8B8A8_UNORM, 8, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 8, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R8G8B8A8_UINT, 8, CONVF_UINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R8G8B8A8_SNORM, 8, CONVF_SNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R8G8B8A8_SINT, 8, CONVF_SINT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_R16G16_FLOAT, 16, CONVF_FLOAT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R16G16_UNORM, 16, CONVF_UNORM | CONVF_R | CONVF_G }, { DXGI_FORMAT_R16G16_UINT, 16, CONVF_UINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R16G16_SNORM, 16, CONVF_SNORM | CONVF_R | CONVF_G }, { DXGI_FORMAT_R16G16_SINT, 16, CONVF_SINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_D32_FLOAT, 32, CONVF_FLOAT | CONVF_DEPTH }, { DXGI_FORMAT_R32_FLOAT, 32, CONVF_FLOAT | CONVF_R }, { DXGI_FORMAT_R32_UINT, 32, CONVF_UINT | CONVF_R }, { DXGI_FORMAT_R32_SINT, 32, CONVF_SINT | CONVF_R }, { DXGI_FORMAT_D24_UNORM_S8_UINT, 32, CONVF_UNORM | CONVF_DEPTH | CONVF_STENCIL }, { DXGI_FORMAT_R8G8_UNORM, 8, CONVF_UNORM | CONVF_R | CONVF_G }, { DXGI_FORMAT_R8G8_UINT, 8, CONVF_UINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R8G8_SNORM, 8, CONVF_SNORM | CONVF_R | CONVF_G }, { DXGI_FORMAT_R8G8_SINT, 8, CONVF_SINT | CONVF_R | CONVF_G }, { DXGI_FORMAT_R16_FLOAT, 16, CONVF_FLOAT | CONVF_R }, { DXGI_FORMAT_D16_UNORM, 16, CONVF_UNORM | CONVF_DEPTH }, { DXGI_FORMAT_R16_UNORM, 16, CONVF_UNORM | CONVF_R }, { DXGI_FORMAT_R16_UINT, 16, CONVF_UINT | CONVF_R }, { DXGI_FORMAT_R16_SNORM, 16, CONVF_SNORM | CONVF_R }, { DXGI_FORMAT_R16_SINT, 16, CONVF_SINT | CONVF_R }, { DXGI_FORMAT_R8_UNORM, 8, CONVF_UNORM | CONVF_R }, { DXGI_FORMAT_R8_UINT, 8, CONVF_UINT | CONVF_R }, { DXGI_FORMAT_R8_SNORM, 8, CONVF_SNORM | CONVF_R }, { DXGI_FORMAT_R8_SINT, 8, CONVF_SINT | CONVF_R }, { DXGI_FORMAT_A8_UNORM, 8, CONVF_UNORM | CONVF_A }, { DXGI_FORMAT_R1_UNORM, 1, CONVF_UNORM | CONVF_R }, { DXGI_FORMAT_R9G9B9E5_SHAREDEXP, 9, CONVF_SHAREDEXP | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R8G8_B8G8_UNORM, 8, CONVF_UNORM | CONVF_PACKED | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_G8R8_G8B8_UNORM, 8, CONVF_UNORM | CONVF_PACKED | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_BC1_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC1_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC2_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC2_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC3_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC3_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC4_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R }, { DXGI_FORMAT_BC4_SNORM, 8, CONVF_SNORM | CONVF_BC | CONVF_R }, { DXGI_FORMAT_BC5_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G }, { DXGI_FORMAT_BC5_SNORM, 8, CONVF_SNORM | CONVF_BC | CONVF_R | CONVF_G }, { DXGI_FORMAT_B5G6R5_UNORM, 5, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_B5G5R5A1_UNORM, 5, CONVF_UNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_B8G8R8A8_UNORM, 8, CONVF_UNORM | CONVF_BGR | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_B8G8R8X8_UNORM, 8, CONVF_UNORM | CONVF_BGR | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, 10, CONVF_UNORM | CONVF_XR | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BGR | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BGR | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_BC6H_UF16, 16, CONVF_FLOAT | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC6H_SF16, 16, CONVF_FLOAT | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC7_UNORM, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_BC7_UNORM_SRGB, 8, CONVF_UNORM | CONVF_BC | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_AYUV, 8, CONVF_UNORM | CONVF_YUV | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_Y410, 10, CONVF_UNORM | CONVF_YUV | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_Y416, 16, CONVF_UNORM | CONVF_YUV | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { DXGI_FORMAT_YUY2, 8, CONVF_UNORM | CONVF_YUV | CONVF_PACKED | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_Y210, 10, CONVF_UNORM | CONVF_YUV | CONVF_PACKED | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_Y216, 16, CONVF_UNORM | CONVF_YUV | CONVF_PACKED | CONVF_R | CONVF_G | CONVF_B }, { DXGI_FORMAT_B4G4R4A4_UNORM, 4, CONVF_UNORM | CONVF_BGR | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT, 10, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT, 10, CONVF_FLOAT | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM,10, CONVF_SNORM | CONVF_R | CONVF_G | CONVF_B | CONVF_A }, { XBOX_DXGI_FORMAT_R4G4_UNORM, 4, CONVF_UNORM | CONVF_R | CONVF_G }, }; #pragma prefast( suppress : 25004, "Signature must match bsearch_s" ); static int __cdecl _ConvertCompare( void *context, const void* ptr1, const void *ptr2 ) { UNREFERENCED_PARAMETER(context); const ConvertData *p1 = reinterpret_cast<const ConvertData*>(ptr1); const ConvertData *p2 = reinterpret_cast<const ConvertData*>(ptr2); if ( p1->format == p2->format ) return 0; else return (p1->format < p2->format ) ? -1 : 1; } _Use_decl_annotations_ DWORD _GetConvertFlags( DXGI_FORMAT format ) { #ifdef _DEBUG // Ensure conversion table is in ascending order assert( _countof(g_ConvertTable) > 0 ); DXGI_FORMAT lastvalue = g_ConvertTable[0].format; for( size_t index=1; index < _countof(g_ConvertTable); ++index ) { assert( g_ConvertTable[index].format > lastvalue ); lastvalue = g_ConvertTable[index].format; } #endif ConvertData key = { format, 0 }; const ConvertData* in = (const ConvertData*) bsearch_s( &key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), _ConvertCompare, 0 ); return (in) ? in->flags : 0; } _Use_decl_annotations_ void _ConvertScanline( XMVECTOR* pBuffer, size_t count, DXGI_FORMAT outFormat, DXGI_FORMAT inFormat, DWORD flags ) { assert( pBuffer && count > 0 && (((uintptr_t)pBuffer & 0xF) == 0) ); assert( IsValid(outFormat) && !IsTypeless(outFormat) && !IsPlanar(outFormat) && !IsPalettized(outFormat) ); assert( IsValid(inFormat) && !IsTypeless(inFormat) && !IsPlanar(inFormat) && !IsPalettized(inFormat) ); if ( !pBuffer ) return; #ifdef _DEBUG // Ensure conversion table is in ascending order assert( _countof(g_ConvertTable) > 0 ); DXGI_FORMAT lastvalue = g_ConvertTable[0].format; for( size_t index=1; index < _countof(g_ConvertTable); ++index ) { assert( g_ConvertTable[index].format > lastvalue ); lastvalue = g_ConvertTable[index].format; } #endif // Determine conversion details about source and dest formats ConvertData key = { inFormat, 0 }; const ConvertData* in = (const ConvertData*) bsearch_s( &key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), _ConvertCompare, 0 ); key.format = outFormat; const ConvertData* out = (const ConvertData*) bsearch_s( &key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), _ConvertCompare, 0 ); if ( !in || !out ) { assert(false); return; } assert( _GetConvertFlags( inFormat ) == in->flags ); assert( _GetConvertFlags( outFormat ) == out->flags ); // Handle SRGB filtering modes switch ( inFormat ) { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: case DXGI_FORMAT_BC7_UNORM_SRGB: flags |= TEX_FILTER_SRGB_IN; break; case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: flags &= ~TEX_FILTER_SRGB_IN; break; } switch ( outFormat ) { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: case DXGI_FORMAT_BC7_UNORM_SRGB: flags |= TEX_FILTER_SRGB_OUT; break; case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: flags &= ~TEX_FILTER_SRGB_OUT; break; } if ( (flags & (TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT)) == (TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT) ) { flags &= ~(TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT); } // sRGB input processing (sRGB -> Linear RGB) if ( flags & TEX_FILTER_SRGB_IN ) { if ( !(in->flags & CONVF_DEPTH) && ( (in->flags & CONVF_FLOAT) || (in->flags & CONVF_UNORM) ) ) { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i, ++ptr ) { *ptr = XMColorSRGBToRGB( *ptr ); } } } // Handle conversion special cases DWORD diffFlags = in->flags ^ out->flags; if ( diffFlags != 0 ) { static const XMVECTORF32 s_two = { 2.0f, 2.0f, 2.0f, 2.0f }; if ( diffFlags & CONVF_DEPTH ) { if ( in->flags & CONVF_DEPTH ) { // CONVF_DEPTH -> !CONVF_DEPTH if ( in->flags & CONVF_STENCIL ) { // Stencil -> Alpha static const XMVECTORF32 S = { 1.f, 1.f, 1.f, 255.f }; if( out->flags & CONVF_UNORM ) { // UINT -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatY( v ); v1 = XMVectorClamp( v1, g_XMZero, S ); v1 = XMVectorDivide( v1, S ); v = XMVectorSelect( v1, v, g_XMSelect1110 ); *ptr++ = v; } } else if ( out->flags & CONVF_SNORM ) { // UINT -> SNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatY( v ); v1 = XMVectorClamp( v1, g_XMZero, S ); v1 = XMVectorDivide( v1, S ); v1 = XMVectorMultiplyAdd( v1, s_two, g_XMNegativeOne ); v = XMVectorSelect( v1, v, g_XMSelect1110 ); *ptr++ = v; } } else { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatY( v ); v = XMVectorSelect( v1, v, g_XMSelect1110 ); *ptr++ = v; } } } // Depth -> RGB if ( ( out->flags & CONVF_UNORM ) && ( in->flags & CONVF_FLOAT ) ) { // Depth FLOAT -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSaturate( v ); v1 = XMVectorSplatX( v1 ); v = XMVectorSelect( v, v1, g_XMSelect1110 ); *ptr++ = v; } } else if ( out->flags & CONVF_SNORM ) { if ( in->flags & CONVF_UNORM ) { // Depth UNORM -> SNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorMultiplyAdd( v, s_two, g_XMNegativeOne ); v1 = XMVectorSplatX( v1 ); v = XMVectorSelect( v, v1, g_XMSelect1110 ); *ptr++ = v; } } else { // Depth FLOAT -> SNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorClamp( v, g_XMNegativeOne, g_XMOne ); v1 = XMVectorSplatX( v1 ); v = XMVectorSelect( v, v1, g_XMSelect1110 ); *ptr++ = v; } } } else { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatX( v ); v = XMVectorSelect( v, v1, g_XMSelect1110 ); *ptr++ = v; } } } else { // !CONVF_DEPTH -> CONVF_DEPTH // RGB -> Depth (red channel) switch( flags & ( TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN | TEX_FILTER_RGB_COPY_BLUE ) ) { case TEX_FILTER_RGB_COPY_GREEN: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatY( v ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } break; case TEX_FILTER_RGB_COPY_BLUE: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatZ( v ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } break; default: if ( (in->flags & CONVF_UNORM) && ( (in->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G|CONVF_B) ) ) { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVector3Dot( v, g_Grayscale ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } break; } // fall-through case TEX_FILTER_RGB_COPY_RED: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatX( v ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } break; } // Finialize type conversion for depth (red channel) if ( out->flags & CONVF_UNORM ) { if ( in->flags & CONVF_SNORM ) { // SNORM -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorMultiplyAdd( v, g_XMOneHalf, g_XMOneHalf ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } else if ( in->flags & CONVF_FLOAT ) { // FLOAT -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSaturate( v ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } } if ( out->flags & CONVF_STENCIL ) { // Alpha -> Stencil (green channel) static const XMVECTORU32 select0100 = { XM_SELECT_0, XM_SELECT_1, XM_SELECT_0, XM_SELECT_0 }; static const XMVECTORF32 S = { 255.f, 255.f, 255.f, 255.f }; if ( in->flags & CONVF_UNORM ) { // UNORM -> UINT XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorMultiply( v, S ); v1 = XMVectorSplatW( v1 ); v = XMVectorSelect( v, v1, select0100 ); *ptr++ = v; } } else if ( in->flags & CONVF_SNORM ) { // SNORM -> UINT XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorMultiplyAdd( v, g_XMOneHalf, g_XMOneHalf ); v1 = XMVectorMultiply( v1, S ); v1 = XMVectorSplatW( v1 ); v = XMVectorSelect( v, v1, select0100 ); *ptr++ = v; } } else { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatW( v ); v = XMVectorSelect( v, v1, select0100 ); *ptr++ = v; } } } } } else if ( out->flags & CONVF_DEPTH ) { // CONVF_DEPTH -> CONVF_DEPTH if ( diffFlags & CONVF_FLOAT ) { if ( in->flags & CONVF_FLOAT ) { // FLOAT -> UNORM depth, preserve stencil XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSaturate( v ); v = XMVectorSelect( v, v1, g_XMSelect1000 ); *ptr++ = v; } } } } else if ( out->flags & CONVF_UNORM ) { if ( in->flags & CONVF_SNORM ) { // SNORM -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorMultiplyAdd( v, g_XMOneHalf, g_XMOneHalf ); } } else if ( in->flags & CONVF_FLOAT ) { // FLOAT -> UNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorSaturate( v ); } } } else if ( out->flags & CONVF_SNORM ) { if ( in->flags & CONVF_UNORM ) { // UNORM -> SNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorMultiplyAdd( v, s_two, g_XMNegativeOne ); } } else if ( in->flags & CONVF_FLOAT ) { // FLOAT -> SNORM XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorClamp( v, g_XMNegativeOne, g_XMOne ); } } } // !CONVF_A -> CONVF_A is handled because LoadScanline ensures alpha defaults to 1.0 for no-alpha formats // CONVF_PACKED cases are handled because LoadScanline/StoreScanline handles packing/unpacking if ( ((out->flags & CONVF_RGBA_MASK) == CONVF_A) && !(in->flags & CONVF_A) ) { // !CONVF_A -> A format switch( flags & ( TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN | TEX_FILTER_RGB_COPY_BLUE ) ) { case TEX_FILTER_RGB_COPY_GREEN: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorSplatY( v ); } } break; case TEX_FILTER_RGB_COPY_BLUE: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorSplatZ( v ); } } break; default: if ( (in->flags & CONVF_UNORM) && ( (in->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G|CONVF_B) ) ) { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVector3Dot( v, g_Grayscale ); } break; } // fall-through case TEX_FILTER_RGB_COPY_RED: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorSplatX( v ); } } break; } } else if ( ((in->flags & CONVF_RGBA_MASK) == CONVF_A) && !(out->flags & CONVF_A) ) { // A format -> !CONVF_A XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; *ptr++ = XMVectorSplatW( v ); } } else if ( (in->flags & CONVF_RGB_MASK) == CONVF_R ) { if ( (out->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G|CONVF_B) ) { // R format -> RGB format XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatX( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1110 ); } } else if ( (out->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G) ) { // R format -> RG format XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatX( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1100 ); } } } else if ( (in->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G|CONVF_B) ) { if ( (out->flags & CONVF_RGB_MASK) == CONVF_R ) { // RGB format -> R format switch( flags & ( TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN | TEX_FILTER_RGB_COPY_BLUE ) ) { case TEX_FILTER_RGB_COPY_GREEN: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatY( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1110 ); } } break; case TEX_FILTER_RGB_COPY_BLUE: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSplatZ( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1110 ); } } break; default: if ( in->flags & CONVF_UNORM ) { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVector3Dot( v, g_Grayscale ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1110 ); } break; } // fall-through case TEX_FILTER_RGB_COPY_RED: // Leave data unchanged and the store will handle this... break; } } else if ( (out->flags & CONVF_RGB_MASK) == (CONVF_R|CONVF_G) ) { // RGB format -> RG format switch( flags & ( TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN | TEX_FILTER_RGB_COPY_BLUE ) ) { case TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_BLUE: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSwizzle<0,2,0,2>( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1100 ); } } break; case TEX_FILTER_RGB_COPY_GREEN | TEX_FILTER_RGB_COPY_BLUE: { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i ) { XMVECTOR v = *ptr; XMVECTOR v1 = XMVectorSwizzle<1,2,3,0>( v ); *ptr++ = XMVectorSelect( v, v1, g_XMSelect1100 ); } } break; case TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN: default: // Leave data unchanged and the store will handle this... break; } } } } // sRGB output processing (Linear RGB -> sRGB) if ( flags & TEX_FILTER_SRGB_OUT ) { if ( !(out->flags & CONVF_DEPTH) && ( (out->flags & CONVF_FLOAT) || (out->flags & CONVF_UNORM) ) ) { XMVECTOR* ptr = pBuffer; for( size_t i=0; i < count; ++i, ++ptr ) { *ptr = XMColorRGBToSRGB( *ptr ); } } } } //------------------------------------------------------------------------------------- // Dithering //------------------------------------------------------------------------------------- // 4X4X4 ordered dithering matrix static const float g_Dither[] = { // (z & 3) + ( (y & 3) * 8) + (x & 3) 0.468750f, -0.031250f, 0.343750f, -0.156250f, 0.468750f, -0.031250f, 0.343750f, -0.156250f, -0.281250f, 0.218750f, -0.406250f, 0.093750f, -0.281250f, 0.218750f, -0.406250f, 0.093750f, 0.281250f, -0.218750f, 0.406250f, -0.093750f, 0.281250f, -0.218750f, 0.406250f, -0.093750f, -0.468750f, 0.031250f, -0.343750f, 0.156250f, -0.468750f, 0.031250f, -0.343750f, 0.156250f, }; static const XMVECTORF32 g_Scale16pc = { 65535.f, 65535.f, 65535.f, 65535.f }; static const XMVECTORF32 g_Scale15pc = { 32767.f, 32767.f, 32767.f, 32767.f }; static const XMVECTORF32 g_Scale10pc = { 1023.f, 1023.f, 1023.f, 3.f }; static const XMVECTORF32 g_Scale9pc = { 511.f, 511.f, 511.f, 3.f }; static const XMVECTORF32 g_Scale8pc = { 255.f, 255.f, 255.f, 255.f }; static const XMVECTORF32 g_Scale7pc = { 127.f, 127.f, 127.f, 127.f }; static const XMVECTORF32 g_Scale565pc = { 31.f, 63.f, 31.f, 1.f }; static const XMVECTORF32 g_Scale5551pc = { 31.f, 31.f, 31.f, 1.f }; static const XMVECTORF32 g_Scale4pc = { 15.f, 15.f, 15.f, 15.f }; static const XMVECTORF32 g_ErrorWeight3 = { 3.f/16.f, 3.f/16.f, 3.f/16.f, 3.f/16.f }; static const XMVECTORF32 g_ErrorWeight5 = { 5.f/16.f, 5.f/16.f, 5.f/16.f, 5.f/16.f }; static const XMVECTORF32 g_ErrorWeight1 = { 1.f/16.f, 1.f/16.f, 1.f/16.f, 1.f/16.f }; static const XMVECTORF32 g_ErrorWeight7 = { 7.f/16.f, 7.f/16.f, 7.f/16.f, 7.f/16.f }; #define STORE_SCANLINE( type, scalev, clampzero, norm, itype, mask, row, bgr ) \ if ( size >= sizeof(type) ) \ { \ type * __restrict dest = reinterpret_cast<type*>(pDestination); \ for( size_t i = 0; i < count; ++i ) \ { \ ptrdiff_t index = static_cast<ptrdiff_t>( ( row & 1 ) ? ( count - i - 1 ) : i ); \ ptrdiff_t delta = ( row & 1 ) ? -2 : 0; \ \ XMVECTOR v = sPtr[ index ]; \ if ( bgr ) { v = XMVectorSwizzle<2, 1, 0, 3>( v ); } \ if ( norm && clampzero ) v = XMVectorSaturate( v ) ; \ else if ( clampzero ) v = XMVectorClamp( v, g_XMZero, scalev ); \ else if ( norm ) v = XMVectorClamp( v, g_XMNegativeOne, g_XMOne ); \ else v = XMVectorClamp( v, -scalev + g_XMOne, scalev ); \ v = XMVectorAdd( v, vError ); \ if ( norm ) v = XMVectorMultiply( v, scalev ); \ \ XMVECTOR target; \ if ( pDiffusionErrors ) \ { \ target = XMVectorRound( v ); \ vError = XMVectorSubtract( v, target ); \ if (norm) vError = XMVectorDivide( vError, scalev ); \ \ /* Distribute error to next scanline and next pixel */ \ pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); \ pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); \ pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); \ vError = XMVectorMultiply( vError, g_ErrorWeight7 ); \ } \ else \ { \ /* Applied ordered dither */ \ target = XMVectorAdd( v, ordered[ index & 3 ] ); \ target = XMVectorRound( target ); \ } \ \ target = XMVectorMin( scalev, target ); \ target = XMVectorMax( (clampzero) ? g_XMZero : ( -scalev + g_XMOne ), target ); \ \ XMFLOAT4A tmp; \ XMStoreFloat4A( &tmp, target ); \ \ auto dPtr = &dest[ index ]; \ dPtr->x = static_cast<itype>( tmp.x ) & mask; \ dPtr->y = static_cast<itype>( tmp.y ) & mask; \ dPtr->z = static_cast<itype>( tmp.z ) & mask; \ dPtr->w = static_cast<itype>( tmp.w ) & mask; \ } \ return true; \ } \ return false; #define STORE_SCANLINE2( type, scalev, clampzero, norm, itype, mask, row ) \ /* The 2 component cases are always bgr=false */ \ if ( size >= sizeof(type) ) \ { \ type * __restrict dest = reinterpret_cast<type*>(pDestination); \ for( size_t i = 0; i < count; ++i ) \ { \ ptrdiff_t index = static_cast<ptrdiff_t>( ( row & 1 ) ? ( count - i - 1 ) : i ); \ ptrdiff_t delta = ( row & 1 ) ? -2 : 0; \ \ XMVECTOR v = sPtr[ index ]; \ if ( norm && clampzero ) v = XMVectorSaturate( v ) ; \ else if ( clampzero ) v = XMVectorClamp( v, g_XMZero, scalev ); \ else if ( norm ) v = XMVectorClamp( v, g_XMNegativeOne, g_XMOne ); \ else v = XMVectorClamp( v, -scalev + g_XMOne, scalev ); \ v = XMVectorAdd( v, vError ); \ if ( norm ) v = XMVectorMultiply( v, scalev ); \ \ XMVECTOR target; \ if ( pDiffusionErrors ) \ { \ target = XMVectorRound( v ); \ vError = XMVectorSubtract( v, target ); \ if (norm) vError = XMVectorDivide( vError, scalev ); \ \ /* Distribute error to next scanline and next pixel */ \ pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); \ pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); \ pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); \ vError = XMVectorMultiply( vError, g_ErrorWeight7 ); \ } \ else \ { \ /* Applied ordered dither */ \ target = XMVectorAdd( v, ordered[ index & 3 ] ); \ target = XMVectorRound( target ); \ } \ \ target = XMVectorMin( scalev, target ); \ target = XMVectorMax( (clampzero) ? g_XMZero : ( -scalev + g_XMOne ), target ); \ \ XMFLOAT4A tmp; \ XMStoreFloat4A( &tmp, target ); \ \ auto dPtr = &dest[ index ]; \ dPtr->x = static_cast<itype>( tmp.x ) & mask; \ dPtr->y = static_cast<itype>( tmp.y ) & mask; \ } \ return true; \ } \ return false; #define STORE_SCANLINE1( type, scalev, clampzero, norm, mask, row, selectw ) \ /* The 1 component cases are always bgr=false */ \ if ( size >= sizeof(type) ) \ { \ type * __restrict dest = reinterpret_cast<type*>(pDestination); \ for( size_t i = 0; i < count; ++i ) \ { \ ptrdiff_t index = static_cast<ptrdiff_t>( ( row & 1 ) ? ( count - i - 1 ) : i ); \ ptrdiff_t delta = ( row & 1 ) ? -2 : 0; \ \ XMVECTOR v = sPtr[ index ]; \ if ( norm && clampzero ) v = XMVectorSaturate( v ) ; \ else if ( clampzero ) v = XMVectorClamp( v, g_XMZero, scalev ); \ else if ( norm ) v = XMVectorClamp( v, g_XMNegativeOne, g_XMOne ); \ else v = XMVectorClamp( v, -scalev + g_XMOne, scalev ); \ v = XMVectorAdd( v, vError ); \ if ( norm ) v = XMVectorMultiply( v, scalev ); \ \ XMVECTOR target; \ if ( pDiffusionErrors ) \ { \ target = XMVectorRound( v ); \ vError = XMVectorSubtract( v, target ); \ if (norm) vError = XMVectorDivide( vError, scalev ); \ \ /* Distribute error to next scanline and next pixel */ \ pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); \ pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); \ pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); \ vError = XMVectorMultiply( vError, g_ErrorWeight7 ); \ } \ else \ { \ /* Applied ordered dither */ \ target = XMVectorAdd( v, ordered[ index & 3 ] ); \ target = XMVectorRound( target ); \ } \ \ target = XMVectorMin( scalev, target ); \ target = XMVectorMax( (clampzero) ? g_XMZero : ( -scalev + g_XMOne ), target ); \ \ dest[ index ] = static_cast<type>( (selectw) ? XMVectorGetW( target ) : XMVectorGetX( target ) ) & mask; \ } \ return true; \ } \ return false; #pragma warning(push) #pragma warning( disable : 4127 ) _Use_decl_annotations_ bool _StoreScanlineDither( LPVOID pDestination, size_t size, DXGI_FORMAT format, XMVECTOR* pSource, size_t count, float threshold, size_t y, size_t z, XMVECTOR* pDiffusionErrors ) { assert( pDestination && size > 0 ); assert( pSource && count > 0 && (((uintptr_t)pSource & 0xF) == 0) ); assert( IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format) ); XMVECTOR ordered[4]; if ( pDiffusionErrors ) { // If pDiffusionErrors != 0, then this function performs error diffusion dithering (aka Floyd-Steinberg dithering) // To avoid the need for another temporary scanline buffer, we allow this function to overwrite the source buffer in-place // Given the intended usage in the conversion routines, this is not a problem. XMVECTOR* ptr = pSource; const XMVECTOR* err = pDiffusionErrors + 1; for( size_t i=0; i < count; ++i ) { // Add contribution from previous scanline XMVECTOR v = XMVectorAdd( *ptr, *err++ ); *ptr++ = v; } // Reset errors for next scanline memset( pDiffusionErrors, 0, sizeof(XMVECTOR)*(count+2) ); } else { // If pDiffusionErrors == 0, then this function performs ordered dithering XMVECTOR dither = XMLoadFloat4( reinterpret_cast<const XMFLOAT4*>( g_Dither + (z & 3) + ( (y & 3) * 8 ) ) ); ordered[0] = XMVectorSplatX( dither ); ordered[1] = XMVectorSplatY( dither ); ordered[2] = XMVectorSplatZ( dither ); ordered[3] = XMVectorSplatW( dither ); } const XMVECTOR* __restrict sPtr = pSource; if ( !sPtr ) return false; XMVECTOR vError = XMVectorZero(); switch( static_cast<int>(format) ) { case DXGI_FORMAT_R16G16B16A16_UNORM: STORE_SCANLINE( XMUSHORTN4, g_Scale16pc, true, true, uint16_t, 0xFFFF, y, false ) case DXGI_FORMAT_R16G16B16A16_UINT: STORE_SCANLINE( XMUSHORT4, g_Scale16pc, true, false, uint16_t, 0xFFFF, y, false ) case DXGI_FORMAT_R16G16B16A16_SNORM: STORE_SCANLINE( XMSHORTN4, g_Scale15pc, false, true, int16_t, 0xFFFF, y, false ) case DXGI_FORMAT_R16G16B16A16_SINT: STORE_SCANLINE( XMSHORT4, g_Scale15pc, false, false, int16_t, 0xFFFF, y, false ) case DXGI_FORMAT_R10G10B10A2_UNORM: STORE_SCANLINE( XMUDECN4, g_Scale10pc, true, true, uint16_t, 0x3FF, y, false ) case DXGI_FORMAT_R10G10B10A2_UINT: STORE_SCANLINE( XMUDEC4, g_Scale10pc, true, false, uint16_t, 0x3FF, y, false ) case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: if ( size >= sizeof(XMUDEC4) ) { static const XMVECTORF32 Scale = { 510.0f, 510.0f, 510.0f, 3.0f }; static const XMVECTORF32 Bias = { 384.0f, 384.0f, 384.0f, 0.0f }; static const XMVECTORF32 MinXR = { -0.7529f, -0.7529f, -0.7529f, 0.f }; static const XMVECTORF32 MaxXR = { 1.2529f, 1.2529f, 1.2529f, 1.0f }; XMUDEC4 * __restrict dest = reinterpret_cast<XMUDEC4*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorClamp( sPtr[ index ], MinXR, MaxXR ); v = XMVectorMultiplyAdd( v, Scale, vError ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, Scale ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorAdd( target, Bias ); target = XMVectorClamp( target, g_XMZero, g_Scale10pc ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); auto dPtr = &dest[ index ]; dPtr->x = static_cast<uint16_t>( tmp.x ) & 0x3FF; dPtr->y = static_cast<uint16_t>( tmp.y ) & 0x3FF; dPtr->z = static_cast<uint16_t>( tmp.z ) & 0x3FF; dPtr->w = static_cast<uint16_t>( tmp.w ); } return true; } return false; case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: STORE_SCANLINE( XMUBYTEN4, g_Scale8pc, true, true, uint8_t, 0xFF, y, false ) case DXGI_FORMAT_R8G8B8A8_UINT: STORE_SCANLINE( XMUBYTE4, g_Scale8pc, true, false, uint8_t, 0xFF, y, false ) case DXGI_FORMAT_R8G8B8A8_SNORM: STORE_SCANLINE( XMBYTEN4, g_Scale7pc, false, true, int8_t, 0xFF, y, false ) case DXGI_FORMAT_R8G8B8A8_SINT: STORE_SCANLINE( XMBYTE4, g_Scale7pc, false, false, int8_t, 0xFF, y, false ) case DXGI_FORMAT_R16G16_UNORM: STORE_SCANLINE2( XMUSHORTN2, g_Scale16pc, true, true, uint16_t, 0xFFFF, y ) case DXGI_FORMAT_R16G16_UINT: STORE_SCANLINE2( XMUSHORT2, g_Scale16pc, true, false, uint16_t, 0xFFFF, y ) case DXGI_FORMAT_R16G16_SNORM: STORE_SCANLINE2( XMSHORTN2, g_Scale15pc, false, true, int16_t, 0xFFFF, y ) case DXGI_FORMAT_R16G16_SINT: STORE_SCANLINE2( XMSHORT2, g_Scale15pc, false, false, int16_t, 0xFFFF, y ) case DXGI_FORMAT_D24_UNORM_S8_UINT: if ( size >= sizeof(uint32_t) ) { static const XMVECTORF32 Clamp = { 1.f, 255.f, 0.f, 0.f }; static const XMVECTORF32 Scale = { 16777215.f, 1.f, 0.f, 0.f }; static const XMVECTORF32 Scale2 = { 16777215.f, 255.f, 0.f, 0.f }; uint32_t * __restrict dest = reinterpret_cast<uint32_t*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorClamp( sPtr[ index ], g_XMZero, Clamp ); v = XMVectorAdd( v, vError ); v = XMVectorMultiply( v, Scale ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, Scale ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorClamp( target, g_XMZero, Scale2 ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); auto dPtr = &dest[ index ]; *dPtr = (static_cast<uint32_t>( tmp.x ) & 0xFFFFFF) | ((static_cast<uint32_t>( tmp.y ) & 0xFF) << 24); } return true; } return false; case DXGI_FORMAT_R8G8_UNORM: STORE_SCANLINE2( XMUBYTEN2, g_Scale8pc, true, true, uint8_t, 0xFF, y ) case DXGI_FORMAT_R8G8_UINT: STORE_SCANLINE2( XMUBYTE2, g_Scale8pc, true, false, uint8_t, 0xFF, y ) case DXGI_FORMAT_R8G8_SNORM: STORE_SCANLINE2( XMBYTEN2, g_Scale7pc, false, true, int8_t, 0xFF, y ) case DXGI_FORMAT_R8G8_SINT: STORE_SCANLINE2( XMBYTE2, g_Scale7pc, false, false, int8_t, 0xFF, y ) case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: STORE_SCANLINE1( uint16_t, g_Scale16pc, true, true, 0xFFFF, y, false ) case DXGI_FORMAT_R16_UINT: STORE_SCANLINE1( uint16_t, g_Scale16pc, true, false, 0xFFFF, y, false ) case DXGI_FORMAT_R16_SNORM: STORE_SCANLINE1( int16_t, g_Scale15pc, false, true, 0xFFFF, y, false ) case DXGI_FORMAT_R16_SINT: STORE_SCANLINE1( int16_t, g_Scale15pc, false, false, 0xFFFF, y, false ) case DXGI_FORMAT_R8_UNORM: STORE_SCANLINE1( uint8_t, g_Scale8pc, true, true, 0xFF, y, false ) case DXGI_FORMAT_R8_UINT: STORE_SCANLINE1( uint8_t, g_Scale8pc, true, false, 0xFF, y, false ) case DXGI_FORMAT_R8_SNORM: STORE_SCANLINE1( int8_t, g_Scale7pc, false, true, 0xFF, y, false ) case DXGI_FORMAT_R8_SINT: STORE_SCANLINE1( int8_t, g_Scale7pc, false, false, 0xFF, y, false ) case DXGI_FORMAT_A8_UNORM: STORE_SCANLINE1( uint8_t, g_Scale8pc, true, true, 0xFF, y, true ) case DXGI_FORMAT_B5G6R5_UNORM: if ( size >= sizeof(XMU565) ) { XMU565 * __restrict dest = reinterpret_cast<XMU565*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( sPtr[ index ] ); v = XMVectorSaturate( v ); v = XMVectorAdd( v, vError ); v = XMVectorMultiply( v, g_Scale565pc ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, g_Scale565pc ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorClamp( target, g_XMZero, g_Scale565pc ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); auto dPtr = &dest[ index ]; dPtr->x = static_cast<uint16_t>( tmp.x ) & 0x1F; dPtr->y = static_cast<uint16_t>( tmp.y ) & 0x3F; dPtr->z = static_cast<uint16_t>( tmp.z ) & 0x1F; } return true; } return false; case DXGI_FORMAT_B5G5R5A1_UNORM: if ( size >= sizeof(XMU555) ) { XMU555 * __restrict dest = reinterpret_cast<XMU555*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( sPtr[ index ] ); v = XMVectorSaturate( v ); v = XMVectorAdd( v, vError ); v = XMVectorMultiply( v, g_Scale5551pc ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, g_Scale5551pc ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorClamp( target, g_XMZero, g_Scale5551pc ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); auto dPtr = &dest[ index ]; dPtr->x = static_cast<uint16_t>( tmp.x ) & 0x1F; dPtr->y = static_cast<uint16_t>( tmp.y ) & 0x1F; dPtr->z = static_cast<uint16_t>( tmp.z ) & 0x1F; dPtr->w = ( XMVectorGetW( target ) > threshold ) ? 1 : 0; } return true; } return false; case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: STORE_SCANLINE( XMUBYTEN4, g_Scale8pc, true, true, uint8_t, 0xFF, y, true ) case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: if ( size >= sizeof(XMUBYTEN4) ) { XMUBYTEN4 * __restrict dest = reinterpret_cast<XMUBYTEN4*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorSwizzle<2, 1, 0, 3>( sPtr[ index ] ); v = XMVectorSaturate( v ); v = XMVectorAdd( v, vError ); v = XMVectorMultiply( v, g_Scale8pc ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, g_Scale8pc ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorClamp( target, g_XMZero, g_Scale8pc ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); auto dPtr = &dest[ index ]; dPtr->x = static_cast<uint8_t>( tmp.x ) & 0xFF; dPtr->y = static_cast<uint8_t>( tmp.y ) & 0xFF; dPtr->z = static_cast<uint8_t>( tmp.z ) & 0xFF; dPtr->w = 0; } return true; } return false; case DXGI_FORMAT_B4G4R4A4_UNORM: STORE_SCANLINE( XMUNIBBLE4, g_Scale4pc, true, true, uint8_t, 0xF, y, true ) case XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM: STORE_SCANLINE( XMXDECN4, g_Scale9pc, false, true, uint16_t, 0x3FF, y, false ) case XBOX_DXGI_FORMAT_R4G4_UNORM: if ( size >= sizeof(uint8_t) ) { uint8_t * __restrict dest = reinterpret_cast<uint8_t*>(pDestination); for( size_t i = 0; i < count; ++i ) { ptrdiff_t index = static_cast<ptrdiff_t>( ( y & 1 ) ? ( count - i - 1 ) : i ); ptrdiff_t delta = ( y & 1 ) ? -2 : 0; XMVECTOR v = XMVectorSaturate( sPtr[ index ] ); v = XMVectorAdd( v, vError ); v = XMVectorMultiply( v, g_Scale4pc ); XMVECTOR target; if ( pDiffusionErrors ) { target = XMVectorRound( v ); vError = XMVectorSubtract( v, target ); vError = XMVectorDivide( vError, g_Scale4pc ); // Distribute error to next scanline and next pixel pDiffusionErrors[ index-delta ] += XMVectorMultiply( g_ErrorWeight3, vError ); pDiffusionErrors[ index+1 ] += XMVectorMultiply( g_ErrorWeight5, vError ); pDiffusionErrors[ index+2+delta ] += XMVectorMultiply( g_ErrorWeight1, vError ); vError = XMVectorMultiply( vError, g_ErrorWeight7 ); } else { // Applied ordered dither target = XMVectorAdd( v, ordered[ index & 3 ] ); target = XMVectorRound( target ); } target = XMVectorClamp( target, g_XMZero, g_Scale4pc ); XMFLOAT4A tmp; XMStoreFloat4A( &tmp, target ); dest[index] = ( static_cast<uint8_t>( tmp.x ) & 0xF ) | ( ( static_cast<uint8_t>( tmp.y ) & 0xF ) << 4 ); } return true; } return false; default: return _StoreScanline( pDestination, size, format, pSource, count, threshold ); } } #pragma warning(pop) #undef STORE_SCANLINE #undef STORE_SCANLINE2 #undef STORE_SCANLINE1 //------------------------------------------------------------------------------------- // Selection logic for using WIC vs. our own routines //------------------------------------------------------------------------------------- static inline bool _UseWICConversion( _In_ DWORD filter, _In_ DXGI_FORMAT sformat, _In_ DXGI_FORMAT tformat, _Out_ WICPixelFormatGUID& pfGUID, _Out_ WICPixelFormatGUID& targetGUID ) { memcpy( &pfGUID, &GUID_NULL, sizeof(GUID) ); memcpy( &targetGUID, &GUID_NULL, sizeof(GUID) ); if ( filter & TEX_FILTER_FORCE_NON_WIC ) { // Explicit flag indicates use of non-WIC code paths return false; } if ( !_DXGIToWIC( sformat, pfGUID ) || !_DXGIToWIC( tformat, targetGUID ) ) { // Source or target format are not WIC supported native pixel formats return false; } if ( filter & TEX_FILTER_FORCE_WIC ) { // Explicit flag to use WIC code paths, skips all the case checks below return true; } if ( filter & TEX_FILTER_SEPARATE_ALPHA ) { // Alpha is not premultiplied, so use non-WIC code paths return false; } #if defined(_XBOX_ONE) && defined(_TITLE) if ( sformat == DXGI_FORMAT_R16G16B16A16_FLOAT || sformat == DXGI_FORMAT_R16_FLOAT || tformat == DXGI_FORMAT_R16G16B16A16_FLOAT || tformat == DXGI_FORMAT_R16_FLOAT ) { // Use non-WIC code paths as these conversions are not supported by Xbox One XDK return false; } #endif // Check for special cases switch ( sformat ) { case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: switch( tformat ) { case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_D32_FLOAT: // WIC converts via UNORM formats and ends up converting colorspaces for these cases case DXGI_FORMAT_A8_UNORM: // Conversion logic for these kinds of textures is unintuitive for WIC code paths return false; } break; case DXGI_FORMAT_R16_FLOAT: switch( tformat ) { case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_D32_FLOAT: // WIC converts via UNORM formats and ends up converting colorspaces for these cases case DXGI_FORMAT_A8_UNORM: // Conversion logic for these kinds of textures is unintuitive for WIC code paths return false; } break; case DXGI_FORMAT_A8_UNORM: // Conversion logic for these kinds of textures is unintuitive for WIC code paths return false; default: switch( tformat ) { case DXGI_FORMAT_A8_UNORM: // Conversion logic for these kinds of textures is unintuitive for WIC code paths return false; } } // Check for implicit color space changes if ( IsSRGB( sformat ) ) filter |= TEX_FILTER_SRGB_IN; if ( IsSRGB( tformat ) ) filter |= TEX_FILTER_SRGB_OUT; if ( (filter & (TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT)) == (TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT) ) { filter &= ~(TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT); } DWORD wicsrgb = _CheckWICColorSpace( pfGUID, targetGUID ); if ( wicsrgb != (filter & (TEX_FILTER_SRGB_IN|TEX_FILTER_SRGB_OUT)) ) { // WIC will perform a colorspace conversion we didn't request return false; } return true; } //------------------------------------------------------------------------------------- // Convert the source image using WIC //------------------------------------------------------------------------------------- static HRESULT _ConvertUsingWIC( _In_ const Image& srcImage, _In_ const WICPixelFormatGUID& pfGUID, _In_ const WICPixelFormatGUID& targetGUID, _In_ DWORD filter, _In_ float threshold, _In_ const Image& destImage ) { assert( srcImage.width == destImage.width ); assert( srcImage.height == destImage.height ); bool iswic2 = false; IWICImagingFactory* pWIC = GetWICFactory(iswic2); if ( !pWIC ) return E_NOINTERFACE; ComPtr<IWICFormatConverter> FC; HRESULT hr = pWIC->CreateFormatConverter( FC.GetAddressOf() ); if ( FAILED(hr) ) return hr; // Note that WIC conversion ignores the TEX_FILTER_SRGB_IN and TEX_FILTER_SRGB_OUT flags, // but also always assumes UNORM <-> FLOAT conversions are changing color spaces sRGB <-> scRGB BOOL canConvert = FALSE; hr = FC->CanConvert( pfGUID, targetGUID, &canConvert ); if ( FAILED(hr) || !canConvert ) { // This case is not an issue for the subset of WIC formats that map directly to DXGI return E_UNEXPECTED; } ComPtr<IWICBitmap> source; hr = pWIC->CreateBitmapFromMemory( static_cast<UINT>( srcImage.width ), static_cast<UINT>( srcImage.height ), pfGUID, static_cast<UINT>( srcImage.rowPitch ), static_cast<UINT>( srcImage.slicePitch ), srcImage.pixels, source.GetAddressOf() ); if ( FAILED(hr) ) return hr; hr = FC->Initialize( source.Get(), targetGUID, _GetWICDither( filter ), 0, threshold * 100.f, WICBitmapPaletteTypeCustom ); if ( FAILED(hr) ) return hr; hr = FC->CopyPixels( 0, static_cast<UINT>( destImage.rowPitch ), static_cast<UINT>( destImage.slicePitch ), destImage.pixels ); if ( FAILED(hr) ) return hr; return S_OK; } //------------------------------------------------------------------------------------- // Convert the source image (not using WIC) //------------------------------------------------------------------------------------- static HRESULT _Convert( _In_ const Image& srcImage, _In_ DWORD filter, _In_ const Image& destImage, _In_ float threshold, _In_ size_t z ) { assert( srcImage.width == destImage.width ); assert( srcImage.height == destImage.height ); const uint8_t *pSrc = srcImage.pixels; uint8_t *pDest = destImage.pixels; if ( !pSrc || !pDest ) return E_POINTER; size_t width = srcImage.width; if ( filter & TEX_FILTER_DITHER_DIFFUSION ) { // Error diffusion dithering (aka Floyd-Steinberg dithering) ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*(width*2 + 2)), 16 ) ) ); if ( !scanline ) return E_OUTOFMEMORY; XMVECTOR* pDiffusionErrors = scanline.get() + width; memset( pDiffusionErrors, 0, sizeof(XMVECTOR)*(width+2) ); for( size_t h = 0; h < srcImage.height; ++h ) { if ( !_LoadScanline( scanline.get(), width, pSrc, srcImage.rowPitch, srcImage.format ) ) return E_FAIL; _ConvertScanline( scanline.get(), width, destImage.format, srcImage.format, filter ); if ( !_StoreScanlineDither( pDest, destImage.rowPitch, destImage.format, scanline.get(), width, threshold, h, z, pDiffusionErrors ) ) return E_FAIL; pSrc += srcImage.rowPitch; pDest += destImage.rowPitch; } } else { ScopedAlignedArrayXMVECTOR scanline( reinterpret_cast<XMVECTOR*>( _aligned_malloc( (sizeof(XMVECTOR)*width), 16 ) ) ); if ( !scanline ) return E_OUTOFMEMORY; if ( filter & TEX_FILTER_DITHER ) { // Ordered dithering for( size_t h = 0; h < srcImage.height; ++h ) { if ( !_LoadScanline( scanline.get(), width, pSrc, srcImage.rowPitch, srcImage.format ) ) return E_FAIL; _ConvertScanline( scanline.get(), width, destImage.format, srcImage.format, filter ); if ( !_StoreScanlineDither( pDest, destImage.rowPitch, destImage.format, scanline.get(), width, threshold, h, z, nullptr ) ) return E_FAIL; pSrc += srcImage.rowPitch; pDest += destImage.rowPitch; } } else { // No dithering for( size_t h = 0; h < srcImage.height; ++h ) { if ( !_LoadScanline( scanline.get(), width, pSrc, srcImage.rowPitch, srcImage.format ) ) return E_FAIL; _ConvertScanline( scanline.get(), width, destImage.format, srcImage.format, filter ); if ( !_StoreScanline( pDest, destImage.rowPitch, destImage.format, scanline.get(), width, threshold ) ) return E_FAIL; pSrc += srcImage.rowPitch; pDest += destImage.rowPitch; } } } return S_OK; } //------------------------------------------------------------------------------------- static DXGI_FORMAT _PlanarToSingle( _In_ DXGI_FORMAT format ) { switch (format) { case DXGI_FORMAT_NV12: case DXGI_FORMAT_NV11: return DXGI_FORMAT_YUY2; case DXGI_FORMAT_P010: return DXGI_FORMAT_Y210; case DXGI_FORMAT_P016: return DXGI_FORMAT_Y216; // We currently do not support conversion for Xbox One specific 16-bit depth formats // We can't do anything with DXGI_FORMAT_420_OPAQUE because it's an opaque blob of bits // We don't support conversion of JPEG Hardware decode formats default: return DXGI_FORMAT_UNKNOWN; } } //------------------------------------------------------------------------------------- // Convert the image from a planar to non-planar image //------------------------------------------------------------------------------------- #define CONVERT_420_TO_422( srcType, destType )\ {\ size_t rowPitch = srcImage.rowPitch;\ \ auto sourceE = reinterpret_cast<const srcType*>( pSrc + srcImage.slicePitch );\ auto pSrcUV = pSrc + ( srcImage.height * rowPitch );\ \ for( size_t y = 0; y < srcImage.height; y+= 2 )\ {\ auto sPtrY0 = reinterpret_cast<const srcType*>( pSrc );\ auto sPtrY2 = reinterpret_cast<const srcType*>( pSrc + rowPitch );\ auto sPtrUV = reinterpret_cast<const srcType*>( pSrcUV );\ \ destType * __restrict dPtr0 = reinterpret_cast<destType*>(pDest);\ destType * __restrict dPtr1 = reinterpret_cast<destType*>(pDest + destImage.rowPitch);\ \ for( size_t x = 0; x < srcImage.width; x+= 2 )\ {\ if ( (sPtrUV+1) >= sourceE ) break;\ \ srcType u = *(sPtrUV++);\ srcType v = *(sPtrUV++);\ \ dPtr0->x = *(sPtrY0++);\ dPtr0->y = u;\ dPtr0->z = *(sPtrY0++);\ dPtr0->w = v;\ ++dPtr0;\ \ dPtr1->x = *(sPtrY2++);\ dPtr1->y = u;\ dPtr1->z = *(sPtrY2++);\ dPtr1->w = v;\ ++dPtr1;\ }\ \ pSrc += rowPitch * 2;\ pSrcUV += rowPitch;\ \ pDest += destImage.rowPitch * 2;\ }\ } static HRESULT _ConvertToSinglePlane( _In_ const Image& srcImage, _In_ const Image& destImage ) { assert( srcImage.width == destImage.width ); assert( srcImage.height == destImage.height ); const uint8_t *pSrc = srcImage.pixels; uint8_t *pDest = destImage.pixels; if ( !pSrc || !pDest ) return E_POINTER; switch ( srcImage.format ) { case DXGI_FORMAT_NV12: assert( destImage.format == DXGI_FORMAT_YUY2 ); CONVERT_420_TO_422( uint8_t, XMUBYTEN4 ); return S_OK; case DXGI_FORMAT_P010: assert( destImage.format == DXGI_FORMAT_Y210 ); CONVERT_420_TO_422( uint16_t, XMUSHORTN4 ); return S_OK; case DXGI_FORMAT_P016: assert( destImage.format == DXGI_FORMAT_Y216 ); CONVERT_420_TO_422( uint16_t, XMUSHORTN4 ); return S_OK; case DXGI_FORMAT_NV11: assert( destImage.format == DXGI_FORMAT_YUY2 ); // Convert 4:1:1 to 4:2:2 { size_t rowPitch = srcImage.rowPitch; const uint8_t* sourceE = pSrc + srcImage.slicePitch; const uint8_t* pSrcUV = pSrc + ( srcImage.height * rowPitch ); for( size_t y = 0; y < srcImage.height; ++y ) { const uint8_t* sPtrY = pSrc; const uint8_t* sPtrUV = pSrcUV; XMUBYTEN4 * __restrict dPtr = reinterpret_cast<XMUBYTEN4*>(pDest); for( size_t x = 0; x < srcImage.width; x+= 4 ) { if ( (sPtrUV+1) >= sourceE ) break; uint8_t u = *(sPtrUV++); uint8_t v = *(sPtrUV++); dPtr->x = *(sPtrY++); dPtr->y = u; dPtr->z = *(sPtrY++); dPtr->w = v; ++dPtr; dPtr->x = *(sPtrY++); dPtr->y = u; dPtr->z = *(sPtrY++); dPtr->w = v; ++dPtr; } pSrc += rowPitch; pSrcUV += (rowPitch >> 1); pDest += destImage.rowPitch; } } return S_OK; default: return E_UNEXPECTED; } } #undef CONVERT_420_TO_422 //===================================================================================== // Entry-points //===================================================================================== //------------------------------------------------------------------------------------- // Convert image //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT Convert( const Image& srcImage, DXGI_FORMAT format, DWORD filter, float threshold, ScratchImage& image ) { if ( (srcImage.format == format) || !IsValid( format ) ) return E_INVALIDARG; if ( !srcImage.pixels ) return E_POINTER; if ( IsCompressed(srcImage.format) || IsCompressed(format) || IsPlanar(srcImage.format) || IsPlanar(format) || IsPalettized(srcImage.format) || IsPalettized(format) || IsTypeless(srcImage.format) || IsTypeless(format) ) return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); #ifdef _M_X64 if ( (srcImage.width > 0xFFFFFFFF) || (srcImage.height > 0xFFFFFFFF) ) return E_INVALIDARG; #endif HRESULT hr = image.Initialize2D( format, srcImage.width, srcImage.height, 1, 1 ); if ( FAILED(hr) ) return hr; const Image *rimage = image.GetImage( 0, 0, 0 ); if ( !rimage ) { image.Release(); return E_POINTER; } WICPixelFormatGUID pfGUID, targetGUID; if ( _UseWICConversion( filter, srcImage.format, format, pfGUID, targetGUID ) ) { hr = _ConvertUsingWIC( srcImage, pfGUID, targetGUID, filter, threshold, *rimage ); } else { hr = _Convert( srcImage, filter, *rimage, threshold, 0 ); } if ( FAILED(hr) ) { image.Release(); return hr; } return S_OK; } //------------------------------------------------------------------------------------- // Convert image (complex) //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT Convert( const Image* srcImages, size_t nimages, const TexMetadata& metadata, DXGI_FORMAT format, DWORD filter, float threshold, ScratchImage& result ) { if ( !srcImages || !nimages || (metadata.format == format) || !IsValid(format) ) return E_INVALIDARG; if ( IsCompressed(metadata.format) || IsCompressed(format) || IsPlanar(metadata.format) || IsPlanar(format) || IsPalettized(metadata.format) || IsPalettized(format) || IsTypeless(metadata.format) || IsTypeless(format) ) return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); #ifdef _M_X64 if ( (metadata.width > 0xFFFFFFFF) || (metadata.height > 0xFFFFFFFF) ) return E_INVALIDARG; #endif TexMetadata mdata2 = metadata; mdata2.format = format; HRESULT hr = result.Initialize( mdata2 ); if ( FAILED(hr) ) return hr; if ( nimages != result.GetImageCount() ) { result.Release(); return E_FAIL; } const Image* dest = result.GetImages(); if ( !dest ) { result.Release(); return E_POINTER; } WICPixelFormatGUID pfGUID, targetGUID; bool usewic = _UseWICConversion( filter, metadata.format, format, pfGUID, targetGUID ); switch (metadata.dimension) { case TEX_DIMENSION_TEXTURE1D: case TEX_DIMENSION_TEXTURE2D: for( size_t index=0; index < nimages; ++index ) { const Image& src = srcImages[ index ]; if ( src.format != metadata.format ) { result.Release(); return E_FAIL; } #ifdef _M_X64 if ( (src.width > 0xFFFFFFFF) || (src.height > 0xFFFFFFFF) ) return E_FAIL; #endif const Image& dst = dest[ index ]; assert( dst.format == format ); if ( src.width != dst.width || src.height != dst.height ) { result.Release(); return E_FAIL; } if ( usewic ) { hr = _ConvertUsingWIC( src, pfGUID, targetGUID, filter, threshold, dst ); } else { hr = _Convert( src, filter, dst, threshold, 0 ); } if ( FAILED(hr) ) { result.Release(); return hr; } } break; case TEX_DIMENSION_TEXTURE3D: { size_t index = 0; size_t d = metadata.depth; for( size_t level = 0; level < metadata.mipLevels; ++level ) { for( size_t slice = 0; slice < d; ++slice, ++index ) { if ( index >= nimages ) return E_FAIL; const Image& src = srcImages[ index ]; if ( src.format != metadata.format ) { result.Release(); return E_FAIL; } #ifdef _M_X64 if ( (src.width > 0xFFFFFFFF) || (src.height > 0xFFFFFFFF) ) return E_FAIL; #endif const Image& dst = dest[ index ]; assert( dst.format == format ); if ( src.width != dst.width || src.height != dst.height ) { result.Release(); return E_FAIL; } if ( usewic ) { hr = _ConvertUsingWIC( src, pfGUID, targetGUID, filter, threshold, dst ); } else { hr = _Convert( src, filter, dst, threshold, slice ); } if ( FAILED(hr) ) { result.Release(); return hr; } } if ( d > 1 ) d >>= 1; } } break; default: return E_FAIL; } return S_OK; } //------------------------------------------------------------------------------------- // Convert image from planar to single plane (image) //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT ConvertToSinglePlane( const Image& srcImage, ScratchImage& image ) { if ( !IsPlanar(srcImage.format) ) return E_INVALIDARG; if ( !srcImage.pixels ) return E_POINTER; DXGI_FORMAT format = _PlanarToSingle( srcImage.format ); if ( format == DXGI_FORMAT_UNKNOWN ) return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); #ifdef _M_X64 if ( (srcImage.width > 0xFFFFFFFF) || (srcImage.height > 0xFFFFFFFF) ) return E_INVALIDARG; #endif HRESULT hr = image.Initialize2D( format, srcImage.width, srcImage.height, 1, 1 ); if ( FAILED(hr) ) return hr; const Image *rimage = image.GetImage( 0, 0, 0 ); if ( !rimage ) { image.Release(); return E_POINTER; } hr = _ConvertToSinglePlane( srcImage, *rimage ); if ( FAILED(hr) ) { image.Release(); return hr; } return S_OK; } //------------------------------------------------------------------------------------- // Convert image from planar to single plane (complex) //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT ConvertToSinglePlane( const Image* srcImages, size_t nimages, const TexMetadata& metadata, ScratchImage& result ) { if ( !srcImages || !nimages ) return E_INVALIDARG; if ( metadata.IsVolumemap() ) { // Direct3D does not support any planar formats for Texture3D return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); } DXGI_FORMAT format = _PlanarToSingle( metadata.format ); if ( format == DXGI_FORMAT_UNKNOWN ) return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); #ifdef _M_X64 if ( (metadata.width > 0xFFFFFFFF) || (metadata.height > 0xFFFFFFFF) ) return E_INVALIDARG; #endif TexMetadata mdata2 = metadata; mdata2.format = format; HRESULT hr = result.Initialize( mdata2 ); if ( FAILED(hr) ) return hr; if ( nimages != result.GetImageCount() ) { result.Release(); return E_FAIL; } const Image* dest = result.GetImages(); if ( !dest ) { result.Release(); return E_POINTER; } for( size_t index=0; index < nimages; ++index ) { const Image& src = srcImages[ index ]; if ( src.format != metadata.format ) { result.Release(); return E_FAIL; } #ifdef _M_X64 if ( (src.width > 0xFFFFFFFF) || (src.height > 0xFFFFFFFF) ) return E_FAIL; #endif const Image& dst = dest[ index ]; assert( dst.format == format ); if ( src.width != dst.width || src.height != dst.height ) { result.Release(); return E_FAIL; } hr = _ConvertToSinglePlane( src, dst ); if ( FAILED(hr) ) { result.Release(); return hr; } } return S_OK; } }; // namespace
39.030905
145
0.487781
Jin02
741fe7871459e8a008402fab0c4260c15cc47254
20,376
cpp
C++
ToolKit/Controls/Dialog/XTPColorPageCustom.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/Controls/Dialog/XTPColorPageCustom.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/Controls/Dialog/XTPColorPageCustom.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPColorPageCustom.cpp : implementation file // // This file is a part of the XTREME CONTROLS MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPDrawHelpers.h" #include "Common/XTPColorManager.h" #include "Common/XTPSystemHelpers.h" #include "Controls/Resource.h" #include "Controls/Defines.h" #include "Controls/Dialog/XTPColorDialog.h" #include "Controls/Dialog/XTPColorPageCustom.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define DEFAULT_LUMINANCE 0.50f ///////////////////////////////////////////////////////////////////////////// // CXTPColorBase CXTPColorBase::CXTPColorBase() { m_nLum = 0.0; m_nSat = 0.0; m_nHue = 0.0; m_ptMousePos = CPoint(0, 0); m_bPreSubclassInit = true; } CXTPColorBase::~CXTPColorBase() { } CXTPColorBase::FocusedControl CXTPColorBase::m_eHasFocus = focusNone; BEGIN_MESSAGE_MAP(CXTPColorBase, CStatic) //{{AFX_MSG_MAP(CXTPColorBase) ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_LBUTTONUP() ON_WM_LBUTTONDBLCLK() ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXTPColorBase message handlers bool CXTPColorBase::Init() { if (::IsWindow(m_hWnd)) { // Set the style to SS_NOTIFY. DWORD dwStyle = ::GetWindowLong(m_hWnd, GWL_STYLE); ::SetWindowLong(m_hWnd, GWL_STYLE, dwStyle | SS_NOTIFY); return true; } return false; } void CXTPColorBase::PreSubclassWindow() { CWnd::PreSubclassWindow(); if (m_bPreSubclassInit) { // Initialize the control. Init(); } } int CXTPColorBase::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; // Initialize the control. Init(); return 0; } BOOL CXTPColorBase::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE; // When creating controls dynamically Init() must // be called from OnCreate() and not from // PreSubclassWindow(). m_bPreSubclassInit = false; return TRUE; } void CXTPColorBase::OnLButtonDown(UINT nFlags, CPoint point) { CWnd::OnLButtonDown(nFlags, point); SetCapture(); UpdateCursorPos(point); if (GetFocus() != this) { SetFocus(); } } void CXTPColorBase::OnLButtonUp(UINT nFlags, CPoint point) { ReleaseCapture(); CStatic::OnLButtonUp(nFlags, point); } void CXTPColorBase::OnMouseMove(UINT nFlags, CPoint point) { CWnd::OnMouseMove(nFlags, point); if ((nFlags & MK_LBUTTON) && (GetCapture() == this)) { UpdateCursorPos(point); if (GetFocus() != this) { SetFocus(); } } } void CXTPColorBase::OnLButtonDblClk(UINT nFlags, CPoint point) { UpdateCursorPos(point); CWnd* pWnd = GetOwner(); if (pWnd) { pWnd->SendMessage(WM_XTP_COLORDBLCLK, (WPARAM)0, (LPARAM)MAKELPARAM(LOWORD(point.x),HIWORD(point.y))); } CStatic::OnLButtonDblClk(nFlags, point); } void CXTPColorBase::UpdateCursorPos(CPoint /*point*/) { } COLORREF CXTPColorBase::HLStoRGB(double h, double l, double s) { return CXTPDrawHelpers::HSLtoRGB(h, s, l); } void CXTPColorBase::RGBtoHSL(COLORREF color, double* h, double* s, double* l) { CXTPDrawHelpers::RGBtoHSL(color, *h, *s, *l); } ///////////////////////////////////////////////////////////////////////////// // CXTPColorWnd CXTPColorWnd::CXTPColorWnd() { } CXTPColorWnd::~CXTPColorWnd() { } BEGIN_MESSAGE_MAP(CXTPColorWnd, CXTPColorBase) //{{AFX_MSG_MAP(CXTPColorWnd) ON_WM_PAINT() ON_WM_SETFOCUS() ON_WM_KILLFOCUS() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXTPColorWnd message handlers void CXTPColorWnd::OnPaint() { CPaintDC dc(this); // device context for painting CRect rc; GetClientRect(&rc); CXTPBufferDC memDC(dc); int cy = rc.Height(); int cx = rc.Width(); if (m_bmpPicker.GetSafeHandle() == NULL) { // create bitmap m_bmpPicker.CreateCompatibleBitmap(&memDC, cx, cy); // create picker DC CXTPCompatibleDC dcPicker(&memDC, m_bmpPicker); // fill color picker bitmap int x; for (x = 0; x < cx; x++) { int y; for (y = 0; y < cy; y++) { COLORREF clr = HLStoRGB((double)x/(double)cx, DEFAULT_LUMINANCE, (double)y/(double)cy); dcPicker.SetPixelV(x, (cy-1)-y, clr); } } } memDC.DrawState(CPoint(0, 0), CSize(0, 0), &m_bmpPicker, DSS_NORMAL, NULL); DrawCrossHair(&memDC); } BOOL CXTPColorWnd::OnEraseBkgnd(CDC* /*pDC*/) { return TRUE; } void CXTPColorWnd::UpdateCursorPos(CPoint point) { CRect rcClient; GetClientRect(rcClient); if (point.y < 0) point.y = 0; if (point.x < 0) point.x = 0; if (point.y > rcClient.bottom) point.y = rcClient.bottom; if (point.x > rcClient.right) point.x = rcClient.right; m_ptMousePos = point; m_nHue = (double)point.x / (double)rcClient.Width(); m_nSat = (double)(rcClient.Height() - point.y) / (double)rcClient.Height(); m_nLum = DEFAULT_LUMINANCE; CWnd* pWnd = GetOwner(); if (pWnd) { pWnd->SendMessage(WM_XTP_UPDATECOLOR, (WPARAM)HLStoRGB(m_nHue, m_nLum, m_nSat), (LPARAM)m_hWnd); } Invalidate(FALSE); } BOOL CXTPColorWnd::PreTranslateMessage(MSG* pMsg) { if (m_eHasFocus == focusColorWheel) { switch (pMsg->message) { case WM_KEYDOWN: { CRect rect; GetClientRect(&rect); TCHAR vkey = (TCHAR)pMsg->wParam; switch (vkey) { case VK_LEFT: m_ptMousePos.x--; UpdateCursorPos(m_ptMousePos); return TRUE; case VK_UP: m_ptMousePos.y--; UpdateCursorPos(m_ptMousePos); return TRUE; case VK_RIGHT: m_ptMousePos.x++; UpdateCursorPos(m_ptMousePos); return TRUE; case VK_DOWN: m_ptMousePos.y++; UpdateCursorPos(m_ptMousePos); return TRUE; } } break; } } return CStatic::PreTranslateMessage(pMsg); } void CXTPColorWnd::DrawCrossHair(CDC* pDC) { int x = m_ptMousePos.x; int y = m_ptMousePos.y; CPen pen1(PS_SOLID, 1, RGB(0xff, 0xff, 0xff)); CPen pen2(PS_SOLID, 1, RGB(0x00, 0x00, 0x00)); CPen* pOldPen = pDC->SelectObject((m_eHasFocus == focusColorWheel) ? &pen1 : &pen2); pDC->MoveTo(x-5, y-1); pDC->LineTo(x-10, y-1); pDC->MoveTo(x-5, y); pDC->LineTo(x-10, y); pDC->MoveTo(x-5, y + 1); pDC->LineTo(x-10, y + 1); pDC->MoveTo(x + 5, y-1); pDC->LineTo(x + 10, y-1); pDC->MoveTo(x + 5, y); pDC->LineTo(x + 10, y); pDC->MoveTo(x + 5, y + 1); pDC->LineTo(x + 10, y + 1); pDC->MoveTo(x-1, y-5); pDC->LineTo(x-1, y-10); pDC->MoveTo(x, y-5); pDC->LineTo(x, y-10); pDC->MoveTo(x + 1, y-5); pDC->LineTo(x + 1, y-10); pDC->MoveTo(x-1, y + 5); pDC->LineTo(x-1, y + 10); pDC->MoveTo(x, y + 5); pDC->LineTo(x, y + 10); pDC->MoveTo(x + 1, y + 5); pDC->LineTo(x + 1, y + 10); pDC->SelectObject(pOldPen); } void CXTPColorWnd::SetColor(double nHue, double nSat) { SetHue(nHue); SetSaturation(nSat); } void CXTPColorWnd::SetHue(double h) { m_nHue = h; CRect rc; GetClientRect(&rc); m_ptMousePos.x = (long)((double)rc.Width() * h); Invalidate(FALSE); } void CXTPColorWnd::SetSaturation(double s) { m_nSat = s; CRect rc; GetClientRect(&rc); m_ptMousePos.y = rc.Height()-(long)((double)rc.Height() * s); Invalidate(FALSE); } void CXTPColorWnd::OnSetFocus(CWnd* pOldWnd) { CXTPColorBase::OnSetFocus(pOldWnd); m_eHasFocus = focusColorWheel; Invalidate(FALSE); } void CXTPColorWnd::OnKillFocus(CWnd* pNewWnd) { CXTPColorBase::OnKillFocus(pNewWnd); m_eHasFocus = focusNone; Invalidate(FALSE); } ///////////////////////////////////////////////////////////////////////////// // CXTPColorLum CXTPColorLum::CXTPColorLum() { m_ptMousePos.y = 0; } CXTPColorLum::~CXTPColorLum() { } BEGIN_MESSAGE_MAP(CXTPColorLum, CXTPColorBase) //{{AFX_MSG_MAP(CXTPColorLum) ON_WM_PAINT() ON_WM_SETFOCUS() ON_WM_KILLFOCUS() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXTPColorLum message handlers void CXTPColorLum::OnPaint() { CPaintDC dc(this); // device context for painting CRect rc; GetClientRect(&rc); CXTPBufferDC memDC(dc); HBRUSH hBrush = (HBRUSH)GetParent()->SendMessage(WM_CTLCOLORSTATIC, (WPARAM)memDC.GetSafeHdc(), (LPARAM)m_hWnd); if (hBrush) { ::FillRect(memDC.GetSafeHdc(), rc, hBrush); } else { memDC.FillSolidRect(rc, GetXtremeColor(COLOR_3DFACE)); } DrawLuminanceBar(&memDC); DrawSliderArrow(&memDC); } BOOL CXTPColorLum::OnEraseBkgnd(CDC* /*pDC*/) { return TRUE; } void CXTPColorLum::GetLumBarRect(CRect& rect) { GetClientRect(&rect); rect.DeflateRect(0, 4); rect.right = rect.left + 14; } void CXTPColorLum::SetColor(double nHue, double nSat) { m_nHue = nHue; m_nSat = nSat; Invalidate(FALSE); } void CXTPColorLum::SetLuminance(double l) { m_nLum = l; CRect rcBar; GetLumBarRect(rcBar); // Set the slider position based on the current // luminance. m_ptMousePos.y = rcBar.top + rcBar.Height()-(long)((double)rcBar.Height() * l); Invalidate(FALSE); } void CXTPColorLum::DrawLuminanceBar(CDC* pDC) { CRect rcBar; GetLumBarRect(rcBar); int cy = rcBar.Height(); int cx = rcBar.Width(); // fill color picker bitmap for (int y = 0; y < cy; y++) { COLORREF clr; if (y == cy) { clr = RGB(0x00, 0x00, 0x00); } else if (y == 0) { clr = RGB(0xff, 0xff, 0xff); } else { clr = HLStoRGB(m_nHue, (double)((double)(cy - y)/(double)cy), m_nSat); } pDC->FillSolidRect(rcBar.left, y + rcBar.top, cx, 1, clr); } } void CXTPColorLum::DrawSliderArrow(CDC* pDC) { CRect rc; GetClientRect(&rc); rc.left += 17; int x = rc.left; int y = m_ptMousePos.y; CRect rcBar; GetLumBarRect(rcBar); y = max(rcBar.top, y); y = min(rcBar.bottom, y); CPen pen1(PS_SOLID, 1, RGB(0x00, 0x00, 0x00)); CPen pen2(PS_SOLID, 1, GetXtremeColor(COLOR_3DSHADOW)); CPen* pOldPen = pDC->SelectObject((m_eHasFocus == focusLumination) ? &pen1 : &pen2); pDC->MoveTo(x + 7, y-4); pDC->LineTo(x + 9, y-4); pDC->MoveTo(x + 5, y-3); pDC->LineTo(x + 9, y-3); pDC->MoveTo(x + 3, y-2); pDC->LineTo(x + 9, y-2); pDC->MoveTo(x + 1, y-1); pDC->LineTo(x + 9, y-1); pDC->MoveTo(x, y); pDC->LineTo(x + 9, y); pDC->MoveTo(x + 2, y + 1); pDC->LineTo(x + 9, y + 1); pDC->MoveTo(x + 4, y + 2); pDC->LineTo(x + 9, y + 2); pDC->MoveTo(x + 6, y + 3); pDC->LineTo(x + 9, y + 3); pDC->MoveTo(x + 8, y + 4); pDC->LineTo(x + 9, y + 4); if (m_eHasFocus != focusLumination) { COLORREF clr = RGB(0x00, 0x00, 0x00); pDC->SetPixel(x, y, clr); pDC->SetPixel(x + 1, y, clr); pDC->SetPixel(x + 1, y-1, clr); pDC->SetPixel(x + 2, y-1, clr); pDC->SetPixel(x + 3, y-2, clr); pDC->SetPixel(x + 4, y-2, clr); pDC->SetPixel(x + 5, y-3, clr); pDC->SetPixel(x + 6, y-3, clr); pDC->SetPixel(x + 7, y-4, clr); pDC->SetPixel(x + 8, y-4, clr); pDC->SetPixel(x + 8, y-3, clr); pDC->SetPixel(x + 8, y-2, clr); pDC->SetPixel(x + 8, y-1, clr); pDC->SetPixel(x + 8, y, clr); pDC->SetPixel(x + 8, y + 1, clr); pDC->SetPixel(x + 8, y + 2, clr); pDC->SetPixel(x + 8, y + 3, clr); pDC->SetPixel(x + 8, y + 4, clr); pDC->SetPixel(x + 7, y + 3, clr); pDC->SetPixel(x + 6, y + 3, clr); pDC->SetPixel(x + 5, y + 2, clr); pDC->SetPixel(x + 4, y + 2, clr); pDC->SetPixel(x + 3, y + 1, clr); pDC->SetPixel(x + 2, y + 1, clr); } pDC->SelectObject(pOldPen); } void CXTPColorLum::UpdateCursorPos(CPoint point) { point.x = 0; CRect rcBar; GetLumBarRect(rcBar); point.y = max(rcBar.top, point.y); point.y = min(rcBar.bottom, point.y); double cy = (double)rcBar.Height(); m_nLum = double(double(cy - (point.y - rcBar.top))/cy); CWnd* pWnd = GetOwner(); if (pWnd) { pWnd->SendMessage(WM_XTP_UPDATECOLOR, (WPARAM)HLStoRGB(m_nHue, m_nLum, m_nSat), (LPARAM)m_hWnd); } m_ptMousePos = point; Invalidate(FALSE); } BOOL CXTPColorLum::PreTranslateMessage(MSG* pMsg) { if (m_eHasFocus == focusLumination) { CRect rcBar; GetLumBarRect(rcBar); switch (pMsg->message) { case WM_KEYDOWN: { TCHAR vkey = (TCHAR)pMsg->wParam; switch (vkey) { case VK_UP: m_ptMousePos.y--; UpdateCursorPos(m_ptMousePos); return TRUE; case VK_DOWN: m_ptMousePos.y++; UpdateCursorPos(m_ptMousePos); return TRUE; } } break; } } return CStatic::PreTranslateMessage(pMsg); } void CXTPColorLum::OnSetFocus(CWnd* pOldWnd) { CXTPColorBase::OnSetFocus(pOldWnd); m_eHasFocus = focusLumination; Invalidate(FALSE); } void CXTPColorLum::OnKillFocus(CWnd* pNewWnd) { CXTPColorBase::OnKillFocus(pNewWnd); m_eHasFocus = focusNone; Invalidate(FALSE); } ///////////////////////////////////////////////////////////////////////////// // CXTPColorPageCustom BEGIN_MESSAGE_MAP(CXTPColorPageCustom, CPropertyPage) //{{AFX_MSG_MAP(CXTPColorPageCustom) ON_EN_CHANGE(XTP_IDC_EDIT_RED, OnChangeEdit) ON_EN_CHANGE(XTP_IDC_EDIT_GREEN, OnChangeEdit) ON_EN_CHANGE(XTP_IDC_EDIT_BLUE, OnChangeEdit) ON_EN_CHANGE(XTP_IDC_EDIT_LUM, OnChangeEditLum) ON_EN_CHANGE(XTP_IDC_EDIT_HUE, OnChangeEditHue) ON_EN_CHANGE(XTP_IDC_EDIT_SAT, OnChangeEditSat) //}}AFX_MSG_MAP ON_MESSAGE(WM_XTP_UPDATECOLOR, OnUpdateColor) ON_MESSAGE(WM_XTP_COLORDBLCLK, OnColorDblClick) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXTPColorPageCustom construction/destruction CXTPColorPageCustom::CXTPColorPageCustom(CXTPColorDialog* pParentSheet) : CPropertyPage(CXTPColorPageCustom::IDD) { m_psp.dwFlags &= ~PSP_HASHELP; m_pParentSheet = pParentSheet; //{{AFX_DATA_INIT(CXTPColorPageCustom) m_nR = 0; m_nB = 0; m_nG = 0; m_nH = 0; m_nL = 0; m_nS = 0; //}}AFX_DATA_INIT } CXTPColorPageCustom::~CXTPColorPageCustom() { } void CXTPColorPageCustom::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CXTPColorPageCustom) DDX_Control(pDX, XTP_IDC_CLR_WND, m_colorWnd); DDX_Control(pDX, XTP_IDC_CLR_LUM, m_colorLum); DDX_Control(pDX, XTP_IDC_TXT_SAT, m_txtSat); DDX_Control(pDX, XTP_IDC_TXT_RED, m_txtRed); DDX_Control(pDX, XTP_IDC_TXT_LUM, m_txtLum); DDX_Control(pDX, XTP_IDC_TXT_HUE, m_txtHue); DDX_Control(pDX, XTP_IDC_TXT_GREEN, m_txtGreen); DDX_Control(pDX, XTP_IDC_TXT_BLUE, m_txtBlue); DDX_Control(pDX, XTP_IDC_SPIN_SAT, m_spinSat); DDX_Control(pDX, XTP_IDC_SPIN_RED, m_spinRed); DDX_Control(pDX, XTP_IDC_SPIN_LUM, m_spinLum); DDX_Control(pDX, XTP_IDC_SPIN_HUE, m_spinHue); DDX_Control(pDX, XTP_IDC_SPIN_GREEN, m_spinGreen); DDX_Control(pDX, XTP_IDC_SPIN_BLUE, m_spinBlue); DDX_Control(pDX, XTP_IDC_EDIT_HUE, m_editHue); DDX_Control(pDX, XTP_IDC_EDIT_GREEN, m_editGreen); DDX_Control(pDX, XTP_IDC_EDIT_BLUE, m_editBlue); DDX_Control(pDX, XTP_IDC_EDIT_LUM, m_editLum); DDX_Control(pDX, XTP_IDC_EDIT_RED, m_editRed); DDX_Control(pDX, XTP_IDC_EDIT_SAT, m_editSat); DDX_Text(pDX, XTP_IDC_EDIT_RED, m_nR); DDV_MinMaxInt(pDX, m_nR, 0, 255); DDX_Text(pDX, XTP_IDC_EDIT_BLUE, m_nB); DDV_MinMaxInt(pDX, m_nB, 0, 255); DDX_Text(pDX, XTP_IDC_EDIT_GREEN, m_nG); DDV_MinMaxInt(pDX, m_nG, 0, 255); DDX_Text(pDX, XTP_IDC_EDIT_HUE, m_nH); DDV_MinMaxInt(pDX, m_nH, 0, 255); DDX_Text(pDX, XTP_IDC_EDIT_LUM, m_nL); DDV_MinMaxInt(pDX, m_nL, 0, 255); DDX_Text(pDX, XTP_IDC_EDIT_SAT, m_nS); DDV_MinMaxInt(pDX, m_nS, 0, 255); //}}AFX_DATA_MAP } BOOL CXTPColorPageCustom::OnInitDialog() { CPropertyPage::OnInitDialog(); // TODO: Add extra initialization here m_spinSat.SetBuddy(&m_editSat); m_spinSat.SetRange(0, 255); m_spinLum.SetBuddy(&m_editLum); m_spinLum.SetRange(0, 255); m_spinHue.SetBuddy(&m_editHue); m_spinHue.SetRange(0, 255); m_spinRed.SetBuddy(&m_editRed); m_spinRed.SetRange(0, 255); m_spinGreen.SetBuddy(&m_editGreen); m_spinGreen.SetRange(0, 255); m_spinBlue.SetBuddy(&m_editBlue); m_spinBlue.SetRange(0, 255); CRect rc; m_colorLum.GetWindowRect(&rc); ScreenToClient(rc); rc.InflateRect(0, 4); m_colorLum.MoveWindow(&rc); return TRUE; } BOOL CXTPColorPageCustom::OnSetActive() { COLORREF clr = m_pParentSheet->GetColor(); RGBtoHSL(clr, &m_nL, &m_nS, &m_nH); m_colorWnd.SetColor((double)m_nH/255, (double)m_nS/255); m_colorLum.SetColor((double)m_nH/255, (double)m_nS/255); m_colorLum.SetLuminance((double)m_nL/255); UpdateRGB(clr); return CPropertyPage::OnSetActive(); } void CXTPColorPageCustom::OnChangeEdit() { UpdateData(); COLORREF clr = (COLORREF)RGB(m_nR, m_nG, m_nB); OnUpdateColor((WPARAM)clr, 0); } void CXTPColorPageCustom::OnChangeEditLum() { UpdateData(); m_colorLum.SetLuminance((double)m_nL/255); COLORREF clr = m_colorLum.HLStoRGB((double)m_nH/255, (double)m_nL/255, (double)m_nS/255); if (clr != m_pParentSheet->GetColor()) m_pParentSheet->SetNewColor(clr, FALSE); UpdateRGB(clr); } void CXTPColorPageCustom::UpdateRGB(COLORREF clr) { m_nR = GetRValue(clr); m_nG = GetGValue(clr); m_nB = GetBValue(clr); UpdateData(FALSE); } void CXTPColorPageCustom::OnChangeEditHue() { UpdateData(); m_colorWnd.SetHue((double)m_nH/255); COLORREF clr = m_colorWnd.HLStoRGB((double)m_nH/255, (double)m_nL/255, (double)m_nS/255); m_colorLum.SetColor((double)m_nH/255, (double)m_nS/255); if (clr != m_pParentSheet->GetColor()) m_pParentSheet->SetNewColor(clr, FALSE); UpdateRGB(clr); } void CXTPColorPageCustom::OnChangeEditSat() { UpdateData(); m_colorWnd.SetSaturation((double)m_nS/255); COLORREF clr = m_colorWnd.HLStoRGB((double)m_nH/255, (double)m_nL/255, (double)m_nS/255); m_colorLum.SetColor((double)m_nH/255, (double)m_nS/255); if (clr != m_pParentSheet->GetColor()) m_pParentSheet->SetNewColor(clr, FALSE); UpdateRGB(clr); } LRESULT CXTPColorPageCustom::OnUpdateColor(WPARAM wParam, LPARAM lParam) { COLORREF clr = (COLORREF)wParam; if ((HWND)lParam == m_colorWnd.m_hWnd) { m_nS = int(m_colorWnd.m_nSat * 255); m_nH = int(m_colorWnd.m_nHue * 255); clr = m_colorWnd.HLStoRGB((double)m_nH/255, DEFAULT_LUMINANCE, (double)m_nS/255); m_colorLum.SetColor((double)m_nH/255, (double)m_nS/255); } else if ((HWND)lParam == m_colorLum.m_hWnd) { m_nL = int(m_colorLum.m_nLum * 255); clr = m_colorWnd.HLStoRGB((double)m_nH/255, (double)m_nL/255, (double)m_nS/255); } else { RGBtoHSL(clr, &m_nL, &m_nS, &m_nH); m_colorWnd.SetColor((double)m_nH/255, (double)m_nS/255); m_colorLum.SetColor((double)m_nH/255, (double)m_nS/255); m_colorLum.SetLuminance((double)m_nL/255); // get a handle to the window at the cursor location. POINT point; ::GetCursorPos(&point); HWND hWnd = ::WindowFromPoint(point); if (::IsWindow(hWnd)) { if ((hWnd == m_colorLum.m_hWnd) || (hWnd == m_colorWnd.m_hWnd)) { ::SetFocus(hWnd); } } } if ((HWND)lParam != m_pParentSheet->GetSafeHwnd()) { if (clr != m_pParentSheet->GetColor()) m_pParentSheet->SetNewColor(clr, FALSE); } UpdateRGB(clr); return 0; } LRESULT CXTPColorPageCustom::OnColorDblClick(WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); m_pParentSheet->EndDialog(IDOK); return 0; } void CXTPColorPageCustom::RGBtoHSL(COLORREF color, int* lum, int* sat, int* hue) { double r = (double)GetRValue(color)/255; double g = (double)GetGValue(color)/255; double b = (double)GetBValue(color)/255; double maxcolor = __max(r, __max(g, b)); double mincolor = __min(r, __min(g, b)); double l = (maxcolor + mincolor)/2; if (maxcolor == mincolor) { *hue = 0; *sat = 0; } else { double s; double h; if (l < 0.5) s = (maxcolor-mincolor)/(maxcolor + mincolor); else s = (maxcolor-mincolor)/(2.0-maxcolor-mincolor); if (r == maxcolor) h = (g-b)/(maxcolor-mincolor); else if (g == maxcolor) h = 2.0+(b-r)/(maxcolor-mincolor); else h = 4.0+(r-g)/(maxcolor-mincolor); h /= 6.0; if (h < 0.0) h += 1; *hue = (int)((double)h * 255); *sat = (int)((double)s * 255); } *lum = (int)((double)l * 255); }
21.676596
113
0.666274
11Zero
7422479ba264bb6f4f05ff74a54138c281f313ca
199,622
cpp
C++
src/game/client/viewrender.cpp
Davideogame/TheHunted
b0f7c92093dcd5060e3c7c019130a82b0f26cf84
[ "Unlicense" ]
null
null
null
src/game/client/viewrender.cpp
Davideogame/TheHunted
b0f7c92093dcd5060e3c7c019130a82b0f26cf84
[ "Unlicense" ]
null
null
null
src/game/client/viewrender.cpp
Davideogame/TheHunted
b0f7c92093dcd5060e3c7c019130a82b0f26cf84
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Responsible for drawing the scene // //===========================================================================// #include "cbase.h" #include "view.h" #include "iviewrender.h" #include "view_shared.h" #include "ivieweffects.h" #include "iinput.h" #include "model_types.h" #include "clientsideeffects.h" #include "particlemgr.h" #include "viewrender.h" #include "iclientmode.h" #include "voice_status.h" #include "glow_overlay.h" #include "materialsystem/imesh.h" #include "materialsystem/itexture.h" #include "materialsystem/imaterial.h" #include "materialsystem/imaterialvar.h" #include "materialsystem/imaterialsystem.h" #include "detailobjectsystem.h" #include "tier0/vprof.h" #include "tier1/mempool.h" #include "vstdlib/jobthread.h" #include "datacache/imdlcache.h" #include "engine/IEngineTrace.h" #include "engine/ivmodelinfo.h" #include "tier0/icommandline.h" #include "view_scene.h" #include "particles_ez.h" #include "engine/IStaticPropMgr.h" #include "engine/ivdebugoverlay.h" #include "c_pixel_visibility.h" #include "clienteffectprecachesystem.h" #include "c_rope.h" #include "c_effects.h" #include "smoke_fog_overlay.h" #include "materialsystem/imaterialsystemhardwareconfig.h" #include "VGuiMatSurface/IMatSystemSurface.h" #include "vgui_int.h" #include "ienginevgui.h" #include "ScreenSpaceEffects.h" #include "toolframework_client.h" #include "c_func_reflective_glass.h" #include "KeyValues.h" #include "renderparm.h" #include "studio_stats.h" #include "con_nprint.h" #include "clientmode_shared.h" #include "headtrack/isourcevirtualreality.h" #include "client_virtualreality.h" #ifdef PORTAL //#include "C_Portal_Player.h" #include "portal_render_targets.h" #include "PortalRender.h" #endif #if defined( HL2_CLIENT_DLL ) || defined( CSTRIKE_DLL ) #define USE_MONITORS #endif #include "rendertexture.h" #include "viewpostprocess.h" #include "viewdebug.h" #if defined USES_ECON_ITEMS #include "econ_wearable.h" #endif #ifdef USE_MONITORS #include "c_point_camera.h" #endif // USE_MONITORS // Projective textures #include "C_Env_Projected_Texture.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static void testfreezeframe_f( void ) { view->FreezeFrame( 3.0 ); } static ConCommand test_freezeframe( "test_freezeframe", testfreezeframe_f, "Test the freeze frame code.", FCVAR_CHEAT ); //----------------------------------------------------------------------------- static ConVar r_visocclusion( "r_visocclusion", "0", FCVAR_CHEAT ); extern ConVar r_flashlightdepthtexture; extern ConVar vcollide_wireframe; extern ConVar mat_motion_blur_enabled; extern ConVar r_depthoverlay; extern ConVar mat_viewportscale; extern ConVar mat_viewportupscale; extern bool g_bDumpRenderTargets; //----------------------------------------------------------------------------- // Convars related to controlling rendering //----------------------------------------------------------------------------- static ConVar cl_maxrenderable_dist("cl_maxrenderable_dist", "3000", FCVAR_CHEAT, "Max distance from the camera at which things will be rendered" ); ConVar r_entityclips( "r_entityclips", "1" ); //FIXME: Nvidia drivers before 81.94 on cards that support user clip planes will have problems with this, require driver update? Detect and disable? // Matches the version in the engine static ConVar r_drawopaqueworld( "r_drawopaqueworld", "1", FCVAR_CHEAT ); static ConVar r_drawtranslucentworld( "r_drawtranslucentworld", "1", FCVAR_CHEAT ); static ConVar r_3dsky( "r_3dsky","1", 0, "Enable the rendering of 3d sky boxes" ); static ConVar r_skybox( "r_skybox","1", FCVAR_CHEAT, "Enable the rendering of sky boxes" ); #ifdef TF_CLIENT_DLL ConVar r_drawviewmodel( "r_drawviewmodel","1", FCVAR_ARCHIVE ); #else ConVar r_drawviewmodel( "r_drawviewmodel","1", FCVAR_CHEAT ); #endif static ConVar r_drawtranslucentrenderables( "r_drawtranslucentrenderables", "1", FCVAR_CHEAT ); static ConVar r_drawopaquerenderables( "r_drawopaquerenderables", "1", FCVAR_CHEAT ); static ConVar r_threaded_renderables( "r_threaded_renderables", "0" ); // FIXME: This is not static because we needed to turn it off for TF2 playtests ConVar r_DrawDetailProps( "r_DrawDetailProps", "1", FCVAR_NONE, "0=Off, 1=Normal, 2=Wireframe" ); ConVar r_worldlistcache( "r_worldlistcache", "1" ); //----------------------------------------------------------------------------- // Convars related to fog color //----------------------------------------------------------------------------- static ConVar fog_override( "fog_override", "0", FCVAR_CHEAT ); // set any of these to use the maps fog static ConVar fog_start( "fog_start", "-1", FCVAR_CHEAT ); static ConVar fog_end( "fog_end", "-1", FCVAR_CHEAT ); static ConVar fog_color( "fog_color", "-1 -1 -1", FCVAR_CHEAT ); static ConVar fog_enable( "fog_enable", "1", FCVAR_CHEAT ); static ConVar fog_startskybox( "fog_startskybox", "-1", FCVAR_CHEAT ); static ConVar fog_endskybox( "fog_endskybox", "-1", FCVAR_CHEAT ); static ConVar fog_maxdensityskybox( "fog_maxdensityskybox", "-1", FCVAR_CHEAT ); static ConVar fog_colorskybox( "fog_colorskybox", "-1 -1 -1", FCVAR_CHEAT ); static ConVar fog_enableskybox( "fog_enableskybox", "1", FCVAR_CHEAT ); static ConVar fog_maxdensity( "fog_maxdensity", "-1", FCVAR_CHEAT ); //----------------------------------------------------------------------------- // Water-related convars //----------------------------------------------------------------------------- static ConVar r_debugcheapwater( "r_debugcheapwater", "0", FCVAR_CHEAT ); #ifndef _X360 static ConVar r_waterforceexpensive( "r_waterforceexpensive", "0", FCVAR_ARCHIVE ); #endif static ConVar r_waterforcereflectentities( "r_waterforcereflectentities", "0" ); static ConVar r_WaterDrawRefraction( "r_WaterDrawRefraction", "1", 0, "Enable water refraction" ); static ConVar r_WaterDrawReflection( "r_WaterDrawReflection", "1", 0, "Enable water reflection" ); static ConVar r_ForceWaterLeaf( "r_ForceWaterLeaf", "1", 0, "Enable for optimization to water - considers view in leaf under water for purposes of culling" ); static ConVar mat_drawwater( "mat_drawwater", "1", FCVAR_CHEAT ); static ConVar mat_clipz( "mat_clipz", "1" ); //----------------------------------------------------------------------------- // Other convars //----------------------------------------------------------------------------- static ConVar r_screenfademinsize( "r_screenfademinsize", "0" ); static ConVar r_screenfademaxsize( "r_screenfademaxsize", "0" ); static ConVar cl_drawmonitors( "cl_drawmonitors", "1" ); static ConVar r_eyewaterepsilon( "r_eyewaterepsilon", "10.0f", FCVAR_CHEAT ); #ifdef TF_CLIENT_DLL static ConVar pyro_dof( "pyro_dof", "1", FCVAR_ARCHIVE ); #endif extern ConVar cl_leveloverview; extern ConVar localplayer_visionflags; //----------------------------------------------------------------------------- // Globals //----------------------------------------------------------------------------- static Vector g_vecCurrentRenderOrigin(0,0,0); static QAngle g_vecCurrentRenderAngles(0,0,0); static Vector g_vecCurrentVForward(0,0,0), g_vecCurrentVRight(0,0,0), g_vecCurrentVUp(0,0,0); static VMatrix g_matCurrentCamInverse; bool s_bCanAccessCurrentView = false; IntroData_t *g_pIntroData = NULL; static bool g_bRenderingView = false; // For debugging... static int g_CurrentViewID = VIEW_NONE; bool g_bRenderingScreenshot = false; #define FREEZECAM_SNAPSHOT_FADE_SPEED 340 float g_flFreezeFlash = 0.0f; //----------------------------------------------------------------------------- CON_COMMAND( r_cheapwaterstart, "" ) { if( args.ArgC() == 2 ) { float dist = atof( args[ 1 ] ); view->SetCheapWaterStartDistance( dist ); } else { float start, end; view->GetWaterLODParams( start, end ); Warning( "r_cheapwaterstart: %f\n", start ); } } CON_COMMAND( r_cheapwaterend, "" ) { if( args.ArgC() == 2 ) { float dist = atof( args[ 1 ] ); view->SetCheapWaterEndDistance( dist ); } else { float start, end; view->GetWaterLODParams( start, end ); Warning( "r_cheapwaterend: %f\n", end ); } } //----------------------------------------------------------------------------- // Describes a pruned set of leaves to be rendered this view. Reference counted // because potentially shared by a number of views //----------------------------------------------------------------------------- struct ClientWorldListInfo_t : public CRefCounted1<WorldListInfo_t> { ClientWorldListInfo_t() { memset( (WorldListInfo_t *)this, 0, sizeof(WorldListInfo_t) ); m_pActualLeafIndex = NULL; m_bPooledAlloc = false; } // Allocate a list intended for pruning static ClientWorldListInfo_t *AllocPooled( const ClientWorldListInfo_t &exemplar ); // Because we remap leaves to eliminate unused leaves, we need a remap // when drawing translucent surfaces, which requires the *original* leaf index // using m_pActualLeafMap[ remapped leaf index ] == actual leaf index LeafIndex_t *m_pActualLeafIndex; private: virtual bool OnFinalRelease(); bool m_bPooledAlloc; static CObjectPool<ClientWorldListInfo_t> gm_Pool; }; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class CWorldListCache { public: CWorldListCache() { } void Flush() { for ( int i = m_Entries.FirstInorder(); i != m_Entries.InvalidIndex(); i = m_Entries.NextInorder( i ) ) { delete m_Entries[i]; } m_Entries.RemoveAll(); } bool Find( const CViewSetup &viewSetup, IWorldRenderList **ppList, ClientWorldListInfo_t **ppListInfo ) { Entry_t lookup( viewSetup ); int i = m_Entries.Find( &lookup ); if ( i != m_Entries.InvalidIndex() ) { Entry_t *pEntry = m_Entries[i]; *ppList = InlineAddRef( pEntry->pList ); *ppListInfo = InlineAddRef( pEntry->pListInfo ); return true; } return false; } void Add( const CViewSetup &viewSetup, IWorldRenderList *pList, ClientWorldListInfo_t *pListInfo ) { m_Entries.Insert( new Entry_t( viewSetup, pList, pListInfo ) ); } private: struct Entry_t { Entry_t( const CViewSetup &viewSetup, IWorldRenderList *pList = NULL, ClientWorldListInfo_t *pListInfo = NULL ) : pList( ( pList ) ? InlineAddRef( pList ) : NULL ), pListInfo( ( pListInfo ) ? InlineAddRef( pListInfo ) : NULL ) { // @NOTE (toml 8/18/2006): because doing memcmp, need to fill all of the fields and the padding! memset( &m_bOrtho, 0, offsetof(Entry_t, pList ) - offsetof(Entry_t, m_bOrtho ) ); m_bOrtho = viewSetup.m_bOrtho; m_OrthoLeft = viewSetup.m_OrthoLeft; m_OrthoTop = viewSetup.m_OrthoTop; m_OrthoRight = viewSetup.m_OrthoRight; m_OrthoBottom = viewSetup.m_OrthoBottom; fov = viewSetup.fov; origin = viewSetup.origin; angles = viewSetup.angles; zNear = viewSetup.zNear; zFar = viewSetup.zFar; m_flAspectRatio = viewSetup.m_flAspectRatio; m_bOffCenter = viewSetup.m_bOffCenter; m_flOffCenterTop = viewSetup.m_flOffCenterTop; m_flOffCenterBottom = viewSetup.m_flOffCenterBottom; m_flOffCenterLeft = viewSetup.m_flOffCenterLeft; m_flOffCenterRight = viewSetup.m_flOffCenterRight; } ~Entry_t() { if ( pList ) pList->Release(); if ( pListInfo ) pListInfo->Release(); } // The fields from CViewSetup that would actually affect the list float m_OrthoLeft; float m_OrthoTop; float m_OrthoRight; float m_OrthoBottom; float fov; Vector origin; QAngle angles; float zNear; float zFar; float m_flAspectRatio; float m_flOffCenterTop; float m_flOffCenterBottom; float m_flOffCenterLeft; float m_flOffCenterRight; bool m_bOrtho; bool m_bOffCenter; IWorldRenderList *pList; ClientWorldListInfo_t *pListInfo; }; class CEntryComparator { public: CEntryComparator( int ) {} bool operator!() const { return false; } bool operator()( const Entry_t *lhs, const Entry_t *rhs ) const { return ( memcmp( lhs, rhs, sizeof(Entry_t) - ( sizeof(Entry_t) - offsetof(Entry_t, pList ) ) ) < 0 ); } }; CUtlRBTree<Entry_t *, unsigned short, CEntryComparator> m_Entries; }; CWorldListCache g_WorldListCache; //----------------------------------------------------------------------------- // Standard 3d skybox view //----------------------------------------------------------------------------- class CSkyboxView : public CRendering3dView { DECLARE_CLASS( CSkyboxView, CRendering3dView ); public: CSkyboxView(CViewRender *pMainView) : CRendering3dView( pMainView ), m_pSky3dParams( NULL ) { } bool Setup( const CViewSetup &view, int *pClearFlags, SkyboxVisibility_t *pSkyboxVisible ); void Draw(); protected: #ifdef PORTAL virtual bool ShouldDrawPortals() { return false; } #endif virtual SkyboxVisibility_t ComputeSkyboxVisibility(); bool GetSkyboxFogEnable(); void Enable3dSkyboxFog( void ); void DrawInternal( view_id_t iSkyBoxViewID = VIEW_3DSKY, bool bInvokePreAndPostRender = true, ITexture *pRenderTarget = NULL ); sky3dparams_t * PreRender3dSkyboxWorld( SkyboxVisibility_t nSkyboxVisible ); sky3dparams_t *m_pSky3dParams; }; //----------------------------------------------------------------------------- // 3d skybox view when drawing portals //----------------------------------------------------------------------------- #ifdef PORTAL class CPortalSkyboxView : public CSkyboxView { DECLARE_CLASS( CPortalSkyboxView, CSkyboxView ); public: CPortalSkyboxView(CViewRender *pMainView) : CSkyboxView( pMainView ), m_pRenderTarget( NULL ) {} bool Setup( const CViewSetup &view, int *pClearFlags, SkyboxVisibility_t *pSkyboxVisible, ITexture *pRenderTarget = NULL ); //Skybox drawing through portals with workarounds to fix area bits, position/scaling, view id's.......... void Draw(); private: virtual SkyboxVisibility_t ComputeSkyboxVisibility(); ITexture *m_pRenderTarget; }; #endif //----------------------------------------------------------------------------- // Shadow depth texture //----------------------------------------------------------------------------- class CShadowDepthView : public CRendering3dView { DECLARE_CLASS( CShadowDepthView, CRendering3dView ); public: CShadowDepthView(CViewRender *pMainView) : CRendering3dView( pMainView ) {} void Setup( const CViewSetup &shadowViewIn, ITexture *pRenderTarget, ITexture *pDepthTexture ); void Draw(); private: ITexture *m_pRenderTarget; ITexture *m_pDepthTexture; }; //----------------------------------------------------------------------------- // Freeze frame. Redraws the frame at which it was enabled. //----------------------------------------------------------------------------- class CFreezeFrameView : public CRendering3dView { DECLARE_CLASS( CFreezeFrameView, CRendering3dView ); public: CFreezeFrameView(CViewRender *pMainView) : CRendering3dView( pMainView ) {} void Setup( const CViewSetup &view ); void Draw(); private: CMaterialReference m_pFreezeFrame; CMaterialReference m_TranslucentSingleColor; }; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- class CBaseWorldView : public CRendering3dView { DECLARE_CLASS( CBaseWorldView, CRendering3dView ); protected: CBaseWorldView(CViewRender *pMainView) : CRendering3dView( pMainView ) {} virtual bool AdjustView( float waterHeight ); void DrawSetup( float waterHeight, int flags, float waterZAdjust, int iForceViewLeaf = -1 ); void DrawExecute( float waterHeight, view_id_t viewID, float waterZAdjust ); virtual void PushView( float waterHeight ); virtual void PopView(); void SSAO_DepthPass(); void DrawDepthOfField(); }; //----------------------------------------------------------------------------- // Draws the scene when there's no water or only cheap water //----------------------------------------------------------------------------- class CSimpleWorldView : public CBaseWorldView { DECLARE_CLASS( CSimpleWorldView, CBaseWorldView ); public: CSimpleWorldView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t& info, ViewCustomVisibility_t *pCustomVisibility = NULL ); void Draw(); private: VisibleFogVolumeInfo_t m_fogInfo; }; //----------------------------------------------------------------------------- // Base class for scenes with water //----------------------------------------------------------------------------- class CBaseWaterView : public CBaseWorldView { DECLARE_CLASS( CBaseWaterView, CBaseWorldView ); public: CBaseWaterView(CViewRender *pMainView) : CBaseWorldView( pMainView ), m_SoftwareIntersectionView( pMainView ) {} // void Setup( const CViewSetup &, const WaterRenderInfo_t& info ); protected: void CalcWaterEyeAdjustments( const VisibleFogVolumeInfo_t &fogInfo, float &newWaterHeight, float &waterZAdjust, bool bSoftwareUserClipPlane ); class CSoftwareIntersectionView : public CBaseWorldView { DECLARE_CLASS( CSoftwareIntersectionView, CBaseWorldView ); public: CSoftwareIntersectionView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup( bool bAboveWater ); void Draw(); private: CBaseWaterView *GetOuter() { return GET_OUTER( CBaseWaterView, m_SoftwareIntersectionView ); } }; friend class CSoftwareIntersectionView; CSoftwareIntersectionView m_SoftwareIntersectionView; WaterRenderInfo_t m_waterInfo; float m_waterHeight; float m_waterZAdjust; bool m_bSoftwareUserClipPlane; VisibleFogVolumeInfo_t m_fogInfo; }; //----------------------------------------------------------------------------- // Scenes above water //----------------------------------------------------------------------------- class CAboveWaterView : public CBaseWaterView { DECLARE_CLASS( CAboveWaterView, CBaseWaterView ); public: CAboveWaterView(CViewRender *pMainView) : CBaseWaterView( pMainView ), m_ReflectionView( pMainView ), m_RefractionView( pMainView ), m_IntersectionView( pMainView ) {} void Setup( const CViewSetup &view, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t& waterInfo ); void Draw(); class CReflectionView : public CBaseWorldView { DECLARE_CLASS( CReflectionView, CBaseWorldView ); public: CReflectionView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup( bool bReflectEntities ); void Draw(); private: CAboveWaterView *GetOuter() { return GET_OUTER( CAboveWaterView, m_ReflectionView ); } }; class CRefractionView : public CBaseWorldView { DECLARE_CLASS( CRefractionView, CBaseWorldView ); public: CRefractionView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup(); void Draw(); private: CAboveWaterView *GetOuter() { return GET_OUTER( CAboveWaterView, m_RefractionView ); } }; class CIntersectionView : public CBaseWorldView { DECLARE_CLASS( CIntersectionView, CBaseWorldView ); public: CIntersectionView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup(); void Draw(); private: CAboveWaterView *GetOuter() { return GET_OUTER( CAboveWaterView, m_IntersectionView ); } }; friend class CRefractionView; friend class CReflectionView; friend class CIntersectionView; bool m_bViewIntersectsWater; CReflectionView m_ReflectionView; CRefractionView m_RefractionView; CIntersectionView m_IntersectionView; }; //----------------------------------------------------------------------------- // Scenes below water //----------------------------------------------------------------------------- class CUnderWaterView : public CBaseWaterView { DECLARE_CLASS( CUnderWaterView, CBaseWaterView ); public: CUnderWaterView(CViewRender *pMainView) : CBaseWaterView( pMainView ), m_RefractionView( pMainView ) {} void Setup( const CViewSetup &view, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t& info ); void Draw(); class CRefractionView : public CBaseWorldView { DECLARE_CLASS( CRefractionView, CBaseWorldView ); public: CRefractionView(CViewRender *pMainView) : CBaseWorldView( pMainView ) {} void Setup(); void Draw(); private: CUnderWaterView *GetOuter() { return GET_OUTER( CUnderWaterView, m_RefractionView ); } }; friend class CRefractionView; bool m_bDrawSkybox; // @MULTICORE (toml 8/17/2006): remove after setup hoisted CRefractionView m_RefractionView; }; //----------------------------------------------------------------------------- // Scenes containing reflective glass //----------------------------------------------------------------------------- class CReflectiveGlassView : public CSimpleWorldView { DECLARE_CLASS( CReflectiveGlassView, CSimpleWorldView ); public: CReflectiveGlassView( CViewRender *pMainView ) : BaseClass( pMainView ) { } virtual bool AdjustView( float flWaterHeight ); virtual void PushView( float waterHeight ); virtual void PopView( ); void Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t &waterInfo, const cplane_t &reflectionPlane ); void Draw(); cplane_t m_ReflectionPlane; }; class CRefractiveGlassView : public CSimpleWorldView { DECLARE_CLASS( CRefractiveGlassView, CSimpleWorldView ); public: CRefractiveGlassView( CViewRender *pMainView ) : BaseClass( pMainView ) { } virtual bool AdjustView( float flWaterHeight ); virtual void PushView( float waterHeight ); virtual void PopView( ); void Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t &waterInfo, const cplane_t &reflectionPlane ); void Draw(); cplane_t m_ReflectionPlane; }; //----------------------------------------------------------------------------- // Computes draw flags for the engine to build its world surface lists //----------------------------------------------------------------------------- static inline unsigned long BuildEngineDrawWorldListFlags( unsigned nDrawFlags ) { unsigned long nEngineFlags = 0; if ( nDrawFlags & DF_DRAWSKYBOX ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_SKYBOX; } if ( nDrawFlags & DF_RENDER_ABOVEWATER ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_STRICTLYABOVEWATER; nEngineFlags |= DRAWWORLDLISTS_DRAW_INTERSECTSWATER; } if ( nDrawFlags & DF_RENDER_UNDERWATER ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_STRICTLYUNDERWATER; nEngineFlags |= DRAWWORLDLISTS_DRAW_INTERSECTSWATER; } if ( nDrawFlags & DF_RENDER_WATER ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_WATERSURFACE; } if( nDrawFlags & DF_CLIP_SKYBOX ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_CLIPSKYBOX; } if( nDrawFlags & DF_SHADOW_DEPTH_MAP ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_SHADOWDEPTH; } if( nDrawFlags & DF_RENDER_REFRACTION ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_REFRACTION; } if( nDrawFlags & DF_RENDER_REFLECTION ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_REFLECTION; } if( nDrawFlags & DF_SSAO_DEPTH_PASS ) { nEngineFlags |= DRAWWORLDLISTS_DRAW_SSAO | DRAWWORLDLISTS_DRAW_STRICTLYUNDERWATER | DRAWWORLDLISTS_DRAW_INTERSECTSWATER | DRAWWORLDLISTS_DRAW_STRICTLYABOVEWATER ; nEngineFlags &= ~( DRAWWORLDLISTS_DRAW_WATERSURFACE | DRAWWORLDLISTS_DRAW_REFRACTION | DRAWWORLDLISTS_DRAW_REFLECTION ); } return nEngineFlags; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static void SetClearColorToFogColor() { unsigned char ucFogColor[3]; CMatRenderContextPtr pRenderContext( materials ); pRenderContext->GetFogColor( ucFogColor ); if( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_INTEGER ) { // @MULTICORE (toml 8/16/2006): Find a way to not do this twice in eye above water case float scale = LinearToGammaFullRange( pRenderContext->GetToneMappingScaleLinear().x ); ucFogColor[0] *= scale; ucFogColor[1] *= scale; ucFogColor[2] *= scale; } pRenderContext->ClearColor4ub( ucFogColor[0], ucFogColor[1], ucFogColor[2], 255 ); } //----------------------------------------------------------------------------- // Precache of necessary materials //----------------------------------------------------------------------------- #ifdef HL2_CLIENT_DLL CLIENTEFFECT_REGISTER_BEGIN( PrecacheViewRender ) CLIENTEFFECT_MATERIAL( "scripted/intro_screenspaceeffect" ) CLIENTEFFECT_REGISTER_END() #endif CLIENTEFFECT_REGISTER_BEGIN( PrecachePostProcessingEffects ) CLIENTEFFECT_MATERIAL( "dev/blurfiltery_and_add_nohdr" ) CLIENTEFFECT_MATERIAL( "dev/blurfilterx" ) CLIENTEFFECT_MATERIAL( "dev/blurfilterx_nohdr" ) CLIENTEFFECT_MATERIAL( "dev/blurfiltery" ) CLIENTEFFECT_MATERIAL( "dev/blurfiltery_nohdr" ) CLIENTEFFECT_MATERIAL( "dev/bloomadd" ) CLIENTEFFECT_MATERIAL( "dev/downsample" ) #ifdef CSTRIKE_DLL CLIENTEFFECT_MATERIAL( "dev/downsample_non_hdr_cstrike" ) #else CLIENTEFFECT_MATERIAL( "dev/downsample_non_hdr" ) #endif CLIENTEFFECT_MATERIAL( "dev/no_pixel_write" ) CLIENTEFFECT_MATERIAL( "dev/lumcompare" ) CLIENTEFFECT_MATERIAL( "dev/floattoscreen_combine" ) CLIENTEFFECT_MATERIAL( "dev/copyfullframefb_vanilla" ) CLIENTEFFECT_MATERIAL( "dev/copyfullframefb" ) CLIENTEFFECT_MATERIAL( "dev/engine_post" ) CLIENTEFFECT_MATERIAL( "dev/motion_blur" ) CLIENTEFFECT_MATERIAL( "dev/upscale" ) #ifdef TF_CLIENT_DLL CLIENTEFFECT_MATERIAL( "dev/pyro_blur_filter_y" ) CLIENTEFFECT_MATERIAL( "dev/pyro_blur_filter_x" ) CLIENTEFFECT_MATERIAL( "dev/pyro_dof" ) CLIENTEFFECT_MATERIAL( "dev/pyro_vignette_border" ) CLIENTEFFECT_MATERIAL( "dev/pyro_vignette" ) CLIENTEFFECT_MATERIAL( "dev/pyro_post" ) #endif CLIENTEFFECT_REGISTER_END_CONDITIONAL( engine->GetDXSupportLevel() >= 90 ) //----------------------------------------------------------------------------- // Accessors to return the current view being rendered //----------------------------------------------------------------------------- const Vector &CurrentViewOrigin() { Assert( s_bCanAccessCurrentView ); return g_vecCurrentRenderOrigin; } const QAngle &CurrentViewAngles() { Assert( s_bCanAccessCurrentView ); return g_vecCurrentRenderAngles; } const Vector &CurrentViewForward() { Assert( s_bCanAccessCurrentView ); return g_vecCurrentVForward; } const Vector &CurrentViewRight() { Assert( s_bCanAccessCurrentView ); return g_vecCurrentVRight; } const Vector &CurrentViewUp() { Assert( s_bCanAccessCurrentView ); return g_vecCurrentVUp; } const VMatrix &CurrentWorldToViewMatrix() { Assert( s_bCanAccessCurrentView ); return g_matCurrentCamInverse; } //----------------------------------------------------------------------------- // Methods to set the current view/guard access to view parameters //----------------------------------------------------------------------------- void AllowCurrentViewAccess( bool allow ) { s_bCanAccessCurrentView = allow; } bool IsCurrentViewAccessAllowed() { return s_bCanAccessCurrentView; } void SetupCurrentView( const Vector &vecOrigin, const QAngle &angles, view_id_t viewID ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // Store off view origin and angles g_vecCurrentRenderOrigin = vecOrigin; g_vecCurrentRenderAngles = angles; // Compute the world->main camera transform ComputeCameraVariables( vecOrigin, angles, &g_vecCurrentVForward, &g_vecCurrentVRight, &g_vecCurrentVUp, &g_matCurrentCamInverse ); g_CurrentViewID = viewID; s_bCanAccessCurrentView = true; // Cache off fade distances float flScreenFadeMinSize, flScreenFadeMaxSize; view->GetScreenFadeDistances( &flScreenFadeMinSize, &flScreenFadeMaxSize ); modelinfo->SetViewScreenFadeRange( flScreenFadeMinSize, flScreenFadeMaxSize ); CMatRenderContextPtr pRenderContext( materials ); #ifdef PORTAL if ( g_pPortalRender->GetViewRecursionLevel() == 0 ) { pRenderContext->SetIntRenderingParameter( INT_RENDERPARM_WRITE_DEPTH_TO_DESTALPHA, ((viewID == VIEW_MAIN) || (viewID == VIEW_3DSKY)) ? 1 : 0 ); } #else pRenderContext->SetIntRenderingParameter( INT_RENDERPARM_WRITE_DEPTH_TO_DESTALPHA, ((viewID == VIEW_MAIN) || (viewID == VIEW_3DSKY)) ? 1 : 0 ); #endif } view_id_t CurrentViewID() { Assert( g_CurrentViewID != VIEW_ILLEGAL ); return ( view_id_t )g_CurrentViewID; } //----------------------------------------------------------------------------- // Purpose: Portal views are considered 'Main' views. This function tests a view id // against all view ids used by portal renderables, as well as the main view. //----------------------------------------------------------------------------- bool IsMainView ( view_id_t id ) { #if defined(PORTAL) return ( (id == VIEW_MAIN) || g_pPortalRender->IsPortalViewID( id ) ); #else return (id == VIEW_MAIN); #endif } void FinishCurrentView() { s_bCanAccessCurrentView = false; } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- void CSimpleRenderExecutor::AddView( CRendering3dView *pView ) { CBase3dView *pPrevRenderer = m_pMainView->SetActiveRenderer( pView ); pView->Draw(); m_pMainView->SetActiveRenderer( pPrevRenderer ); } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CViewRender::CViewRender() : m_SimpleExecutor( this ) { m_flCheapWaterStartDistance = 0.0f; m_flCheapWaterEndDistance = 0.1f; m_BaseDrawFlags = 0; m_pActiveRenderer = NULL; m_pCurrentlyDrawingEntity = NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- inline bool CViewRender::ShouldDrawEntities( void ) { return ( !m_pDrawEntities || (m_pDrawEntities->GetInt() != 0) ); } //----------------------------------------------------------------------------- // Purpose: Check all conditions which would prevent drawing the view model // Input : drawViewmodel - // *viewmodel - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CViewRender::ShouldDrawViewModel( bool bDrawViewmodel ) { if ( !bDrawViewmodel ) return false; if ( !r_drawviewmodel.GetBool() ) return false; if ( C_BasePlayer::ShouldDrawLocalPlayer() ) return false; if ( !ShouldDrawEntities() ) return false; if ( render->GetViewEntity() > gpGlobals->maxClients ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CViewRender::UpdateRefractIfNeededByList( CUtlVector< IClientRenderable * > &list ) { int nCount = list.Count(); for( int i=0; i < nCount; ++i ) { IClientUnknown *pUnk = list[i]->GetIClientUnknown(); Assert( pUnk ); IClientRenderable *pRenderable = pUnk->GetClientRenderable(); Assert( pRenderable ); if ( pRenderable->UsesPowerOfTwoFrameBufferTexture() ) { UpdateRefractTexture(); return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CViewRender::DrawRenderablesInList( CUtlVector< IClientRenderable * > &list, int flags ) { Assert( m_pCurrentlyDrawingEntity == NULL ); int nCount = list.Count(); for( int i=0; i < nCount; ++i ) { IClientUnknown *pUnk = list[i]->GetIClientUnknown(); Assert( pUnk ); IClientRenderable *pRenderable = pUnk->GetClientRenderable(); Assert( pRenderable ); // Non-view models wanting to render in view model list... if ( pRenderable->ShouldDraw() ) { m_pCurrentlyDrawingEntity = pUnk->GetBaseEntity(); pRenderable->DrawModel( STUDIO_RENDER | flags ); } } m_pCurrentlyDrawingEntity = NULL; } //----------------------------------------------------------------------------- // Purpose: Actually draw the view model // Input : drawViewModel - //----------------------------------------------------------------------------- void CViewRender::DrawViewModels( const CViewSetup &view, bool drawViewmodel ) { VPROF( "CViewRender::DrawViewModel" ); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); #ifdef PORTAL //in portal, we'd like a copy of the front buffer without the gun in it for use with the depth doubler g_pPortalRender->UpdateDepthDoublerTexture( view ); #endif bool bShouldDrawPlayerViewModel = ShouldDrawViewModel( drawViewmodel ); bool bShouldDrawToolViewModels = ToolsEnabled(); CMatRenderContextPtr pRenderContext( materials ); PIXEVENT( pRenderContext, "DrawViewModels" ); // Restore the matrices pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PushMatrix(); CViewSetup viewModelSetup( view ); viewModelSetup.zNear = view.zNearViewmodel; viewModelSetup.zFar = view.zFarViewmodel; viewModelSetup.fov = view.fovViewmodel; viewModelSetup.m_flAspectRatio = engine->GetScreenAspectRatio(); render->Push3DView( viewModelSetup, 0, NULL, GetFrustum() ); #ifdef PORTAL //the depth range hack doesn't work well enough for the portal mod (and messing with the depth hack values makes some models draw incorrectly) //step up to a full depth clear if we're extremely close to a portal (in a portal environment) extern bool LocalPlayerIsCloseToPortal( void ); //defined in C_Portal_Player.cpp, abstracting to a single bool function to remove explicit dependence on c_portal_player.h/cpp, you can define the function as a "return true" in other build configurations at the cost of some perf bool bUseDepthHack = !LocalPlayerIsCloseToPortal(); if( !bUseDepthHack ) pRenderContext->ClearBuffers( false, true, false ); #else const bool bUseDepthHack = true; #endif // FIXME: Add code to read the current depth range float depthmin = 0.0f; float depthmax = 1.0f; // HACK HACK: Munge the depth range to prevent view model from poking into walls, etc. // Force clipped down range if( bUseDepthHack ) pRenderContext->DepthRange( 0.0f, 0.1f ); if ( bShouldDrawPlayerViewModel || bShouldDrawToolViewModels ) { CUtlVector< IClientRenderable * > opaqueViewModelList( 32 ); CUtlVector< IClientRenderable * > translucentViewModelList( 32 ); ClientLeafSystem()->CollateViewModelRenderables( opaqueViewModelList, translucentViewModelList ); if ( ToolsEnabled() && ( !bShouldDrawPlayerViewModel || !bShouldDrawToolViewModels ) ) { int nOpaque = opaqueViewModelList.Count(); for ( int i = nOpaque-1; i >= 0; --i ) { IClientRenderable *pRenderable = opaqueViewModelList[ i ]; bool bEntity = pRenderable->GetIClientUnknown()->GetBaseEntity(); if ( ( bEntity && !bShouldDrawPlayerViewModel ) || ( !bEntity && !bShouldDrawToolViewModels ) ) { opaqueViewModelList.FastRemove( i ); } } int nTranslucent = translucentViewModelList.Count(); for ( int i = nTranslucent-1; i >= 0; --i ) { IClientRenderable *pRenderable = translucentViewModelList[ i ]; bool bEntity = pRenderable->GetIClientUnknown()->GetBaseEntity(); if ( ( bEntity && !bShouldDrawPlayerViewModel ) || ( !bEntity && !bShouldDrawToolViewModels ) ) { translucentViewModelList.FastRemove( i ); } } } if ( !UpdateRefractIfNeededByList( opaqueViewModelList ) ) { UpdateRefractIfNeededByList( translucentViewModelList ); } DrawRenderablesInList( opaqueViewModelList ); DrawRenderablesInList( translucentViewModelList, STUDIO_TRANSPARENCY ); } // Reset the depth range to the original values if( bUseDepthHack ) pRenderContext->DepthRange( depthmin, depthmax ); render->PopView( GetFrustum() ); // Restore the matrices pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PopMatrix(); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CViewRender::ShouldDrawBrushModels( void ) { if ( m_pDrawBrushModels && !m_pDrawBrushModels->GetInt() ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Performs screen space effects, if any //----------------------------------------------------------------------------- void CViewRender::PerformScreenSpaceEffects( int x, int y, int w, int h ) { VPROF("CViewRender::PerformScreenSpaceEffects()"); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // FIXME: Screen-space effects are busted in the editor if ( engine->IsHammerRunning() ) return; g_pScreenSpaceEffects->RenderEffects( x, y, w, h ); } //----------------------------------------------------------------------------- // Purpose: Sets the screen space effect material (can't be done during rendering) //----------------------------------------------------------------------------- void CViewRender::SetScreenOverlayMaterial( IMaterial *pMaterial ) { m_ScreenOverlayMaterial.Init( pMaterial ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- IMaterial *CViewRender::GetScreenOverlayMaterial( ) { return m_ScreenOverlayMaterial; } //----------------------------------------------------------------------------- // Purpose: Performs screen space effects, if any //----------------------------------------------------------------------------- void CViewRender::PerformScreenOverlay( int x, int y, int w, int h ) { VPROF("CViewRender::PerformScreenOverlay()"); if (m_ScreenOverlayMaterial) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); if ( m_ScreenOverlayMaterial->NeedsFullFrameBufferTexture() ) { // FIXME: check with multi/sub-rect renders. Should this be 0,0,w,h instead? DrawScreenEffectMaterial( m_ScreenOverlayMaterial, x, y, w, h ); } else if ( m_ScreenOverlayMaterial->NeedsPowerOfTwoFrameBufferTexture() ) { // First copy the FB off to the offscreen texture UpdateRefractTexture( x, y, w, h, true ); // Now draw the entire screen using the material... CMatRenderContextPtr pRenderContext( materials ); ITexture *pTexture = GetPowerOfTwoFrameBufferTexture( ); int sw = pTexture->GetActualWidth(); int sh = pTexture->GetActualHeight(); // Note - don't offset by x,y - already done by the viewport. pRenderContext->DrawScreenSpaceRectangle( m_ScreenOverlayMaterial, 0, 0, w, h, 0, 0, sw-1, sh-1, sw, sh ); } else { byte color[4] = { 255, 255, 255, 255 }; render->ViewDrawFade( color, m_ScreenOverlayMaterial ); } } } void CViewRender::DrawUnderwaterOverlay( void ) { IMaterial *pOverlayMat = m_UnderWaterOverlayMaterial; if ( pOverlayMat ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); CMatRenderContextPtr pRenderContext( materials ); int x, y, w, h; pRenderContext->GetViewport( x, y, w, h ); if ( pOverlayMat->NeedsFullFrameBufferTexture() ) { // FIXME: check with multi/sub-rect renders. Should this be 0,0,w,h instead? DrawScreenEffectMaterial( pOverlayMat, x, y, w, h ); } else if ( pOverlayMat->NeedsPowerOfTwoFrameBufferTexture() ) { // First copy the FB off to the offscreen texture UpdateRefractTexture( x, y, w, h, true ); // Now draw the entire screen using the material... CMatRenderContextPtr pRenderContext( materials ); ITexture *pTexture = GetPowerOfTwoFrameBufferTexture( ); int sw = pTexture->GetActualWidth(); int sh = pTexture->GetActualHeight(); // Note - don't offset by x,y - already done by the viewport. pRenderContext->DrawScreenSpaceRectangle( pOverlayMat, 0, 0, w, h, 0, 0, sw-1, sh-1, sw, sh ); } else { // Note - don't offset by x,y - already done by the viewport. // FIXME: actually test this code path. pRenderContext->DrawScreenSpaceRectangle( pOverlayMat, 0, 0, w, h, 0, 0, 1, 1, 1, 1 ); } } } //----------------------------------------------------------------------------- // Purpose: Returns the min/max fade distances //----------------------------------------------------------------------------- void CViewRender::GetScreenFadeDistances( float *min, float *max ) { if ( min ) { *min = r_screenfademinsize.GetFloat(); } if ( max ) { *max = r_screenfademaxsize.GetFloat(); } } C_BaseEntity *CViewRender::GetCurrentlyDrawingEntity() { return m_pCurrentlyDrawingEntity; } void CViewRender::SetCurrentlyDrawingEntity( C_BaseEntity *pEnt ) { m_pCurrentlyDrawingEntity = pEnt; } bool CViewRender::UpdateShadowDepthTexture( ITexture *pRenderTarget, ITexture *pDepthTexture, const CViewSetup &shadowViewIn ) { VPROF_INCREMENT_COUNTER( "shadow depth textures rendered", 1 ); CMatRenderContextPtr pRenderContext( materials ); char szPIXEventName[128]; sprintf( szPIXEventName, "UpdateShadowDepthTexture (%s)", pDepthTexture->GetName() ); PIXEVENT( pRenderContext, szPIXEventName ); CRefPtr<CShadowDepthView> pShadowDepthView = new CShadowDepthView( this ); pShadowDepthView->Setup( shadowViewIn, pRenderTarget, pDepthTexture ); AddViewToScene( pShadowDepthView ); return true; } //----------------------------------------------------------------------------- // Purpose: Renders world and all entities, etc. //----------------------------------------------------------------------------- void CViewRender::ViewDrawScene( bool bDrew3dSkybox, SkyboxVisibility_t nSkyboxVisible, const CViewSetup &view, int nClearFlags, view_id_t viewID, bool bDrawViewModel, int baseDrawFlags, ViewCustomVisibility_t *pCustomVisibility ) { VPROF( "CViewRender::ViewDrawScene" ); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // this allows the refract texture to be updated once per *scene* on 360 // (e.g. once for a monitor scene and once for the main scene) g_viewscene_refractUpdateFrame = gpGlobals->framecount - 1; g_pClientShadowMgr->PreRender(); // Shadowed flashlights supported on ps_2_b and up... if ( r_flashlightdepthtexture.GetBool() && (viewID == VIEW_MAIN) ) { g_pClientShadowMgr->ComputeShadowDepthTextures( view ); } m_BaseDrawFlags = baseDrawFlags; SetupCurrentView( view.origin, view.angles, viewID ); // Invoke pre-render methods IGameSystem::PreRenderAllSystems(); // Start view unsigned int visFlags; SetupVis( view, visFlags, pCustomVisibility ); if ( !bDrew3dSkybox && ( nSkyboxVisible == SKYBOX_NOT_VISIBLE ) && ( visFlags & IVRenderView::VIEW_SETUP_VIS_EX_RETURN_FLAGS_USES_RADIAL_VIS ) ) { // This covers the case where we don't see a 3dskybox, yet radial vis is clipping // the far plane. Need to clear to fog color in this case. nClearFlags |= VIEW_CLEAR_COLOR; SetClearColorToFogColor( ); } bool drawSkybox = r_skybox.GetBool(); if ( bDrew3dSkybox || ( nSkyboxVisible == SKYBOX_NOT_VISIBLE ) ) { drawSkybox = false; } ParticleMgr()->IncrementFrameCode(); DrawWorldAndEntities( drawSkybox, view, nClearFlags, pCustomVisibility ); // Disable fog for the rest of the stuff DisableFog(); // UNDONE: Don't do this with masked brush models, they should probably be in a separate list // render->DrawMaskEntities() // Here are the overlays... CGlowOverlay::DrawOverlays( view.m_bCacheFullSceneState ); // issue the pixel visibility tests if ( IsMainView( CurrentViewID() ) ) { PixelVisibility_EndCurrentView(); } // Draw rain.. DrawPrecipitation(); // Make sure sound doesn't stutter engine->Sound_ExtraUpdate(); // Debugging info goes over the top CDebugViewRender::Draw3DDebuggingInfo( view ); // Draw client side effects // NOTE: These are not sorted against the rest of the frame clienteffects->DrawEffects( gpGlobals->frametime ); // Mark the frame as locked down for client fx additions SetFXCreationAllowed( false ); // Invoke post-render methods IGameSystem::PostRenderAllSystems(); FinishCurrentView(); // Free shadow depth textures for use in future view if ( r_flashlightdepthtexture.GetBool() ) { g_pClientShadowMgr->UnlockAllShadowDepthTextures(); } } void CheckAndTransitionColor( float flPercent, float *pColor, float *pLerpToColor ) { if ( pLerpToColor[0] != pColor[0] || pLerpToColor[1] != pColor[1] || pLerpToColor[2] != pColor[2] ) { float flDestColor[3]; flDestColor[0] = pLerpToColor[0]; flDestColor[1] = pLerpToColor[1]; flDestColor[2] = pLerpToColor[2]; pColor[0] = FLerp( pColor[0], flDestColor[0], flPercent ); pColor[1] = FLerp( pColor[1], flDestColor[1], flPercent ); pColor[2] = FLerp( pColor[2], flDestColor[2], flPercent ); } else { pColor[0] = pLerpToColor[0]; pColor[1] = pLerpToColor[1]; pColor[2] = pLerpToColor[2]; } } static void GetFogColorTransition( fogparams_t *pFogParams, float *pColorPrimary, float *pColorSecondary ) { if ( !pFogParams ) return; if ( pFogParams->lerptime >= gpGlobals->curtime ) { float flPercent = 1.0f - (( pFogParams->lerptime - gpGlobals->curtime ) / pFogParams->duration ); float flPrimaryColorLerp[3] = { pFogParams->colorPrimaryLerpTo.GetR(), pFogParams->colorPrimaryLerpTo.GetG(), pFogParams->colorPrimaryLerpTo.GetB() }; float flSecondaryColorLerp[3] = { pFogParams->colorSecondaryLerpTo.GetR(), pFogParams->colorSecondaryLerpTo.GetG(), pFogParams->colorSecondaryLerpTo.GetB() }; CheckAndTransitionColor( flPercent, pColorPrimary, flPrimaryColorLerp ); CheckAndTransitionColor( flPercent, pColorSecondary, flSecondaryColorLerp ); } } //----------------------------------------------------------------------------- // Purpose: Returns the fog color to use in rendering the current frame. //----------------------------------------------------------------------------- static void GetFogColor( fogparams_t *pFogParams, float *pColor ) { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if ( !pbp || !pFogParams ) return; const char *fogColorString = fog_color.GetString(); if( fog_override.GetInt() && fogColorString ) { sscanf( fogColorString, "%f%f%f", pColor, pColor+1, pColor+2 ); } else { float flPrimaryColor[3] = { pFogParams->colorPrimary.GetR(), pFogParams->colorPrimary.GetG(), pFogParams->colorPrimary.GetB() }; float flSecondaryColor[3] = { pFogParams->colorSecondary.GetR(), pFogParams->colorSecondary.GetG(), pFogParams->colorSecondary.GetB() }; GetFogColorTransition( pFogParams, flPrimaryColor, flSecondaryColor ); if( pFogParams->blend ) { // // Blend between two fog colors based on viewing angle. // The secondary fog color is at 180 degrees to the primary fog color. // Vector forward; pbp->EyeVectors( &forward, NULL, NULL ); Vector vNormalized = pFogParams->dirPrimary; VectorNormalize( vNormalized ); pFogParams->dirPrimary = vNormalized; float flBlendFactor = 0.5 * forward.Dot( pFogParams->dirPrimary ) + 0.5; // FIXME: convert to linear colorspace pColor[0] = flPrimaryColor[0] * flBlendFactor + flSecondaryColor[0] * ( 1 - flBlendFactor ); pColor[1] = flPrimaryColor[1] * flBlendFactor + flSecondaryColor[1] * ( 1 - flBlendFactor ); pColor[2] = flPrimaryColor[2] * flBlendFactor + flSecondaryColor[2] * ( 1 - flBlendFactor ); } else { pColor[0] = flPrimaryColor[0]; pColor[1] = flPrimaryColor[1]; pColor[2] = flPrimaryColor[2]; } } VectorScale( pColor, 1.0f / 255.0f, pColor ); } static float GetFogStart( fogparams_t *pFogParams ) { if( !pFogParams ) return 0.0f; if( fog_override.GetInt() ) { if( fog_start.GetFloat() == -1.0f ) { return pFogParams->start; } else { return fog_start.GetFloat(); } } else { if ( pFogParams->lerptime > gpGlobals->curtime ) { if ( pFogParams->start != pFogParams->startLerpTo ) { if ( pFogParams->lerptime > gpGlobals->curtime ) { float flPercent = 1.0f - (( pFogParams->lerptime - gpGlobals->curtime ) / pFogParams->duration ); return FLerp( pFogParams->start, pFogParams->startLerpTo, flPercent ); } else { if ( pFogParams->start != pFogParams->startLerpTo ) { pFogParams->start = pFogParams->startLerpTo; } } } } return pFogParams->start; } } static float GetFogEnd( fogparams_t *pFogParams ) { if( !pFogParams ) return 0.0f; if( fog_override.GetInt() ) { if( fog_end.GetFloat() == -1.0f ) { return pFogParams->end; } else { return fog_end.GetFloat(); } } else { if ( pFogParams->lerptime > gpGlobals->curtime ) { if ( pFogParams->end != pFogParams->endLerpTo ) { if ( pFogParams->lerptime > gpGlobals->curtime ) { float flPercent = 1.0f - (( pFogParams->lerptime - gpGlobals->curtime ) / pFogParams->duration ); return FLerp( pFogParams->end, pFogParams->endLerpTo, flPercent ); } else { if ( pFogParams->end != pFogParams->endLerpTo ) { pFogParams->end = pFogParams->endLerpTo; } } } } return pFogParams->end; } } static bool GetFogEnable( fogparams_t *pFogParams ) { if ( cl_leveloverview.GetFloat() > 0 ) return false; // Ask the clientmode if ( g_pClientMode->ShouldDrawFog() == false ) return false; if( fog_override.GetInt() ) { if( fog_enable.GetInt() ) { return true; } else { return false; } } else { if( pFogParams ) return pFogParams->enable != false; return false; } } static float GetFogMaxDensity( fogparams_t *pFogParams ) { if( !pFogParams ) return 1.0f; if ( cl_leveloverview.GetFloat() > 0 ) return 1.0f; // Ask the clientmode if ( !g_pClientMode->ShouldDrawFog() ) return 1.0f; if ( fog_override.GetInt() ) { if ( fog_maxdensity.GetFloat() == -1.0f ) return pFogParams->maxdensity; else return fog_maxdensity.GetFloat(); } else return pFogParams->maxdensity; } //----------------------------------------------------------------------------- // Purpose: Returns the skybox fog color to use in rendering the current frame. //----------------------------------------------------------------------------- static void GetSkyboxFogColor( float *pColor ) { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if( !pbp ) { return; } CPlayerLocalData *local = &pbp->m_Local; const char *fogColorString = fog_colorskybox.GetString(); if( fog_override.GetInt() && fogColorString ) { sscanf( fogColorString, "%f%f%f", pColor, pColor+1, pColor+2 ); } else { if( local->m_skybox3d.fog.blend ) { // // Blend between two fog colors based on viewing angle. // The secondary fog color is at 180 degrees to the primary fog color. // Vector forward; pbp->EyeVectors( &forward, NULL, NULL ); Vector vNormalized = local->m_skybox3d.fog.dirPrimary; VectorNormalize( vNormalized ); local->m_skybox3d.fog.dirPrimary = vNormalized; float flBlendFactor = 0.5 * forward.Dot( local->m_skybox3d.fog.dirPrimary ) + 0.5; // FIXME: convert to linear colorspace pColor[0] = local->m_skybox3d.fog.colorPrimary.GetR() * flBlendFactor + local->m_skybox3d.fog.colorSecondary.GetR() * ( 1 - flBlendFactor ); pColor[1] = local->m_skybox3d.fog.colorPrimary.GetG() * flBlendFactor + local->m_skybox3d.fog.colorSecondary.GetG() * ( 1 - flBlendFactor ); pColor[2] = local->m_skybox3d.fog.colorPrimary.GetB() * flBlendFactor + local->m_skybox3d.fog.colorSecondary.GetB() * ( 1 - flBlendFactor ); } else { pColor[0] = local->m_skybox3d.fog.colorPrimary.GetR(); pColor[1] = local->m_skybox3d.fog.colorPrimary.GetG(); pColor[2] = local->m_skybox3d.fog.colorPrimary.GetB(); } } VectorScale( pColor, 1.0f / 255.0f, pColor ); } static float GetSkyboxFogStart( void ) { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if( !pbp ) { return 0.0f; } CPlayerLocalData *local = &pbp->m_Local; if( fog_override.GetInt() ) { if( fog_startskybox.GetFloat() == -1.0f ) { return local->m_skybox3d.fog.start; } else { return fog_startskybox.GetFloat(); } } else { return local->m_skybox3d.fog.start; } } static float GetSkyboxFogEnd( void ) { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if( !pbp ) { return 0.0f; } CPlayerLocalData *local = &pbp->m_Local; if( fog_override.GetInt() ) { if( fog_endskybox.GetFloat() == -1.0f ) { return local->m_skybox3d.fog.end; } else { return fog_endskybox.GetFloat(); } } else { return local->m_skybox3d.fog.end; } } static float GetSkyboxFogMaxDensity() { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if ( !pbp ) return 1.0f; CPlayerLocalData *local = &pbp->m_Local; if ( cl_leveloverview.GetFloat() > 0 ) return 1.0f; // Ask the clientmode if ( !g_pClientMode->ShouldDrawFog() ) return 1.0f; if ( fog_override.GetInt() ) { if ( fog_maxdensityskybox.GetFloat() == -1.0f ) return local->m_skybox3d.fog.maxdensity; else return fog_maxdensityskybox.GetFloat(); } else return local->m_skybox3d.fog.maxdensity; } void CViewRender::DisableFog( void ) { VPROF("CViewRander::DisableFog()"); CMatRenderContextPtr pRenderContext( materials ); pRenderContext->FogMode( MATERIAL_FOG_NONE ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CViewRender::SetupVis( const CViewSetup& view, unsigned int &visFlags, ViewCustomVisibility_t *pCustomVisibility ) { VPROF( "CViewRender::SetupVis" ); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); if ( pCustomVisibility && pCustomVisibility->m_nNumVisOrigins ) { // Pass array or vis origins to merge render->ViewSetupVisEx( ShouldForceNoVis(), pCustomVisibility->m_nNumVisOrigins, pCustomVisibility->m_rgVisOrigins, visFlags ); } else { // Use render origin as vis origin by default render->ViewSetupVisEx( ShouldForceNoVis(), 1, &view.origin, visFlags ); } } //----------------------------------------------------------------------------- // Purpose: Renders voice feedback and other sprites attached to players // Input : none //----------------------------------------------------------------------------- void CViewRender::RenderPlayerSprites() { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); GetClientVoiceMgr()->DrawHeadLabels(); } //----------------------------------------------------------------------------- // Sets up, cleans up the main 3D view //----------------------------------------------------------------------------- void CViewRender::SetupMain3DView( const CViewSetup &view, int &nClearFlags ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // FIXME: I really want these fields removed from CViewSetup // and passed in as independent flags // Clear the color here if requested. int nDepthStencilFlags = nClearFlags & ( VIEW_CLEAR_DEPTH | VIEW_CLEAR_STENCIL ); nClearFlags &= ~( nDepthStencilFlags ); // Clear these flags if ( nClearFlags & VIEW_CLEAR_COLOR ) { nClearFlags |= nDepthStencilFlags; // Add them back in if we're clearing color } // If we are using HDR, we render to the HDR full frame buffer texture // instead of whatever was previously the render target if( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_FLOAT ) { render->Push3DView( view, nClearFlags, GetFullFrameFrameBufferTexture( 0 ), GetFrustum() ); } else { render->Push3DView( view, nClearFlags, NULL, GetFrustum() ); } // If we didn't clear the depth here, we'll need to clear it later nClearFlags ^= nDepthStencilFlags; // Toggle these bits if ( nClearFlags & VIEW_CLEAR_COLOR ) { // If we cleared the color here, we don't need to clear it later nClearFlags &= ~( VIEW_CLEAR_COLOR | VIEW_CLEAR_FULL_TARGET ); } } void CViewRender::CleanupMain3DView( const CViewSetup &view ) { render->PopView( GetFrustum() ); } //----------------------------------------------------------------------------- // Queues up an overlay rendering //----------------------------------------------------------------------------- void CViewRender::QueueOverlayRenderView( const CViewSetup &view, int nClearFlags, int whatToDraw ) { // Can't have 2 in a single scene Assert( !m_bDrawOverlay ); m_bDrawOverlay = true; m_OverlayViewSetup = view; m_OverlayClearFlags = nClearFlags; m_OverlayDrawFlags = whatToDraw; } //----------------------------------------------------------------------------- // Purpose: Force the view to freeze on the next frame for the specified time //----------------------------------------------------------------------------- void CViewRender::FreezeFrame( float flFreezeTime ) { if ( flFreezeTime == 0 ) { m_flFreezeFrameUntil = 0; for( int i=0; i < STEREO_EYE_MAX; i++ ) { m_rbTakeFreezeFrame[ i ] = false; } } else { if ( m_flFreezeFrameUntil > gpGlobals->curtime ) { m_flFreezeFrameUntil += flFreezeTime; } else { m_flFreezeFrameUntil = gpGlobals->curtime + flFreezeTime; for( int i=GetFirstEye(); i <= GetLastEye(); i++ ) { m_rbTakeFreezeFrame[ i ] = true; } } } } const char *COM_GetModDirectory(); //----------------------------------------------------------------------------- // Purpose: This renders the entire 3D view and the in-game hud/viewmodel // Input : &view - // whatToDraw - //----------------------------------------------------------------------------- // This renders the entire 3D view. void CViewRender::RenderView( const CViewSetup &view, int nClearFlags, int whatToDraw ) { m_UnderWaterOverlayMaterial.Shutdown(); // underwater view will set m_CurrentView = view; C_BaseAnimating::AutoAllowBoneAccess boneaccess( true, true ); VPROF( "CViewRender::RenderView" ); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // Don't want TF2 running less than DX 8 if ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() < 80 ) { // We know they were running at least 8.0 when the game started...we check the // value in ClientDLL_Init()...so they must be messing with their DirectX settings. if ( ( Q_stricmp( COM_GetModDirectory(), "tf" ) == 0 ) || ( Q_stricmp( COM_GetModDirectory(), "tf_beta" ) == 0 ) ) { static bool bFirstTime = true; if ( bFirstTime ) { bFirstTime = false; Msg( "This game has a minimum requirement of DirectX 8.0 to run properly.\n" ); } return; } } CMatRenderContextPtr pRenderContext( materials ); ITexture *saveRenderTarget = pRenderContext->GetRenderTarget(); pRenderContext.SafeRelease(); // don't want to hold for long periods in case in a locking active share thread mode if ( !m_rbTakeFreezeFrame[ view.m_eStereoEye ] && m_flFreezeFrameUntil > gpGlobals->curtime ) { CRefPtr<CFreezeFrameView> pFreezeFrameView = new CFreezeFrameView( this ); pFreezeFrameView->Setup( view ); AddViewToScene( pFreezeFrameView ); g_bRenderingView = true; s_bCanAccessCurrentView = true; } else { g_flFreezeFlash = 0.0f; g_pClientShadowMgr->AdvanceFrame(); #ifdef USE_MONITORS if ( cl_drawmonitors.GetBool() && ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() >= 70 ) && ( ( whatToDraw & RENDERVIEW_SUPPRESSMONITORRENDERING ) == 0 ) ) { CViewSetup viewMiddle = GetView( STEREO_EYE_MONO ); DrawMonitors( viewMiddle ); } #endif g_bRenderingView = true; // Must be first render->SceneBegin(); pRenderContext.GetFrom( materials ); pRenderContext->TurnOnToneMapping(); pRenderContext.SafeRelease(); // clear happens here probably SetupMain3DView( view, nClearFlags ); bool bDrew3dSkybox = false; SkyboxVisibility_t nSkyboxVisible = SKYBOX_NOT_VISIBLE; // if the 3d skybox world is drawn, then don't draw the normal skybox CSkyboxView *pSkyView = new CSkyboxView( this ); if ( ( bDrew3dSkybox = pSkyView->Setup( view, &nClearFlags, &nSkyboxVisible ) ) != false ) { AddViewToScene( pSkyView ); } SafeRelease( pSkyView ); // Force it to clear the framebuffer if they're in solid space. if ( ( nClearFlags & VIEW_CLEAR_COLOR ) == 0 ) { if ( enginetrace->GetPointContents( view.origin ) == CONTENTS_SOLID ) { nClearFlags |= VIEW_CLEAR_COLOR; } } // Render world and all entities, particles, etc. if( !g_pIntroData ) { ViewDrawScene( bDrew3dSkybox, nSkyboxVisible, view, nClearFlags, VIEW_MAIN, whatToDraw & RENDERVIEW_DRAWVIEWMODEL ); } else { ViewDrawScene_Intro( view, nClearFlags, *g_pIntroData ); } // We can still use the 'current view' stuff set up in ViewDrawScene s_bCanAccessCurrentView = true; engine->DrawPortals(); DisableFog(); // Finish scene render->SceneEnd(); // Draw lightsources if enabled render->DrawLights(); RenderPlayerSprites(); // Image-space motion blur if ( !building_cubemaps.GetBool() && view.m_bDoBloomAndToneMapping ) // We probably should use a different view. variable here { if ( ( mat_motion_blur_enabled.GetInt() ) && ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() >= 90 ) ) { pRenderContext.GetFrom( materials ); { PIXEVENT( pRenderContext, "DoImageSpaceMotionBlur" ); DoImageSpaceMotionBlur( view, view.x, view.y, view.width, view.height ); } pRenderContext.SafeRelease(); } } GetClientModeNormal()->DoPostScreenSpaceEffects( &view ); // Now actually draw the viewmodel DrawViewModels( view, whatToDraw & RENDERVIEW_DRAWVIEWMODEL ); DrawUnderwaterOverlay(); PixelVisibility_EndScene(); // Draw fade over entire screen if needed byte color[4]; bool blend; vieweffects->GetFadeParams( &color[0], &color[1], &color[2], &color[3], &blend ); // Draw an overlay to make it even harder to see inside smoke particle systems. DrawSmokeFogOverlay(); // Overlay screen fade on entire screen IMaterial* pMaterial = blend ? m_ModulateSingleColor : m_TranslucentSingleColor; render->ViewDrawFade( color, pMaterial ); PerformScreenOverlay( view.x, view.y, view.width, view.height ); // Prevent sound stutter if going slow engine->Sound_ExtraUpdate(); if ( !building_cubemaps.GetBool() && view.m_bDoBloomAndToneMapping ) { pRenderContext.GetFrom( materials ); { PIXEVENT( pRenderContext, "DoEnginePostProcessing" ); bool bFlashlightIsOn = false; C_BasePlayer *pLocal = C_BasePlayer::GetLocalPlayer(); if ( pLocal ) { bFlashlightIsOn = pLocal->IsEffectActive( EF_DIMLIGHT ); } DoEnginePostProcessing( view.x, view.y, view.width, view.height, bFlashlightIsOn ); } pRenderContext.SafeRelease(); } // And here are the screen-space effects if ( IsPC() ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "GrabPreColorCorrectedFrame" ); // Grab the pre-color corrected frame for editing purposes engine->GrabPreColorCorrectedFrame( view.x, view.y, view.width, view.height ); } PerformScreenSpaceEffects( 0, 0, view.width, view.height ); if ( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_INTEGER ) { pRenderContext.GetFrom( materials ); pRenderContext->SetToneMappingScaleLinear(Vector(1,1,1)); pRenderContext.SafeRelease(); } CleanupMain3DView( view ); if ( m_rbTakeFreezeFrame[ view.m_eStereoEye ] ) { Rect_t rect; rect.x = view.x; rect.y = view.y; rect.width = view.width; rect.height = view.height; pRenderContext = materials->GetRenderContext(); if ( IsX360() ) { // 360 doesn't create the Fullscreen texture pRenderContext->CopyRenderTargetToTextureEx( GetFullFrameFrameBufferTexture( 1 ), 0, &rect, &rect ); } else { pRenderContext->CopyRenderTargetToTextureEx( GetFullscreenTexture(), 0, &rect, &rect ); } pRenderContext.SafeRelease(); m_rbTakeFreezeFrame[ view.m_eStereoEye ] = false; } pRenderContext = materials->GetRenderContext(); pRenderContext->SetRenderTarget( saveRenderTarget ); pRenderContext.SafeRelease(); // Draw the overlay if ( m_bDrawOverlay ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "DrawOverlay" ); // This allows us to be ok if there are nested overlay views CViewSetup currentView = m_CurrentView; CViewSetup tempView = m_OverlayViewSetup; tempView.fov = ScaleFOVByWidthRatio( tempView.fov, tempView.m_flAspectRatio / ( 4.0f / 3.0f ) ); tempView.m_bDoBloomAndToneMapping = false; // FIXME: Hack to get Mark up and running m_bDrawOverlay = false; RenderView( tempView, m_OverlayClearFlags, m_OverlayDrawFlags ); m_CurrentView = currentView; } } if ( mat_viewportupscale.GetBool() && mat_viewportscale.GetFloat() < 1.0f ) { CMatRenderContextPtr pRenderContext( materials ); ITexture *pFullFrameFB1 = materials->FindTexture( "_rt_FullFrameFB1", TEXTURE_GROUP_RENDER_TARGET ); IMaterial *pCopyMaterial = materials->FindMaterial( "dev/upscale", TEXTURE_GROUP_OTHER ); pCopyMaterial->IncrementReferenceCount(); Rect_t DownscaleRect, UpscaleRect; DownscaleRect.x = view.x; DownscaleRect.y = view.y; DownscaleRect.width = view.width; DownscaleRect.height = view.height; UpscaleRect.x = view.m_nUnscaledX; UpscaleRect.y = view.m_nUnscaledY; UpscaleRect.width = view.m_nUnscaledWidth; UpscaleRect.height = view.m_nUnscaledHeight; pRenderContext->CopyRenderTargetToTextureEx( pFullFrameFB1, 0, &DownscaleRect, &DownscaleRect ); pRenderContext->DrawScreenSpaceRectangle( pCopyMaterial, UpscaleRect.x, UpscaleRect.y, UpscaleRect.width, UpscaleRect.height, DownscaleRect.x, DownscaleRect.y, DownscaleRect.x+DownscaleRect.width-1, DownscaleRect.y+DownscaleRect.height-1, pFullFrameFB1->GetActualWidth(), pFullFrameFB1->GetActualHeight() ); pCopyMaterial->DecrementReferenceCount(); } // Draw the 2D graphics render->Push2DView( view, 0, saveRenderTarget, GetFrustum() ); Render2DEffectsPreHUD( view ); if ( whatToDraw & RENDERVIEW_DRAWHUD ) { VPROF_BUDGET( "VGui_DrawHud", VPROF_BUDGETGROUP_OTHER_VGUI ); int viewWidth = view.m_nUnscaledWidth; int viewHeight = view.m_nUnscaledHeight; int viewActualWidth = view.m_nUnscaledWidth; int viewActualHeight = view.m_nUnscaledHeight; int viewX = view.m_nUnscaledX; int viewY = view.m_nUnscaledY; int viewFramebufferX = 0; int viewFramebufferY = 0; int viewFramebufferWidth = viewWidth; int viewFramebufferHeight = viewHeight; bool bClear = false; bool bPaintMainMenu = false; ITexture *pTexture = NULL; if( UseVR() ) { if( g_ClientVirtualReality.ShouldRenderHUDInWorld() ) { pTexture = materials->FindTexture( "_rt_gui", NULL, false ); if( pTexture ) { bPaintMainMenu = true; bClear = true; viewX = 0; viewY = 0; viewActualWidth = pTexture->GetActualWidth(); viewActualHeight = pTexture->GetActualHeight(); vgui::surface()->GetScreenSize( viewWidth, viewHeight ); viewFramebufferX = view.m_eStereoEye == STEREO_EYE_RIGHT ? viewFramebufferWidth : 0; viewFramebufferY = 0; } } else { viewFramebufferX = view.m_eStereoEye == STEREO_EYE_RIGHT ? viewWidth : 0; viewFramebufferY = 0; } } // Get the render context out of materials to avoid some debug stuff. // WARNING THIS REQUIRES THE .SafeRelease below or it'll never release the ref pRenderContext = materials->GetRenderContext(); // clear depth in the backbuffer before we push the render target if( bClear ) { pRenderContext->ClearBuffers( false, true, true ); } // constrain where VGUI can render to the view pRenderContext->PushRenderTargetAndViewport( pTexture, NULL, viewX, viewY, viewActualWidth, viewActualHeight ); // If drawing off-screen, force alpha for that pass if (pTexture) { pRenderContext->OverrideAlphaWriteEnable( true, true ); } // let vgui know where to render stuff for the forced-to-framebuffer panels if( UseVR() ) { vgui::surface()->SetFullscreenViewport( viewFramebufferX, viewFramebufferY, viewFramebufferWidth, viewFramebufferHeight ); } // clear the render target if we need to if( bClear ) { pRenderContext->ClearColor4ub( 0, 0, 0, 0 ); pRenderContext->ClearBuffers( true, false ); } pRenderContext.SafeRelease(); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "VGui_DrawHud", __FUNCTION__ ); // paint the vgui screen VGui_PreRender(); // Make sure the client .dll root panel is at the proper point before doing the "SolveTraverse" calls vgui::VPANEL root = enginevgui->GetPanel( PANEL_CLIENTDLL ); if ( root != 0 ) { vgui::ipanel()->SetSize( root, viewWidth, viewHeight ); } // Same for client .dll tools root = enginevgui->GetPanel( PANEL_CLIENTDLL_TOOLS ); if ( root != 0 ) { vgui::ipanel()->SetSize( root, viewWidth, viewHeight ); } // The crosshair, etc. needs to get at the current setup stuff AllowCurrentViewAccess( true ); // Draw the in-game stuff based on the actual viewport being used render->VGui_Paint( PAINT_INGAMEPANELS ); // maybe paint the main menu and cursor too if we're in stereo hud mode if( bPaintMainMenu ) render->VGui_Paint( PAINT_UIPANELS | PAINT_CURSOR ); AllowCurrentViewAccess( false ); VGui_PostRender(); g_pClientMode->PostRenderVGui(); pRenderContext = materials->GetRenderContext(); if (pTexture) { pRenderContext->OverrideAlphaWriteEnable( false, true ); } pRenderContext->PopRenderTargetAndViewport(); if ( UseVR() ) { // figure out if we really want to draw the HUD based on freeze cam C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); bool bInFreezeCam = ( pPlayer && pPlayer->GetObserverMode() == OBS_MODE_FREEZECAM ); // draw the HUD after the view model so its "I'm closer" depth queues work right. if( !bInFreezeCam && g_ClientVirtualReality.ShouldRenderHUDInWorld() ) { // Now we've rendered the HUD to its texture, actually get it on the screen. // Since we're drawing it as a 3D object, we need correctly set up frustum, etc. int ClearFlags = 0; SetupMain3DView( view, ClearFlags ); // TODO - a bit of a shonky test - basically trying to catch the main menu, the briefing screen, the loadout screen, etc. bool bTranslucent = !g_pMatSystemSurface->IsCursorVisible(); g_ClientVirtualReality.RenderHUDQuad( g_pClientMode->ShouldBlackoutAroundHUD(), bTranslucent ); CleanupMain3DView( view ); } } pRenderContext->Flush(); pRenderContext.SafeRelease(); } CDebugViewRender::Draw2DDebuggingInfo( view ); Render2DEffectsPostHUD( view ); g_bRenderingView = false; // We can no longer use the 'current view' stuff set up in ViewDrawScene s_bCanAccessCurrentView = false; if ( IsPC() ) { CDebugViewRender::GenerateOverdrawForTesting(); } render->PopView( GetFrustum() ); g_WorldListCache.Flush(); } //----------------------------------------------------------------------------- // Purpose: Renders extra 2D effects in derived classes while the 2D view is on the stack //----------------------------------------------------------------------------- void CViewRender::Render2DEffectsPreHUD( const CViewSetup &view ) { } //----------------------------------------------------------------------------- // Purpose: Renders extra 2D effects in derived classes while the 2D view is on the stack //----------------------------------------------------------------------------- void CViewRender::Render2DEffectsPostHUD( const CViewSetup &view ) { } //----------------------------------------------------------------------------- // // NOTE: Below here is all of the stuff that needs to be done for water rendering // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Determines what kind of water we're going to use //----------------------------------------------------------------------------- void CViewRender::DetermineWaterRenderInfo( const VisibleFogVolumeInfo_t &fogVolumeInfo, WaterRenderInfo_t &info ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); // By default, assume cheap water (even if there's no water in the scene!) info.m_bCheapWater = true; info.m_bRefract = false; info.m_bReflect = false; info.m_bReflectEntities = false; info.m_bDrawWaterSurface = false; info.m_bOpaqueWater = true; IMaterial *pWaterMaterial = fogVolumeInfo.m_pFogVolumeMaterial; if (( fogVolumeInfo.m_nVisibleFogVolume == -1 ) || !pWaterMaterial ) return; // Use cheap water if mat_drawwater is set info.m_bDrawWaterSurface = mat_drawwater.GetBool(); if ( !info.m_bDrawWaterSurface ) { info.m_bOpaqueWater = false; return; } #ifdef _X360 bool bForceExpensive = false; #else bool bForceExpensive = r_waterforceexpensive.GetBool(); #endif bool bForceReflectEntities = r_waterforcereflectentities.GetBool(); #ifdef PORTAL switch( g_pPortalRender->ShouldForceCheaperWaterLevel() ) { case 0: //force cheap water info.m_bCheapWater = true; return; case 1: //downgrade level to "simple reflection" bForceExpensive = false; case 2: //downgrade level to "reflect world" bForceReflectEntities = false; default: break; }; #endif // Determine if the water surface is opaque or not info.m_bOpaqueWater = !pWaterMaterial->IsTranslucent(); // DX level 70 can't handle anything but cheap water if (engine->GetDXSupportLevel() < 80) return; bool bForceCheap = false; // The material can override the default settings though IMaterialVar *pForceCheapVar = pWaterMaterial->FindVar( "$forcecheap", NULL, false ); IMaterialVar *pForceExpensiveVar = pWaterMaterial->FindVar( "$forceexpensive", NULL, false ); if ( pForceCheapVar && pForceCheapVar->IsDefined() ) { bForceCheap = ( pForceCheapVar->GetIntValueFast() != 0 ); if ( bForceCheap ) { bForceExpensive = false; } } if ( !bForceCheap && pForceExpensiveVar && pForceExpensiveVar->IsDefined() ) { bForceExpensive = bForceExpensive || ( pForceExpensiveVar->GetIntValueFast() != 0 ); } bool bDebugCheapWater = r_debugcheapwater.GetBool(); if( bDebugCheapWater ) { Msg( "Water material: %s dist to water: %f\nforcecheap: %s forceexpensive: %s\n", pWaterMaterial->GetName(), fogVolumeInfo.m_flDistanceToWater, bForceCheap ? "true" : "false", bForceExpensive ? "true" : "false" ); } // Unless expensive water is active, reflections are off. bool bLocalReflection; #ifdef _X360 if( !r_WaterDrawReflection.GetBool() ) #else if( !bForceExpensive || !r_WaterDrawReflection.GetBool() ) #endif { bLocalReflection = false; } else { IMaterialVar *pReflectTextureVar = pWaterMaterial->FindVar( "$reflecttexture", NULL, false ); bLocalReflection = pReflectTextureVar && (pReflectTextureVar->GetType() == MATERIAL_VAR_TYPE_TEXTURE); } // Brian says FIXME: I disabled cheap water LOD when local specular is specified. // There are very few places that appear to actually // take advantage of it (places where water is in the PVS, but outside of LOD range). // It was 2 hours before code lock, and I had the choice of either doubling fill-rate everywhere // by making cheap water lod actually work (the water LOD wasn't actually rendering!!!) // or to just always render the reflection + refraction if there's a local specular specified. // Note that water LOD *does* work with refract-only water // Gary says: I'm reverting this change so that water LOD works on dx9 for ep2. // Check if the water is out of the cheap water LOD range; if so, use cheap water #ifdef _X360 if ( !bForceExpensive && ( bForceCheap || ( fogVolumeInfo.m_flDistanceToWater >= m_flCheapWaterEndDistance ) ) ) { return; } #else if ( ( (fogVolumeInfo.m_flDistanceToWater >= m_flCheapWaterEndDistance) && !bLocalReflection ) || bForceCheap ) return; #endif // Get the material that is for the water surface that is visible and check to see // what render targets need to be rendered, if any. if ( !r_WaterDrawRefraction.GetBool() ) { info.m_bRefract = false; } else { IMaterialVar *pRefractTextureVar = pWaterMaterial->FindVar( "$refracttexture", NULL, false ); info.m_bRefract = pRefractTextureVar && (pRefractTextureVar->GetType() == MATERIAL_VAR_TYPE_TEXTURE); // Refractive water can be seen through if ( info.m_bRefract ) { info.m_bOpaqueWater = false; } } info.m_bReflect = bLocalReflection; if ( info.m_bReflect ) { if( bForceReflectEntities ) { info.m_bReflectEntities = true; } else { IMaterialVar *pReflectEntitiesVar = pWaterMaterial->FindVar( "$reflectentities", NULL, false ); info.m_bReflectEntities = pReflectEntitiesVar && (pReflectEntitiesVar->GetIntValueFast() != 0); } } info.m_bCheapWater = !info.m_bReflect && !info.m_bRefract; if( bDebugCheapWater ) { Warning( "refract: %s reflect: %s\n", info.m_bRefract ? "true" : "false", info.m_bReflect ? "true" : "false" ); } } //----------------------------------------------------------------------------- // Draws the world and all entities //----------------------------------------------------------------------------- void CViewRender::DrawWorldAndEntities( bool bDrawSkybox, const CViewSetup &viewIn, int nClearFlags, ViewCustomVisibility_t *pCustomVisibility ) { MDLCACHE_CRITICAL_SECTION(); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); VisibleFogVolumeInfo_t fogVolumeInfo; #ifdef PORTAL //in portal, we can't use the fog volume for the camera since it's almost never in the same fog volume as what's in front of the portal if( g_pPortalRender->GetViewRecursionLevel() == 0 ) { render->GetVisibleFogVolume( viewIn.origin, &fogVolumeInfo ); } else { render->GetVisibleFogVolume( g_pPortalRender->GetExitPortalFogOrigin(), &fogVolumeInfo ); } #else render->GetVisibleFogVolume( viewIn.origin, &fogVolumeInfo ); #endif WaterRenderInfo_t info; DetermineWaterRenderInfo( fogVolumeInfo, info ); if ( info.m_bCheapWater ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "bCheapWater" ); cplane_t glassReflectionPlane; if ( IsReflectiveGlassInView( viewIn, glassReflectionPlane ) ) { CRefPtr<CReflectiveGlassView> pGlassReflectionView = new CReflectiveGlassView( this ); pGlassReflectionView->Setup( viewIn, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, bDrawSkybox, fogVolumeInfo, info, glassReflectionPlane ); AddViewToScene( pGlassReflectionView ); CRefPtr<CRefractiveGlassView> pGlassRefractionView = new CRefractiveGlassView( this ); pGlassRefractionView->Setup( viewIn, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, bDrawSkybox, fogVolumeInfo, info, glassReflectionPlane ); AddViewToScene( pGlassRefractionView ); } CRefPtr<CSimpleWorldView> pNoWaterView = new CSimpleWorldView( this ); pNoWaterView->Setup( viewIn, nClearFlags, bDrawSkybox, fogVolumeInfo, info, pCustomVisibility ); AddViewToScene( pNoWaterView ); return; } Assert( !pCustomVisibility ); // Blat out the visible fog leaf if we're not going to use it if ( !r_ForceWaterLeaf.GetBool() ) { fogVolumeInfo.m_nVisibleFogVolumeLeaf = -1; } // We can see water of some sort if ( !fogVolumeInfo.m_bEyeInFogVolume ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "CAboveWaterView" ); CRefPtr<CAboveWaterView> pAboveWaterView = new CAboveWaterView( this ); pAboveWaterView->Setup( viewIn, bDrawSkybox, fogVolumeInfo, info ); AddViewToScene( pAboveWaterView ); } else { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "CUnderWaterView" ); CRefPtr<CUnderWaterView> pUnderWaterView = new CUnderWaterView( this ); pUnderWaterView->Setup( viewIn, bDrawSkybox, fogVolumeInfo, info ); AddViewToScene( pUnderWaterView ); } } //----------------------------------------------------------------------------- // Pushes a water render target //----------------------------------------------------------------------------- static Vector SavedLinearLightMapScale(-1,-1,-1); // x<0 = no saved scale static void SetLightmapScaleForWater(void) { if (g_pMaterialSystemHardwareConfig->GetHDRType()==HDR_TYPE_INTEGER) { CMatRenderContextPtr pRenderContext( materials ); SavedLinearLightMapScale=pRenderContext->GetToneMappingScaleLinear(); Vector t25=SavedLinearLightMapScale; t25*=0.25; pRenderContext->SetToneMappingScaleLinear(t25); } } //----------------------------------------------------------------------------- // Returns true if the view plane intersects the water //----------------------------------------------------------------------------- bool DoesViewPlaneIntersectWater( float waterZ, int leafWaterDataID ) { if ( leafWaterDataID == -1 ) return false; #ifdef PORTAL //when rendering portal views point/plane intersections just don't cut it. if( g_pPortalRender->GetViewRecursionLevel() != 0 ) return g_pPortalRender->DoesExitPortalViewIntersectWaterPlane( waterZ, leafWaterDataID ); #endif CMatRenderContextPtr pRenderContext( materials ); VMatrix viewMatrix, projectionMatrix, viewProjectionMatrix, inverseViewProjectionMatrix; pRenderContext->GetMatrix( MATERIAL_VIEW, &viewMatrix ); pRenderContext->GetMatrix( MATERIAL_PROJECTION, &projectionMatrix ); MatrixMultiply( projectionMatrix, viewMatrix, viewProjectionMatrix ); MatrixInverseGeneral( viewProjectionMatrix, inverseViewProjectionMatrix ); Vector mins, maxs; ClearBounds( mins, maxs ); Vector testPoint[4]; testPoint[0].Init( -1.0f, -1.0f, 0.0f ); testPoint[1].Init( -1.0f, 1.0f, 0.0f ); testPoint[2].Init( 1.0f, -1.0f, 0.0f ); testPoint[3].Init( 1.0f, 1.0f, 0.0f ); int i; bool bAbove = false; bool bBelow = false; float fudge = 7.0f; for( i = 0; i < 4; i++ ) { Vector worldPos; Vector3DMultiplyPositionProjective( inverseViewProjectionMatrix, testPoint[i], worldPos ); AddPointToBounds( worldPos, mins, maxs ); // Warning( "viewplanez: %f waterZ: %f\n", worldPos.z, waterZ ); if( worldPos.z + fudge > waterZ ) { bAbove = true; } if( worldPos.z - fudge < waterZ ) { bBelow = true; } } // early out if the near plane doesn't cross the z plane of the water. if( !( bAbove && bBelow ) ) return false; Vector vecFudge( fudge, fudge, fudge ); mins -= vecFudge; maxs += vecFudge; // the near plane does cross the z value for the visible water volume. Call into // the engine to find out if the near plane intersects the water volume. return render->DoesBoxIntersectWaterVolume( mins, maxs, leafWaterDataID ); } #ifdef PORTAL //----------------------------------------------------------------------------- // Purpose: Draw the scene during another draw scene call. We must draw our portals // after opaques but before translucents, so this ViewDrawScene resets the view // and doesn't flag the rendering as ended when it ends. // Input : bDrawSkybox - do we draw the skybox // &view - the camera view to render from // nClearFlags - how to clear the buffer //----------------------------------------------------------------------------- void CViewRender::ViewDrawScene_PortalStencil( const CViewSetup &viewIn, ViewCustomVisibility_t *pCustomVisibility ) { VPROF( "CViewRender::ViewDrawScene_PortalStencil" ); CViewSetup view( viewIn ); // Record old view stats Vector vecOldOrigin = CurrentViewOrigin(); QAngle vecOldAngles = CurrentViewAngles(); int iCurrentViewID = g_CurrentViewID; int iRecursionLevel = g_pPortalRender->GetViewRecursionLevel(); Assert( iRecursionLevel > 0 ); //get references to reflection textures CTextureReference pPrimaryWaterReflectionTexture; pPrimaryWaterReflectionTexture.Init( GetWaterReflectionTexture() ); CTextureReference pReplacementWaterReflectionTexture; pReplacementWaterReflectionTexture.Init( portalrendertargets->GetWaterReflectionTextureForStencilDepth( iRecursionLevel ) ); //get references to refraction textures CTextureReference pPrimaryWaterRefractionTexture; pPrimaryWaterRefractionTexture.Init( GetWaterRefractionTexture() ); CTextureReference pReplacementWaterRefractionTexture; pReplacementWaterRefractionTexture.Init( portalrendertargets->GetWaterRefractionTextureForStencilDepth( iRecursionLevel ) ); //swap texture contents for the primary render targets with those we set aside for this recursion level if( pReplacementWaterReflectionTexture != NULL ) pPrimaryWaterReflectionTexture->SwapContents( pReplacementWaterReflectionTexture ); if( pReplacementWaterRefractionTexture != NULL ) pPrimaryWaterRefractionTexture->SwapContents( pReplacementWaterRefractionTexture ); bool bDrew3dSkybox = false; SkyboxVisibility_t nSkyboxVisible = SKYBOX_NOT_VISIBLE; int iClearFlags = 0; Draw3dSkyboxworld_Portal( view, iClearFlags, bDrew3dSkybox, nSkyboxVisible ); bool drawSkybox = r_skybox.GetBool(); if ( bDrew3dSkybox || ( nSkyboxVisible == SKYBOX_NOT_VISIBLE ) ) { drawSkybox = false; } //generate unique view ID's for each stencil view view_id_t iNewViewID = (view_id_t)g_pPortalRender->GetCurrentViewId(); SetupCurrentView( view.origin, view.angles, (view_id_t)iNewViewID ); // update vis data unsigned int visFlags; SetupVis( view, visFlags, pCustomVisibility ); VisibleFogVolumeInfo_t fogInfo; if( g_pPortalRender->GetViewRecursionLevel() == 0 ) { render->GetVisibleFogVolume( view.origin, &fogInfo ); } else { render->GetVisibleFogVolume( g_pPortalRender->GetExitPortalFogOrigin(), &fogInfo ); } WaterRenderInfo_t waterInfo; DetermineWaterRenderInfo( fogInfo, waterInfo ); if ( waterInfo.m_bCheapWater ) { cplane_t glassReflectionPlane; if ( IsReflectiveGlassInView( viewIn, glassReflectionPlane ) ) { CRefPtr<CReflectiveGlassView> pGlassReflectionView = new CReflectiveGlassView( this ); pGlassReflectionView->Setup( viewIn, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR | VIEW_CLEAR_OBEY_STENCIL, drawSkybox, fogInfo, waterInfo, glassReflectionPlane ); AddViewToScene( pGlassReflectionView ); CRefPtr<CRefractiveGlassView> pGlassRefractionView = new CRefractiveGlassView( this ); pGlassRefractionView->Setup( viewIn, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR | VIEW_CLEAR_OBEY_STENCIL, drawSkybox, fogInfo, waterInfo, glassReflectionPlane ); AddViewToScene( pGlassRefractionView ); } CSimpleWorldView *pClientView = new CSimpleWorldView( this ); pClientView->Setup( view, VIEW_CLEAR_OBEY_STENCIL, drawSkybox, fogInfo, waterInfo, pCustomVisibility ); AddViewToScene( pClientView ); SafeRelease( pClientView ); } else { // We can see water of some sort if ( !fogInfo.m_bEyeInFogVolume ) { CRefPtr<CAboveWaterView> pAboveWaterView = new CAboveWaterView( this ); pAboveWaterView->Setup( viewIn, drawSkybox, fogInfo, waterInfo ); AddViewToScene( pAboveWaterView ); } else { CRefPtr<CUnderWaterView> pUnderWaterView = new CUnderWaterView( this ); pUnderWaterView->Setup( viewIn, drawSkybox, fogInfo, waterInfo ); AddViewToScene( pUnderWaterView ); } } // Disable fog for the rest of the stuff DisableFog(); CGlowOverlay::DrawOverlays( view.m_bCacheFullSceneState ); // Draw rain.. DrawPrecipitation(); //prerender version only // issue the pixel visibility tests PixelVisibility_EndCurrentView(); // Make sure sound doesn't stutter engine->Sound_ExtraUpdate(); // Debugging info goes over the top CDebugViewRender::Draw3DDebuggingInfo( view ); // Return to the previous view SetupCurrentView( vecOldOrigin, vecOldAngles, (view_id_t)iCurrentViewID ); g_CurrentViewID = iCurrentViewID; //just in case the cast to view_id_t screwed up the id # //swap back the water render targets if( pReplacementWaterReflectionTexture != NULL ) pPrimaryWaterReflectionTexture->SwapContents( pReplacementWaterReflectionTexture ); if( pReplacementWaterRefractionTexture != NULL ) pPrimaryWaterRefractionTexture->SwapContents( pReplacementWaterRefractionTexture ); } void CViewRender::Draw3dSkyboxworld_Portal( const CViewSetup &view, int &nClearFlags, bool &bDrew3dSkybox, SkyboxVisibility_t &nSkyboxVisible, ITexture *pRenderTarget ) { CRefPtr<CPortalSkyboxView> pSkyView = new CPortalSkyboxView( this ); if ( ( bDrew3dSkybox = pSkyView->Setup( view, &nClearFlags, &nSkyboxVisible, pRenderTarget ) ) == true ) { AddViewToScene( pSkyView ); } } #endif //PORTAL //----------------------------------------------------------------------------- // Methods related to controlling the cheap water distance //----------------------------------------------------------------------------- void CViewRender::SetCheapWaterStartDistance( float flCheapWaterStartDistance ) { m_flCheapWaterStartDistance = flCheapWaterStartDistance; } void CViewRender::SetCheapWaterEndDistance( float flCheapWaterEndDistance ) { m_flCheapWaterEndDistance = flCheapWaterEndDistance; } void CViewRender::GetWaterLODParams( float &flCheapWaterStartDistance, float &flCheapWaterEndDistance ) { flCheapWaterStartDistance = m_flCheapWaterStartDistance; flCheapWaterEndDistance = m_flCheapWaterEndDistance; } //----------------------------------------------------------------------------- // Purpose: // Input : &view - // &introData - //----------------------------------------------------------------------------- void CViewRender::ViewDrawScene_Intro( const CViewSetup &view, int nClearFlags, const IntroData_t &introData ) { VPROF( "CViewRender::ViewDrawScene" ); CMatRenderContextPtr pRenderContext( materials ); // this allows the refract texture to be updated once per *scene* on 360 // (e.g. once for a monitor scene and once for the main scene) g_viewscene_refractUpdateFrame = gpGlobals->framecount - 1; // ----------------------------------------------------------------------- // Set the clear color to black since we are going to be adding up things // in the frame buffer. // ----------------------------------------------------------------------- // Clear alpha to 255 so that masking with the vortigaunts (0) works properly. pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); // ----------------------------------------------------------------------- // Draw the primary scene and copy it to the first framebuffer texture // ----------------------------------------------------------------------- unsigned int visFlags; // NOTE: We only increment this once since time doesn't move forward. ParticleMgr()->IncrementFrameCode(); if( introData.m_bDrawPrimary ) { CViewSetup playerView( view ); playerView.origin = introData.m_vecCameraView; playerView.angles = introData.m_vecCameraViewAngles; if ( introData.m_playerViewFOV ) { playerView.fov = ScaleFOVByWidthRatio( introData.m_playerViewFOV, engine->GetScreenAspectRatio() / ( 4.0f / 3.0f ) ); } g_pClientShadowMgr->PreRender(); // Shadowed flashlights supported on ps_2_b and up... if ( r_flashlightdepthtexture.GetBool() ) { g_pClientShadowMgr->ComputeShadowDepthTextures( playerView ); } SetupCurrentView( playerView.origin, playerView.angles, VIEW_INTRO_PLAYER ); // Invoke pre-render methods IGameSystem::PreRenderAllSystems(); // Start view, clear frame/z buffer if necessary SetupVis( playerView, visFlags ); render->Push3DView( playerView, VIEW_CLEAR_COLOR | VIEW_CLEAR_DEPTH, NULL, GetFrustum() ); DrawWorldAndEntities( true /* drawSkybox */, playerView, VIEW_CLEAR_COLOR | VIEW_CLEAR_DEPTH ); render->PopView( GetFrustum() ); // Free shadow depth textures for use in future view if ( r_flashlightdepthtexture.GetBool() ) { g_pClientShadowMgr->UnlockAllShadowDepthTextures(); } } else { pRenderContext->ClearBuffers( true, true ); } Rect_t actualRect; UpdateScreenEffectTexture( 0, view.x, view.y, view.width, view.height, false, &actualRect ); g_pClientShadowMgr->PreRender(); // Shadowed flashlights supported on ps_2_b and up... if ( r_flashlightdepthtexture.GetBool() ) { g_pClientShadowMgr->ComputeShadowDepthTextures( view ); } // ----------------------------------------------------------------------- // Draw the secondary scene and copy it to the second framebuffer texture // ----------------------------------------------------------------------- SetupCurrentView( view.origin, view.angles, VIEW_INTRO_CAMERA ); // Invoke pre-render methods IGameSystem::PreRenderAllSystems(); // Start view, clear frame/z buffer if necessary SetupVis( view, visFlags ); // Clear alpha to 255 so that masking with the vortigaunts (0) works properly. pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); DrawWorldAndEntities( true /* drawSkybox */, view, VIEW_CLEAR_COLOR | VIEW_CLEAR_DEPTH ); UpdateScreenEffectTexture( 1, view.x, view.y, view.width, view.height ); // ----------------------------------------------------------------------- // Draw quads on the screen for each screenspace pass. // ----------------------------------------------------------------------- // Find the material that we use to render the overlays IMaterial *pOverlayMaterial = materials->FindMaterial( "scripted/intro_screenspaceeffect", TEXTURE_GROUP_OTHER ); IMaterialVar *pModeVar = pOverlayMaterial->FindVar( "$mode", NULL ); IMaterialVar *pAlphaVar = pOverlayMaterial->FindVar( "$alpha", NULL ); pRenderContext->ClearBuffers( true, true ); pRenderContext->MatrixMode( MATERIAL_VIEW ); pRenderContext->PushMatrix(); pRenderContext->LoadIdentity(); pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PushMatrix(); pRenderContext->LoadIdentity(); int passID; for( passID = 0; passID < introData.m_Passes.Count(); passID++ ) { const IntroDataBlendPass_t& pass = introData.m_Passes[passID]; if ( pass.m_Alpha == 0 ) continue; // Pick one of the blend modes for the material. if ( pass.m_BlendMode >= 0 && pass.m_BlendMode <= 9 ) { pModeVar->SetIntValue( pass.m_BlendMode ); } else { Assert(0); } // Set the alpha value for the material. pAlphaVar->SetFloatValue( pass.m_Alpha ); // Draw a quad for this pass. ITexture *pTexture = GetFullFrameFrameBufferTexture( 0 ); pRenderContext->DrawScreenSpaceRectangle( pOverlayMaterial, 0, 0, view.width, view.height, actualRect.x, actualRect.y, actualRect.x+actualRect.width-1, actualRect.y+actualRect.height-1, pTexture->GetActualWidth(), pTexture->GetActualHeight() ); } pRenderContext->MatrixMode( MATERIAL_VIEW ); pRenderContext->PopMatrix(); pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PopMatrix(); // Draw the starfield // FIXME // blur? // Disable fog for the rest of the stuff DisableFog(); // Here are the overlays... CGlowOverlay::DrawOverlays( view.m_bCacheFullSceneState ); // issue the pixel visibility tests PixelVisibility_EndCurrentView(); // And here are the screen-space effects PerformScreenSpaceEffects( 0, 0, view.width, view.height ); // Make sure sound doesn't stutter engine->Sound_ExtraUpdate(); // Debugging info goes over the top CDebugViewRender::Draw3DDebuggingInfo( view ); // Let the particle manager simulate things that haven't been simulated. ParticleMgr()->PostRender(); FinishCurrentView(); // Free shadow depth textures for use in future view if ( r_flashlightdepthtexture.GetBool() ) { g_pClientShadowMgr->UnlockAllShadowDepthTextures(); } } //----------------------------------------------------------------------------- // Purpose: Sets up scene and renders camera view // Input : cameraNum - // &cameraView // *localPlayer - // x - // y - // width - // height - // highend - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CViewRender::DrawOneMonitor( ITexture *pRenderTarget, int cameraNum, C_PointCamera *pCameraEnt, const CViewSetup &cameraView, C_BasePlayer *localPlayer, int x, int y, int width, int height ) { #ifdef USE_MONITORS VPROF_INCREMENT_COUNTER( "cameras rendered", 1 ); // Setup fog state for the camera. fogparams_t oldFogParams; float flOldZFar = 0.0f; bool fogEnabled = pCameraEnt->IsFogEnabled(); CViewSetup monitorView = cameraView; fogparams_t *pFogParams = NULL; if ( fogEnabled ) { if ( !localPlayer ) return false; pFogParams = localPlayer->GetFogParams(); // Save old fog data. oldFogParams = *pFogParams; flOldZFar = cameraView.zFar; pFogParams->enable = true; pFogParams->start = pCameraEnt->GetFogStart(); pFogParams->end = pCameraEnt->GetFogEnd(); pFogParams->farz = pCameraEnt->GetFogEnd(); pFogParams->maxdensity = pCameraEnt->GetFogMaxDensity(); unsigned char r, g, b; pCameraEnt->GetFogColor( r, g, b ); pFogParams->colorPrimary.SetR( r ); pFogParams->colorPrimary.SetG( g ); pFogParams->colorPrimary.SetB( b ); monitorView.zFar = pCameraEnt->GetFogEnd(); } monitorView.width = width; monitorView.height = height; monitorView.x = x; monitorView.y = y; monitorView.origin = pCameraEnt->GetAbsOrigin(); monitorView.angles = pCameraEnt->GetAbsAngles(); monitorView.fov = pCameraEnt->GetFOV(); monitorView.m_bOrtho = false; monitorView.m_flAspectRatio = pCameraEnt->UseScreenAspectRatio() ? 0.0f : 1.0f; monitorView.m_bViewToProjectionOverride = false; // @MULTICORE (toml 8/11/2006): this should be a renderer.... Frustum frustum; render->Push3DView( monitorView, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, pRenderTarget, (VPlane *)frustum ); ViewDrawScene( false, SKYBOX_2DSKYBOX_VISIBLE, monitorView, 0, VIEW_MONITOR ); render->PopView( frustum ); // Reset the world fog parameters. if ( fogEnabled ) { if ( pFogParams ) { *pFogParams = oldFogParams; } monitorView.zFar = flOldZFar; } #endif // USE_MONITORS return true; } void CViewRender::DrawMonitors( const CViewSetup &cameraView ) { #ifdef PORTAL g_pPortalRender->DrawPortalsToTextures( this, cameraView ); #endif #ifdef USE_MONITORS // Early out if no cameras C_PointCamera *pCameraEnt = GetPointCameraList(); if ( !pCameraEnt ) return; tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); #ifdef _DEBUG g_bRenderingCameraView = true; #endif // FIXME: this should check for the ability to do a render target maybe instead. // FIXME: shouldn't have to truck through all of the visible entities for this!!!! ITexture *pCameraTarget = GetCameraTexture(); int width = pCameraTarget->GetActualWidth(); int height = pCameraTarget->GetActualHeight(); C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); int cameraNum; for ( cameraNum = 0; pCameraEnt != NULL; pCameraEnt = pCameraEnt->m_pNext ) { if ( !pCameraEnt->IsActive() || pCameraEnt->IsDormant() ) continue; if ( !DrawOneMonitor( pCameraTarget, cameraNum, pCameraEnt, cameraView, player, 0, 0, width, height ) ) continue; ++cameraNum; } if ( IsX360() && cameraNum > 0 ) { // resolve render target to system memory texture // resolving *after* all monitors drawn to ensure a single blit using fastest resolve path CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PushRenderTargetAndViewport( pCameraTarget ); pRenderContext->CopyRenderTargetToTextureEx( pCameraTarget, 0, NULL, NULL ); pRenderContext->PopRenderTargetAndViewport(); } #ifdef _DEBUG g_bRenderingCameraView = false; #endif #endif // USE_MONITORS } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- ClientWorldListInfo_t *ClientWorldListInfo_t::AllocPooled( const ClientWorldListInfo_t &exemplar ) { size_t nBytes = AlignValue( ( exemplar.m_LeafCount * ((sizeof(LeafIndex_t) * 2) + sizeof(LeafFogVolume_t)) ), 4096 ); ClientWorldListInfo_t *pResult = gm_Pool.GetObject(); byte *pMemory = (byte *)pResult->m_pLeafList; if ( pMemory ) { // Previously allocated, add a reference. Otherwise comes out of GetObject as a new object with a refcount of 1 pResult->AddRef(); } if ( !pMemory || _msize( pMemory ) < nBytes ) { pMemory = (byte *)realloc( pMemory, nBytes ); } pResult->m_pLeafList = (LeafIndex_t*)pMemory; pResult->m_pLeafFogVolume = (LeafFogVolume_t*)( pMemory + exemplar.m_LeafCount * sizeof(LeafIndex_t) ); pResult->m_pActualLeafIndex = (LeafIndex_t*)( (byte *)( pResult->m_pLeafFogVolume ) + exemplar.m_LeafCount * sizeof(LeafFogVolume_t) ); pResult->m_bPooledAlloc = true; return pResult; } bool ClientWorldListInfo_t::OnFinalRelease() { if ( m_bPooledAlloc ) { Assert( m_pLeafList ); gm_Pool.PutObject( this ); return false; } return true; } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CBase3dView::CBase3dView( CViewRender *pMainView ) : m_pMainView( pMainView ), m_Frustum( pMainView->m_Frustum ) { } //----------------------------------------------------------------------------- // Purpose: // Input : *pEnt - // Output : int //----------------------------------------------------------------------------- VPlane* CBase3dView::GetFrustum() { // The frustum is only valid while in a RenderView call. // @MULTICORE (toml 8/11/2006): reimplement this when ready -- Assert(g_bRenderingView || g_bRenderingCameraView || g_bRenderingScreenshot); return m_Frustum; } CObjectPool<ClientWorldListInfo_t> ClientWorldListInfo_t::gm_Pool; //----------------------------------------------------------------------------- // Base class for 3d views //----------------------------------------------------------------------------- CRendering3dView::CRendering3dView(CViewRender *pMainView) : CBase3dView( pMainView ), m_pWorldRenderList( NULL ), m_pRenderablesList( NULL ), m_pWorldListInfo( NULL ), m_pCustomVisibility( NULL ), m_DrawFlags( 0 ), m_ClearFlags( 0 ) { } //----------------------------------------------------------------------------- // Sort entities in a back-to-front ordering //----------------------------------------------------------------------------- void CRendering3dView::Setup( const CViewSetup &setup ) { // @MULTICORE (toml 8/15/2006): don't reset if parameters don't require it. For now, just reset memcpy( static_cast<CViewSetup *>(this), &setup, sizeof( setup ) ); ReleaseLists(); m_pRenderablesList = new CClientRenderablesList; m_pCustomVisibility = NULL; } //----------------------------------------------------------------------------- // Sort entities in a back-to-front ordering //----------------------------------------------------------------------------- void CRendering3dView::ReleaseLists() { SafeRelease( m_pWorldRenderList ); SafeRelease( m_pRenderablesList ); SafeRelease( m_pWorldListInfo ); m_pCustomVisibility = NULL; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CRendering3dView::SetupRenderablesList( int viewID ) { VPROF( "CViewRender::SetupRenderablesList" ); // Clear the list. int i; for( i=0; i < RENDER_GROUP_COUNT; i++ ) { m_pRenderablesList->m_RenderGroupCounts[i] = 0; } // Now collate the entities in the leaves. if( m_pMainView->ShouldDrawEntities() ) { // Precache information used commonly in CollateRenderables SetupRenderInfo_t setupInfo; setupInfo.m_pWorldListInfo = m_pWorldListInfo; setupInfo.m_nRenderFrame = m_pMainView->BuildRenderablesListsNumber(); // only one incremented? setupInfo.m_nDetailBuildFrame = m_pMainView->BuildWorldListsNumber(); // setupInfo.m_pRenderList = m_pRenderablesList; setupInfo.m_bDrawDetailObjects = g_pClientMode->ShouldDrawDetailObjects() && r_DrawDetailProps.GetInt(); setupInfo.m_bDrawTranslucentObjects = (viewID != VIEW_SHADOW_DEPTH_TEXTURE); setupInfo.m_vecRenderOrigin = origin; setupInfo.m_vecRenderForward = CurrentViewForward(); float fMaxDist = cl_maxrenderable_dist.GetFloat(); // Shadowing light typically has a smaller farz than cl_maxrenderable_dist setupInfo.m_flRenderDistSq = (viewID == VIEW_SHADOW_DEPTH_TEXTURE) ? MIN(zFar, fMaxDist) : fMaxDist; setupInfo.m_flRenderDistSq *= setupInfo.m_flRenderDistSq; ClientLeafSystem()->BuildRenderablesList( setupInfo ); } } //----------------------------------------------------------------------------- // Purpose: Builds lists of things to render in the world, called once per view //----------------------------------------------------------------------------- void CRendering3dView::UpdateRenderablesOpacity() { // Compute the prop opacity based on the view position and fov zoom scale float flFactor = 1.0f; C_BasePlayer *pLocal = C_BasePlayer::GetLocalPlayer(); if ( pLocal ) { flFactor = pLocal->GetFOVDistanceAdjustFactor(); } if ( cl_leveloverview.GetFloat() > 0 ) { // disable prop fading flFactor = -1; } // When zoomed in, tweak the opacity to stay visible from further away staticpropmgr->ComputePropOpacity( origin, flFactor ); // Build a list of detail props to render DetailObjectSystem()->BuildDetailObjectRenderLists( origin ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- // Kinda awkward...three optional parameters at the end... void CRendering3dView::BuildWorldRenderLists( bool bDrawEntities, int iForceViewLeaf /* = -1 */, bool bUseCacheIfEnabled /* = true */, bool bShadowDepth /* = false */, float *pReflectionWaterHeight /*= NULL*/ ) { VPROF_BUDGET( "BuildWorldRenderLists", VPROF_BUDGETGROUP_WORLD_RENDERING ); // @MULTICORE (toml 8/18/2006): to address.... extern void UpdateClientRenderableInPVSStatus(); UpdateClientRenderableInPVSStatus(); Assert( !m_pWorldRenderList && !m_pWorldListInfo); m_pMainView->IncWorldListsNumber(); // Override vis data if specified this render, otherwise use default behavior with NULL VisOverrideData_t* pVisData = ( m_pCustomVisibility && m_pCustomVisibility->m_VisData.m_fDistToAreaPortalTolerance != FLT_MAX ) ? &m_pCustomVisibility->m_VisData : NULL; bool bUseCache = ( bUseCacheIfEnabled && r_worldlistcache.GetBool() ); if ( !bUseCache || pVisData || !g_WorldListCache.Find( *this, &m_pWorldRenderList, &m_pWorldListInfo ) ) { // @MULTICORE (toml 8/18/2006): when make parallel, will have to change caching to be atomic, where follow ons receive a pointer to a list that is not yet built m_pWorldRenderList = render->CreateWorldList(); m_pWorldListInfo = new ClientWorldListInfo_t; render->BuildWorldLists( m_pWorldRenderList, m_pWorldListInfo, ( m_pCustomVisibility ) ? m_pCustomVisibility->m_iForceViewLeaf : iForceViewLeaf, pVisData, bShadowDepth, pReflectionWaterHeight ); if ( bUseCache && !pVisData ) { g_WorldListCache.Add( *this, m_pWorldRenderList, m_pWorldListInfo ); } } if ( bDrawEntities ) { UpdateRenderablesOpacity(); } } //----------------------------------------------------------------------------- // Purpose: Computes the actual world list info based on the render flags //----------------------------------------------------------------------------- void CRendering3dView::PruneWorldListInfo() { // Drawing everything? Just return the world list info as-is int nWaterDrawFlags = m_DrawFlags & (DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER); if ( nWaterDrawFlags == (DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER) ) { return; } ClientWorldListInfo_t *pNewInfo; // Only allocate memory if actually will draw something if ( m_pWorldListInfo->m_LeafCount > 0 && nWaterDrawFlags ) { pNewInfo = ClientWorldListInfo_t::AllocPooled( *m_pWorldListInfo ); } else { pNewInfo = new ClientWorldListInfo_t; } pNewInfo->m_ViewFogVolume = m_pWorldListInfo->m_ViewFogVolume; pNewInfo->m_LeafCount = 0; // Not drawing anything? Then don't bother with renderable lists if ( nWaterDrawFlags != 0 ) { // Create a sub-list based on the actual leaves being rendered bool bRenderingUnderwater = (nWaterDrawFlags & DF_RENDER_UNDERWATER) != 0; for ( int i = 0; i < m_pWorldListInfo->m_LeafCount; ++i ) { bool bLeafIsUnderwater = ( m_pWorldListInfo->m_pLeafFogVolume[i] != -1 ); if ( bRenderingUnderwater == bLeafIsUnderwater ) { pNewInfo->m_pLeafList[ pNewInfo->m_LeafCount ] = m_pWorldListInfo->m_pLeafList[ i ]; pNewInfo->m_pLeafFogVolume[ pNewInfo->m_LeafCount ] = m_pWorldListInfo->m_pLeafFogVolume[ i ]; pNewInfo->m_pActualLeafIndex[ pNewInfo->m_LeafCount ] = i; ++pNewInfo->m_LeafCount; } } } m_pWorldListInfo->Release(); m_pWorldListInfo = pNewInfo; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static inline void UpdateBrushModelLightmap( IClientRenderable *pEnt ) { model_t *pModel = ( model_t * )pEnt->GetModel(); render->UpdateBrushModelLightmap( pModel, pEnt ); } void CRendering3dView::BuildRenderableRenderLists( int viewID ) { MDLCACHE_CRITICAL_SECTION(); if ( viewID != VIEW_SHADOW_DEPTH_TEXTURE ) { render->BeginUpdateLightmaps(); } m_pMainView->IncRenderablesListsNumber(); ClientWorldListInfo_t& info = *m_pWorldListInfo; // For better sorting, find out the leaf *nearest* to the camera // and render translucent objects as if they are in that leaf. if( m_pMainView->ShouldDrawEntities() && ( viewID != VIEW_SHADOW_DEPTH_TEXTURE ) ) { ClientLeafSystem()->ComputeTranslucentRenderLeaf( info.m_LeafCount, info.m_pLeafList, info.m_pLeafFogVolume, m_pMainView->BuildRenderablesListsNumber(), viewID ); } SetupRenderablesList( viewID ); if ( viewID == VIEW_MAIN ) { StudioStats_FindClosestEntity( m_pRenderablesList ); } if ( viewID != VIEW_SHADOW_DEPTH_TEXTURE ) { // update lightmap on brush models if necessary CClientRenderablesList::CEntry *pEntities = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_OPAQUE_BRUSH]; int nOpaque = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_OPAQUE_BRUSH]; int i; for( i=0; i < nOpaque; ++i ) { Assert(pEntities[i].m_TwoPass==0); UpdateBrushModelLightmap( pEntities[i].m_pRenderable ); } // update lightmap on brush models if necessary pEntities = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_TRANSLUCENT_ENTITY]; int nTranslucent = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_TRANSLUCENT_ENTITY]; for( i=0; i < nTranslucent; ++i ) { const model_t *pModel = pEntities[i].m_pRenderable->GetModel(); if( pModel ) { int nModelType = modelinfo->GetModelType( pModel ); if( nModelType == mod_brush ) { UpdateBrushModelLightmap( pEntities[i].m_pRenderable ); } } } render->EndUpdateLightmaps(); } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CRendering3dView::DrawWorld( float waterZAdjust ) { VPROF_INCREMENT_COUNTER( "RenderWorld", 1 ); VPROF_BUDGET( "DrawWorld", VPROF_BUDGETGROUP_WORLD_RENDERING ); if( !r_drawopaqueworld.GetBool() ) { return; } unsigned long engineFlags = BuildEngineDrawWorldListFlags( m_DrawFlags ); render->DrawWorldLists( m_pWorldRenderList, engineFlags, waterZAdjust ); } CMaterialReference g_material_WriteZ; //init'ed on by CViewRender::Init() //----------------------------------------------------------------------------- // Fakes per-entity clip planes on cards that don't support user clip planes. // Achieves the effect by drawing an invisible box that writes to the depth buffer // around the clipped area. It's not perfect, but better than nothing. //----------------------------------------------------------------------------- static void DrawClippedDepthBox( IClientRenderable *pEnt, float *pClipPlane ) { //#define DEBUG_DRAWCLIPPEDDEPTHBOX //uncomment to draw the depth box as a colorful box static const int iQuads[6][5] = { { 0, 4, 6, 2, 0 }, //always an extra copy of first index at end to make some algorithms simpler { 3, 7, 5, 1, 3 }, { 1, 5, 4, 0, 1 }, { 2, 6, 7, 3, 2 }, { 0, 2, 3, 1, 0 }, { 5, 7, 6, 4, 5 } }; static const int iLines[12][2] = { { 0, 1 }, { 0, 2 }, { 0, 4 }, { 1, 3 }, { 1, 5 }, { 2, 3 }, { 2, 6 }, { 3, 7 }, { 4, 6 }, { 4, 5 }, { 5, 7 }, { 6, 7 } }; #ifdef DEBUG_DRAWCLIPPEDDEPTHBOX static const float fColors[6][3] = { { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f }, { 1.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 0.0f } }; #endif Vector vNormal = *(Vector *)pClipPlane; float fPlaneDist = pClipPlane[3]; Vector vMins, vMaxs; pEnt->GetRenderBounds( vMins, vMaxs ); Vector vOrigin = pEnt->GetRenderOrigin(); QAngle qAngles = pEnt->GetRenderAngles(); Vector vForward, vUp, vRight; AngleVectors( qAngles, &vForward, &vRight, &vUp ); Vector vPoints[8]; vPoints[0] = vOrigin + (vForward * vMins.x) + (vRight * vMins.y) + (vUp * vMins.z); vPoints[1] = vOrigin + (vForward * vMaxs.x) + (vRight * vMins.y) + (vUp * vMins.z); vPoints[2] = vOrigin + (vForward * vMins.x) + (vRight * vMaxs.y) + (vUp * vMins.z); vPoints[3] = vOrigin + (vForward * vMaxs.x) + (vRight * vMaxs.y) + (vUp * vMins.z); vPoints[4] = vOrigin + (vForward * vMins.x) + (vRight * vMins.y) + (vUp * vMaxs.z); vPoints[5] = vOrigin + (vForward * vMaxs.x) + (vRight * vMins.y) + (vUp * vMaxs.z); vPoints[6] = vOrigin + (vForward * vMins.x) + (vRight * vMaxs.y) + (vUp * vMaxs.z); vPoints[7] = vOrigin + (vForward * vMaxs.x) + (vRight * vMaxs.y) + (vUp * vMaxs.z); int iClipped[8]; float fDists[8]; for( int i = 0; i != 8; ++i ) { fDists[i] = vPoints[i].Dot( vNormal ) - fPlaneDist; iClipped[i] = (fDists[i] > 0.0f) ? 1 : 0; } Vector vSplitPoints[8][8]; //obviously there are only 12 lines, not 64 lines or 64 split points, but the indexing is way easier like this int iLineStates[8][8]; //0 = unclipped, 2 = wholly clipped, 3 = first point clipped, 4 = second point clipped //categorize lines and generate split points where needed for( int i = 0; i != 12; ++i ) { const int *pPoints = iLines[i]; int iLineState = (iClipped[pPoints[0]] + iClipped[pPoints[1]]); if( iLineState != 1 ) //either both points are clipped, or neither are clipped { iLineStates[pPoints[0]][pPoints[1]] = iLineStates[pPoints[1]][pPoints[0]] = iLineState; } else { //one point is clipped, the other is not if( iClipped[pPoints[0]] == 1 ) { //first point was clipped, index 1 has the negative distance float fInvTotalDist = 1.0f / (fDists[pPoints[0]] - fDists[pPoints[1]]); vSplitPoints[pPoints[0]][pPoints[1]] = vSplitPoints[pPoints[1]][pPoints[0]] = (vPoints[pPoints[1]] * (fDists[pPoints[0]] * fInvTotalDist)) - (vPoints[pPoints[0]] * (fDists[pPoints[1]] * fInvTotalDist)); Assert( fabs( vNormal.Dot( vSplitPoints[pPoints[0]][pPoints[1]] ) - fPlaneDist ) < 0.01f ); iLineStates[pPoints[0]][pPoints[1]] = 3; iLineStates[pPoints[1]][pPoints[0]] = 4; } else { //second point was clipped, index 0 has the negative distance float fInvTotalDist = 1.0f / (fDists[pPoints[1]] - fDists[pPoints[0]]); vSplitPoints[pPoints[0]][pPoints[1]] = vSplitPoints[pPoints[1]][pPoints[0]] = (vPoints[pPoints[0]] * (fDists[pPoints[1]] * fInvTotalDist)) - (vPoints[pPoints[1]] * (fDists[pPoints[0]] * fInvTotalDist)); Assert( fabs( vNormal.Dot( vSplitPoints[pPoints[0]][pPoints[1]] ) - fPlaneDist ) < 0.01f ); iLineStates[pPoints[0]][pPoints[1]] = 4; iLineStates[pPoints[1]][pPoints[0]] = 3; } } } CMatRenderContextPtr pRenderContext( materials ); #ifdef DEBUG_DRAWCLIPPEDDEPTHBOX pRenderContext->Bind( materials->FindMaterial( "debug/debugvertexcolor", TEXTURE_GROUP_OTHER ), NULL ); #else pRenderContext->Bind( g_material_WriteZ, NULL ); #endif CMeshBuilder meshBuilder; IMesh* pMesh = pRenderContext->GetDynamicMesh( false ); meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, 18 ); //6 sides, possible one cut per side. Any side is capable of having 3 tri's. Lots of padding for things that aren't possible //going to draw as a collection of triangles, arranged as a triangle fan on each side for( int i = 0; i != 6; ++i ) { const int *pPoints = iQuads[i]; //can't start the fan on a wholly clipped line, so seek to one that isn't int j = 0; do { if( iLineStates[pPoints[j]][pPoints[j+1]] != 2 ) //at least part of this line will be drawn break; ++j; } while( j != 3 ); if( j == 3 ) //not enough lines to even form a triangle continue; float *pStartPoint = 0; float *pTriangleFanPoints[4]; //at most, one of our fans will have 5 points total, with the first point being stored separately as pStartPoint int iTriangleFanPointCount = 1; //the switch below creates the first for sure //figure out how to start the fan switch( iLineStates[pPoints[j]][pPoints[j+1]] ) { case 0: //uncut pStartPoint = &vPoints[pPoints[j]].x; pTriangleFanPoints[0] = &vPoints[pPoints[j+1]].x; break; case 4: //second index was clipped pStartPoint = &vPoints[pPoints[j]].x; pTriangleFanPoints[0] = &vSplitPoints[pPoints[j]][pPoints[j+1]].x; break; case 3: //first index was clipped pStartPoint = &vSplitPoints[pPoints[j]][pPoints[j+1]].x; pTriangleFanPoints[0] = &vPoints[pPoints[j + 1]].x; break; default: Assert( false ); break; }; for( ++j; j != 3; ++j ) //add end points for the rest of the indices, we're assembling a triangle fan { switch( iLineStates[pPoints[j]][pPoints[j+1]] ) { case 0: //uncut line, normal endpoint pTriangleFanPoints[iTriangleFanPointCount] = &vPoints[pPoints[j+1]].x; ++iTriangleFanPointCount; break; case 2: //wholly cut line, no endpoint break; case 3: //first point is clipped, normal endpoint //special case, adds start and end point pTriangleFanPoints[iTriangleFanPointCount] = &vSplitPoints[pPoints[j]][pPoints[j+1]].x; ++iTriangleFanPointCount; pTriangleFanPoints[iTriangleFanPointCount] = &vPoints[pPoints[j+1]].x; ++iTriangleFanPointCount; break; case 4: //second point is clipped pTriangleFanPoints[iTriangleFanPointCount] = &vSplitPoints[pPoints[j]][pPoints[j+1]].x; ++iTriangleFanPointCount; break; default: Assert( false ); break; }; } //special case endpoints, half-clipped lines have a connecting line between them and the next line (first line in this case) switch( iLineStates[pPoints[j]][pPoints[j+1]] ) { case 3: case 4: pTriangleFanPoints[iTriangleFanPointCount] = &vSplitPoints[pPoints[j]][pPoints[j+1]].x; ++iTriangleFanPointCount; break; }; Assert( iTriangleFanPointCount <= 4 ); //add the fan to the mesh int iLoopStop = iTriangleFanPointCount - 1; for( int k = 0; k != iLoopStop; ++k ) { meshBuilder.Position3fv( pStartPoint ); #ifdef DEBUG_DRAWCLIPPEDDEPTHBOX float fHalfColors[3] = { fColors[i][0] * 0.5f, fColors[i][1] * 0.5f, fColors[i][2] * 0.5f }; meshBuilder.Color3fv( fHalfColors ); #endif meshBuilder.AdvanceVertex(); meshBuilder.Position3fv( pTriangleFanPoints[k] ); #ifdef DEBUG_DRAWCLIPPEDDEPTHBOX meshBuilder.Color3fv( fColors[i] ); #endif meshBuilder.AdvanceVertex(); meshBuilder.Position3fv( pTriangleFanPoints[k+1] ); #ifdef DEBUG_DRAWCLIPPEDDEPTHBOX meshBuilder.Color3fv( fColors[i] ); #endif meshBuilder.AdvanceVertex(); } } meshBuilder.End(); pMesh->Draw(); pRenderContext->Flush( false ); } //----------------------------------------------------------------------------- // Draws all opaque renderables in leaves that were rendered //----------------------------------------------------------------------------- static inline void DrawOpaqueRenderable( IClientRenderable *pEnt, bool bTwoPass, ERenderDepthMode DepthMode, int nDefaultFlags = 0 ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ ); float color[3]; pEnt->GetColorModulation( color ); render->SetColorModulation( color ); int flags = nDefaultFlags | STUDIO_RENDER; if ( bTwoPass ) { flags |= STUDIO_TWOPASS; } if ( DepthMode == DEPTH_MODE_SHADOW ) { flags |= STUDIO_SHADOWDEPTHTEXTURE; } else if ( DepthMode == DEPTH_MODE_SSA0 ) { flags |= STUDIO_SSAODEPTHTEXTURE; } float *pRenderClipPlane = NULL; if( r_entityclips.GetBool() ) pRenderClipPlane = pEnt->GetRenderClipPlane(); if( pRenderClipPlane ) { CMatRenderContextPtr pRenderContext( materials ); if( !materials->UsingFastClipping() ) //do NOT change the fast clip plane mid-scene, depth problems result. Regular user clip planes are fine though pRenderContext->PushCustomClipPlane( pRenderClipPlane ); else DrawClippedDepthBox( pEnt, pRenderClipPlane ); Assert( view->GetCurrentlyDrawingEntity() == NULL ); view->SetCurrentlyDrawingEntity( pEnt->GetIClientUnknown()->GetBaseEntity() ); pEnt->DrawModel( flags ); view->SetCurrentlyDrawingEntity( NULL ); if( pRenderClipPlane && !materials->UsingFastClipping() ) pRenderContext->PopCustomClipPlane(); } else { Assert( view->GetCurrentlyDrawingEntity() == NULL ); view->SetCurrentlyDrawingEntity( pEnt->GetIClientUnknown()->GetBaseEntity() ); pEnt->DrawModel( flags ); view->SetCurrentlyDrawingEntity( NULL ); } } //------------------------------------- ConVar r_drawopaquestaticpropslast( "r_drawopaquestaticpropslast", "0", 0, "Whether opaque static props are rendered after non-npcs" ); #define DEBUG_BUCKETS 0 #if DEBUG_BUCKETS ConVar r_drawopaque_old( "r_drawopaque_old", "0", 0, "Whether old unbucketed technique is used" ); ConVar r_drawopaquesbucket( "r_drawopaquesbucket", "0", FCVAR_CHEAT, "Draw only specific bucket: positive - props, negative - ents" ); ConVar r_drawopaquesbucket_stats( "r_drawopaquesbucket_stats", "0", FCVAR_CHEAT, "Draw distribution of props/ents in the buckets" ); #endif static void SetupBonesOnBaseAnimating( C_BaseAnimating *&pBaseAnimating ) { pBaseAnimating->SetupBones( NULL, -1, -1, gpGlobals->curtime ); } static void DrawOpaqueRenderables_DrawBrushModels( CClientRenderablesList::CEntry *pEntitiesBegin, CClientRenderablesList::CEntry *pEntitiesEnd, ERenderDepthMode DepthMode ) { for( CClientRenderablesList::CEntry *itEntity = pEntitiesBegin; itEntity < pEntitiesEnd; ++ itEntity ) { Assert( !itEntity->m_TwoPass ); DrawOpaqueRenderable( itEntity->m_pRenderable, false, DepthMode ); } } static void DrawOpaqueRenderables_DrawStaticProps( CClientRenderablesList::CEntry *pEntitiesBegin, CClientRenderablesList::CEntry *pEntitiesEnd, ERenderDepthMode DepthMode ) { if ( pEntitiesEnd == pEntitiesBegin ) return; float one[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; render->SetColorModulation( one ); render->SetBlend( 1.0f ); const int MAX_STATICS_PER_BATCH = 512; IClientRenderable *pStatics[ MAX_STATICS_PER_BATCH ]; int numScheduled = 0, numAvailable = MAX_STATICS_PER_BATCH; for( CClientRenderablesList::CEntry *itEntity = pEntitiesBegin; itEntity < pEntitiesEnd; ++ itEntity ) { if ( itEntity->m_pRenderable ) NULL; else continue; if ( g_pStudioStatsEntity != NULL && g_CurrentViewID == VIEW_MAIN && itEntity->m_pRenderable == g_pStudioStatsEntity ) { DrawOpaqueRenderable( itEntity->m_pRenderable, false, DepthMode, STUDIO_GENERATE_STATS ); continue; } pStatics[ numScheduled ++ ] = itEntity->m_pRenderable; if ( -- numAvailable > 0 ) continue; // place a hint for compiler to predict more common case in the loop staticpropmgr->DrawStaticProps( pStatics, numScheduled, DepthMode, vcollide_wireframe.GetBool() ); numScheduled = 0; numAvailable = MAX_STATICS_PER_BATCH; } if ( numScheduled ) staticpropmgr->DrawStaticProps( pStatics, numScheduled, DepthMode, vcollide_wireframe.GetBool() ); } static void DrawOpaqueRenderables_Range( CClientRenderablesList::CEntry *pEntitiesBegin, CClientRenderablesList::CEntry *pEntitiesEnd, ERenderDepthMode DepthMode ) { for( CClientRenderablesList::CEntry *itEntity = pEntitiesBegin; itEntity < pEntitiesEnd; ++ itEntity ) { if ( itEntity->m_pRenderable ) DrawOpaqueRenderable( itEntity->m_pRenderable, ( itEntity->m_TwoPass != 0 ), DepthMode ); } } void CRendering3dView::DrawOpaqueRenderables( ERenderDepthMode DepthMode ) { VPROF_BUDGET("CViewRender::DrawOpaqueRenderables", "DrawOpaqueRenderables" ); if( !r_drawopaquerenderables.GetBool() ) return; if( !m_pMainView->ShouldDrawEntities() ) return; render->SetBlend( 1 ); // // Prepare to iterate over all leaves that were visible, and draw opaque things in them. // RopeManager()->ResetRenderCache(); g_pParticleSystemMgr->ResetRenderCache(); bool const bDrawopaquestaticpropslast = r_drawopaquestaticpropslast.GetBool(); // // First do the brush models // { CClientRenderablesList::CEntry *pEntitiesBegin, *pEntitiesEnd; pEntitiesBegin = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_OPAQUE_BRUSH]; pEntitiesEnd = pEntitiesBegin + m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_OPAQUE_BRUSH]; DrawOpaqueRenderables_DrawBrushModels( pEntitiesBegin, pEntitiesEnd, DepthMode ); } #if DEBUG_BUCKETS { con_nprint_s nxPrn = { 0 }; nxPrn.index = 16; nxPrn.time_to_live = -1; nxPrn.color[0] = 0.9f, nxPrn.color[1] = 1.0f, nxPrn.color[2] = 0.9f; nxPrn.fixed_width_font = true; engine->Con_NXPrintf( &nxPrn, "Draw Opaque Technique : NEW" ); if ( r_drawopaque_old.GetBool() ) { engine->Con_NXPrintf( &nxPrn, "Draw Opaque Technique : OLD" ); // now the static props { for ( int bucket = RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS - 1; bucket -- > 0; ) { CClientRenderablesList::CEntry * const pEntitiesBegin = m_pRenderablesList->m_RenderGroups[ RENDER_GROUP_OPAQUE_STATIC_HUGE + 2 * bucket ], * const pEntitiesEnd = pEntitiesBegin + m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_STATIC_HUGE + 2 * bucket ]; DrawOpaqueRenderables_DrawStaticProps( pEntitiesBegin, pEntitiesEnd, bShadowDepth ); } } // now the other opaque entities for ( int bucket = RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS - 1; bucket -- > 0; ) { CClientRenderablesList::CEntry * const pEntitiesBegin = m_pRenderablesList->m_RenderGroups[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ], * const pEntitiesEnd = pEntitiesBegin + m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ]; DrawOpaqueRenderables_Range( pEntitiesBegin, pEntitiesEnd, bShadowDepth ); } // // Ropes and particles // RopeManager()->DrawRenderCache( bShadowDepth ); g_pParticleSystemMgr->DrawRenderCache( bShadowDepth ); return; } } #endif // // Sort everything that's not a static prop // int numOpaqueEnts = 0; for ( int bucket = 0; bucket < RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS; ++ bucket ) numOpaqueEnts += m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ]; CUtlVector< C_BaseAnimating * > arrBoneSetupNpcsLast( (C_BaseAnimating **)_alloca( numOpaqueEnts * sizeof( C_BaseAnimating * ) ), numOpaqueEnts, numOpaqueEnts ); CUtlVector< CClientRenderablesList::CEntry > arrRenderEntsNpcsFirst( (CClientRenderablesList::CEntry *)_alloca( numOpaqueEnts * sizeof( CClientRenderablesList::CEntry ) ), numOpaqueEnts, numOpaqueEnts ); int numNpcs = 0, numNonNpcsAnimating = 0; for ( int bucket = 0; bucket < RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS; ++ bucket ) { for( CClientRenderablesList::CEntry * const pEntitiesBegin = m_pRenderablesList->m_RenderGroups[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ], * const pEntitiesEnd = pEntitiesBegin + m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ], *itEntity = pEntitiesBegin; itEntity < pEntitiesEnd; ++ itEntity ) { C_BaseEntity *pEntity = itEntity->m_pRenderable ? itEntity->m_pRenderable->GetIClientUnknown()->GetBaseEntity() : NULL; if ( pEntity ) { if ( pEntity->IsNPC() ) { C_BaseAnimating *pba = assert_cast<C_BaseAnimating *>( pEntity ); arrRenderEntsNpcsFirst[ numNpcs ++ ] = *itEntity; arrBoneSetupNpcsLast[ numOpaqueEnts - numNpcs ] = pba; itEntity->m_pRenderable = NULL; // We will render NPCs separately itEntity->m_RenderHandle = NULL; continue; } else if ( pEntity->GetBaseAnimating() ) { C_BaseAnimating *pba = assert_cast<C_BaseAnimating *>( pEntity ); arrBoneSetupNpcsLast[ numNonNpcsAnimating ++ ] = pba; // fall through } } } } if ( 0 && r_threaded_renderables.GetBool() ) { ParallelProcess( "BoneSetupNpcsLast", arrBoneSetupNpcsLast.Base() + numOpaqueEnts - numNpcs, numNpcs, &SetupBonesOnBaseAnimating ); ParallelProcess( "BoneSetupNpcsLast NonNPCs", arrBoneSetupNpcsLast.Base(), numNonNpcsAnimating, &SetupBonesOnBaseAnimating ); } // // Draw static props + opaque entities from the biggest bucket to the smallest // { CClientRenderablesList::CEntry * pEnts[ RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS ][2]; CClientRenderablesList::CEntry * pProps[ RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS ][2]; for ( int bucket = 0; bucket < RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS; ++ bucket ) { pEnts[bucket][0] = m_pRenderablesList->m_RenderGroups[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ]; pEnts[bucket][1] = pEnts[bucket][0] + m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_ENTITY_HUGE + 2 * bucket ]; pProps[bucket][0] = m_pRenderablesList->m_RenderGroups[ RENDER_GROUP_OPAQUE_STATIC_HUGE + 2 * bucket ]; pProps[bucket][1] = pProps[bucket][0] + m_pRenderablesList->m_RenderGroupCounts[ RENDER_GROUP_OPAQUE_STATIC_HUGE + 2 * bucket ]; // Render sequence debugging #if DEBUG_BUCKETS if ( r_drawopaquesbucket_stats.GetBool() ) { con_nprint_s nxPrn = { 0 }; nxPrn.index = 20 + bucket * 3; nxPrn.time_to_live = -1; nxPrn.color[0] = 0.9f, nxPrn.color[1] = 1.0f, nxPrn.color[2] = 0.9f; nxPrn.fixed_width_font = true; if ( bDrawopaquestaticpropslast ) engine->Con_NXPrintf( &nxPrn, "[ %2d ] Ents : %3d", bucket + 1, pEnts[bucket][1] - pEnts[bucket][0] ), ++ nxPrn.index, engine->Con_NXPrintf( &nxPrn, "[ %2d ] Props: %3d", bucket + 1, pProps[bucket][1] - pProps[bucket][0] ); else engine->Con_NXPrintf( &nxPrn, "[ %2d ] Props: %3d", bucket + 1, pProps[bucket][1] - pProps[bucket][0] ), ++ nxPrn.index, engine->Con_NXPrintf( &nxPrn, "[ %2d ] Ents : %3d", bucket + 1, pEnts[bucket][1] - pEnts[bucket][0] ); } #endif } #if DEBUG_BUCKETS if ( int iBucket = r_drawopaquesbucket.GetInt() ) { if ( iBucket > 0 && iBucket <= RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS ) { DrawOpaqueRenderables_Range( pEnts[iBucket - 1][0], pEnts[iBucket - 1][1], bShadowDepth ); } if ( iBucket < 0 && iBucket >= -RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS ) { DrawOpaqueRenderables_DrawStaticProps( pProps[- 1 - iBucket][0], pProps[- 1 - iBucket][1], bShadowDepth ); } } else #endif for ( int bucket = 0; bucket < RENDER_GROUP_CFG_NUM_OPAQUE_ENT_BUCKETS; ++ bucket ) { if ( bDrawopaquestaticpropslast ) { DrawOpaqueRenderables_Range( pEnts[bucket][0], pEnts[bucket][1], DepthMode ); DrawOpaqueRenderables_DrawStaticProps( pProps[bucket][0], pProps[bucket][1], DepthMode ); } else { DrawOpaqueRenderables_Range( pEnts[bucket][0], pEnts[bucket][1], DepthMode ); DrawOpaqueRenderables_DrawStaticProps( pProps[bucket][0], pProps[bucket][1], DepthMode ); } } } // // Draw NPCs now // DrawOpaqueRenderables_Range( arrRenderEntsNpcsFirst.Base(), arrRenderEntsNpcsFirst.Base() + numNpcs, DepthMode ); // // Ropes and particles // RopeManager()->DrawRenderCache( DepthMode ); g_pParticleSystemMgr->DrawRenderCache( DepthMode ); } //----------------------------------------------------------------------------- // Renders all translucent world + detail objects in a particular set of leaves //----------------------------------------------------------------------------- void CRendering3dView::DrawTranslucentWorldInLeaves( bool bShadowDepth ) { VPROF_BUDGET( "CViewRender::DrawTranslucentWorldInLeaves", VPROF_BUDGETGROUP_WORLD_RENDERING ); const ClientWorldListInfo_t& info = *m_pWorldListInfo; for( int iCurLeafIndex = info.m_LeafCount - 1; iCurLeafIndex >= 0; iCurLeafIndex-- ) { int nActualLeafIndex = info.m_pActualLeafIndex ? info.m_pActualLeafIndex[ iCurLeafIndex ] : iCurLeafIndex; Assert( nActualLeafIndex != INVALID_LEAF_INDEX ); if ( render->LeafContainsTranslucentSurfaces( m_pWorldRenderList, nActualLeafIndex, m_DrawFlags ) ) { // Now draw the surfaces in this leaf render->DrawTranslucentSurfaces( m_pWorldRenderList, nActualLeafIndex, m_DrawFlags, bShadowDepth ); } } } //----------------------------------------------------------------------------- // Renders all translucent world + detail objects in a particular set of leaves //----------------------------------------------------------------------------- void CRendering3dView::DrawTranslucentWorldAndDetailPropsInLeaves( int iCurLeafIndex, int iFinalLeafIndex, int nEngineDrawFlags, int &nDetailLeafCount, LeafIndex_t* pDetailLeafList, bool bShadowDepth ) { VPROF_BUDGET( "CViewRender::DrawTranslucentWorldAndDetailPropsInLeaves", VPROF_BUDGETGROUP_WORLD_RENDERING ); const ClientWorldListInfo_t& info = *m_pWorldListInfo; for( ; iCurLeafIndex >= iFinalLeafIndex; iCurLeafIndex-- ) { int nActualLeafIndex = info.m_pActualLeafIndex ? info.m_pActualLeafIndex[ iCurLeafIndex ] : iCurLeafIndex; Assert( nActualLeafIndex != INVALID_LEAF_INDEX ); if ( render->LeafContainsTranslucentSurfaces( m_pWorldRenderList, nActualLeafIndex, nEngineDrawFlags ) ) { // First draw any queued-up detail props from previously visited leaves DetailObjectSystem()->RenderTranslucentDetailObjects( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nDetailLeafCount, pDetailLeafList ); nDetailLeafCount = 0; // Now draw the surfaces in this leaf render->DrawTranslucentSurfaces( m_pWorldRenderList, nActualLeafIndex, nEngineDrawFlags, bShadowDepth ); } // Queue up detail props that existed in this leaf if ( ClientLeafSystem()->ShouldDrawDetailObjectsInLeaf( info.m_pLeafList[iCurLeafIndex], m_pMainView->BuildWorldListsNumber() ) ) { pDetailLeafList[nDetailLeafCount] = info.m_pLeafList[iCurLeafIndex]; ++nDetailLeafCount; } } } //----------------------------------------------------------------------------- // Renders all translucent entities in the render list //----------------------------------------------------------------------------- static inline void DrawTranslucentRenderable( IClientRenderable *pEnt, bool twoPass, bool bShadowDepth, bool bIgnoreDepth ) { // Determine blending amount and tell engine float blend = (float)( pEnt->GetFxBlend() / 255.0f ); // Totally gone if ( blend <= 0.0f ) return; if ( pEnt->IgnoresZBuffer() != bIgnoreDepth ) return; // Tell engine render->SetBlend( blend ); float color[3]; pEnt->GetColorModulation( color ); render->SetColorModulation( color ); int flags = STUDIO_RENDER | STUDIO_TRANSPARENCY; if ( twoPass ) flags |= STUDIO_TWOPASS; if ( bShadowDepth ) flags |= STUDIO_SHADOWDEPTHTEXTURE; float *pRenderClipPlane = NULL; if( r_entityclips.GetBool() ) pRenderClipPlane = pEnt->GetRenderClipPlane(); if( pRenderClipPlane ) { CMatRenderContextPtr pRenderContext( materials ); if( !materials->UsingFastClipping() ) //do NOT change the fast clip plane mid-scene, depth problems result. Regular user clip planes are fine though pRenderContext->PushCustomClipPlane( pRenderClipPlane ); else DrawClippedDepthBox( pEnt, pRenderClipPlane ); Assert( view->GetCurrentlyDrawingEntity() == NULL ); view->SetCurrentlyDrawingEntity( pEnt->GetIClientUnknown()->GetBaseEntity() ); pEnt->DrawModel( flags ); view->SetCurrentlyDrawingEntity( NULL ); if( pRenderClipPlane && !materials->UsingFastClipping() ) pRenderContext->PopCustomClipPlane(); } else { Assert( view->GetCurrentlyDrawingEntity() == NULL ); view->SetCurrentlyDrawingEntity( pEnt->GetIClientUnknown()->GetBaseEntity() ); pEnt->DrawModel( flags ); view->SetCurrentlyDrawingEntity( NULL ); } } //----------------------------------------------------------------------------- // Renders all translucent entities in the render list //----------------------------------------------------------------------------- void CRendering3dView::DrawTranslucentRenderablesNoWorld( bool bInSkybox ) { VPROF( "CViewRender::DrawTranslucentRenderablesNoWorld" ); if ( !m_pMainView->ShouldDrawEntities() || !r_drawtranslucentrenderables.GetBool() ) return; // Draw the particle singletons. DrawParticleSingletons( bInSkybox ); bool bShadowDepth = (m_DrawFlags & ( DF_SHADOW_DEPTH_MAP | DF_SSAO_DEPTH_PASS ) ) != 0; CClientRenderablesList::CEntry *pEntities = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_TRANSLUCENT_ENTITY]; int iCurTranslucentEntity = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_TRANSLUCENT_ENTITY] - 1; while( iCurTranslucentEntity >= 0 ) { IClientRenderable *pRenderable = pEntities[iCurTranslucentEntity].m_pRenderable; if ( pRenderable->UsesPowerOfTwoFrameBufferTexture() ) { UpdateRefractTexture(); } if ( pRenderable->UsesFullFrameBufferTexture() ) { UpdateScreenEffectTexture(); } DrawTranslucentRenderable( pRenderable, pEntities[iCurTranslucentEntity].m_TwoPass != 0, bShadowDepth, false ); --iCurTranslucentEntity; } // Reset the blend state. render->SetBlend( 1 ); } //----------------------------------------------------------------------------- // Renders all translucent entities in the render list that ignore the Z buffer //----------------------------------------------------------------------------- void CRendering3dView::DrawNoZBufferTranslucentRenderables( void ) { VPROF( "CViewRender::DrawNoZBufferTranslucentRenderables" ); if ( !m_pMainView->ShouldDrawEntities() || !r_drawtranslucentrenderables.GetBool() ) return; bool bShadowDepth = (m_DrawFlags & ( DF_SHADOW_DEPTH_MAP | DF_SSAO_DEPTH_PASS ) ) != 0; CClientRenderablesList::CEntry *pEntities = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_TRANSLUCENT_ENTITY]; int iCurTranslucentEntity = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_TRANSLUCENT_ENTITY] - 1; while( iCurTranslucentEntity >= 0 ) { IClientRenderable *pRenderable = pEntities[iCurTranslucentEntity].m_pRenderable; if ( pRenderable->UsesPowerOfTwoFrameBufferTexture() ) { UpdateRefractTexture(); } if ( pRenderable->UsesFullFrameBufferTexture() ) { UpdateScreenEffectTexture(); } DrawTranslucentRenderable( pRenderable, pEntities[iCurTranslucentEntity].m_TwoPass != 0, bShadowDepth, true ); --iCurTranslucentEntity; } // Reset the blend state. render->SetBlend( 1 ); } //----------------------------------------------------------------------------- // Renders all translucent world, entities, and detail objects in a particular set of leaves //----------------------------------------------------------------------------- void CRendering3dView::DrawTranslucentRenderables( bool bInSkybox, bool bShadowDepth ) { const ClientWorldListInfo_t& info = *m_pWorldListInfo; #ifdef PORTAL //if we're in the portal mod, we need to make a detour so we can render portal views using stencil areas if( ShouldDrawPortals() ) //no recursive stencil views during skybox rendering (although we might be drawing a skybox while already in a recursive stencil view) { int iDrawFlagsBackup = m_DrawFlags; if( g_pPortalRender->DrawPortalsUsingStencils( (CViewRender *)m_pMainView ) )// @MULTICORE (toml 8/10/2006): remove this hack cast { m_DrawFlags = iDrawFlagsBackup; //reset visibility unsigned int iVisFlags = 0; m_pMainView->SetupVis( *this, iVisFlags, m_pCustomVisibility ); //recreate drawlists (since I can't find an easy way to backup the originals) { SafeRelease( m_pWorldRenderList ); SafeRelease( m_pWorldListInfo ); BuildWorldRenderLists( ((m_DrawFlags & DF_DRAW_ENTITITES) != 0), m_pCustomVisibility ? m_pCustomVisibility->m_iForceViewLeaf : -1, false ); AssertMsg( m_DrawFlags & DF_DRAW_ENTITITES, "It shouldn't be possible to get here if this wasn't set, needs special case investigation" ); for( int i = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_TRANSLUCENT_ENTITY]; --i >= 0; ) { m_pRenderablesList->m_RenderGroups[RENDER_GROUP_TRANSLUCENT_ENTITY][i].m_pRenderable->ComputeFxBlend(); } } if( r_depthoverlay.GetBool() ) { CMatRenderContextPtr pRenderContext( materials ); ITexture *pDepthTex = GetFullFrameDepthTexture(); IMaterial *pMaterial = materials->FindMaterial( "debug/showz", TEXTURE_GROUP_OTHER, true ); pMaterial->IncrementReferenceCount(); IMaterialVar *BaseTextureVar = pMaterial->FindVar( "$basetexture", NULL, false ); IMaterialVar *pDepthInAlpha = NULL; if( IsPC() ) { pDepthInAlpha = pMaterial->FindVar( "$ALPHADEPTH", NULL, false ); pDepthInAlpha->SetIntValue( 1 ); } BaseTextureVar->SetTextureValue( pDepthTex ); pRenderContext->OverrideDepthEnable( true, false ); //don't write to depth, or else we'll never see translucents pRenderContext->DrawScreenSpaceQuad( pMaterial ); pRenderContext->OverrideDepthEnable( false, true ); pMaterial->DecrementReferenceCount(); } } else { //done recursing in, time to go back out and do translucents CMatRenderContextPtr pRenderContext( materials ); UpdateFullScreenDepthTexture(); } } #else { //opaques generally write depth, and translucents generally don't. //So immediately after opaques are done is the best time to snap off the depth buffer to a texture. switch ( g_CurrentViewID ) { case VIEW_MAIN: #ifdef _X360 case VIEW_INTRO_CAMERA: case VIEW_INTRO_PLAYER: #endif UpdateFullScreenDepthTexture(); break; default: materials->GetRenderContext()->SetFullScreenDepthTextureValidityFlag( false ); break; } } #endif if ( !r_drawtranslucentworld.GetBool() ) { DrawTranslucentRenderablesNoWorld( bInSkybox ); return; } VPROF_BUDGET( "CViewRender::DrawTranslucentRenderables", "DrawTranslucentRenderables" ); int iPrevLeaf = info.m_LeafCount - 1; int nDetailLeafCount = 0; LeafIndex_t *pDetailLeafList = (LeafIndex_t*)stackalloc( info.m_LeafCount * sizeof(LeafIndex_t) ); // bool bDrawUnderWater = (nFlags & DF_RENDER_UNDERWATER) != 0; // bool bDrawAboveWater = (nFlags & DF_RENDER_ABOVEWATER) != 0; // bool bDrawWater = (nFlags & DF_RENDER_WATER) != 0; // bool bClipSkybox = (nFlags & DF_CLIP_SKYBOX ) != 0; unsigned long nEngineDrawFlags = BuildEngineDrawWorldListFlags( m_DrawFlags & ~DF_DRAWSKYBOX ); DetailObjectSystem()->BeginTranslucentDetailRendering(); if ( m_pMainView->ShouldDrawEntities() && r_drawtranslucentrenderables.GetBool() ) { MDLCACHE_CRITICAL_SECTION(); // Draw the particle singletons. DrawParticleSingletons( bInSkybox ); CClientRenderablesList::CEntry *pEntities = m_pRenderablesList->m_RenderGroups[RENDER_GROUP_TRANSLUCENT_ENTITY]; int iCurTranslucentEntity = m_pRenderablesList->m_RenderGroupCounts[RENDER_GROUP_TRANSLUCENT_ENTITY] - 1; bool bRenderingWaterRenderTargets = m_DrawFlags & ( DF_RENDER_REFRACTION | DF_RENDER_REFLECTION ); while( iCurTranslucentEntity >= 0 ) { // Seek the current leaf up to our current translucent-entity leaf. int iThisLeaf = pEntities[iCurTranslucentEntity].m_iWorldListInfoLeaf; // First draw the translucent parts of the world up to and including those in this leaf DrawTranslucentWorldAndDetailPropsInLeaves( iPrevLeaf, iThisLeaf, nEngineDrawFlags, nDetailLeafCount, pDetailLeafList, bShadowDepth ); // We're traversing the leaf list backwards to get the appropriate sort ordering (back to front) iPrevLeaf = iThisLeaf - 1; // Draw all the translucent entities with this leaf. int nLeaf = info.m_pLeafList[iThisLeaf]; bool bDrawDetailProps = ClientLeafSystem()->ShouldDrawDetailObjectsInLeaf( nLeaf, m_pMainView->BuildWorldListsNumber() ); if ( bDrawDetailProps ) { // Draw detail props up to but not including this leaf Assert( nDetailLeafCount > 0 ); --nDetailLeafCount; Assert( pDetailLeafList[nDetailLeafCount] == nLeaf ); DetailObjectSystem()->RenderTranslucentDetailObjects( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nDetailLeafCount, pDetailLeafList ); // Draw translucent renderables in the leaf interspersed with detail props for( ;pEntities[iCurTranslucentEntity].m_iWorldListInfoLeaf == iThisLeaf && iCurTranslucentEntity >= 0; --iCurTranslucentEntity ) { IClientRenderable *pRenderable = pEntities[iCurTranslucentEntity].m_pRenderable; // Draw any detail props in this leaf that's farther than the entity const Vector &vecRenderOrigin = pRenderable->GetRenderOrigin(); DetailObjectSystem()->RenderTranslucentDetailObjectsInLeaf( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nLeaf, &vecRenderOrigin ); bool bUsesPowerOfTwoFB = pRenderable->UsesPowerOfTwoFrameBufferTexture(); bool bUsesFullFB = pRenderable->UsesFullFrameBufferTexture(); if ( ( bUsesPowerOfTwoFB || bUsesFullFB )&& !bShadowDepth ) { if( bRenderingWaterRenderTargets ) { continue; } CMatRenderContextPtr pRenderContext( materials ); ITexture *rt = pRenderContext->GetRenderTarget(); if ( rt && bUsesFullFB ) { UpdateScreenEffectTexture( 0, 0, 0, rt->GetActualWidth(), rt->GetActualHeight(), true ); } else if ( bUsesPowerOfTwoFB ) { UpdateRefractTexture(); } pRenderContext.SafeRelease(); } // Then draw the translucent renderable DrawTranslucentRenderable( pRenderable, (pEntities[iCurTranslucentEntity].m_TwoPass != 0), bShadowDepth, false ); } // Draw all remaining props in this leaf DetailObjectSystem()->RenderTranslucentDetailObjectsInLeaf( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nLeaf, NULL ); } else { // Draw queued up detail props (we know that the list of detail leaves won't include this leaf, since ShouldDrawDetailObjectsInLeaf is false) // Therefore no fixup on nDetailLeafCount is required as in the above section DetailObjectSystem()->RenderTranslucentDetailObjects( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nDetailLeafCount, pDetailLeafList ); for( ;pEntities[iCurTranslucentEntity].m_iWorldListInfoLeaf == iThisLeaf && iCurTranslucentEntity >= 0; --iCurTranslucentEntity ) { IClientRenderable *pRenderable = pEntities[iCurTranslucentEntity].m_pRenderable; bool bUsesPowerOfTwoFB = pRenderable->UsesPowerOfTwoFrameBufferTexture(); bool bUsesFullFB = pRenderable->UsesFullFrameBufferTexture(); if ( ( bUsesPowerOfTwoFB || bUsesFullFB )&& !bShadowDepth ) { if( bRenderingWaterRenderTargets ) { continue; } CMatRenderContextPtr pRenderContext( materials ); ITexture *rt = pRenderContext->GetRenderTarget(); if ( rt ) { if ( bUsesFullFB ) { UpdateScreenEffectTexture( 0, 0, 0, rt->GetActualWidth(), rt->GetActualHeight(), true ); } else if ( bUsesPowerOfTwoFB ) { UpdateRefractTexture(0, 0, rt->GetActualWidth(), rt->GetActualHeight()); } } else { if ( bUsesPowerOfTwoFB ) { UpdateRefractTexture(); } } pRenderContext.SafeRelease(); } DrawTranslucentRenderable( pRenderable, (pEntities[iCurTranslucentEntity].m_TwoPass != 0), bShadowDepth, false ); } } nDetailLeafCount = 0; } } // Draw the rest of the surfaces in world leaves DrawTranslucentWorldAndDetailPropsInLeaves( iPrevLeaf, 0, nEngineDrawFlags, nDetailLeafCount, pDetailLeafList, bShadowDepth ); // Draw any queued-up detail props from previously visited leaves DetailObjectSystem()->RenderTranslucentDetailObjects( CurrentViewOrigin(), CurrentViewForward(), CurrentViewRight(), CurrentViewUp(), nDetailLeafCount, pDetailLeafList ); // Reset the blend state. render->SetBlend( 1 ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CRendering3dView::EnableWorldFog( void ) { VPROF("CViewRender::EnableWorldFog"); CMatRenderContextPtr pRenderContext( materials ); fogparams_t *pFogParams = NULL; C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if ( pbp ) { pFogParams = pbp->GetFogParams(); } if( GetFogEnable( pFogParams ) ) { float fogColor[3]; GetFogColor( pFogParams, fogColor ); pRenderContext->FogMode( MATERIAL_FOG_LINEAR ); pRenderContext->FogColor3fv( fogColor ); pRenderContext->FogStart( GetFogStart( pFogParams ) ); pRenderContext->FogEnd( GetFogEnd( pFogParams ) ); pRenderContext->FogMaxDensity( GetFogMaxDensity( pFogParams ) ); } else { pRenderContext->FogMode( MATERIAL_FOG_NONE ); } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int CRendering3dView::GetDrawFlags() { return m_DrawFlags; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CRendering3dView::SetFogVolumeState( const VisibleFogVolumeInfo_t &fogInfo, bool bUseHeightFog ) { render->SetFogVolumeState( fogInfo.m_nVisibleFogVolume, bUseHeightFog ); #ifdef PORTAL //the idea behind fog shifting is this... //Normal fog simulates the effect of countless tiny particles between your viewpoint and whatever geometry is rendering. //But, when rendering to a portal view, there's a large space between the virtual camera and the portal exit surface. //This space isn't supposed to exist, and therefore has none of the tiny particles that make up fog. //So, we have to shift fog start/end out to align the distances with the portal exit surface instead of the virtual camera to eliminate fog simulation in the non-space if( g_pPortalRender->GetViewRecursionLevel() == 0 ) return; //rendering one of the primary views, do nothing g_pPortalRender->ShiftFogForExitPortalView(); #endif //#ifdef PORTAL } //----------------------------------------------------------------------------- // Standard 3d skybox view //----------------------------------------------------------------------------- SkyboxVisibility_t CSkyboxView::ComputeSkyboxVisibility() { return engine->IsSkyboxVisibleFromPoint( origin ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CSkyboxView::GetSkyboxFogEnable() { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if( !pbp ) { return false; } CPlayerLocalData *local = &pbp->m_Local; if( fog_override.GetInt() ) { if( fog_enableskybox.GetInt() ) { return true; } else { return false; } } else { return !!local->m_skybox3d.fog.enable; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CSkyboxView::Enable3dSkyboxFog( void ) { C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); if( !pbp ) { return; } CPlayerLocalData *local = &pbp->m_Local; CMatRenderContextPtr pRenderContext( materials ); if( GetSkyboxFogEnable() ) { float fogColor[3]; GetSkyboxFogColor( fogColor ); float scale = 1.0f; if ( local->m_skybox3d.scale > 0.0f ) { scale = 1.0f / local->m_skybox3d.scale; } pRenderContext->FogMode( MATERIAL_FOG_LINEAR ); pRenderContext->FogColor3fv( fogColor ); pRenderContext->FogStart( GetSkyboxFogStart() * scale ); pRenderContext->FogEnd( GetSkyboxFogEnd() * scale ); pRenderContext->FogMaxDensity( GetSkyboxFogMaxDensity() ); } else { pRenderContext->FogMode( MATERIAL_FOG_NONE ); } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- sky3dparams_t *CSkyboxView::PreRender3dSkyboxWorld( SkyboxVisibility_t nSkyboxVisible ) { if ( ( nSkyboxVisible != SKYBOX_3DSKYBOX_VISIBLE ) && r_3dsky.GetInt() != 2 ) return NULL; // render the 3D skybox if ( !r_3dsky.GetInt() ) return NULL; C_BasePlayer *pbp = C_BasePlayer::GetLocalPlayer(); // No local player object yet... if ( !pbp ) return NULL; CPlayerLocalData* local = &pbp->m_Local; if ( local->m_skybox3d.area == 255 ) return NULL; return &local->m_skybox3d; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CSkyboxView::DrawInternal( view_id_t iSkyBoxViewID, bool bInvokePreAndPostRender, ITexture *pRenderTarget ) { unsigned char **areabits = render->GetAreaBits(); unsigned char *savebits; unsigned char tmpbits[ 32 ]; savebits = *areabits; memset( tmpbits, 0, sizeof(tmpbits) ); // set the sky area bit tmpbits[m_pSky3dParams->area>>3] |= 1 << (m_pSky3dParams->area&7); *areabits = tmpbits; // if you can get really close to the skybox geometry it's possible that you'll be able to clip into it // with this near plane. If so, move it in a bit. It's at 2.0 to give us more precision. That means you // need to keep the eye position at least 2 * scale away from the geometry in the skybox zNear = 2.0; zFar = MAX_TRACE_LENGTH; // scale origin by sky scale if ( m_pSky3dParams->scale > 0 ) { float scale = 1.0f / m_pSky3dParams->scale; VectorScale( origin, scale, origin ); } Enable3dSkyboxFog(); VectorAdd( origin, m_pSky3dParams->origin, origin ); // BUGBUG: Fix this!!! We shouldn't need to call setup vis for the sky if we're connecting // the areas. We'd have to mark all the clusters in the skybox area in the PVS of any // cluster with sky. Then we could just connect the areas to do our vis. //m_bOverrideVisOrigin could hose us here, so call direct render->ViewSetupVis( false, 1, &m_pSky3dParams->origin.Get() ); render->Push3DView( (*this), m_ClearFlags, pRenderTarget, GetFrustum() ); // Store off view origin and angles SetupCurrentView( origin, angles, iSkyBoxViewID ); #if defined( _X360 ) CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PushVertexShaderGPRAllocation( 32 ); pRenderContext.SafeRelease(); #endif // Invoke pre-render methods if ( bInvokePreAndPostRender ) { IGameSystem::PreRenderAllSystems(); } render->BeginUpdateLightmaps(); BuildWorldRenderLists( true, true, -1 ); BuildRenderableRenderLists( iSkyBoxViewID ); render->EndUpdateLightmaps(); g_pClientShadowMgr->ComputeShadowTextures( (*this), m_pWorldListInfo->m_LeafCount, m_pWorldListInfo->m_pLeafList ); DrawWorld( 0.0f ); // Iterate over all leaves and render objects in those leaves DrawOpaqueRenderables( DEPTH_MODE_NORMAL ); // Iterate over all leaves and render objects in those leaves DrawTranslucentRenderables( true, false ); DrawNoZBufferTranslucentRenderables(); m_pMainView->DisableFog(); CGlowOverlay::UpdateSkyOverlays( zFar, m_bCacheFullSceneState ); PixelVisibility_EndCurrentView(); // restore old area bits *areabits = savebits; // Invoke post-render methods if( bInvokePreAndPostRender ) { IGameSystem::PostRenderAllSystems(); FinishCurrentView(); } render->PopView( GetFrustum() ); #if defined( _X360 ) pRenderContext.GetFrom( materials ); pRenderContext->PopVertexShaderGPRAllocation(); #endif } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CSkyboxView::Setup( const CViewSetup &view, int *pClearFlags, SkyboxVisibility_t *pSkyboxVisible ) { BaseClass::Setup( view ); // The skybox might not be visible from here *pSkyboxVisible = ComputeSkyboxVisibility(); m_pSky3dParams = PreRender3dSkyboxWorld( *pSkyboxVisible ); if ( !m_pSky3dParams ) { return false; } // At this point, we've cleared everything we need to clear // The next path will need to clear depth, though. m_ClearFlags = *pClearFlags; *pClearFlags &= ~( VIEW_CLEAR_COLOR | VIEW_CLEAR_DEPTH | VIEW_CLEAR_STENCIL | VIEW_CLEAR_FULL_TARGET ); *pClearFlags |= VIEW_CLEAR_DEPTH; // Need to clear depth after rednering the skybox m_DrawFlags = DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER | DF_RENDER_WATER; if( r_skybox.GetBool() ) { m_DrawFlags |= DF_DRAWSKYBOX; } return true; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CSkyboxView::Draw() { VPROF_BUDGET( "CViewRender::Draw3dSkyboxworld", "3D Skybox" ); DrawInternal(); } #ifdef PORTAL //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CPortalSkyboxView::Setup( const CViewSetup &view, int *pClearFlags, SkyboxVisibility_t *pSkyboxVisible, ITexture *pRenderTarget ) { if ( !BaseClass::Setup( view, pClearFlags, pSkyboxVisible ) ) return false; m_pRenderTarget = pRenderTarget; return true; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- SkyboxVisibility_t CPortalSkyboxView::ComputeSkyboxVisibility() { return g_pPortalRender->IsSkyboxVisibleFromExitPortal(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CPortalSkyboxView::Draw() { AssertMsg( (g_pPortalRender->GetViewRecursionLevel() != 0) && g_pPortalRender->IsRenderingPortal(), "This is designed for through-portal views. Use the regular skybox drawing code for primary views" ); VPROF_BUDGET( "CViewRender::Draw3dSkyboxworld_Portal", "3D Skybox (portal view)" ); int iCurrentViewID = g_CurrentViewID; Frustum FrustumBackup; memcpy( FrustumBackup, GetFrustum(), sizeof( Frustum ) ); CMatRenderContextPtr pRenderContext( materials ); bool bClippingEnabled = pRenderContext->EnableClipping( false ); //NOTE: doesn't magically map to VIEW_3DSKY at (0,0) like PORTAL_VIEWID maps to VIEW_MAIN view_id_t iSkyBoxViewID = (view_id_t)g_pPortalRender->GetCurrentSkyboxViewId(); bool bInvokePreAndPostRender = ( g_pPortalRender->ShouldUseStencilsToRenderPortals() == false ); DrawInternal( iSkyBoxViewID, bInvokePreAndPostRender, m_pRenderTarget ); pRenderContext->EnableClipping( bClippingEnabled ); memcpy( GetFrustum(), FrustumBackup, sizeof( Frustum ) ); render->OverrideViewFrustum( FrustumBackup ); g_CurrentViewID = iCurrentViewID; } #endif // PORTAL //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CShadowDepthView::Setup( const CViewSetup &shadowViewIn, ITexture *pRenderTarget, ITexture *pDepthTexture ) { BaseClass::Setup( shadowViewIn ); m_pRenderTarget = pRenderTarget; m_pDepthTexture = pDepthTexture; } bool DrawingShadowDepthView( void ) //for easy externing { return (CurrentViewID() == VIEW_SHADOW_DEPTH_TEXTURE); } bool DrawingMainView() //for easy externing { return (CurrentViewID() == VIEW_MAIN); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CShadowDepthView::Draw() { VPROF_BUDGET( "CShadowDepthView::Draw", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); // Start view unsigned int visFlags; m_pMainView->SetupVis( (*this), visFlags ); // @MULTICORE (toml 8/9/2006): Portal problem, not sending custom vis down CMatRenderContextPtr pRenderContext( materials ); pRenderContext->ClearColor3ub(0xFF, 0xFF, 0xFF); #if defined( _X360 ) pRenderContext->PushVertexShaderGPRAllocation( 112 ); //almost all work is done in vertex shaders for depth rendering, max out their threads #endif pRenderContext.SafeRelease(); if( IsPC() ) { render->Push3DView( (*this), VIEW_CLEAR_DEPTH, m_pRenderTarget, GetFrustum(), m_pDepthTexture ); } else if( IsX360() ) { //for the 360, the dummy render target has a separate depth buffer which we Resolve() from afterward render->Push3DView( (*this), VIEW_CLEAR_DEPTH, m_pRenderTarget, GetFrustum() ); } SetupCurrentView( origin, angles, VIEW_SHADOW_DEPTH_TEXTURE ); MDLCACHE_CRITICAL_SECTION(); { VPROF_BUDGET( "BuildWorldRenderLists", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); BuildWorldRenderLists( true, -1, true, true ); // @MULTICORE (toml 8/9/2006): Portal problem, not sending custom vis down } { VPROF_BUDGET( "BuildRenderableRenderLists", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); BuildRenderableRenderLists( CurrentViewID() ); } engine->Sound_ExtraUpdate(); // Make sure sound doesn't stutter m_DrawFlags = m_pMainView->GetBaseDrawFlags() | DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER | DF_SHADOW_DEPTH_MAP; // Don't draw water surface... { VPROF_BUDGET( "DrawWorld", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); DrawWorld( 0.0f ); } // Draw opaque and translucent renderables with appropriate override materials // OVERRIDE_DEPTH_WRITE is OK with a NULL material pointer modelrender->ForcedMaterialOverride( NULL, OVERRIDE_DEPTH_WRITE ); { VPROF_BUDGET( "DrawOpaqueRenderables", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); DrawOpaqueRenderables( DEPTH_MODE_SHADOW ); } modelrender->ForcedMaterialOverride( 0 ); m_DrawFlags = 0; pRenderContext.GetFrom( materials ); if( IsX360() ) { //Resolve() the depth texture here. Before the pop so the copy will recognize that the resolutions are the same pRenderContext->CopyRenderTargetToTextureEx( m_pDepthTexture, -1, NULL, NULL ); } render->PopView( GetFrustum() ); #if defined( _X360 ) pRenderContext->PopVertexShaderGPRAllocation(); #endif } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CFreezeFrameView::Setup( const CViewSetup &shadowViewIn ) { BaseClass::Setup( shadowViewIn ); KeyValues *pVMTKeyValues = new KeyValues( "UnlitGeneric" ); pVMTKeyValues->SetString( "$basetexture", IsX360() ? "_rt_FullFrameFB1" : "_rt_FullScreen" ); pVMTKeyValues->SetInt( "$nocull", 1 ); pVMTKeyValues->SetInt( "$nofog", 1 ); pVMTKeyValues->SetInt( "$ignorez", 1 ); m_pFreezeFrame.Init( "FreezeFrame_FullScreen", TEXTURE_GROUP_OTHER, pVMTKeyValues ); m_pFreezeFrame->Refresh(); m_TranslucentSingleColor.Init( "debug/debugtranslucentsinglecolor", TEXTURE_GROUP_OTHER ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFreezeFrameView::Draw( void ) { CMatRenderContextPtr pRenderContext( materials ); #if defined( _X360 ) pRenderContext->PushVertexShaderGPRAllocation( 16 ); //max out pixel shader threads #endif // we might only need half of the texture if we're rendering in stereo int nTexX0 = 0, nTexY0 = 0; int nTexX1 = width, nTexY1 = height; int nTexWidth = width, nTexHeight = height; switch( m_eStereoEye ) { case STEREO_EYE_LEFT: nTexX1 = width; nTexWidth *= 2; break; case STEREO_EYE_RIGHT: nTexX0 = width; nTexX1 = width*2; nTexWidth *= 2; break; } pRenderContext->DrawScreenSpaceRectangle( m_pFreezeFrame, x, y, width, height, nTexX0, nTexY0, nTexX1-1, nTexY1-1, nTexWidth, nTexHeight ); //Fake a fade during freezeframe view. if ( g_flFreezeFlash >= gpGlobals->curtime && engine->IsTakingScreenshot() == false ) { // Overlay screen fade on entire screen IMaterial* pMaterial = m_TranslucentSingleColor; int iFadeAlpha = FREEZECAM_SNAPSHOT_FADE_SPEED * ( g_flFreezeFlash - gpGlobals->curtime ); iFadeAlpha = MIN( iFadeAlpha, 255 ); iFadeAlpha = MAX( 0, iFadeAlpha ); pMaterial->AlphaModulate( iFadeAlpha * ( 1.0f / 255.0f ) ); pMaterial->ColorModulate( 1.0f, 1.0f, 1.0f ); pMaterial->SetMaterialVarFlag( MATERIAL_VAR_IGNOREZ, true ); pRenderContext->DrawScreenSpaceRectangle( pMaterial, x, y, width, height, 0, 0, width-1, height-1, width, height ); } #if defined( _X360 ) pRenderContext->PopVertexShaderGPRAllocation(); #endif } //----------------------------------------------------------------------------- // Pops a water render target //----------------------------------------------------------------------------- bool CBaseWorldView::AdjustView( float waterHeight ) { if( m_DrawFlags & DF_RENDER_REFRACTION ) { ITexture *pTexture = GetWaterRefractionTexture(); // Use the aspect ratio of the main view! So, don't recompute it here x = y = 0; width = pTexture->GetActualWidth(); height = pTexture->GetActualHeight(); return true; } if( m_DrawFlags & DF_RENDER_REFLECTION ) { ITexture *pTexture = GetWaterReflectionTexture(); // If the main view is overriding the projection matrix (for Stereo or // some other nefarious purpose) make sure to include any Y offset in // the custom projection matrix in our reflected overridden projection // matrix. if( m_bViewToProjectionOverride ) { m_ViewToProjection[1][2] = -m_ViewToProjection[1][2]; } // Use the aspect ratio of the main view! So, don't recompute it here x = y = 0; width = pTexture->GetActualWidth(); height = pTexture->GetActualHeight(); angles[0] = -angles[0]; angles[2] = -angles[2]; origin[2] -= 2.0f * ( origin[2] - (waterHeight)); return true; } return false; } //----------------------------------------------------------------------------- // Pops a water render target //----------------------------------------------------------------------------- void CBaseWorldView::PushView( float waterHeight ) { float spread = 2.0f; if( m_DrawFlags & DF_FUDGE_UP ) { waterHeight += spread; } else { waterHeight -= spread; } MaterialHeightClipMode_t clipMode = MATERIAL_HEIGHTCLIPMODE_DISABLE; if ( ( m_DrawFlags & DF_CLIP_Z ) && mat_clipz.GetBool() ) { if( m_DrawFlags & DF_CLIP_BELOW ) { clipMode = MATERIAL_HEIGHTCLIPMODE_RENDER_ABOVE_HEIGHT; } else { clipMode = MATERIAL_HEIGHTCLIPMODE_RENDER_BELOW_HEIGHT; } } CMatRenderContextPtr pRenderContext( materials ); if( m_DrawFlags & DF_RENDER_REFRACTION ) { pRenderContext->SetFogZ( waterHeight ); pRenderContext->SetHeightClipZ( waterHeight ); pRenderContext->SetHeightClipMode( clipMode ); // Have to re-set up the view since we reset the size render->Push3DView( *this, m_ClearFlags, GetWaterRefractionTexture(), GetFrustum() ); return; } if( m_DrawFlags & DF_RENDER_REFLECTION ) { ITexture *pTexture = GetWaterReflectionTexture(); pRenderContext->SetFogZ( waterHeight ); bool bSoftwareUserClipPlane = g_pMaterialSystemHardwareConfig->UseFastClipping(); if( bSoftwareUserClipPlane && ( origin[2] > waterHeight - r_eyewaterepsilon.GetFloat() ) ) { waterHeight = origin[2] + r_eyewaterepsilon.GetFloat(); } pRenderContext->SetHeightClipZ( waterHeight ); pRenderContext->SetHeightClipMode( clipMode ); render->Push3DView( *this, m_ClearFlags, pTexture, GetFrustum() ); SetLightmapScaleForWater(); return; } if ( m_ClearFlags & ( VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR | VIEW_CLEAR_STENCIL ) ) { if ( m_ClearFlags & VIEW_CLEAR_OBEY_STENCIL ) { pRenderContext->ClearBuffersObeyStencil( m_ClearFlags & VIEW_CLEAR_COLOR, m_ClearFlags & VIEW_CLEAR_DEPTH ); } else { pRenderContext->ClearBuffers( m_ClearFlags & VIEW_CLEAR_COLOR, m_ClearFlags & VIEW_CLEAR_DEPTH, m_ClearFlags & VIEW_CLEAR_STENCIL ); } } pRenderContext->SetHeightClipMode( clipMode ); if ( clipMode != MATERIAL_HEIGHTCLIPMODE_DISABLE ) { pRenderContext->SetHeightClipZ( waterHeight ); } } //----------------------------------------------------------------------------- // Pops a water render target //----------------------------------------------------------------------------- void CBaseWorldView::PopView() { CMatRenderContextPtr pRenderContext( materials ); pRenderContext->SetHeightClipMode( MATERIAL_HEIGHTCLIPMODE_DISABLE ); if( m_DrawFlags & (DF_RENDER_REFRACTION | DF_RENDER_REFLECTION) ) { if ( IsX360() ) { // these renders paths used their surfaces, so blit their results if ( m_DrawFlags & DF_RENDER_REFRACTION ) { pRenderContext->CopyRenderTargetToTextureEx( GetWaterRefractionTexture(), NULL, NULL ); } if ( m_DrawFlags & DF_RENDER_REFLECTION ) { pRenderContext->CopyRenderTargetToTextureEx( GetWaterReflectionTexture(), NULL, NULL ); } } render->PopView( GetFrustum() ); if (SavedLinearLightMapScale.x>=0) { pRenderContext->SetToneMappingScaleLinear(SavedLinearLightMapScale); SavedLinearLightMapScale.x=-1; } } } //----------------------------------------------------------------------------- // Draws the world + entities //----------------------------------------------------------------------------- void CBaseWorldView::DrawSetup( float waterHeight, int nSetupFlags, float waterZAdjust, int iForceViewLeaf ) { int savedViewID = g_CurrentViewID; g_CurrentViewID = VIEW_ILLEGAL; bool bViewChanged = AdjustView( waterHeight ); if ( bViewChanged ) { render->Push3DView( *this, 0, NULL, GetFrustum() ); } render->BeginUpdateLightmaps(); bool bDrawEntities = ( nSetupFlags & DF_DRAW_ENTITITES ) != 0; bool bDrawReflection = ( nSetupFlags & DF_RENDER_REFLECTION ) != 0; BuildWorldRenderLists( bDrawEntities, iForceViewLeaf, true, false, bDrawReflection ? &waterHeight : NULL ); PruneWorldListInfo(); if ( bDrawEntities ) { BuildRenderableRenderLists( savedViewID ); } render->EndUpdateLightmaps(); if ( bViewChanged ) { render->PopView( GetFrustum() ); } #ifdef TF_CLIENT_DLL bool bVisionOverride = ( localplayer_visionflags.GetInt() & ( 0x01 ) ); // Pyro-vision Goggles if ( savedViewID == VIEW_MAIN && bVisionOverride && pyro_dof.GetBool() ) { SSAO_DepthPass(); } #endif g_CurrentViewID = savedViewID; } void MaybeInvalidateLocalPlayerAnimation() { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( ( pPlayer != NULL ) && pPlayer->InFirstPersonView() ) { // We sometimes need different animation for the main view versus the shadow rendering, // so we need to reset the cache to ensure this actually happens. pPlayer->InvalidateBoneCache(); C_BaseCombatWeapon *pWeapon = pPlayer->GetActiveWeapon(); if ( pWeapon != NULL ) { pWeapon->InvalidateBoneCache(); } #if defined USES_ECON_ITEMS // ...and all the things you're wearing/holding/etc int NumWearables = pPlayer->GetNumWearables(); for ( int i = 0; i < NumWearables; ++i ) { CEconWearable* pItem = pPlayer->GetWearable ( i ); if ( pItem != NULL ) { pItem->InvalidateBoneCache(); } } #endif // USES_ECON_ITEMS } } void CBaseWorldView::DrawExecute( float waterHeight, view_id_t viewID, float waterZAdjust ) { int savedViewID = g_CurrentViewID; // @MULTICORE (toml 8/16/2006): rethink how, where, and when this is done... g_CurrentViewID = VIEW_SHADOW_DEPTH_TEXTURE; MaybeInvalidateLocalPlayerAnimation(); g_pClientShadowMgr->ComputeShadowTextures( *this, m_pWorldListInfo->m_LeafCount, m_pWorldListInfo->m_pLeafList ); MaybeInvalidateLocalPlayerAnimation(); // Make sure sound doesn't stutter engine->Sound_ExtraUpdate(); g_CurrentViewID = viewID; // Update our render view flags. int iDrawFlagsBackup = m_DrawFlags; m_DrawFlags |= m_pMainView->GetBaseDrawFlags(); PushView( waterHeight ); CMatRenderContextPtr pRenderContext( materials ); #if defined( _X360 ) pRenderContext->PushVertexShaderGPRAllocation( 32 ); #endif ITexture *pSaveFrameBufferCopyTexture = pRenderContext->GetFrameBufferCopyTexture( 0 ); if ( engine->GetDXSupportLevel() >= 80 ) { pRenderContext->SetFrameBufferCopyTexture( GetPowerOfTwoFrameBufferTexture() ); } pRenderContext.SafeRelease(); ERenderDepthMode DepthMode = DEPTH_MODE_NORMAL; if ( m_DrawFlags & DF_DRAW_ENTITITES ) { DrawWorld( waterZAdjust ); DrawOpaqueRenderables( DepthMode ); #ifdef TF_CLIENT_DLL bool bVisionOverride = ( localplayer_visionflags.GetInt() & ( 0x01 ) ); // Pyro-vision Goggles if ( g_CurrentViewID == VIEW_MAIN && bVisionOverride && pyro_dof.GetBool() ) // Pyro-vision Goggles { DrawDepthOfField(); } #endif DrawTranslucentRenderables( false, false ); DrawNoZBufferTranslucentRenderables(); } else { DrawWorld( waterZAdjust ); #ifdef TF_CLIENT_DLL bool bVisionOverride = ( localplayer_visionflags.GetInt() & ( 0x01 ) ); // Pyro-vision Goggles if ( g_CurrentViewID == VIEW_MAIN && bVisionOverride && pyro_dof.GetBool() ) // Pyro-vision Goggles { DrawDepthOfField(); } #endif // Draw translucent world brushes only, no entities DrawTranslucentWorldInLeaves( false ); } // issue the pixel visibility tests for sub-views if ( !IsMainView( CurrentViewID() ) && CurrentViewID() != VIEW_INTRO_CAMERA ) { PixelVisibility_EndCurrentView(); } pRenderContext.GetFrom( materials ); pRenderContext->SetFrameBufferCopyTexture( pSaveFrameBufferCopyTexture ); PopView(); m_DrawFlags = iDrawFlagsBackup; g_CurrentViewID = savedViewID; #if defined( _X360 ) pRenderContext->PopVertexShaderGPRAllocation(); #endif } void CBaseWorldView::SSAO_DepthPass() { if ( !g_pMaterialSystemHardwareConfig->SupportsPixelShaders_2_0() ) { return; } #if 1 VPROF_BUDGET( "CSimpleWorldView::SSAO_DepthPass", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); int savedViewID = g_CurrentViewID; g_CurrentViewID = VIEW_SSAO; ITexture *pSSAO = materials->FindTexture( "_rt_ResolvedFullFrameDepth", TEXTURE_GROUP_RENDER_TARGET ); CMatRenderContextPtr pRenderContext( materials ); pRenderContext->ClearColor4ub( 255, 255, 255, 255 ); #if defined( _X360 ) Assert(0); // rebalance this if we ever use this on 360 pRenderContext->PushVertexShaderGPRAllocation( 112 ); //almost all work is done in vertex shaders for depth rendering, max out their threads #endif pRenderContext.SafeRelease(); if( IsPC() ) { render->Push3DView( (*this), VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, pSSAO, GetFrustum() ); } else if( IsX360() ) { render->Push3DView( (*this), VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, pSSAO, GetFrustum() ); } MDLCACHE_CRITICAL_SECTION(); engine->Sound_ExtraUpdate(); // Make sure sound doesn't stutter m_DrawFlags |= DF_SSAO_DEPTH_PASS; { VPROF_BUDGET( "DrawWorld", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); DrawWorld( 0.0f ); } // Draw opaque and translucent renderables with appropriate override materials // OVERRIDE_SSAO_DEPTH_WRITE is OK with a NULL material pointer modelrender->ForcedMaterialOverride( NULL, OVERRIDE_SSAO_DEPTH_WRITE ); { VPROF_BUDGET( "DrawOpaqueRenderables", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); DrawOpaqueRenderables( DEPTH_MODE_SSA0 ); } #if 0 if ( m_bRenderFlashlightDepthTranslucents || r_flashlightdepth_drawtranslucents.GetBool() ) { VPROF_BUDGET( "DrawTranslucentRenderables", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING ); DrawTranslucentRenderables( false, true ); } #endif modelrender->ForcedMaterialOverride( 0 ); m_DrawFlags &= ~DF_SSAO_DEPTH_PASS; pRenderContext.GetFrom( materials ); if( IsX360() ) { //Resolve() the depth texture here. Before the pop so the copy will recognize that the resolutions are the same pRenderContext->CopyRenderTargetToTextureEx( NULL, -1, NULL, NULL ); } render->PopView( GetFrustum() ); #if defined( _X360 ) pRenderContext->PopVertexShaderGPRAllocation(); #endif pRenderContext.SafeRelease(); g_CurrentViewID = savedViewID; #endif } void CBaseWorldView::DrawDepthOfField( ) { if ( !g_pMaterialSystemHardwareConfig->SupportsPixelShaders_2_0() ) { return; } CMatRenderContextPtr pRenderContext( materials ); ITexture *pSmallFB0 = materials->FindTexture( "_rt_smallfb0", TEXTURE_GROUP_RENDER_TARGET ); ITexture *pSmallFB1 = materials->FindTexture( "_rt_smallfb1", TEXTURE_GROUP_RENDER_TARGET ); Rect_t DestRect; int w = pSmallFB0->GetActualWidth(); int h = pSmallFB0->GetActualHeight(); DestRect.x = 0; DestRect.y = 0; DestRect.width = w; DestRect.height = h; pRenderContext->CopyRenderTargetToTextureEx( pSmallFB0, 0, NULL, &DestRect ); IMaterial *pPyroBlurXMaterial = materials->FindMaterial( "dev/pyro_blur_filter_x", TEXTURE_GROUP_OTHER ); IMaterial *pPyroBlurYMaterial = materials->FindMaterial( "dev/pyro_blur_filter_y", TEXTURE_GROUP_OTHER ); pRenderContext->PushRenderTargetAndViewport( pSmallFB1, 0, 0, w, h ); pRenderContext->DrawScreenSpaceRectangle( pPyroBlurYMaterial, 0, 0, w, h, 0, 0, w - 1, h - 1, w, h ); pRenderContext->PopRenderTargetAndViewport(); pRenderContext->PushRenderTargetAndViewport( pSmallFB0, 0, 0, w, h ); pRenderContext->DrawScreenSpaceRectangle( pPyroBlurXMaterial, 0, 0, w, h, 0, 0, w - 1, h - 1, w, h ); pRenderContext->PopRenderTargetAndViewport(); IMaterial *pPyroDepthOfFieldMaterial = materials->FindMaterial( "dev/pyro_dof", TEXTURE_GROUP_OTHER ); pRenderContext->DrawScreenSpaceRectangle( pPyroDepthOfFieldMaterial, x, y, width, height, 0, 0, width-1, height-1, width, height ); } //----------------------------------------------------------------------------- // Draws the scene when there's no water or only cheap water //----------------------------------------------------------------------------- void CSimpleWorldView::Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t &waterInfo, ViewCustomVisibility_t *pCustomVisibility ) { BaseClass::Setup( view ); m_ClearFlags = nClearFlags; m_DrawFlags = DF_DRAW_ENTITITES; if ( !waterInfo.m_bOpaqueWater ) { m_DrawFlags |= DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER; } else { bool bViewIntersectsWater = DoesViewPlaneIntersectWater( fogInfo.m_flWaterHeight, fogInfo.m_nVisibleFogVolume ); if( bViewIntersectsWater ) { // have to draw both sides if we can see both. m_DrawFlags |= DF_RENDER_UNDERWATER | DF_RENDER_ABOVEWATER; } else if ( fogInfo.m_bEyeInFogVolume ) { m_DrawFlags |= DF_RENDER_UNDERWATER; } else { m_DrawFlags |= DF_RENDER_ABOVEWATER; } } if ( waterInfo.m_bDrawWaterSurface ) { m_DrawFlags |= DF_RENDER_WATER; } if ( !fogInfo.m_bEyeInFogVolume && bDrawSkybox ) { m_DrawFlags |= DF_DRAWSKYBOX; } m_pCustomVisibility = pCustomVisibility; m_fogInfo = fogInfo; } //----------------------------------------------------------------------------- // Draws the scene when there's no water or only cheap water //----------------------------------------------------------------------------- void CSimpleWorldView::Draw() { VPROF( "CViewRender::ViewDrawScene_NoWater" ); CMatRenderContextPtr pRenderContext( materials ); PIXEVENT( pRenderContext, "CSimpleWorldView::Draw" ); #if defined( _X360 ) pRenderContext->PushVertexShaderGPRAllocation( 32 ); //lean toward pixel shader threads #endif pRenderContext.SafeRelease(); DrawSetup( 0, m_DrawFlags, 0 ); if ( !m_fogInfo.m_bEyeInFogVolume ) { EnableWorldFog(); } else { m_ClearFlags |= VIEW_CLEAR_COLOR; SetFogVolumeState( m_fogInfo, false ); pRenderContext.GetFrom( materials ); unsigned char ucFogColor[3]; pRenderContext->GetFogColor( ucFogColor ); pRenderContext->ClearColor4ub( ucFogColor[0], ucFogColor[1], ucFogColor[2], 255 ); } pRenderContext.SafeRelease(); DrawExecute( 0, CurrentViewID(), 0 ); pRenderContext.GetFrom( materials ); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); #if defined( _X360 ) pRenderContext->PopVertexShaderGPRAllocation(); #endif } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CBaseWaterView::CalcWaterEyeAdjustments( const VisibleFogVolumeInfo_t &fogInfo, float &newWaterHeight, float &waterZAdjust, bool bSoftwareUserClipPlane ) { if( !bSoftwareUserClipPlane ) { newWaterHeight = fogInfo.m_flWaterHeight; waterZAdjust = 0.0f; return; } newWaterHeight = fogInfo.m_flWaterHeight; float eyeToWaterZDelta = origin[2] - fogInfo.m_flWaterHeight; float epsilon = r_eyewaterepsilon.GetFloat(); waterZAdjust = 0.0f; if( fabs( eyeToWaterZDelta ) < epsilon ) { if( eyeToWaterZDelta > 0 ) { newWaterHeight = origin[2] - epsilon; } else { newWaterHeight = origin[2] + epsilon; } waterZAdjust = newWaterHeight - fogInfo.m_flWaterHeight; } // Warning( "view.origin[2]: %f newWaterHeight: %f fogInfo.m_flWaterHeight: %f waterZAdjust: %f\n", // ( float )view.origin[2], newWaterHeight, fogInfo.m_flWaterHeight, waterZAdjust ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CBaseWaterView::CSoftwareIntersectionView::Setup( bool bAboveWater ) { BaseClass::Setup( *GetOuter() ); m_DrawFlags = 0; m_DrawFlags = ( bAboveWater ) ? DF_RENDER_UNDERWATER : DF_RENDER_ABOVEWATER; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CBaseWaterView::CSoftwareIntersectionView::Draw() { DrawSetup( GetOuter()->m_waterHeight, m_DrawFlags, GetOuter()->m_waterZAdjust ); DrawExecute( GetOuter()->m_waterHeight, CurrentViewID(), GetOuter()->m_waterZAdjust ); } //----------------------------------------------------------------------------- // Draws the scene when the view point is above the level of the water //----------------------------------------------------------------------------- void CAboveWaterView::Setup( const CViewSetup &view, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t& waterInfo ) { BaseClass::Setup( view ); m_bSoftwareUserClipPlane = g_pMaterialSystemHardwareConfig->UseFastClipping(); CalcWaterEyeAdjustments( fogInfo, m_waterHeight, m_waterZAdjust, m_bSoftwareUserClipPlane ); // BROKEN STUFF! if ( m_waterZAdjust == 0.0f ) { m_bSoftwareUserClipPlane = false; } m_DrawFlags = DF_RENDER_ABOVEWATER | DF_DRAW_ENTITITES; m_ClearFlags = VIEW_CLEAR_DEPTH; #ifdef PORTAL if( g_pPortalRender->ShouldObeyStencilForClears() ) m_ClearFlags |= VIEW_CLEAR_OBEY_STENCIL; #endif if ( bDrawSkybox ) { m_DrawFlags |= DF_DRAWSKYBOX; } if ( waterInfo.m_bDrawWaterSurface ) { m_DrawFlags |= DF_RENDER_WATER; } if ( !waterInfo.m_bRefract && !waterInfo.m_bOpaqueWater ) { m_DrawFlags |= DF_RENDER_UNDERWATER; } m_fogInfo = fogInfo; m_waterInfo = waterInfo; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::Draw() { VPROF( "CViewRender::ViewDrawScene_EyeAboveWater" ); // eye is outside of water CMatRenderContextPtr pRenderContext( materials ); // render the reflection if( m_waterInfo.m_bReflect ) { m_ReflectionView.Setup( m_waterInfo.m_bReflectEntities ); m_pMainView->AddViewToScene( &m_ReflectionView ); } bool bViewIntersectsWater = false; // render refraction if ( m_waterInfo.m_bRefract ) { m_RefractionView.Setup(); m_pMainView->AddViewToScene( &m_RefractionView ); if( !m_bSoftwareUserClipPlane ) { bViewIntersectsWater = DoesViewPlaneIntersectWater( m_fogInfo.m_flWaterHeight, m_fogInfo.m_nVisibleFogVolume ); } } else if ( !( m_DrawFlags & DF_DRAWSKYBOX ) ) { m_ClearFlags |= VIEW_CLEAR_COLOR; } #ifdef PORTAL if( g_pPortalRender->ShouldObeyStencilForClears() ) m_ClearFlags |= VIEW_CLEAR_OBEY_STENCIL; #endif // NOTE!!!!! YOU CAN ONLY DO THIS IF YOU HAVE HARDWARE USER CLIP PLANES!!!!!! bool bHardwareUserClipPlanes = !g_pMaterialSystemHardwareConfig->UseFastClipping(); if( bViewIntersectsWater && bHardwareUserClipPlanes ) { // This is necessary to keep the non-water fogged world from drawing underwater in // the case where we want to partially see into the water. m_DrawFlags |= DF_CLIP_Z | DF_CLIP_BELOW; } // render the world DrawSetup( m_waterHeight, m_DrawFlags, m_waterZAdjust ); EnableWorldFog(); DrawExecute( m_waterHeight, CurrentViewID(), m_waterZAdjust ); if ( m_waterInfo.m_bRefract ) { if ( m_bSoftwareUserClipPlane ) { m_SoftwareIntersectionView.Setup( true ); m_SoftwareIntersectionView.Draw( ); } else if ( bViewIntersectsWater ) { m_IntersectionView.Setup(); m_pMainView->AddViewToScene( &m_IntersectionView ); } } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CReflectionView::Setup( bool bReflectEntities ) { BaseClass::Setup( *GetOuter() ); m_ClearFlags = VIEW_CLEAR_DEPTH; // NOTE: Clearing the color is unnecessary since we're drawing the skybox // and dest-alpha is never used in the reflection m_DrawFlags = DF_RENDER_REFLECTION | DF_CLIP_Z | DF_CLIP_BELOW | DF_RENDER_ABOVEWATER; // NOTE: This will cause us to draw the 2d skybox in the reflection // (which we want to do instead of drawing the 3d skybox) m_DrawFlags |= DF_DRAWSKYBOX; if( bReflectEntities ) { m_DrawFlags |= DF_DRAW_ENTITITES; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CReflectionView::Draw() { #ifdef PORTAL g_pPortalRender->WaterRenderingHandler_PreReflection(); #endif // Store off view origin and angles and set the new view int nSaveViewID = CurrentViewID(); SetupCurrentView( origin, angles, VIEW_REFLECTION ); // Disable occlusion visualization in reflection bool bVisOcclusion = r_visocclusion.GetInt(); r_visocclusion.SetValue( 0 ); DrawSetup( GetOuter()->m_fogInfo.m_flWaterHeight, m_DrawFlags, 0.0f, GetOuter()->m_fogInfo.m_nVisibleFogVolumeLeaf ); EnableWorldFog(); DrawExecute( GetOuter()->m_fogInfo.m_flWaterHeight, VIEW_REFLECTION, 0.0f ); r_visocclusion.SetValue( bVisOcclusion ); #ifdef PORTAL // deal with stencil g_pPortalRender->WaterRenderingHandler_PostReflection(); #endif // finish off the view and restore the previous view. SetupCurrentView( origin, angles, ( view_id_t )nSaveViewID ); // This is here for multithreading CMatRenderContextPtr pRenderContext( materials ); pRenderContext->Flush(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CRefractionView::Setup() { BaseClass::Setup( *GetOuter() ); m_ClearFlags = VIEW_CLEAR_COLOR | VIEW_CLEAR_DEPTH; m_DrawFlags = DF_RENDER_REFRACTION | DF_CLIP_Z | DF_RENDER_UNDERWATER | DF_FUDGE_UP | DF_DRAW_ENTITITES ; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CRefractionView::Draw() { #ifdef PORTAL g_pPortalRender->WaterRenderingHandler_PreRefraction(); #endif // Store off view origin and angles and set the new view int nSaveViewID = CurrentViewID(); SetupCurrentView( origin, angles, VIEW_REFRACTION ); DrawSetup( GetOuter()->m_waterHeight, m_DrawFlags, GetOuter()->m_waterZAdjust ); SetFogVolumeState( GetOuter()->m_fogInfo, true ); SetClearColorToFogColor(); DrawExecute( GetOuter()->m_waterHeight, VIEW_REFRACTION, GetOuter()->m_waterZAdjust ); #ifdef PORTAL // deal with stencil g_pPortalRender->WaterRenderingHandler_PostRefraction(); #endif // finish off the view. restore the previous view. SetupCurrentView( origin, angles, ( view_id_t )nSaveViewID ); // This is here for multithreading CMatRenderContextPtr pRenderContext( materials ); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); pRenderContext->Flush(); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CIntersectionView::Setup() { BaseClass::Setup( *GetOuter() ); m_DrawFlags = DF_RENDER_UNDERWATER | DF_CLIP_Z | DF_DRAW_ENTITITES; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CAboveWaterView::CIntersectionView::Draw() { DrawSetup( GetOuter()->m_fogInfo.m_flWaterHeight, m_DrawFlags, 0 ); SetFogVolumeState( GetOuter()->m_fogInfo, true ); SetClearColorToFogColor( ); DrawExecute( GetOuter()->m_fogInfo.m_flWaterHeight, VIEW_NONE, 0 ); CMatRenderContextPtr pRenderContext( materials ); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); } //----------------------------------------------------------------------------- // Draws the scene when the view point is under the level of the water //----------------------------------------------------------------------------- void CUnderWaterView::Setup( const CViewSetup &view, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t& waterInfo ) { BaseClass::Setup( view ); m_bSoftwareUserClipPlane = g_pMaterialSystemHardwareConfig->UseFastClipping(); CalcWaterEyeAdjustments( fogInfo, m_waterHeight, m_waterZAdjust, m_bSoftwareUserClipPlane ); IMaterial *pWaterMaterial = fogInfo.m_pFogVolumeMaterial; if (engine->GetDXSupportLevel() >= 90 ) // screen voerlays underwater are a dx9 feature { IMaterialVar *pScreenOverlayVar = pWaterMaterial->FindVar( "$underwateroverlay", NULL, false ); if ( pScreenOverlayVar && ( pScreenOverlayVar->IsDefined() ) ) { char const *pOverlayName = pScreenOverlayVar->GetStringValue(); if ( pOverlayName[0] != '0' ) // fixme!!! { IMaterial *pOverlayMaterial = materials->FindMaterial( pOverlayName, TEXTURE_GROUP_OTHER ); m_pMainView->SetWaterOverlayMaterial( pOverlayMaterial ); } } } // NOTE: We're not drawing the 2d skybox under water since it's assumed to not be visible. // render the world underwater // Clear the color to get the appropriate underwater fog color m_DrawFlags = DF_FUDGE_UP | DF_RENDER_UNDERWATER | DF_DRAW_ENTITITES; m_ClearFlags = VIEW_CLEAR_DEPTH; if( !m_bSoftwareUserClipPlane ) { m_DrawFlags |= DF_CLIP_Z; } if ( waterInfo.m_bDrawWaterSurface ) { m_DrawFlags |= DF_RENDER_WATER; } if ( !waterInfo.m_bRefract && !waterInfo.m_bOpaqueWater ) { m_DrawFlags |= DF_RENDER_ABOVEWATER; } m_fogInfo = fogInfo; m_waterInfo = waterInfo; m_bDrawSkybox = bDrawSkybox; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CUnderWaterView::Draw() { // FIXME: The 3d skybox shouldn't be drawn when the eye is under water VPROF( "CViewRender::ViewDrawScene_EyeUnderWater" ); CMatRenderContextPtr pRenderContext( materials ); // render refraction (out of water) if ( m_waterInfo.m_bRefract ) { m_RefractionView.Setup( ); m_pMainView->AddViewToScene( &m_RefractionView ); } if ( !m_waterInfo.m_bRefract ) { SetFogVolumeState( m_fogInfo, true ); unsigned char ucFogColor[3]; pRenderContext->GetFogColor( ucFogColor ); pRenderContext->ClearColor4ub( ucFogColor[0], ucFogColor[1], ucFogColor[2], 255 ); } DrawSetup( m_waterHeight, m_DrawFlags, m_waterZAdjust ); SetFogVolumeState( m_fogInfo, false ); DrawExecute( m_waterHeight, CurrentViewID(), m_waterZAdjust ); m_ClearFlags = 0; if( m_waterZAdjust != 0.0f && m_bSoftwareUserClipPlane && m_waterInfo.m_bRefract ) { m_SoftwareIntersectionView.Setup( false ); m_SoftwareIntersectionView.Draw( ); } pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CUnderWaterView::CRefractionView::Setup() { BaseClass::Setup( *GetOuter() ); // NOTE: Refraction renders into the back buffer, over the top of the 3D skybox // It is then blitted out into the refraction target. This is so that // we only have to set up 3d sky vis once, and only render it once also! m_DrawFlags = DF_CLIP_Z | DF_CLIP_BELOW | DF_RENDER_ABOVEWATER | DF_DRAW_ENTITITES; m_ClearFlags = VIEW_CLEAR_DEPTH; if ( GetOuter()->m_bDrawSkybox ) { m_ClearFlags |= VIEW_CLEAR_COLOR; m_DrawFlags |= DF_DRAWSKYBOX | DF_CLIP_SKYBOX; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CUnderWaterView::CRefractionView::Draw() { CMatRenderContextPtr pRenderContext( materials ); SetFogVolumeState( GetOuter()->m_fogInfo, true ); unsigned char ucFogColor[3]; pRenderContext->GetFogColor( ucFogColor ); pRenderContext->ClearColor4ub( ucFogColor[0], ucFogColor[1], ucFogColor[2], 255 ); DrawSetup( GetOuter()->m_waterHeight, m_DrawFlags, GetOuter()->m_waterZAdjust ); EnableWorldFog(); DrawExecute( GetOuter()->m_waterHeight, VIEW_REFRACTION, GetOuter()->m_waterZAdjust ); Rect_t srcRect; srcRect.x = x; srcRect.y = y; srcRect.width = width; srcRect.height = height; // Optionally write the rendered image to a debug texture if ( g_bDumpRenderTargets ) { DumpTGAofRenderTarget( width, height, "WaterRefract" ); } ITexture *pTexture = GetWaterRefractionTexture(); pRenderContext->CopyRenderTargetToTextureEx( pTexture, 0, &srcRect, NULL ); } //----------------------------------------------------------------------------- // // Reflective glass view starts here // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Draws the scene when the view contains reflective glass //----------------------------------------------------------------------------- void CReflectiveGlassView::Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t &waterInfo, const cplane_t &reflectionPlane ) { BaseClass::Setup( view, nClearFlags, bDrawSkybox, fogInfo, waterInfo, NULL ); m_ReflectionPlane = reflectionPlane; } bool CReflectiveGlassView::AdjustView( float flWaterHeight ) { ITexture *pTexture = GetWaterReflectionTexture(); // Use the aspect ratio of the main view! So, don't recompute it here x = y = 0; width = pTexture->GetActualWidth(); height = pTexture->GetActualHeight(); // Reflect the camera origin + vectors around the reflection plane float flDist = DotProduct( origin, m_ReflectionPlane.normal ) - m_ReflectionPlane.dist; VectorMA( origin, - 2.0f * flDist, m_ReflectionPlane.normal, origin ); Vector vecForward, vecUp; AngleVectors( angles, &vecForward, NULL, &vecUp ); float flDot = DotProduct( vecForward, m_ReflectionPlane.normal ); VectorMA( vecForward, - 2.0f * flDot, m_ReflectionPlane.normal, vecForward ); flDot = DotProduct( vecUp, m_ReflectionPlane.normal ); VectorMA( vecUp, - 2.0f * flDot, m_ReflectionPlane.normal, vecUp ); VectorAngles( vecForward, vecUp, angles ); return true; } void CReflectiveGlassView::PushView( float waterHeight ) { render->Push3DView( *this, m_ClearFlags, GetWaterReflectionTexture(), GetFrustum() ); Vector4D plane; VectorCopy( m_ReflectionPlane.normal, plane.AsVector3D() ); plane.w = m_ReflectionPlane.dist + 0.1f; CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PushCustomClipPlane( plane.Base() ); } void CReflectiveGlassView::PopView( ) { CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PopCustomClipPlane( ); render->PopView( GetFrustum() ); } //----------------------------------------------------------------------------- // Renders reflective or refractive parts of glass //----------------------------------------------------------------------------- void CReflectiveGlassView::Draw() { VPROF( "CReflectiveGlassView::Draw" ); CMatRenderContextPtr pRenderContext( materials ); PIXEVENT( pRenderContext, "CReflectiveGlassView::Draw" ); // Disable occlusion visualization in reflection bool bVisOcclusion = r_visocclusion.GetInt(); r_visocclusion.SetValue( 0 ); BaseClass::Draw(); r_visocclusion.SetValue( bVisOcclusion ); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); pRenderContext->Flush(); } //----------------------------------------------------------------------------- // Draws the scene when the view contains reflective glass //----------------------------------------------------------------------------- void CRefractiveGlassView::Setup( const CViewSetup &view, int nClearFlags, bool bDrawSkybox, const VisibleFogVolumeInfo_t &fogInfo, const WaterRenderInfo_t &waterInfo, const cplane_t &reflectionPlane ) { BaseClass::Setup( view, nClearFlags, bDrawSkybox, fogInfo, waterInfo, NULL ); m_ReflectionPlane = reflectionPlane; } bool CRefractiveGlassView::AdjustView( float flWaterHeight ) { ITexture *pTexture = GetWaterRefractionTexture(); // Use the aspect ratio of the main view! So, don't recompute it here x = y = 0; width = pTexture->GetActualWidth(); height = pTexture->GetActualHeight(); return true; } void CRefractiveGlassView::PushView( float waterHeight ) { render->Push3DView( *this, m_ClearFlags, GetWaterRefractionTexture(), GetFrustum() ); Vector4D plane; VectorMultiply( m_ReflectionPlane.normal, -1, plane.AsVector3D() ); plane.w = -m_ReflectionPlane.dist + 0.1f; CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PushCustomClipPlane( plane.Base() ); } void CRefractiveGlassView::PopView( ) { CMatRenderContextPtr pRenderContext( materials ); pRenderContext->PopCustomClipPlane( ); render->PopView( GetFrustum() ); } //----------------------------------------------------------------------------- // Renders reflective or refractive parts of glass //----------------------------------------------------------------------------- void CRefractiveGlassView::Draw() { VPROF( "CRefractiveGlassView::Draw" ); CMatRenderContextPtr pRenderContext( materials ); PIXEVENT( pRenderContext, "CRefractiveGlassView::Draw" ); BaseClass::Draw(); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); pRenderContext->Flush(); }
32.052344
278
0.661861
Davideogame
74262ac36c6cb1420abb410d40a05f779f2c85ec
797
hpp
C++
cpp/include/state/attached/device/Ready.hpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
1
2018-06-06T20:33:28.000Z
2018-06-06T20:33:28.000Z
cpp/include/state/attached/device/Ready.hpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
null
null
null
cpp/include/state/attached/device/Ready.hpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
1
2020-07-31T03:39:15.000Z
2020-07-31T03:39:15.000Z
#ifndef STATE_ATTACHED_DEVICE_READY_HPP #define STATE_ATTACHED_DEVICE_READY_HPP #include "state/attached/IAttachedState.hpp" namespace sl { namespace state { namespace attached { namespace device { class Ready : public IAttachedState { public: Ready(ILiveCycleState::Listener& listener); Ready(ILiveCycleState::Listener& listener, const event::bridge::Event* const _event); void start() noexcept override; IAttachedState* handleEvent(const event::endpoint::Event& event) override; IAttachedState* handleMessage(std::shared_ptr<skylync::BridgeMessage> message) override; std::string toString() const noexcept override; private: const event::bridge::Event* event; }; } // device } // attached } // state } // sl #endif // STATE_ATTACHED_DEVICE_READY_HPP
17.326087
92
0.749059
skydiveuas
742711a106919168cb2cc16bcc74628c4b4ebd27
6,421
hxx
C++
ivp/ivp_collision/ivp_mindist_minimize.hxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
ivp/ivp_collision/ivp_mindist_minimize.hxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
ivp/ivp_collision/ivp_mindist_minimize.hxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. #ifndef IVP_HASH_INCLUDED # include <ivu_hash.hxx> #endif class IVP_Cache_Ball; class IVP_Cache_Ledge_Point; // set IVP_LOOP_LIST_SIZE if you want to use a linear list for loop check instead of a HASH #define IVP_LOOP_LIST_SIZE 256 #if defined(IVP_LOOP_LIST_SIZE) struct IVP_MM_Loop_Hash_Struct { int a; int b; }; #endif class IVP_Mindist_Minimize_Solver { protected: ////////// initialisation static IVP_MRC_TYPE minimize_illegal(IVP_Mindist_Minimize_Solver *); static IVP_MRC_TYPE minimize_default_poly_poly(IVP_Mindist_Minimize_Solver *); // not all cases static IVP_MRC_TYPE minimize_swapped_poly_poly(IVP_Mindist_Minimize_Solver *); // swap and call default static IVP_MRC_TYPE minimize_PB(IVP_Mindist_Minimize_Solver *); static IVP_MRC_TYPE minimize_KB(IVP_Mindist_Minimize_Solver *); static IVP_MRC_TYPE minimize_FB(IVP_Mindist_Minimize_Solver *); static IVP_MRC_TYPE minimize_B_POLY(IVP_Mindist_Minimize_Solver *); //static IVP_MRC_TYPE minimize_BK(IVP_Mindist_Minimize_Solver *); //static IVP_MRC_TYPE minimize_BF(IVP_Mindist_Minimize_Solver *); static IVP_MRC_TYPE minimize_BB(IVP_Mindist_Minimize_Solver *); void swap_synapses(){ mindist->synapse_sort_flag ^= 1; } void sort_synapses( IVP_Synapse *a, IVP_Synapse *){ if ( a != mindist->get_sorted_synapse(0) ) swap_synapses(); } static IVP_MRC_TYPE (*mms_function_table[IVP_ST_MAX_LEGAL][IVP_ST_MAX_LEGAL])(IVP_Mindist_Minimize_Solver *mms); /////////// real functions void init_loop_hash(); IVP_BOOL check_loop_hash(IVP_SYNAPSE_POLYGON_STATUS s0, const IVP_Compact_Edge *e0, IVP_SYNAPSE_POLYGON_STATUS s1, const IVP_Compact_Edge *e1); IVP_MRC_TYPE p_minimize_PF(const IVP_Compact_Edge *P, const IVP_Compact_Edge *F, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_F); IVP_MRC_TYPE p_minimize_Leave_PF(const IVP_Compact_Edge *P,const IVP_U_Point *P_Fos, const IVP_Compact_Edge *F, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_F); IVP_MRC_TYPE p_minimize_PK(const IVP_Compact_Edge *P, const IVP_Compact_Edge *K, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_K); IVP_MRC_TYPE p_minimize_Leave_PK(const IVP_Compact_Edge *P,const IVP_Compact_Edge *K, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_K); IVP_MRC_TYPE p_minimize_PP(const IVP_Compact_Edge *A, const IVP_Compact_Edge *B, IVP_Cache_Ledge_Point *m_cache_A, IVP_Cache_Ledge_Point *m_cache_B); IVP_MRC_TYPE p_minimize_KK(const IVP_Compact_Edge *K,const IVP_Compact_Edge *L, IVP_Cache_Ledge_Point *m_cache_K, IVP_Cache_Ledge_Point *m_cache_L); IVP_MRC_TYPE p_minimize_Leave_KK(const IVP_Compact_Edge *K,const IVP_Compact_Edge *L, const class IVP_KK_Input &kkin, const class IVP_Unscaled_KK_Result *kkr, IVP_Cache_Ledge_Point *m_cache_K, IVP_Cache_Ledge_Point *m_cache_L); IVP_MRC_TYPE p_minimize_FF(const IVP_Compact_Edge *F, const IVP_Compact_Edge *G, IVP_Cache_Ledge_Point *m_cache_F, IVP_Cache_Ledge_Point *m_cache_G); IVP_MRC_TYPE p_minimize_BP(IVP_Cache_Ball *m_cache_ball, const IVP_Compact_Edge *P, IVP_Cache_Ledge_Point *m_cache_P); IVP_MRC_TYPE p_minimize_BK(IVP_Cache_Ball *m_cache_ball, const IVP_Compact_Edge *K, IVP_Cache_Ledge_Point *m_cache_K); IVP_MRC_TYPE p_minimize_Leave_BK(IVP_Cache_Ball *m_cache_ball, const IVP_Compact_Edge *K, IVP_Cache_Ledge_Point *m_cache_K); IVP_MRC_TYPE p_minimize_BF(IVP_Cache_Ball *m_cache_ball, const IVP_Compact_Edge *F, IVP_Cache_Ledge_Point *m_cache_F); #ifdef DEBUG_CHECK_LEN IVP_RETURN_TYPE validate_termination_len(IVP_DOUBLE now_val); // used by check_len_xx() IVP_RETURN_TYPE check_len_PP(IVP_Compact_Edge *A, IVP_Compact_Edge *B, IVP_Cache_Ledge_Point *m_cache_A, IVP_Cache_Ledge_Point *m_cache_B); IVP_RETURN_TYPE check_len_PK(IVP_Compact_Edge *P, IVP_Compact_Edge *K, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_K); IVP_RETURN_TYPE check_len_PF(IVP_Compact_Edge *P, IVP_Compact_Edge *F, IVP_Cache_Ledge_Point *m_cache_P, IVP_Cache_Ledge_Point *m_cache_F); IVP_RETURN_TYPE check_len_KK(IVP_Compact_Edge *K, IVP_Compact_Edge *L, IVP_Cache_Ledge_Point *m_cache_K, IVP_Cache_Ledge_Point *m_cache_L); IVP_RETURN_TYPE check_len_FF(IVP_Compact_Edge *F, IVP_Compact_Edge *G, IVP_Cache_Ledge_Point *m_cache_F, IVP_Cache_Ledge_Point *m_cache_G); #endif // for debug function proove() IVP_DOUBLE p_optimize_FF( const IVP_Compact_Edge *A, const IVP_Compact_Edge *B, IVP_Cache_Ledge_Point *m_cache_A, IVP_Cache_Ledge_Point *m_cache_B, IVP_DOUBLE min_qdist); #ifdef DEBUG IVP_RETURN_TYPE proove_polypoly(); IVP_RETURN_TYPE proove_ballpoly(); #endif public: IVP_Mindist *mindist; int P_Finish_Counter; // global for debug/termination purposes #ifdef DEBUG IVP_DOUBLE termination_len; // used for termination function test #endif void pierce_mindist(); IVP_U_Point pos_opposite_BacksideOs; // position of synapse opposite backside cases in backside space #if !defined(IVP_LOOP_LIST_SIZE) IVP_Hash *loop_hash; // record situations for loop check #else IVP_MM_Loop_Hash_Struct loop_hash[IVP_LOOP_LIST_SIZE]; int loop_hash_size; #endif IVP_Mindist_Minimize_Solver(IVP_Mindist *md) { mindist = md; #if !defined(IVP_LOOP_LIST_SIZE) loop_hash = NULL; #else loop_hash_size = 0; #endif P_Finish_Counter = IVP_MAX_MINIMIZE_BEFORE_HASH_CHECK; #ifdef DEBUG termination_len = P_DOUBLE_MAX; #endif }; static void init_mms_function_table(); ~IVP_Mindist_Minimize_Solver() { #if !defined(IVP_LOOP_LIST_SIZE) P_DELETE(loop_hash); #endif }; IVP_MRC_TYPE recalc_mindist_sub(){ IVP_IF_PREFETCH_ENABLED(IVP_TRUE){ IVP_PREFETCH( mindist->get_synapse(0)->edge,0); IVP_PREFETCH( mindist->get_synapse(1)->edge,0); } IVP_SYNAPSE_POLYGON_STATUS s0 = mindist->get_sorted_synapse(0)->get_status(); IVP_SYNAPSE_POLYGON_STATUS s1 = mindist->get_sorted_synapse(1)->get_status(); IVP_ASSERT(s0 < IVP_ST_MAX_LEGAL ); IVP_ASSERT(s1 < IVP_ST_MAX_LEGAL ); IVP_MRC_TYPE ret = mms_function_table[s0][s1]( this ); return ret; } };
43.680272
162
0.770752
DannyParker0001
742952d4b82d39bfb88cccf03030aa7b47ae7b08
2,308
cpp
C++
variant.cpp
erikvanhamme/ruleparser
2f3bc212aaa13c2b037a7c028f6dc218ac68e872
[ "MIT" ]
null
null
null
variant.cpp
erikvanhamme/ruleparser
2f3bc212aaa13c2b037a7c028f6dc218ac68e872
[ "MIT" ]
null
null
null
variant.cpp
erikvanhamme/ruleparser
2f3bc212aaa13c2b037a7c028f6dc218ac68e872
[ "MIT" ]
null
null
null
#include "variant.hpp" #include <string> #include <variant> namespace wf { bool is_int(const variant_t &v) { return std::holds_alternative<int>(v); } bool is_char(const variant_t &v) { return std::holds_alternative<char>(v); } bool is_bool(const variant_t &v) { return std::holds_alternative<bool>(v); } bool is_float(const variant_t &v) { return std::holds_alternative<float>(v); } bool is_double(const variant_t &v) { return std::holds_alternative<double>(v); } bool is_string(const variant_t &v) { return std::holds_alternative<std::string>(v); } variant_type_t type(const variant_t v) { if (is_int(v)) { return variant_type_t::INT; } if (is_char(v)) { return variant_type_t::CHAR; } if (is_bool(v)) { return variant_type_t::BOOL; } if (is_float(v)) { return variant_type_t::FLOAT; } if (is_double(v)) { return variant_type_t::DOUBLE; } return variant_type_t::STRING; } int get_int(const variant_t &v) { return std::get<int>(v); } char get_char(const variant_t &v) { return std::get<char>(v); } bool get_bool(const variant_t &v) { return std::get<bool>(v); } float get_float(const variant_t &v) { return std::get<float>(v); } double get_double(const variant_t &v) { return std::get<double>(v); } std::string get_string(const variant_t &v) { return std::get<std::string>(v); } std::string to_string(const variant_t &v) { std::string out = "variant: [type: "; if (is_int(v)) { out.append("int, value: ").append(std::to_string(get_int(v))); } else if (is_char(v)) { out.append("char, value: ").append(std::to_string(get_char(v))); } else if (is_bool(v)) { out.append("bool, value: ").append(std::to_string(get_bool(v))); } else if (is_float(v)) { out.append("float, value: ").append(std::to_string(get_float(v))); } else if (is_double(v)) { out.append("double, value: ").append(std::to_string(get_double(v))); } else if (is_string(v)) { out.append("string, value: ").append(get_string(v)); } else { out.append("invalid. WTF?!?"); } out.append("]"); return out; } } // End namespace wf.
17.618321
76
0.599653
erikvanhamme
742cdc6e01b69db56e47ebf6c3c7057338ee36da
2,376
cpp
C++
nano/core_test/unchecked_map.cpp
CathalT/raiblocks
3e2b49e20832074bb0105e288e8fa0762d5c8130
[ "BSD-2-Clause" ]
882
2018-02-13T22:06:38.000Z
2019-01-02T19:43:34.000Z
nano/core_test/unchecked_map.cpp
CathalT/raiblocks
3e2b49e20832074bb0105e288e8fa0762d5c8130
[ "BSD-2-Clause" ]
746
2018-02-13T19:44:54.000Z
2019-01-02T15:09:36.000Z
nano/core_test/unchecked_map.cpp
CathalT/raiblocks
3e2b49e20832074bb0105e288e8fa0762d5c8130
[ "BSD-2-Clause" ]
312
2018-02-14T00:25:33.000Z
2019-01-02T08:03:27.000Z
#include <nano/lib/blockbuilders.hpp> #include <nano/lib/logger_mt.hpp> #include <nano/node/unchecked_map.hpp> #include <nano/secure/store.hpp> #include <nano/secure/utility.hpp> #include <nano/test_common/system.hpp> #include <nano/test_common/testutil.hpp> #include <gtest/gtest.h> #include <memory> using namespace std::chrono_literals; namespace { class context { public: context () : store{ nano::make_store (logger, nano::unique_path (), nano::dev::constants) }, unchecked{ *store, false } { } nano::logger_mt logger; std::unique_ptr<nano::store> store; nano::unchecked_map unchecked; }; std::shared_ptr<nano::block> block () { nano::block_builder builder; return builder.state () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1) .link (nano::dev::genesis_key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (0) .build_shared (); } } TEST (unchecked_map, construction) { context context; } TEST (unchecked_map, put_one) { context context; nano::unchecked_info info{ block (), nano::dev::genesis_key.pub }; context.unchecked.put (info.block->previous (), info); } TEST (block_store, one_bootstrap) { nano::system system{}; nano::logger_mt logger{}; auto store = nano::make_store (logger, nano::unique_path (), nano::dev::constants); nano::unchecked_map unchecked{ *store, false }; ASSERT_TRUE (!store->init_error ()); auto block1 = std::make_shared<nano::send_block> (0, 1, 2, nano::keypair ().prv, 4, 5); unchecked.put (block1->hash (), nano::unchecked_info{ block1 }); auto check_block_is_listed = [&] (nano::transaction const & transaction_a, nano::block_hash const & block_hash_a) { return unchecked.get (transaction_a, block_hash_a).size () > 0; }; // Waits for the block1 to get saved in the database ASSERT_TIMELY (10s, check_block_is_listed (store->tx_begin_read (), block1->hash ())); auto transaction = store->tx_begin_read (); auto [begin, end] = unchecked.full_range (transaction); ASSERT_NE (end, begin); auto hash1 = begin->first.key (); ASSERT_EQ (block1->hash (), hash1); auto blocks = unchecked.get (transaction, hash1); ASSERT_EQ (1, blocks.size ()); auto block2 = blocks[0].block; ASSERT_EQ (*block1, *block2); ++begin; ASSERT_EQ (end, begin); }
28.97561
116
0.7117
CathalT
293b44e7ecff3e44eecaf5620d1e5cdd809b6d4a
20,772
cpp
C++
test/src/test_aichrono.cpp
aicpp/ailib
7b6dbe8d61db03a8e0fd3524a1d4bdc3cff5f597
[ "MIT" ]
2
2019-05-17T14:33:52.000Z
2022-03-04T18:10:38.000Z
test/src/test_aichrono.cpp
aicpp/ailib
7b6dbe8d61db03a8e0fd3524a1d4bdc3cff5f597
[ "MIT" ]
null
null
null
test/src/test_aichrono.cpp
aicpp/ailib
7b6dbe8d61db03a8e0fd3524a1d4bdc3cff5f597
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <ailib/aichrono.h> #include <fmt/format.h> using namespace ai; //--------------------------------------------------------------------------- class Test_aichrono : public ::testing::Test { public: Test_aichrono(void) { }; virtual ~Test_aichrono(void) { }; static void SetUpTestCase() { } void SetUp() override { } void TearDown() override { } protected: }; TEST_F(Test_aichrono, isEmpty_Duration) { ASSERT_TRUE (isEmpty(Duration(0))); ASSERT_FALSE(isEmpty(Duration(-1))); ASSERT_FALSE(isEmpty(Duration(1))); ASSERT_TRUE (isEmpty(Nanoseconds(0))); ASSERT_FALSE(isEmpty(Nanoseconds(-1))); ASSERT_FALSE(isEmpty(Nanoseconds(1))); ASSERT_TRUE (isEmpty(Microseconds(0))); ASSERT_FALSE(isEmpty(Microseconds(-1))); ASSERT_FALSE(isEmpty(Microseconds(1))); ASSERT_TRUE (isEmpty(Milliseconds(0))); ASSERT_FALSE(isEmpty(Milliseconds(-1))); ASSERT_FALSE(isEmpty(Milliseconds(1))); ASSERT_TRUE (isEmpty(Seconds(0))); ASSERT_FALSE(isEmpty(Seconds(-1))); ASSERT_FALSE(isEmpty(Seconds(1))); ASSERT_TRUE (isEmpty(Minutes(0))); ASSERT_FALSE(isEmpty(Minutes(-1))); ASSERT_FALSE(isEmpty(Minutes(1))); ASSERT_TRUE (isEmpty(Hours(0))); ASSERT_FALSE(isEmpty(Hours(-1))); ASSERT_FALSE(isEmpty(Hours(1))); ASSERT_TRUE (isEmpty(Days(0))); ASSERT_FALSE(isEmpty(Days(-1))); ASSERT_FALSE(isEmpty(Days(1))); } TEST_F(Test_aichrono, isEmpty_TimePoint) { ASSERT_TRUE (isEmpty(TimePoint())); ASSERT_TRUE (isEmpty(TimePoint::clock::from_time_t(0))); ASSERT_FALSE(isEmpty(TimePoint::clock::from_time_t(-1))); ASSERT_FALSE(isEmpty(TimePoint::clock::from_time_t(1))); ASSERT_FALSE(isEmpty(TimePoint::clock::now())); } TEST_F(Test_aichrono, isEmpty_SteadyTimePoint) { ASSERT_TRUE (isEmpty(SteadyTimePoint())); ASSERT_FALSE(isEmpty(SteadyTimePoint::clock::now())); } TEST_F(Test_aichrono, toDuration) { ASSERT_EQ(toDuration(Nanoseconds(123)).count() , 123); ASSERT_EQ(toDuration(Microseconds(123)).count(), 123 * 1000); ASSERT_EQ(toDuration(Milliseconds(123)).count(), 123 * 1000000); ASSERT_EQ(toDuration(Seconds(123)).count() , 123 * 1000000000LL); ASSERT_EQ(toDuration(Minutes(123)).count() , 123 * 1000000000LL * 60); ASSERT_EQ(toDuration(Hours(123)).count() , 123 * 1000000000LL * 60 * 60); ASSERT_EQ(toDuration(Days(123)).count() , 123 * 1000000000LL * 60 * 60 * 24); } TEST_F(Test_aichrono, toNanoseconds) { ASSERT_EQ(toNanoseconds(Nanoseconds(123)).count() , 123); ASSERT_EQ(toNanoseconds(Microseconds(123)).count(), 123 * 1000); ASSERT_EQ(toNanoseconds(Milliseconds(123)).count(), 123 * 1000000); ASSERT_EQ(toNanoseconds(Seconds(123)).count() , 123 * 1000000000LL); ASSERT_EQ(toNanoseconds(Minutes(123)).count() , 123 * 1000000000LL * 60); ASSERT_EQ(toNanoseconds(Hours(123)).count() , 123 * 1000000000LL * 60 * 60); ASSERT_EQ(toNanoseconds(Days(123)).count() , 123 * 1000000000LL * 60 * 60 * 24); } TEST_F(Test_aichrono, toMicroseconds) { ASSERT_EQ(toMicroseconds(Nanoseconds(123)).count() , 0); ASSERT_EQ(toMicroseconds(Nanoseconds(12345)).count(), 12); ASSERT_EQ(toMicroseconds(Microseconds(123)).count() , 123); ASSERT_EQ(toMicroseconds(Milliseconds(123)).count() , 123 * 1000); ASSERT_EQ(toMicroseconds(Seconds(123)).count() , 123 * 1000000LL); ASSERT_EQ(toMicroseconds(Minutes(123)).count() , 123 * 1000000LL * 60); ASSERT_EQ(toMicroseconds(Hours(123)).count() , 123 * 1000000LL * 60 * 60); ASSERT_EQ(toMicroseconds(Days(123)).count() , 123 * 1000000LL * 60 * 60 * 24); } TEST_F(Test_aichrono, toMilliseconds) { ASSERT_EQ(toMilliseconds(Nanoseconds(12345)).count(), 0); ASSERT_EQ(toMilliseconds(Microseconds(123)).count() , 0); ASSERT_EQ(toMilliseconds(Microseconds(723)).count() , 0); ASSERT_EQ(toMilliseconds(Microseconds(1723)).count(), 1); ASSERT_EQ(toMilliseconds(Milliseconds(123)).count() , 123); ASSERT_EQ(toMilliseconds(Seconds(123)).count() , 123 * 1000LL); ASSERT_EQ(toMilliseconds(Minutes(123)).count() , 123 * 1000LL * 60); ASSERT_EQ(toMilliseconds(Hours(123)).count() , 123 * 1000LL * 60 * 60); ASSERT_EQ(toMilliseconds(Days(123)).count() , 123 * 1000LL * 60 * 60 * 24); } TEST_F(Test_aichrono, toSeconds) { ASSERT_EQ(toSeconds(Nanoseconds(12345)).count(), 0); ASSERT_EQ(toSeconds(Microseconds(123)).count() , 0); ASSERT_EQ(toSeconds(Milliseconds(123)).count() , 0); ASSERT_EQ(toSeconds(Milliseconds(723)).count() , 0); ASSERT_EQ(toSeconds(Milliseconds(1723)).count(), 1); ASSERT_EQ(toSeconds(Seconds(123)).count() , 123 * 1LL); ASSERT_EQ(toSeconds(Minutes(123)).count() , 123 * 1LL * 60); ASSERT_EQ(toSeconds(Hours(123)).count() , 123 * 1LL * 60 * 60); ASSERT_EQ(toSeconds(Days(123)).count() , 123 * 1LL * 60 * 60 * 24); } TEST_F(Test_aichrono, toMinutes) { ASSERT_EQ(toMinutes(Nanoseconds(12345)).count(), 0); ASSERT_EQ(toMinutes(Microseconds(123)).count() , 0); ASSERT_EQ(toMinutes(Milliseconds(123)).count() , 0); ASSERT_EQ(toMinutes(Seconds(59)).count() , 0); ASSERT_EQ(toMinutes(Seconds(60)).count() , 1); ASSERT_EQ(toMinutes(Seconds(119)).count() , 1); ASSERT_EQ(toMinutes(Minutes(123)).count() , 123 * 1LL); ASSERT_EQ(toMinutes(Hours(123)).count() , 123 * 1LL * 60); ASSERT_EQ(toMinutes(Days(123)).count() , 123 * 1LL * 60 * 24); } TEST_F(Test_aichrono, toHours) { ASSERT_EQ(toHours(Nanoseconds(12345)).count(), 0); ASSERT_EQ(toHours(Microseconds(123)).count() , 0); ASSERT_EQ(toHours(Milliseconds(123)).count() , 0); ASSERT_EQ(toHours(Seconds(123)).count() , 0); ASSERT_EQ(toHours(Minutes(59)).count() , 0); ASSERT_EQ(toHours(Minutes(60)).count() , 1); ASSERT_EQ(toHours(Minutes(119)).count() , 1); ASSERT_EQ(toHours(Hours(123)).count() , 123 * 1LL); ASSERT_EQ(toHours(Days(123)).count() , 123 * 1LL * 24); } TEST_F(Test_aichrono, toDays) { ASSERT_EQ(toDays(Nanoseconds(12345)).count(), 0); ASSERT_EQ(toDays(Microseconds(123)).count() , 0); ASSERT_EQ(toDays(Milliseconds(123)).count() , 0); ASSERT_EQ(toDays(Seconds(60 * 60 * 24 - 1)).count() , 0); ASSERT_EQ(toDays(Seconds(60 * 60 * 24)).count() , 1); ASSERT_EQ(toDays(Minutes(123)).count() , 0); ASSERT_EQ(toDays(Hours(23)).count() , 0); ASSERT_EQ(toDays(Hours(24)).count() , 1); ASSERT_EQ(toDays(Hours(40)).count() , 1); ASSERT_EQ(toDays(Days(123)).count() , 123); } TEST_F(Test_aichrono, toCTime) { Clock::time_point empty; ASSERT_EQ(toCTime(empty), toSeconds(empty.time_since_epoch()).count()); Clock::time_point now = Clock::now(); ASSERT_EQ(toCTime(now), toSeconds(now.time_since_epoch()).count()); } TEST_F(Test_aichrono, fromCTime) { time_t empty = 0; ASSERT_EQ(fromCTime(empty), Clock::time_point()); time_t now = time(nullptr); ASSERT_EQ(fromCTime(now), Clock::from_time_t(now)); } TEST_F(Test_aichrono, tmGMT) { std::time_t now = std::time(nullptr); ASSERT_NO_THROW(ai::tmGMT(now)); const std::time_t invalid_max = std::numeric_limits<std::time_t>::max(); #ifndef _USE_32BIT_TIME_T ASSERT_THROW(ai::tmGMT(invalid_max), std::runtime_error); #endif const std::time_t invalid_min = std::numeric_limits<std::time_t>::min(); ASSERT_THROW(ai::tmGMT(invalid_min), std::runtime_error); const std::time_t invalid_min2 = -(time_t)(ai::toSeconds(ai::day * 1).count()); // above one day to exceed timezone limit ASSERT_THROW(ai::tmGMT(invalid_min2), std::runtime_error); std::time_t* invalid_ptr = nullptr; ASSERT_DEATH(ai::tmGMT(*invalid_ptr), ""); } TEST_F(Test_aichrono, tmLocal) { std::time_t now = std::time(nullptr); ASSERT_NO_THROW(ai::tmLocal(now)); const std::time_t invalid_max = std::numeric_limits<std::time_t>::max(); ASSERT_THROW(ai::tmLocal(invalid_max), std::runtime_error); const std::time_t invalid_min = std::numeric_limits<std::time_t>::min(); ASSERT_THROW(ai::tmLocal(invalid_min), std::runtime_error); const std::time_t invalid_min2 = -(time_t)(ai::toSeconds(ai::day * 1).count()); // above one day to exceed timezone limit ASSERT_THROW(ai::tmLocal(invalid_min2), std::runtime_error); std::time_t* invalid_ptr = nullptr; ASSERT_DEATH(ai::tmLocal(*invalid_ptr), ""); } TEST_F(Test_aichrono, gmtFromTm) { std::time_t now = std::time(nullptr); const auto tm_gmt = ai::tmGMT(now); const auto res_now = ai::gmtFromTm(tm_gmt); ASSERT_EQ(now, res_now); constexpr std::time_t invalid_time = -1; ASSERT_THROW(ai::gmtFromTm(ai::tmGMT(-1)), std::runtime_error); std::tm tm_invalid; std::memset(&tm_invalid, -1, sizeof(tm_invalid)); ASSERT_THROW(ai::gmtFromTm(tm_invalid), std::runtime_error) << "tm_invalid"; } TEST_F(Test_aichrono, toLocalTime) { std::time_t now = std::time(nullptr); ASSERT_GT(now, ai::toSeconds(ai::day).count()); const auto now_local = ai::toLocalTime(now); const auto tm_local = ai::tmGMT(now_local); const auto res_local_now = ai::gmtFromTm(tm_local); ASSERT_EQ(now_local, res_local_now); // const auto zero_local = ai::toLocalTime(0); // const auto tm_zero = ai::tmGMT(zero_local); // const auto res_zero = ai::gmtFromTm(tm_zero); // ASSERT_EQ(zero_local, res_zero); } TEST_F(Test_aichrono, toGMTTime) { std::time_t now = std::time(nullptr); ASSERT_GT(now, ai::toSeconds(ai::day).count()); const auto now_gmt = ai::toGMTTime(now); const auto tm_gmt = ai::tmGMT(now_gmt); const auto res_gmt = ai::gmtFromTm(tm_gmt); ASSERT_EQ(now_gmt, res_gmt); } TEST_F(Test_aichrono, offsetLocalTimezoneInSeconds) { const auto diff = difftime(123, 123); ASSERT_EQ(diff, 0.0); const auto offset_seconds = ai::offsetLocalTimezoneInSeconds(); std::time_t now = std::time(nullptr); const auto now_local = ai::toLocalTime(now); const auto now_gmt = ai::toGMTTime(now); const auto diff_times = now_local - now_gmt; ASSERT_EQ(diff_times, offset_seconds); } TEST_F(Test_aichrono, timePointFromString_DefaultSuccess) { std::string src_time = "2000-01-01 23:43:59"; std::string format = ai::default_format_time_point; const auto tp = ai::timePointFromString(src_time, format); // get etalon std::tm tm = {}; std::istringstream ss(src_time); ss >> std::get_time(&tm, format.c_str()); const auto tp_etalon = ai::fromCTime(ai::gmtFromTm(tm)); ASSERT_EQ(tp, tp_etalon); } TEST_F(Test_aichrono, timePointFromString_Success1) { std::string src_time = "2000-01-01"; std::string format = "%Y-%m-%d"; // locale independent format const auto tp = ai::timePointFromString(src_time, format); // get etalon std::tm tm = {}; std::istringstream ss(src_time); ss >> std::get_time(&tm, format.c_str()); const auto tp_etalon = ai::fromCTime(ai::gmtFromTm(tm)); ASSERT_EQ(tp, tp_etalon); } TEST_F(Test_aichrono, timePointFromString_Success2) { std::string src_time = "2018-12-31"; std::string format = "%Y-%m-%d"; const auto tp = ai::timePointFromString(src_time, format); // get etalon std::tm tm = {}; std::istringstream ss(src_time); ss >> std::get_time(&tm, format.c_str()); const auto tp_etalon = ai::fromCTime(ai::gmtFromTm(tm)); ASSERT_EQ(tp, tp_etalon); } TEST_F(Test_aichrono, timePointFromString_Success3) { std::string src_time = "2018 12 31"; std::string format = "%Y %m %d"; // locale independent format const auto tp = ai::timePointFromString(src_time, format); // get etalon std::tm tm = {}; std::istringstream ss(src_time); ss >> std::get_time(&tm, format.c_str()); const auto tp_etalon = ai::fromCTime(ai::gmtFromTm(tm)); ASSERT_EQ(tp, tp_etalon); } TEST_F(Test_aichrono, timePointFromString_EmptyInputTime) { std::string src_time = ""; std::string format = "%Y-%m-%d"; ASSERT_THROW(ai::timePointFromString(src_time, format), std::runtime_error); } TEST_F(Test_aichrono, timePointFromString_EmptyInputFormat) { std::string src_time = "2000-01-01 23:43:59"; std::string format = ""; ASSERT_THROW(ai::timePointFromString(src_time, format), std::runtime_error); } TEST_F(Test_aichrono, timePointFromString_InvalidInputTime) { std::string src_time = "dsa000 fd2s1 f0a1"; std::string format = "%Y-%m-%d"; ASSERT_THROW(ai::timePointFromString(src_time, format), std::runtime_error); } TEST_F(Test_aichrono, timePointFromString_InvalidInputFormat) { std::string src_time = "2000-01-01 23:43:59"; std::string format = "2000-01-01 23:43:59"; ASSERT_THROW(ai::timePointFromString(src_time, format), std::runtime_error); } TEST_F(Test_aichrono, stringFromTimePoint_DefaultSuccess) { const auto now = ai::Clock::now(); std::string format = ai::default_format_time_point; const auto str_time = ai::stringFromTimePoint(now); // get etalon const auto tm = tmGMT(toCTime(now)); std::ostringstream ss; ss << std::put_time(&tm, format.c_str()); const auto etalon = ss.str(); ASSERT_EQ(str_time, etalon); } TEST_F(Test_aichrono, stringFromTimePoint_Success1) { const auto now = ai::Clock::now(); std::string format = "%Y-%m-%d"; const auto str_time = ai::stringFromTimePoint(now, format); // get etalon const auto tm = tmGMT(toCTime(now)); std::ostringstream ss; ss << std::put_time(&tm, format.c_str()); const auto etalon = ss.str(); ASSERT_EQ(str_time, etalon); } TEST_F(Test_aichrono, stringFromTimePoint_Success2) { const auto now = ai::Clock::now(); std::string format = "%Y %m %d"; const auto str_time = ai::stringFromTimePoint(now, format); // get etalon const auto tm = tmGMT(toCTime(now)); std::ostringstream ss; ss << std::put_time(&tm, format.c_str()); const auto etalon = ss.str(); ASSERT_EQ(str_time, etalon); } TEST_F(Test_aichrono, stringFromTimePoint_EmptyInputFormat) { const auto now = ai::Clock::now(); std::string format = ""; ASSERT_EQ(ai::stringFromTimePoint(now, format), ""); } TEST_F(Test_aichrono, stringFromTimePoint_EmptyInputTime) { const ai::TimePoint tp = {}; std::string format = "%Y-%m-%d"; ASSERT_EQ(ai::stringFromTimePoint(tp, format), "1970-01-01"); } TEST_F(Test_aichrono, stringFromTimePoint_InvalidInputFormat1) { const auto now = ai::Clock::now(); std::string format = "dsa000 fd2s1 f0a1"; ASSERT_EQ(ai::stringFromTimePoint(now, format), format); } TEST_F(Test_aichrono, stringFromTimePoint_InvalidInputFormat2) { const auto now = ai::Clock::now(); std::string format = "%q"; // invalid sp ASSERT_DEATH(ai::stringFromTimePoint(now, format), ""); } TEST_F(Test_aichrono, durationFromString_Empty) { std::string str_duration = ""; const auto dur = ai::durationFromString(str_duration); ASSERT_EQ(dur, ai::Duration{}); } TEST_F(Test_aichrono, durationFromString_Invalid) { ASSERT_EQ(ai::durationFromString("asdf"), ai::Duration{}); ASSERT_EQ(ai::durationFromString(" "), ai::Duration{}); ASSERT_EQ(ai::durationFromString(" fs"), ai::Duration{}); ASSERT_EQ(ai::durationFromString(" hj45gd"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45gd"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("tr45d"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("tr45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45se"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45s e"), ai::Duration{}); } TEST_F(Test_aichrono, durationFromString_InvalidMultipleRatios) { // doesn't allow multiple ratios ASSERT_EQ(ai::durationFromString("45s45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45m45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45m 45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("45m 45"), ai::Duration{}); } TEST_F(Test_aichrono, durationFromString_InvalidNegative) { // doesn't allow multiple ratios ASSERT_EQ(ai::durationFromString("-45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString(" -45s"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("-45"), ai::Duration{}); ASSERT_EQ(ai::durationFromString("-45m"), ai::Duration{}); } TEST_F(Test_aichrono, durationFromString_Valid) { static std::pair<std::string, Duration> ratios[] = { std::make_pair("ms", millisecond), std::make_pair("s", second), std::make_pair("m", minute), std::make_pair("h", hour), std::make_pair("d", day), }; static size_t numbers[] = { 1, 2, 9, 10, 99, 101, 999, 54201, }; for (const auto& ratio : ratios) { for (const auto& num : numbers) { const auto str_base = std::to_string(num) + ratio.first; const auto dur_match = ratio.second * num; ASSERT_EQ(ai::durationFromString(str_base), dur_match) << "ratio:" << ratio.first << " num:" << num; ASSERT_EQ(ai::durationFromString(str_base + " "), dur_match) << "ratio:" << ratio.first << " num:" << num; ASSERT_EQ(ai::durationFromString(" " + str_base), dur_match) << "ratio:" << ratio.first << " num:" << num; ASSERT_EQ(ai::durationFromString(" " + str_base + " "), dur_match) << "ratio:" << ratio.first << " num:" << num; if (ratio.second == second) { ASSERT_EQ(ai::durationFromString(std::to_string(num)), dur_match) << "ratio:" << ratio.first << " num:" << num; } } } } TEST_F(Test_aichrono, stringFromDuration_Days) { static size_t parts[] = { 1, 2, 9, 10, 99, 101, 999, 54201, }; for (const auto& num : parts) { const auto str_match = std::to_string(num * 24) + ":00:00.000"; const auto dur = day * num; ASSERT_EQ(stringFromDuration(dur), str_match) << "num:" << num; ASSERT_EQ(stringFromDuration(-dur), "-" + str_match) << "num:" << num; } } TEST_F(Test_aichrono, stringFromDuration_Hours) { static size_t parts[] = { 1, 2, 9, 10, 99, 101, 999, 54201, }; for (const auto& num : parts) { const auto str_match = fmt::format("{:02}", num) + ":00:00.000"; const auto dur = hour * num; ASSERT_EQ(stringFromDuration(dur), str_match) << "num:" << num; ASSERT_EQ(stringFromDuration(-dur), "-" + str_match) << "num:" << num; } } TEST_F(Test_aichrono, stringFromDuration_Minutes) { static size_t parts[] = { 1, 2, 9, 10, 59, }; for (const auto& num : parts) { const auto str_match = fmt::format("{:02}", num) + ":00.000"; const auto dur = minute * num; ASSERT_EQ(stringFromDuration(dur), str_match) << "num:" << num; ASSERT_EQ(stringFromDuration(-dur), "-" + str_match) << "num:" << num; } } TEST_F(Test_aichrono, stringFromDuration_Seconds) { static size_t parts[] = { 1, 2, 9, 10, 59, }; for (const auto& num : parts) { const auto str_match = fmt::format("{:02}", num) + ".000"; const auto dur = second * num; ASSERT_EQ(stringFromDuration(dur), str_match) << "num:" << num; ASSERT_EQ(stringFromDuration(-dur), "-" + str_match) << "num:" << num; } } TEST_F(Test_aichrono, stringFromDuration_Milliseconds) { static size_t parts[] = { 1, 2, 9, 10, 59, 101, 999, }; for (const auto& num : parts) { const auto str_match = "00." + fmt::format("{:03}", num); const auto dur = millisecond * num; ASSERT_EQ(stringFromDuration(dur), str_match) << "num:" << num; ASSERT_EQ(stringFromDuration(-dur), "-" + str_match) << "num:" << num; } } TEST_F(Test_aichrono, stringFromDuration_Complex) { ASSERT_EQ(stringFromDuration(134h + 33min + 5s + 543ms), "134:33:05.543"); ASSERT_EQ(stringFromDuration(0h + 33min + 5s + 543ms), "33:05.543"); ASSERT_EQ(stringFromDuration(0h + 120min + 5s + 543ms), "02:00:05.543"); ASSERT_EQ(stringFromDuration(0h + 120min + 5s + 0ms), "02:00:05.000"); } TEST_F(Test_aichrono, stringFromDuration_Empty) { ASSERT_EQ(stringFromDuration({}), "00.000"); }
32.154799
127
0.639322
aicpp
293e373d22d3fe317cccd815b276a5ee7a705068
416
cpp
C++
_site/Competitive Programming/UVa/UVa11389.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
1
2019-06-10T04:39:49.000Z
2019-06-10T04:39:49.000Z
_site/Competitive Programming/UVa/UVa11389.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
2
2021-09-27T23:34:07.000Z
2022-02-26T05:54:27.000Z
_site/Competitive Programming/UVa/UVa11389.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
3
2019-06-23T14:15:08.000Z
2019-07-09T20:40:58.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int n, d, r; while(cin>>n>>d>>r && n+d+r){ int m[n], e[n]; for (int i = 0; i < n; ++i) { cin>>m[i]; } for (int i = 0; i < n; ++i) { cin>>e[i]; } sort(m,m+n); sort(e,e+n,greater<int>()); int money = 0; for (int i = 0; i < n; ++i) { int tmp = m[i] + e[i]; if(tmp > d) money += (tmp-d); } cout<<money*r<<"\n"; } }
15.407407
30
0.430288
anujkyadav07
2940f7d1d152cf41740bb3d0587d248193e2737e
4,653
cpp
C++
ouzel/graphics/opengl/RenderTargetOGL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/graphics/opengl/RenderTargetOGL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/graphics/opengl/RenderTargetOGL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "RenderTargetOGL.h" #include "TextureOGL.h" #include "core/Engine.h" #include "RendererOGL.h" #include "utils/Utils.h" namespace ouzel { namespace graphics { RenderTargetOGL::RenderTargetOGL() { } RenderTargetOGL::~RenderTargetOGL() { if (depthBufferId) { RendererOGL::deleteResource(depthBufferId, RendererOGL::ResourceType::RenderBuffer); } if (frameBufferId) { RendererOGL::deleteResource(frameBufferId, RendererOGL::ResourceType::FrameBuffer); } } void RenderTargetOGL::free() { RenderTarget::free(); if (depthBufferId) { RendererOGL::deleteResource(depthBufferId, RendererOGL::ResourceType::RenderBuffer); depthBufferId = 0; } if (frameBufferId) { RendererOGL::deleteResource(frameBufferId, RendererOGL::ResourceType::FrameBuffer); frameBufferId = 0; } } bool RenderTargetOGL::upload() { if (uploadData.dirty) { if (!texture->upload()) { return false; } if (!frameBufferId) { glGenFramebuffers(1, &frameBufferId); if (RendererOGL::checkOpenGLError()) { Log(Log::Level::ERR) << "Failed to create frame buffer"; return false; } clearMask = GL_COLOR_BUFFER_BIT; if (uploadData.depthBuffer) { clearMask |= GL_DEPTH_BUFFER_BIT; } } std::shared_ptr<TextureOGL> textureOGL = std::static_pointer_cast<TextureOGL>(texture); if (!textureOGL->getTextureId()) { Log(Log::Level::ERR) << "OpenGL texture not initialized"; return false; } RendererOGL::bindFrameBuffer(frameBufferId); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { RendererOGL::bindTexture(textureOGL->getTextureId(), 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<GLsizei>(uploadData.size.v[0]), static_cast<GLsizei>(uploadData.size.v[1]), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); if (uploadData.depthBuffer) { glGenRenderbuffers(1, &depthBufferId); glBindRenderbuffer(GL_RENDERBUFFER, depthBufferId); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<GLsizei>(uploadData.size.v[0]), static_cast<GLsizei>(uploadData.size.v[1])); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferId); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureOGL->getTextureId(), 0); #if OUZEL_SUPPORTS_OPENGL // TODO: fix this //GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; //glDrawBuffers(1, drawBuffers); glDrawBuffer(GL_COLOR_ATTACHMENT0); #endif if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { Log(Log::Level::ERR) << "Failed to create frame buffer"; return false; } } frameBufferClearColor[0] = uploadData.clearColor.normR(); frameBufferClearColor[1] = uploadData.clearColor.normG(); frameBufferClearColor[2] = uploadData.clearColor.normB(); frameBufferClearColor[3] = uploadData.clearColor.normA(); uploadData.dirty = false; } return true; } } // namespace graphics } // namespace ouzel
34.723881
127
0.509564
keima97
2944b8a22534b313526e7e17329a41acba76ff86
1,965
cpp
C++
PlayFabSDK/Plugins/PlayFab/Source/PlayFabProxy/Private/Proxy/Admin/PFAdminUpdateRandomResultTables.cpp
fordream/UnrealCppSdk
84a38f3f32712334c29704892c5c8358804b40ae
[ "Apache-2.0" ]
null
null
null
PlayFabSDK/Plugins/PlayFab/Source/PlayFabProxy/Private/Proxy/Admin/PFAdminUpdateRandomResultTables.cpp
fordream/UnrealCppSdk
84a38f3f32712334c29704892c5c8358804b40ae
[ "Apache-2.0" ]
null
null
null
PlayFabSDK/Plugins/PlayFab/Source/PlayFabProxy/Private/Proxy/Admin/PFAdminUpdateRandomResultTables.cpp
fordream/UnrealCppSdk
84a38f3f32712334c29704892c5c8358804b40ae
[ "Apache-2.0" ]
1
2020-04-09T10:55:33.000Z
2020-04-09T10:55:33.000Z
// This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #include "PlayFabProxyPrivatePCH.h" #include "PFAdminUpdateRandomResultTables.h" UPFAdminUpdateRandomResultTables::UPFAdminUpdateRandomResultTables(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , SuccessDelegate(PlayFab::UPlayFabAdminAPI::FUpdateRandomResultTablesDelegate::CreateUObject(this, &ThisClass::OnSuccessCallback)) , ErrorDelegate(PlayFab::FPlayFabErrorDelegate::CreateUObject(this, &ThisClass::OnErrorCallback)) { } UPFAdminUpdateRandomResultTables* UPFAdminUpdateRandomResultTables::UpdateRandomResultTables(UObject* WorldContextObject, class APlayerController* PlayerController , const FString& InCatalogVersion, const TArray<FBPAdminRandomResultTable>& InTables) { UPFAdminUpdateRandomResultTables* Proxy = NewObject<UPFAdminUpdateRandomResultTables>(); //Proxy->PlayerControllerWeakPtr = PlayerController; Proxy->Request.CatalogVersion = InCatalogVersion; for (const FBPAdminRandomResultTable& elem : InTables) { Proxy->Request.Tables.Add(elem.Data); } //Proxy->WorldContextObject = WorldContextObject; return Proxy; } void UPFAdminUpdateRandomResultTables::Activate() { // grab the module, so we can get a valid pointer to the client API PlayFabAdminPtr AdminAPI = IPlayFabModuleInterface::Get().GetAdminAPI(); bool CallResult = false; if(AdminAPI.IsValid()) { CallResult = AdminAPI->UpdateRandomResultTables(Request, SuccessDelegate, ErrorDelegate); } if(CallResult == false) { OnFailure.Broadcast(); } } ////////////////////////////////////////////////////////////////////////// // Delegate handles void UPFAdminUpdateRandomResultTables::OnSuccessCallback(const PlayFab::AdminModels::FUpdateRandomResultTablesResult& Result) { OnSuccess.Broadcast(); } void UPFAdminUpdateRandomResultTables::OnErrorCallback(const PlayFab::FPlayFabError& InError) { OnFailure.Broadcast(); }
33.87931
249
0.776081
fordream
29451961c36f7e1ac55e76379fbd8f7cba14006e
13,364
cpp
C++
WickedEngine/wiImage.cpp
sierra-zero/WickedEngine
85c1ef5df3ada61e9d5ac5357e062e6040baa09d
[ "WTFPL", "MIT" ]
null
null
null
WickedEngine/wiImage.cpp
sierra-zero/WickedEngine
85c1ef5df3ada61e9d5ac5357e062e6040baa09d
[ "WTFPL", "MIT" ]
null
null
null
WickedEngine/wiImage.cpp
sierra-zero/WickedEngine
85c1ef5df3ada61e9d5ac5357e062e6040baa09d
[ "WTFPL", "MIT" ]
null
null
null
#include "wiImage.h" #include "wiResourceManager.h" #include "wiRenderer.h" #include "wiHelper.h" #include "SamplerMapping.h" #include "ResourceMapping.h" #include "ShaderInterop_Image.h" #include "wiBackLog.h" #include "wiEvent.h" #include <atomic> using namespace std; using namespace wiGraphics; namespace wiImage { enum IMAGE_SHADER { IMAGE_SHADER_STANDARD, IMAGE_SHADER_SEPARATENORMALMAP, IMAGE_SHADER_MASKED, IMAGE_SHADER_BACKGROUNDBLUR, IMAGE_SHADER_BACKGROUNDBLUR_MASKED, IMAGE_SHADER_FULLSCREEN, IMAGE_SHADER_COUNT }; GPUBuffer constantBuffer; Shader vertexShader; Shader screenVS; Shader imagePS[IMAGE_SHADER_COUNT]; BlendState blendStates[BLENDMODE_COUNT]; RasterizerState rasterizerState; DepthStencilState depthStencilStates[STENCILMODE_COUNT][STENCILREFMODE_COUNT]; PipelineState imagePSO[IMAGE_SHADER_COUNT][BLENDMODE_COUNT][STENCILMODE_COUNT][STENCILREFMODE_COUNT]; Texture backgroundBlurTextures[COMMANDLIST_COUNT]; std::atomic_bool initialized{ false }; void SetBackgroundBlurTexture(const Texture& texture, CommandList cmd) { backgroundBlurTextures[cmd] = texture; } void Draw(const Texture* texture, const wiImageParams& params, CommandList cmd) { if (!initialized.load()) { return; } GraphicsDevice* device = wiRenderer::GetDevice(); device->EventBegin("Image", cmd); uint32_t stencilRef = params.stencilRef; if (params.stencilRefMode == STENCILREFMODE_USER) { stencilRef = wiRenderer::CombineStencilrefs(STENCILREF_EMPTY, (uint8_t)stencilRef); } device->BindStencilRef(stencilRef, cmd); const Sampler* sampler = wiRenderer::GetSampler(SSLOT_LINEAR_CLAMP); if (params.quality == QUALITY_NEAREST) { if (params.sampleFlag == SAMPLEMODE_MIRROR) sampler = wiRenderer::GetSampler(SSLOT_POINT_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) sampler = wiRenderer::GetSampler(SSLOT_POINT_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) sampler = wiRenderer::GetSampler(SSLOT_POINT_CLAMP); } else if (params.quality == QUALITY_LINEAR) { if (params.sampleFlag == SAMPLEMODE_MIRROR) sampler = wiRenderer::GetSampler(SSLOT_LINEAR_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) sampler = wiRenderer::GetSampler(SSLOT_LINEAR_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) sampler = wiRenderer::GetSampler(SSLOT_LINEAR_CLAMP); } else if (params.quality == QUALITY_ANISOTROPIC) { if (params.sampleFlag == SAMPLEMODE_MIRROR) sampler = wiRenderer::GetSampler(SSLOT_ANISO_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) sampler = wiRenderer::GetSampler(SSLOT_ANISO_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) sampler = wiRenderer::GetSampler(SSLOT_ANISO_CLAMP); } if (device->CheckCapability(GRAPHICSDEVICE_CAPABILITY_BINDLESS_DESCRIPTORS)) { PushConstantsImage push; push.texture_base_index = device->GetDescriptorIndex(texture, SRV); push.texture_mask_index = device->GetDescriptorIndex(params.maskMap, SRV); push.texture_background_index = device->GetDescriptorIndex(&backgroundBlurTextures[cmd], SRV); push.sampler_index = device->GetDescriptorIndex(sampler); device->PushConstants(&push, sizeof(push), cmd); } else { device->BindResource(PS, texture, TEXSLOT_IMAGE_BASE, cmd); device->BindResource(PS, params.maskMap, TEXSLOT_IMAGE_MASK, cmd); device->BindResource(PS, &backgroundBlurTextures[cmd], TEXSLOT_IMAGE_BACKGROUND, cmd); device->BindSampler(PS, sampler, SSLOT_ONDEMAND0, cmd); } ImageCB cb; cb.xColor = params.color; const float darken = 1 - params.fade; cb.xColor.x *= darken; cb.xColor.y *= darken; cb.xColor.z *= darken; cb.xColor.w *= params.opacity; if (params.isFullScreenEnabled()) { device->BindPipelineState(&imagePSO[IMAGE_SHADER_FULLSCREEN][params.blendFlag][params.stencilComp][params.stencilRefMode], cmd); device->UpdateBuffer(&constantBuffer, &cb, cmd); device->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(ImageCB), cmd); device->Draw(3, 0, cmd); device->EventEnd(cmd); return; } XMMATRIX M = XMMatrixScaling(params.scale.x * params.siz.x, params.scale.y * params.siz.y, 1); M = M * XMMatrixRotationZ(params.rotation); if (params.customRotation != nullptr) { M = M * (*params.customRotation); } M = M * XMMatrixTranslation(params.pos.x, params.pos.y, params.pos.z); if (params.customProjection != nullptr) { M = XMMatrixScaling(1, -1, 1) * M; // reason: screen projection is Y down (like UV-space) and that is the common case for image rendering. But custom projections will use the "world space" M = M * (*params.customProjection); } else { M = M * device->GetScreenProjection(); } for (int i = 0; i < 4; ++i) { XMVECTOR V = XMVectorSet(params.corners[i].x - params.pivot.x, params.corners[i].y - params.pivot.y, 0, 1); V = XMVector2Transform(V, M); // division by w will happen on GPU XMStoreFloat4(&cb.xCorners[i], V); } if (params.isMirrorEnabled()) { std::swap(cb.xCorners[0], cb.xCorners[1]); std::swap(cb.xCorners[2], cb.xCorners[3]); } const TextureDesc& desc = texture->GetDesc(); const float inv_width = 1.0f / float(desc.Width); const float inv_height = 1.0f / float(desc.Height); if (params.isDrawRectEnabled()) { cb.xTexMulAdd.x = params.drawRect.z * inv_width; // drawRec.width: mul cb.xTexMulAdd.y = params.drawRect.w * inv_height; // drawRec.heigh: mul cb.xTexMulAdd.z = params.drawRect.x * inv_width; // drawRec.x: add cb.xTexMulAdd.w = params.drawRect.y * inv_height; // drawRec.y: add } else { cb.xTexMulAdd = XMFLOAT4(1, 1, 0, 0); // disabled draw rect } cb.xTexMulAdd.z += params.texOffset.x * inv_width; // texOffset.x: add cb.xTexMulAdd.w += params.texOffset.y * inv_height; // texOffset.y: add if (params.isDrawRect2Enabled()) { cb.xTexMulAdd2.x = params.drawRect2.z * inv_width; // drawRec.width: mul cb.xTexMulAdd2.y = params.drawRect2.w * inv_height; // drawRec.heigh: mul cb.xTexMulAdd2.z = params.drawRect2.x * inv_width; // drawRec.x: add cb.xTexMulAdd2.w = params.drawRect2.y * inv_height; // drawRec.y: add } else { cb.xTexMulAdd2 = XMFLOAT4(1, 1, 0, 0); // disabled draw rect } cb.xTexMulAdd2.z += params.texOffset2.x * inv_width; // texOffset.x: add cb.xTexMulAdd2.w += params.texOffset2.y * inv_height; // texOffset.y: add device->UpdateBuffer(&constantBuffer, &cb, cmd); // Determine relevant image rendering pixel shader: IMAGE_SHADER targetShader; const bool NormalmapSeparate = params.isExtractNormalMapEnabled(); const bool Mask = params.maskMap != nullptr; const bool background_blur = params.isBackgroundBlurEnabled(); if (NormalmapSeparate) { targetShader = IMAGE_SHADER_SEPARATENORMALMAP; } else { if (Mask) { if (background_blur) { targetShader = IMAGE_SHADER_BACKGROUNDBLUR_MASKED; } else { targetShader = IMAGE_SHADER_MASKED; } } else { if (background_blur) { targetShader = IMAGE_SHADER_BACKGROUNDBLUR; } else { targetShader = IMAGE_SHADER_STANDARD; } } } device->BindPipelineState(&imagePSO[targetShader][params.blendFlag][params.stencilComp][params.stencilRefMode], cmd); device->BindConstantBuffer(VS, &constantBuffer, CB_GETBINDSLOT(ImageCB), cmd); device->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(ImageCB), cmd); device->Draw(4, 0, cmd); device->EventEnd(cmd); } void LoadShaders() { std::string path = wiRenderer::GetShaderPath(); wiRenderer::LoadShader(VS, vertexShader, "imageVS.cso"); wiRenderer::LoadShader(VS, screenVS, "screenVS.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_STANDARD], "imagePS.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_SEPARATENORMALMAP], "imagePS_separatenormalmap.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_MASKED], "imagePS_masked.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_BACKGROUNDBLUR], "imagePS_backgroundblur.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_BACKGROUNDBLUR_MASKED], "imagePS_backgroundblur_masked.cso"); wiRenderer::LoadShader(PS, imagePS[IMAGE_SHADER_FULLSCREEN], "screenPS.cso"); GraphicsDevice* device = wiRenderer::GetDevice(); for (int i = 0; i < IMAGE_SHADER_COUNT; ++i) { PipelineStateDesc desc; desc.vs = &vertexShader; if (i == IMAGE_SHADER_FULLSCREEN) { desc.vs = &screenVS; } desc.rs = &rasterizerState; desc.pt = TRIANGLESTRIP; desc.ps = &imagePS[i]; for (int j = 0; j < BLENDMODE_COUNT; ++j) { desc.bs = &blendStates[j]; for (int k = 0; k < STENCILMODE_COUNT; ++k) { for (int m = 0; m < STENCILREFMODE_COUNT; ++m) { desc.dss = &depthStencilStates[k][m]; device->CreatePipelineState(&desc, &imagePSO[i][j][k][m]); } } } } } void Initialize() { GraphicsDevice* device = wiRenderer::GetDevice(); { GPUBufferDesc bd; bd.Usage = USAGE_DYNAMIC; bd.ByteWidth = sizeof(ImageCB); bd.BindFlags = BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = CPU_ACCESS_WRITE; device->CreateBuffer(&bd, nullptr, &constantBuffer); } RasterizerState rs; rs.FillMode = FILL_SOLID; rs.CullMode = CULL_NONE; rs.FrontCounterClockwise = false; rs.DepthBias = 0; rs.DepthBiasClamp = 0; rs.SlopeScaledDepthBias = 0; rs.DepthClipEnable = true; rs.MultisampleEnable = false; rs.AntialiasedLineEnable = false; rasterizerState = rs; for (int i = 0; i < STENCILREFMODE_COUNT; ++i) { DepthStencilState dsd; dsd.DepthEnable = false; dsd.StencilEnable = false; depthStencilStates[STENCILMODE_DISABLED][i] = dsd; dsd.StencilEnable = true; switch (i) { case STENCILREFMODE_ENGINE: dsd.StencilReadMask = STENCILREF_MASK_ENGINE; break; case STENCILREFMODE_USER: dsd.StencilReadMask = STENCILREF_MASK_USER; break; default: dsd.StencilReadMask = STENCILREF_MASK_ALL; break; } dsd.StencilWriteMask = 0; dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; dsd.FrontFace.StencilFunc = COMPARISON_EQUAL; dsd.BackFace.StencilFunc = COMPARISON_EQUAL; depthStencilStates[STENCILMODE_EQUAL][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_LESS; dsd.BackFace.StencilFunc = COMPARISON_LESS; depthStencilStates[STENCILMODE_LESS][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_LESS_EQUAL; dsd.BackFace.StencilFunc = COMPARISON_LESS_EQUAL; depthStencilStates[STENCILMODE_LESSEQUAL][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_GREATER; dsd.BackFace.StencilFunc = COMPARISON_GREATER; depthStencilStates[STENCILMODE_GREATER][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_GREATER_EQUAL; dsd.BackFace.StencilFunc = COMPARISON_GREATER_EQUAL; depthStencilStates[STENCILMODE_GREATEREQUAL][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_NOT_EQUAL; dsd.BackFace.StencilFunc = COMPARISON_NOT_EQUAL; depthStencilStates[STENCILMODE_NOT][i] = dsd; dsd.FrontFace.StencilFunc = COMPARISON_ALWAYS; dsd.BackFace.StencilFunc = COMPARISON_ALWAYS; depthStencilStates[STENCILMODE_ALWAYS][i] = dsd; } BlendState bd; bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; bd.IndependentBlendEnable = false; blendStates[BLENDMODE_ALPHA] = bd; bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_ONE; bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; bd.IndependentBlendEnable = false; blendStates[BLENDMODE_PREMULTIPLIED] = bd; bd.RenderTarget[0].BlendEnable = false; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; bd.IndependentBlendEnable = false; blendStates[BLENDMODE_OPAQUE] = bd; bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = BLEND_ONE; bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = BLEND_ZERO; bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; bd.IndependentBlendEnable = false; blendStates[BLENDMODE_ADDITIVE] = bd; static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); LoadShaders(); wiBackLog::post("wiImage Initialized"); initialized.store(true); } }
31.518868
191
0.728899
sierra-zero
29482324fc5f521b0594fe41ec4174e3e9179f7e
66,126
hpp
C++
third_party/miniz/miniz.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
third_party/miniz/miniz.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
third_party/miniz/miniz.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
/* miniz.c 2.0.8 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #pragma once /* Defines to completely disable specific portions of miniz.c: If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ #define MINIZ_NO_STDIO /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ /* get/set file times, and the C run-time funcs that get/set times won't be called. */ /* The current downside is the times written to your archives will be from 1979. */ #define MINIZ_NO_TIME /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ /* #define MINIZ_NO_ARCHIVE_APIS */ /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ /* #define MINIZ_NO_ARCHIVE_WRITING_APIS */ /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ /*#define MINIZ_NO_ZLIB_APIS */ /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ /*#define MINIZ_NO_MALLOC */ #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ #define MINIZ_NO_TIME #endif #include <stddef.h> #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) #include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ #define MINIZ_X86_OR_X64_CPU 1 #else #define MINIZ_X86_OR_X64_CPU 0 #endif #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif #if MINIZ_X86_OR_X64_CPU /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 // always 0 because alignment #else #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ #define MINIZ_HAS_64BIT_REGISTERS 1 #else #define MINIZ_HAS_64BIT_REGISTERS 0 #endif namespace guinsoodb_miniz { /* ------------------- zlib-style API Definitions. */ /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ typedef unsigned long mz_ulong; /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ void mz_free(void *p); #define MZ_ADLER32_INIT (1) /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); /* Compression strategies. */ enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; /* Method */ #define MZ_DEFLATED 8 /* Heap allocation callbacks. Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; #define MZ_VERSION "10.0.3" #define MZ_VERNUM 0xA030 #define MZ_VER_MAJOR 10 #define MZ_VER_MINOR 0 #define MZ_VER_REVISION 3 #define MZ_VER_SUBREVISION 0 #ifndef MINIZ_NO_ZLIB_APIS /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; /* Return status codes. MZ_PARAM_ERROR is non-standard. */ enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; /* Window bits */ #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; /* Compression/decompression stream struct. */ typedef struct mz_stream_s { const unsigned char *next_in; /* pointer to next byte to read */ unsigned int avail_in; /* number of bytes available at next_in */ mz_ulong total_in; /* total number of bytes consumed so far */ unsigned char *next_out; /* pointer to next byte to write */ unsigned int avail_out; /* number of bytes that can be written to next_out */ mz_ulong total_out; /* total number of bytes produced so far */ char *msg; /* error msg (unused) */ struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ mz_free_func zfree; /* optional heap free function (defaults to free) */ void *opaque; /* heap alloc function user pointer */ int data_type; /* data_type (unused) */ mz_ulong adler; /* adler32 of the source or uncompressed data */ mz_ulong reserved; /* not used */ } mz_stream; typedef mz_stream *mz_streamp; /* Returns the version string of miniz.c. */ const char *mz_version(void); /* mz_deflateInit() initializes a compressor with default options: */ /* Parameters: */ /* pStream must point to an initialized mz_stream struct. */ /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ /* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ /* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ /* Return values: */ /* MZ_OK on success. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_PARAM_ERROR if the input parameters are bogus. */ /* MZ_MEM_ERROR on out of memory. */ int mz_deflateInit(mz_streamp pStream, int level); /* mz_deflateInit2() is like mz_deflate(), except with more control: */ /* Additional parameters: */ /* method must be MZ_DEFLATED */ /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ int mz_deflateReset(mz_streamp pStream); /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ /* Parameters: */ /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ /* Return values: */ /* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ /* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_PARAM_ERROR if one of the parameters is invalid. */ /* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ int mz_deflate(mz_streamp pStream, int flush); /* mz_deflateEnd() deinitializes a compressor: */ /* Return values: */ /* MZ_OK on success. */ /* MZ_STREAM_ERROR if the stream is bogus. */ int mz_deflateEnd(mz_streamp pStream); /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); /* Single-call compression functions mz_compress() and mz_compress2(): */ /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ mz_ulong mz_compressBound(mz_ulong source_len); /* Initializes a decompressor. */ int mz_inflateInit(mz_streamp pStream); /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ int mz_inflateInit2(mz_streamp pStream, int window_bits); /* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ /* Parameters: */ /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ /* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ /* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ /* Return values: */ /* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ /* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ /* MZ_STREAM_ERROR if the stream is bogus. */ /* MZ_DATA_ERROR if the deflate stream is invalid. */ /* MZ_PARAM_ERROR if one of the parameters is invalid. */ /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ /* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ int mz_inflate(mz_streamp pStream, int flush); /* Deinitializes a decompressor. */ int mz_inflateEnd(mz_streamp pStream); /* Single-call decompression. */ /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); /* Returns a string description of the specified error code, or NULL if the error code is invalid. */ const char *mz_error(int err); /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ #endif /* MINIZ_NO_ZLIB_APIS */ } #pragma once #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <string.h> namespace guinsoodb_miniz { /* ------------------- Types and macros */ typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef int64_t mz_int64; typedef uint64_t mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #define MZ_FILE FILE #endif /* #ifdef MINIZ_NO_STDIO */ #ifdef MINIZ_NO_TIME typedef struct mz_dummy_time_t_tag { int m_dummy; } mz_dummy_time_t; #define MZ_TIME_T mz_dummy_time_t #else #define MZ_TIME_T time_t #endif #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); extern void miniz_def_free_func(void *opaque, void *address); extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); #define MZ_UINT16_MAX (0xFFFFU) #define MZ_UINT32_MAX (0xFFFFFFFFU) #pragma once /* ------------------- Low-level Compression API Definitions */ /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ #define TDEFL_LESS_MEMORY 0 /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; /* High level compression functions: */ /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ /* On entry: */ /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ /* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ /* On return: */ /* Function returns a pointer to the compressed data, or NULL on failure. */ /* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ /* The caller must free() the returned block when it's no longer needed. */ void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ /* Returns 0 on failure. */ size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); /* Compresses an image to a compressed PNG file in memory. */ /* On entry: */ /* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ /* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ /* On return: */ /* Function returns a pointer to the compressed data, or NULL on failure. */ /* *pLen_out will be set to the size of the PNG image file. */ /* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); /* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif /* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; /* tdefl's compression state structure. */ typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; /* Initializes the compressor. */ /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); /* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ /* tdefl_compress_buffer() always consumes the entire input buffer. */ tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); /* Create tdefl_compress() flags given zlib-style compression parameters. */ /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ /* window_bits may be -15 (raw deflate) or 15 (zlib) */ /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); /* Allocate the tdefl_compressor structure in C so that */ /* non-C language bindings to tdefl_ API don't need to worry about */ /* structure size and allocation mechanism. */ tdefl_compressor *tdefl_compressor_alloc(); void tdefl_compressor_free(tdefl_compressor *pComp); #pragma once /* ------------------- Low-level Decompression API Definitions */ /* Decompression flags used by tinfl_decompress(). */ /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; /* High level decompression functions: */ /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ /* On entry: */ /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ /* On return: */ /* Function returns a pointer to the decompressed data, or NULL on failure. */ /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ /* The caller must call mz_free() on the returned block when it's no longer needed. */ void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ /* Returns 1 on success or 0 on failure. */ typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; /* Allocate the tinfl_decompressor structure in C so that */ /* non-C language bindings to tinfl_ API don't need to worry about */ /* structure size and allocation mechanism. */ tinfl_decompressor *tinfl_decompressor_alloc(); void tinfl_decompressor_free(tinfl_decompressor *pDecomp); /* Max size of LZ dictionary. */ #define TINFL_LZ_DICT_SIZE 32768 /* Return status. */ typedef enum { /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ TINFL_STATUS_BAD_PARAM = -3, /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ TINFL_STATUS_ADLER32_MISMATCH = -2, /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ TINFL_STATUS_FAILED = -1, /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ TINFL_STATUS_DONE = 0, /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ TINFL_STATUS_NEEDS_MORE_INPUT = 1, /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ /* so I may need to add some code to address this. */ TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; /* Initializes the decompressor to its initial state. */ #define tinfl_init(r) \ do \ { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); /* Internal/private bits follow. */ enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #else #define TINFL_USE_64BIT_BITBUF 0 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; #pragma once /* ------------------- ZIP archive reading/writing */ #ifndef MINIZ_NO_ARCHIVE_APIS enum { /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 }; typedef struct { /* Central directory file index. */ mz_uint32 m_file_index; /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ mz_uint64 m_central_dir_ofs; /* These fields are copied directly from the zip's central dir. */ mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME MZ_TIME_T m_time; #endif /* CRC-32 of uncompressed data. */ mz_uint32 m_crc32; /* File's compressed size. */ mz_uint64 m_comp_size; /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ mz_uint64 m_uncomp_size; /* Zip internal and external file attributes. */ mz_uint16 m_internal_attr; mz_uint32 m_external_attr; /* Entry's local header file offset in bytes. */ mz_uint64 m_local_header_ofs; /* Size of comment in bytes. */ mz_uint32 m_comment_size; /* MZ_TRUE if the entry appears to be a directory. */ mz_bool m_is_directory; /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ mz_bool m_is_encrypted; /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ mz_bool m_is_supported; /* Filename. If string ends in '/' it's a subdirectory entry. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; /* Comment field. */ /* Guaranteed to be zero terminated, may be truncated to fit. */ char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000 } mz_zip_flags; typedef enum { MZ_ZIP_TYPE_INVALID = 0, MZ_ZIP_TYPE_USER, MZ_ZIP_TYPE_MEMORY, MZ_ZIP_TYPE_HEAP, MZ_ZIP_TYPE_FILE, MZ_ZIP_TYPE_CFILE, MZ_ZIP_TOTAL_TYPES } mz_zip_type; /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ typedef enum { MZ_ZIP_NO_ERROR = 0, MZ_ZIP_UNDEFINED_ERROR, MZ_ZIP_TOO_MANY_FILES, MZ_ZIP_FILE_TOO_LARGE, MZ_ZIP_UNSUPPORTED_METHOD, MZ_ZIP_UNSUPPORTED_ENCRYPTION, MZ_ZIP_UNSUPPORTED_FEATURE, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, MZ_ZIP_NOT_AN_ARCHIVE, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, MZ_ZIP_UNSUPPORTED_MULTIDISK, MZ_ZIP_DECOMPRESSION_FAILED, MZ_ZIP_COMPRESSION_FAILED, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, MZ_ZIP_CRC_CHECK_FAILED, MZ_ZIP_UNSUPPORTED_CDIR_SIZE, MZ_ZIP_ALLOC_FAILED, MZ_ZIP_FILE_OPEN_FAILED, MZ_ZIP_FILE_CREATE_FAILED, MZ_ZIP_FILE_WRITE_FAILED, MZ_ZIP_FILE_READ_FAILED, MZ_ZIP_FILE_CLOSE_FAILED, MZ_ZIP_FILE_SEEK_FAILED, MZ_ZIP_FILE_STAT_FAILED, MZ_ZIP_INVALID_PARAMETER, MZ_ZIP_INVALID_FILENAME, MZ_ZIP_BUF_TOO_SMALL, MZ_ZIP_INTERNAL_ERROR, MZ_ZIP_FILE_NOT_FOUND, MZ_ZIP_ARCHIVE_TOO_LARGE, MZ_ZIP_VALIDATION_FAILED, MZ_ZIP_WRITE_CALLBACK_FAILED, MZ_ZIP_TOTAL_ERRORS } mz_zip_error; typedef struct { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; /* We only support up to UINT32_MAX files in zip64 mode. */ mz_uint32 m_total_files; mz_zip_mode m_zip_mode; mz_zip_type m_zip_type; mz_zip_error m_last_error; mz_uint64 m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; mz_file_needs_keepalive m_pNeeds_keepalive; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef struct { mz_zip_archive *pZip; mz_uint flags; int status; #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS mz_uint file_crc32; #endif mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf; void *pWrite_buf; size_t out_blk_remain; tinfl_decompressor inflator; } mz_zip_reader_extract_iter_state; /* -------- ZIP reading */ /* Inits a ZIP archive reader. */ /* These functions read and validate the archive's central directory. */ mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); #ifndef MINIZ_NO_STDIO /* Read a archive from a disk file. */ /* file_start_ofs is the file offset where the archive actually begins, or 0. */ /* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); /* Read an archive from an already opened FILE, beginning at the current file position. */ /* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */ /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); #endif /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ mz_bool mz_zip_reader_end(mz_zip_archive *pZip); /* -------- ZIP reading or writing */ /* Clears a mz_zip_archive struct to all zeros. */ /* Important: This must be done before passing the struct to any mz_zip functions. */ void mz_zip_zero_struct(mz_zip_archive *pZip); mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); /* Returns the total number of files in the archive. */ mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ /* Note that the m_last_error functionality is not thread safe. */ mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); const char *mz_zip_get_error_string(mz_zip_error mz_err); /* MZ_TRUE if the archive file entry is a directory entry. */ mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the file is encrypted/strong encrypted. */ mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); /* Retrieves the filename of an archive file entry. */ /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); /* Attempts to locates a file in the archive's central directory. */ /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ /* Returns -1 if the file cannot be found. */ int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); /* Returns detailed information about an archive file entry. */ mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); /* MZ_TRUE if the file is in zip64 format. */ /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); /* Returns the total central directory size in bytes. */ /* The current max supported size is <= MZ_UINT32_MAX. */ size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); /* Extracts a archive file to a memory buffer using no memory allocation. */ /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); /* Extracts a archive file to a memory buffer. */ mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); /* Extracts a archive file to a dynamically allocated heap buffer. */ /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ /* Returns NULL and sets the last error on failure. */ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); /* Extracts a archive file using a callback function to output the file's data. */ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); /* Extract a file iteratively */ mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); #ifndef MINIZ_NO_STDIO /* Extracts a archive file to a disk file and sets its last accessed and modified times. */ /* This function only extracts files, not archive directory records. */ mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); /* Extracts a archive file starting at the current position in the destination FILE stream. */ mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); #endif #if 0 /* TODO */ typedef void *mz_zip_streaming_extract_state_ptr; mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); #endif /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ /* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); /* Validates an entire archive by calling mz_zip_validate_file() on each file. */ mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); /* Misc utils/helpers, valid for ZIP reading or writing */ mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ mz_bool mz_zip_end(mz_zip_archive *pZip); /* -------- ZIP writing */ #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS /* Inits a ZIP archive writer. */ /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); #endif /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ /* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ /* the archive is finalized the file's central directory will be hosed. */ mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); /* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ /* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len); #ifndef MINIZ_NO_STDIO /* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len); #endif /* Adds a file to an archive by fully cloning the data from another archive. */ /* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); /* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ /* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ /* An archive must be manually finalized by calling this function for it to be valid. */ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); /* Finalizes a heap archive, returning a poiner to the heap block and its size. */ /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); /* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ /* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ mz_bool mz_zip_writer_end(mz_zip_archive *pZip); /* -------- Misc. high-level helper functions: */ /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); /* Reads a single file from an archive into a heap block. */ /* If pComment is not NULL, only the file with the specified comment will be extracted. */ /* Returns NULL on failure. */ void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ #endif /* MINIZ_NO_ARCHIVE_APIS */ } // namespace guinsoodb_miniz
51.300233
250
0.772601
GuinsooLab
2948e3b0e7b9c6fe3575ec95b76eb65b00b192ce
2,199
cpp
C++
Project3/src/rendering/framebufferobject.cpp
polferrando98/Qt-Project-3
747d9ce5c5c0f2ce5e7497978250636567136a80
[ "MIT" ]
1
2020-06-29T09:49:40.000Z
2020-06-29T09:49:40.000Z
Project3Root/Project3/src/rendering/framebufferobject.cpp
MarcFly/AGP-ShaderLearning
b4e448423480a651ff5de350340291497f146fa8
[ "Unlicense" ]
null
null
null
Project3Root/Project3/src/rendering/framebufferobject.cpp
MarcFly/AGP-ShaderLearning
b4e448423480a651ff5de350340291497f146fa8
[ "Unlicense" ]
null
null
null
#include "framebufferobject.h" #include "rendering/gl.h" #include <QOpenGLFramebufferObject> #include <QDebug> FramebufferObject::FramebufferObject() { } void FramebufferObject::create() { gl->glGenFramebuffers(1, &id); } void FramebufferObject::destroy() { gl->glDeleteFramebuffers(1, &id); } void FramebufferObject::addColorAttachment(GLuint attachment, GLuint textureId, GLint level) { gl->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachment, GL_TEXTURE_2D, textureId, level); } void FramebufferObject::addDepthAttachment(GLuint textureId, GLint level) { gl->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, textureId, level); } void FramebufferObject::checkStatus() { GLenum status; status = gl->glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // Everything's OK break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; case GL_FRAMEBUFFER_UNSUPPORTED: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "GL_FRAMEBUFFER_UNSUPPORTED"; break; default: qDebug() << "FBO::checkStatus() ERROR: " << name << " " << "Unknown ERROR"; } } void FramebufferObject::bind() { gl->glBindFramebuffer(GL_FRAMEBUFFER, id); } void FramebufferObject::release() { QOpenGLFramebufferObject::bindDefault(); }
29.716216
115
0.643474
polferrando98
2949008e76c96c22627a030483de826a33777b4c
496
cpp
C++
old_solutions/check_if_string_is_isogram_or_not.cpp
DSC-JSS-NOIDA/competitive
aa8807db24df389e52ba66dd0c5847e60237930b
[ "Apache-2.0" ]
null
null
null
old_solutions/check_if_string_is_isogram_or_not.cpp
DSC-JSS-NOIDA/competitive
aa8807db24df389e52ba66dd0c5847e60237930b
[ "Apache-2.0" ]
null
null
null
old_solutions/check_if_string_is_isogram_or_not.cpp
DSC-JSS-NOIDA/competitive
aa8807db24df389e52ba66dd0c5847e60237930b
[ "Apache-2.0" ]
7
2018-10-25T12:13:25.000Z
2020-10-01T18:09:05.000Z
#include <bits/stdc++.h> #define ull unsigned long long int #define ll long long int using namespace std; int main() { int t; cin>>t; while(t--){ int flag = 1; string s; cin>>s; std::map<char, int> map; for (int j = 0; j < s.length(); ++j) { if(map[s[j]]) map[s[j]]++; else map[s[j]] = 1; } for (std::map<char, int>::iterator it = map.begin(); it!=map.end(); it++) { if(it->second > 1){ flag = 0; break; } } cout<<flag<<endl; } return 0; }
15.5
75
0.522177
DSC-JSS-NOIDA
294bc7b4226007252f5a42f20d7ea035b332e615
10,329
cpp
C++
src/ttauri/text/unicode_bidi_tests.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
src/ttauri/text/unicode_bidi_tests.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
src/ttauri/text/unicode_bidi_tests.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2020-2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "ttauri/text/unicode_bidi.hpp" #include "ttauri/file_view.hpp" #include "ttauri/charconv.hpp" #include "ttauri/ranges.hpp" #include "ttauri/strings.hpp" #include <gtest/gtest.h> #include <iostream> #include <string> #include <string_view> #include <span> #include <fmt/format.h> using namespace tt; using namespace tt::detail; struct unicode_bidi_test { std::vector<int> levels; std::vector<int> reorder; int line_nr; std::vector<unicode_bidi_class> input; bool test_for_LTR = false; bool test_for_RTL = false; bool test_for_auto = false; [[nodiscard]] unicode_bidi_test(std::vector<int> const &levels, std::vector<int> const &reorder, int line_nr) noexcept : levels(levels), reorder(reorder), line_nr(line_nr) { } [[nodiscard]] std::vector<detail::unicode_bidi_char_info> get_input() const noexcept { auto r = std::vector<detail::unicode_bidi_char_info>{}; auto index = 0; for (auto cls : input) { r.emplace_back(index++, cls); } return r; } [[nodiscard]] std::vector<unicode_bidi_class> get_paragraph_directions() const noexcept { auto r = std::vector<unicode_bidi_class>{}; if (test_for_LTR) { r.push_back(unicode_bidi_class::L); } if (test_for_RTL) { r.push_back(unicode_bidi_class::R); } if (test_for_auto) { r.push_back(unicode_bidi_class::unknown); } return r; } }; [[nodiscard]] static std::vector<int> parse_bidi_test_levels(std::string_view line) noexcept { auto r = std::vector<int>{}; for (ttlet value : tt::split(tt::strip(line))) { if (value == "x") { r.push_back(-1); } else { r.push_back(tt::from_string<int>(value)); } } return r; } [[nodiscard]] static std::vector<int> parse_bidi_test_reorder(std::string_view line) noexcept { auto r = std::vector<int>{}; for (ttlet value : split(strip(line))) { if (value == "x") { r.push_back(-1); } else { r.push_back(tt::from_string<int>(value)); } } return r; } [[nodiscard]] static unicode_bidi_test parse_bidi_test_data_line( std::string_view line, std::vector<int> const &levels, std::vector<int> const &reorder, int level_nr) noexcept { auto r = unicode_bidi_test{levels, reorder, level_nr}; auto line_s = split(line, ';'); for (auto bidi_class_str : split(strip(line_s[0]))) { r.input.push_back(unicode_bidi_class_from_string(bidi_class_str)); } auto bitset = tt::from_string<int>(strip(line_s[1]), 16); r.test_for_auto = (bitset & 1) != 0; r.test_for_LTR = (bitset & 2) != 0; r.test_for_RTL = (bitset & 4) != 0; return r; } generator<unicode_bidi_test> parse_bidi_test(int test_line_nr = -1) { ttlet view = file_view(URL("file:BidiTest.txt")); ttlet test_data = view.string_view(); auto levels = std::vector<int>{}; auto reorder = std::vector<int>{}; int line_nr = 1; for (ttlet line : tt::views::split(test_data, "\n")) { ttlet line_ = strip(line); if (line_.empty() || line_.starts_with("#")) { // Comment and empty lines. } else if (line_.starts_with("@Levels:")) { levels = parse_bidi_test_levels(line_.substr(8)); } else if (line_.starts_with("@Reorder:")) { reorder = parse_bidi_test_reorder(line_.substr(9)); } else { auto data = parse_bidi_test_data_line(line_, levels, reorder, line_nr); if (test_line_nr == -1 || line_nr == test_line_nr) { co_yield data; } } if (line_nr == test_line_nr) { break; } line_nr++; } } TEST(unicode_bidi, bidi_test) { for (auto test : parse_bidi_test()) { for (auto paragraph_direction : test.get_paragraph_directions()) { auto test_parameters = unicode_bidi_test_parameters{}; test_parameters.enable_mirrored_brackets = false; test_parameters.enable_line_separator = false; test_parameters.force_paragraph_direction = paragraph_direction; auto input = test.get_input(); auto first = std::begin(input); auto last = std::end(input); last = unicode_bidi_P1(first, last, test_parameters); // We are using the index from the iterator to find embedded levels // in input-order. We ignore all elements that where removed by X9. for (auto it = first; it != last; ++it) { ttlet expected_embedding_level = test.levels[it->index]; ASSERT_TRUE(expected_embedding_level == -1 || expected_embedding_level == it->embedding_level); } ASSERT_EQ(std::distance(first, last), std::ssize(test.reorder)); auto index = 0; for (auto it = first; it != last; ++it, ++index) { ttlet expected_input_index = test.reorder[index]; ASSERT_TRUE(expected_input_index == -1 || expected_input_index == it->index); } } if constexpr (BuildType::current == BuildType::Debug) { if (test.line_nr > 10'000) { break; } } } } struct unicode_bidi_character_test { int line_nr; std::vector<char32_t> characters; unicode_bidi_class paragraph_direction; unicode_bidi_class resolved_paragraph_direction; std::vector<int> resolved_levels; std::vector<int> resolved_order; struct input_character { char32_t code_point; int index; }; [[nodiscard]] std::vector<input_character> get_input() const noexcept { auto r = std::vector<input_character>{}; int index = 0; for (ttlet c : characters) { r.emplace_back(c, index++); } return r; } }; [[nodiscard]] static unicode_bidi_character_test parse_bidi_character_test_line(std::string_view line, int line_nr) { ttlet split_line = split(line, ';'); ttlet hex_characters = split(split_line[0]); ttlet paragraph_direction = tt::from_string<int>(split_line[1]); ttlet resolved_paragraph_direction = tt::from_string<int>(split_line[2]); ttlet int_resolved_levels = split(split_line[3]); ttlet int_resolved_order = split(split_line[4]); auto r = unicode_bidi_character_test{}; r.line_nr = line_nr; std::transform(std::begin(hex_characters), std::end(hex_characters), std::back_inserter(r.characters), [](ttlet &x) { return static_cast<char32_t>(tt::from_string<uint32_t>(x, 16)); }); r.paragraph_direction = paragraph_direction == 0 ? unicode_bidi_class::L : paragraph_direction == 1 ? unicode_bidi_class::R : unicode_bidi_class::unknown; r.resolved_paragraph_direction = resolved_paragraph_direction == 0 ? unicode_bidi_class::L : resolved_paragraph_direction == 1 ? unicode_bidi_class::R : unicode_bidi_class::unknown; std::transform( std::begin(int_resolved_levels), std::end(int_resolved_levels), std::back_inserter(r.resolved_levels), [](ttlet &x) { if (x == "x") { return -1; } else { return tt::from_string<int>(x); } }); std::transform( std::begin(int_resolved_order), std::end(int_resolved_order), std::back_inserter(r.resolved_order), [](ttlet &x) { return tt::from_string<int>(x); }); return r; } generator<unicode_bidi_character_test> parse_bidi_character_test(int test_line_nr = -1) { ttlet view = file_view(URL("file:BidiCharacterTest.txt")); ttlet test_data = view.string_view(); int line_nr = 1; for (ttlet line : tt::views::split(test_data, "\n")) { ttlet line_ = strip(line); if (line_.empty() || line_.starts_with("#")) { // Comment and empty lines. } else { auto data = parse_bidi_character_test_line(line_, line_nr); if (test_line_nr == -1 || line_nr == test_line_nr) { co_yield data; } } if (line_nr == test_line_nr) { break; } line_nr++; } } TEST(unicode_bidi, bidi_character_test) { for (auto test : parse_bidi_character_test()) { auto test_parameters = unicode_bidi_test_parameters{}; test_parameters.enable_mirrored_brackets = true; test_parameters.enable_line_separator = true; test_parameters.force_paragraph_direction = test.paragraph_direction; auto input = test.get_input(); auto first = std::begin(input); auto last = std::end(input); last = unicode_bidi( first, last, [](ttlet &x) { return x.code_point; }, [](auto &x, ttlet &code_point) { x.code_point = code_point; }, test_parameters); // We are using the index from the iterator to find embedded levels // in input-order. We ignore all elements that where removed by X9. // for (auto it = first; it != last; ++it) { // ttlet expected_embedding_level = test.levels[it->index]; // // ASSERT_TRUE(expected_embedding_level == -1 || expected_embedding_level == it->embedding_level); //} ASSERT_EQ(std::distance(first, last), std::ssize(test.resolved_order)); auto index = 0; for (auto it = first; it != last; ++it, ++index) { ttlet expected_input_index = test.resolved_order[index]; ASSERT_TRUE(expected_input_index == -1 || expected_input_index == it->index); } if constexpr (BuildType::current == BuildType::Debug) { if (test.line_nr > 10'000) { break; } } } }
32.07764
125
0.595024
jhalakpatel
294f714c49c974dd220e45d3c453453f39aebfc7
75
hpp
C++
test/src/ProtoBufConverterTest.hpp
weierstrass/protobuf-decoder
4f5a2cab94b3e889f7d44d22463752d93250ac90
[ "MIT" ]
8
2016-08-07T22:04:06.000Z
2020-06-28T14:33:18.000Z
test/src/ProtoBufConverterTest.hpp
weierstrass/protobuf-decoder
4f5a2cab94b3e889f7d44d22463752d93250ac90
[ "MIT" ]
10
2016-07-30T19:54:02.000Z
2018-03-01T01:59:46.000Z
test/src/ProtoBufConverterTest.hpp
weierstrass/protobuf-decoder
4f5a2cab94b3e889f7d44d22463752d93250ac90
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" struct ProtobufConverterTest : testing::Test {};
18.75
48
0.746667
weierstrass
294f9e34d5745b028d7840a0b7448af3ef82ba4a
990
h++
C++
include/ogonek/encoding/iso8859_15.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
25
2016-10-21T12:37:23.000Z
2021-02-22T05:46:46.000Z
include/ogonek/encoding/iso8859_15.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
null
null
null
include/ogonek/encoding/iso8859_15.h++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
4
2016-09-05T10:23:18.000Z
2020-07-09T19:37:37.000Z
// Ogonek // // Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // This file was automatically generated on 2013-11-14T13:59:13.131346Z // ISO-8859-15 encoding form #ifndef OGONEK_ISO8859_15_HPP #define OGONEK_ISO8859_15_HPP #include <ogonek/types.h++> #include <ogonek/encoding/codepage_encoding.h++> namespace ogonek { struct iso8859_15_codepage { static code_point to_unicode[256]; static codepage_entry from_unicode[256]; }; using iso8859_15 = codepage_encoding<iso8859_15_codepage>; } // namespace ogonek #endif // OGONEK_ISO8859_15_HPP
30.9375
96
0.756566
libogonek
29521fa26f956f7d701aee9256b5479a9e2c896a
5,134
cpp
C++
ql/experimental/credit/integralcdoengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/experimental/credit/integralcdoengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/experimental/credit/integralcdoengine.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Roland Lichters Copyright (C) 2009, 2014 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/experimental/credit/integralcdoengine.hpp> #include <ql/cashflows/fixedratecoupon.hpp> #include <ql/termstructures/yieldtermstructure.hpp> namespace QuantLib { void IntegralCDOEngine::calculate() const { Date today = Settings::instance().evaluationDate(); results_.protectionValue = 0.0; results_.premiumValue = 0.0; results_.upfrontPremiumValue = 0.0; results_.error = 0; results_.expectedTrancheLoss.clear(); // todo Should be remaining when considering realized loses results_.xMin = arguments_.basket->attachmentAmount(); results_.xMax = arguments_.basket->detachmentAmount(); results_.remainingNotional = results_.xMax - results_.xMin; const Real inceptionTrancheNotional = arguments_.basket->trancheNotional(); // compute expected loss at the beginning of first relevant period Real e1 = 0; // todo add includeSettlement date flows variable to engine. if (!arguments_.normalizedLeg[0]->hasOccurred(today)) // cast to fixed rate coupon? e1 = arguments_.basket->expectedTrancheLoss( std::dynamic_pointer_cast<Coupon>( arguments_.normalizedLeg[0])->accrualStartDate()); results_.expectedTrancheLoss.emplace_back(e1);// zero or realized losses? for (Size i = 0; i < arguments_.normalizedLeg.size(); i++) { if(arguments_.normalizedLeg[i]->hasOccurred(today)) { // add includeSettlement date flows variable to engine. results_.expectedTrancheLoss.emplace_back(0.); continue; } const std::shared_ptr<Coupon> coupon = std::dynamic_pointer_cast<Coupon>( arguments_.normalizedLeg[i]); Date d1 = coupon->accrualStartDate(); Date d2 = coupon->date(); Date d, d0 = d1; Real e2; do { d = NullCalendar().advance(d0 > today ? d0 : today, stepSize_); if (d > d2) d = d2; e2 = arguments_.basket->expectedTrancheLoss(d); results_.premiumValue // ..check for e2 including past/realized losses += (inceptionTrancheNotional - e2) * arguments_.runningRate * arguments_.dayCounter.yearFraction(d0, d) * discountCurve_->discount(d); // TO DO: Addd default coupon accrual value here----- if (e2 < e1) results_.error ++; results_.protectionValue += (e2 - e1) * discountCurve_->discount(d); d0 = d; e1 = e2; } while (d < d2); results_.expectedTrancheLoss.emplace_back(e2); } // add includeSettlement date flows variable to engine. if (!arguments_.normalizedLeg[0]->hasOccurred(today)) results_.upfrontPremiumValue = inceptionTrancheNotional * arguments_.upfrontRate * discountCurve_->discount( std::dynamic_pointer_cast<Coupon>( arguments_.normalizedLeg[0])->accrualStartDate()); if (arguments_.side == Protection::Buyer) { results_.protectionValue *= -1; results_.premiumValue *= -1; results_.upfrontPremiumValue *= -1; } results_.value = results_.premiumValue - results_.protectionValue + results_.upfrontPremiumValue; results_.errorEstimate = Null<Real>(); // Fair spread GIVEN the upfront Real fairSpread = 0.; if (results_.premiumValue != 0.0) { fairSpread = -(results_.protectionValue + results_.upfrontPremiumValue) *arguments_.runningRate/results_.premiumValue; } results_.additionalResults["fairPremium"] = fairSpread; results_.additionalResults["premiumLegNPV"] = results_.premiumValue + results_.upfrontPremiumValue; results_.additionalResults["protectionLegNPV"] = results_.protectionValue; } }
39.79845
81
0.607713
haozhangphd
29531f05b2c5571c06b264a6f0759b35de33a390
28,059
cpp
C++
libsrc/effectengine/EffectModule.cpp
keesg60/hyperion.ng
7f174b28723456d41a5d48c1f1eed5fa41f418c2
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
1,808
2016-06-29T00:12:07.000Z
2022-03-30T22:55:16.000Z
libsrc/effectengine/EffectModule.cpp
keesg60/hyperion.ng
7f174b28723456d41a5d48c1f1eed5fa41f418c2
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
1,271
2016-06-16T20:12:41.000Z
2022-03-31T17:47:59.000Z
libsrc/effectengine/EffectModule.cpp
keesg60/hyperion.ng
7f174b28723456d41a5d48c1f1eed5fa41f418c2
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
458
2016-06-15T16:08:12.000Z
2022-03-29T15:36:16.000Z
#include <cmath> #include <effectengine/Effect.h> #include <effectengine/EffectModule.h> // hyperion #include <hyperion/Hyperion.h> #include <utils/Logger.h> // qt #include <QJsonArray> #include <QDateTime> #include <QImageReader> #include <QBuffer> #include <QUrl> #include <QNetworkReply> #include <QNetworkAccessManager> #include <QEventLoop> // Get the effect from the capsule #define getEffect() static_cast<Effect*>((Effect*)PyCapsule_Import("hyperion.__effectObj", 0)) // create the hyperion module struct PyModuleDef EffectModule::moduleDef = { PyModuleDef_HEAD_INIT, "hyperion", /* m_name */ "Hyperion module", /* m_doc */ -1, /* m_size */ EffectModule::effectMethods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; PyObject* EffectModule::PyInit_hyperion() { return PyModule_Create(&moduleDef); } void EffectModule::registerHyperionExtensionModule() { PyImport_AppendInittab("hyperion", &PyInit_hyperion); } PyObject *EffectModule::json2python(const QJsonValue &jsonData) { switch (jsonData.type()) { case QJsonValue::Null: Py_RETURN_NONE; case QJsonValue::Undefined: Py_RETURN_NOTIMPLEMENTED; case QJsonValue::Double: { if (std::round(jsonData.toDouble()) != jsonData.toDouble()) return Py_BuildValue("d", jsonData.toDouble()); return Py_BuildValue("i", jsonData.toInt()); } case QJsonValue::Bool: return Py_BuildValue("i", jsonData.toBool() ? 1 : 0); case QJsonValue::String: return Py_BuildValue("s", jsonData.toString().toUtf8().constData()); case QJsonValue::Object: { PyObject * dict= PyDict_New(); QJsonObject objectData = jsonData.toObject(); for (QJsonObject::iterator i = objectData.begin(); i != objectData.end(); ++i) { PyObject * obj = json2python(*i); PyDict_SetItemString(dict, i.key().toStdString().c_str(), obj); Py_XDECREF(obj); } return dict; } case QJsonValue::Array: { QJsonArray arrayData = jsonData.toArray(); PyObject * list = PyList_New(arrayData.size()); int index = 0; for (QJsonArray::iterator i = arrayData.begin(); i != arrayData.end(); ++i, ++index) { PyObject * obj = json2python(*i); Py_INCREF(obj); PyList_SetItem(list, index, obj); Py_XDECREF(obj); } return list; } } assert(false); Py_RETURN_NONE; } // Python method table PyMethodDef EffectModule::effectMethods[] = { {"setColor" , EffectModule::wrapSetColor , METH_VARARGS, "Set a new color for the leds."}, {"setImage" , EffectModule::wrapSetImage , METH_VARARGS, "Set a new image to process and determine new led colors."}, {"getImage" , EffectModule::wrapGetImage , METH_VARARGS, "get image data from file."}, {"abort" , EffectModule::wrapAbort , METH_NOARGS, "Check if the effect should abort execution."}, {"imageShow" , EffectModule::wrapImageShow , METH_VARARGS, "set current effect image to hyperion core."}, {"imageLinearGradient" , EffectModule::wrapImageLinearGradient , METH_VARARGS, ""}, {"imageConicalGradient" , EffectModule::wrapImageConicalGradient , METH_VARARGS, ""}, {"imageRadialGradient" , EffectModule::wrapImageRadialGradient , METH_VARARGS, ""}, {"imageSolidFill" , EffectModule::wrapImageSolidFill , METH_VARARGS, ""}, {"imageDrawLine" , EffectModule::wrapImageDrawLine , METH_VARARGS, ""}, {"imageDrawPoint" , EffectModule::wrapImageDrawPoint , METH_VARARGS, ""}, {"imageDrawRect" , EffectModule::wrapImageDrawRect , METH_VARARGS, ""}, {"imageDrawPolygon" , EffectModule::wrapImageDrawPolygon , METH_VARARGS, ""}, {"imageDrawPie" , EffectModule::wrapImageDrawPie , METH_VARARGS, ""}, {"imageSetPixel" , EffectModule::wrapImageSetPixel , METH_VARARGS, "set pixel color of image"}, {"imageGetPixel" , EffectModule::wrapImageGetPixel , METH_VARARGS, "get pixel color of image"}, {"imageSave" , EffectModule::wrapImageSave , METH_NOARGS, "adds a new background image"}, {"imageMinSize" , EffectModule::wrapImageMinSize , METH_VARARGS, "sets minimal dimension of background image"}, {"imageWidth" , EffectModule::wrapImageWidth , METH_NOARGS, "gets image width"}, {"imageHeight" , EffectModule::wrapImageHeight , METH_NOARGS, "gets image height"}, {"imageCRotate" , EffectModule::wrapImageCRotate , METH_VARARGS, "rotate the coordinate system by given angle"}, {"imageCOffset" , EffectModule::wrapImageCOffset , METH_VARARGS, "Add offset to the coordinate system"}, {"imageCShear" , EffectModule::wrapImageCShear , METH_VARARGS, "Shear of coordinate system by the given horizontal/vertical axis"}, {"imageResetT" , EffectModule::wrapImageResetT , METH_NOARGS, "Resets all coords modifications (rotate,offset,shear)"}, {NULL, NULL, 0, NULL} }; PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args) { // check the number of arguments int argCount = PyTuple_Size(args); if (argCount == 3) { // three separate arguments for red, green, and blue ColorRgb color; if (PyArg_ParseTuple(args, "bbb", &color.red, &color.green, &color.blue)) { getEffect()->_colors.fill(color); QVector<ColorRgb> _cQV = getEffect()->_colors; emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>( _cQV.begin(), _cQV.end() ), getEffect()->getRemaining(), false); Py_RETURN_NONE; } return nullptr; } else if (argCount == 1) { // bytearray of values PyObject * bytearray = nullptr; if (PyArg_ParseTuple(args, "O", &bytearray)) { if (PyByteArray_Check(bytearray)) { size_t length = PyByteArray_Size(bytearray); if (length == 3 * static_cast<size_t>(getEffect()->_hyperion->getLedCount())) { char * data = PyByteArray_AS_STRING(bytearray); memcpy(getEffect()->_colors.data(), data, length); QVector<ColorRgb> _cQV = getEffect()->_colors; emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>( _cQV.begin(), _cQV.end() ), getEffect()->getRemaining(), false); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*ledCount"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Argument is not a bytearray"); return nullptr; } } else { return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Function expect 1 or 3 arguments"); return nullptr; } } PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args) { // bytearray of values int width, height; PyObject * bytearray = nullptr; if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray)) { if (PyByteArray_Check(bytearray)) { int length = PyByteArray_Size(bytearray); if (length == 3 * width * height) { Image<ColorRgb> image(width, height); char * data = PyByteArray_AS_STRING(bytearray); memcpy(image.memptr(), data, length); emit getEffect()->setInputImage(getEffect()->_priority, image, getEffect()->getRemaining(), false); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*width*height"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Argument 3 is not a bytearray"); return nullptr; } } else { return nullptr; } // error PyErr_SetString(PyExc_RuntimeError, "Unknown error"); return nullptr; } PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args) { QBuffer buffer; QImageReader reader; char *source; int cropLeft = 0, cropTop = 0, cropRight = 0, cropBottom = 0; int grayscale = false; if (getEffect()->_imageData.isEmpty()) { Q_INIT_RESOURCE(EffectEngine); if(!PyArg_ParseTuple(args, "s|iiiip", &source, &cropLeft, &cropTop, &cropRight, &cropBottom, &grayscale)) { PyErr_SetString(PyExc_TypeError, "String required"); return nullptr; } const QUrl url = QUrl(source); if (url.isValid()) { QNetworkAccessManager *networkManager = new QNetworkAccessManager(); QNetworkReply * networkReply = networkManager->get(QNetworkRequest(url)); QEventLoop eventLoop; connect(networkReply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); eventLoop.exec(); if (networkReply->error() == QNetworkReply::NoError) { buffer.setData(networkReply->readAll()); buffer.open(QBuffer::ReadOnly); reader.setDecideFormatFromContent(true); reader.setDevice(&buffer); } delete networkReply; delete networkManager; } else { QString file = QString::fromUtf8(source); if (file.mid(0, 1) == ":") file = ":/effects/"+file.mid(1); reader.setDecideFormatFromContent(true); reader.setFileName(file); } } else { PyArg_ParseTuple(args, "|siiiip", &source, &cropLeft, &cropTop, &cropRight, &cropBottom, &grayscale); buffer.setData(QByteArray::fromBase64(getEffect()->_imageData.toUtf8())); buffer.open(QBuffer::ReadOnly); reader.setDecideFormatFromContent(true); reader.setDevice(&buffer); } if (reader.canRead()) { PyObject *result = PyList_New(reader.imageCount()); for (int i = 0; i < reader.imageCount(); ++i) { reader.jumpToImage(i); if (reader.canRead()) { QImage qimage = reader.read(); int width = qimage.width(); int height = qimage.height(); if (cropLeft > 0 || cropTop > 0 || cropRight > 0 || cropBottom > 0) { if (cropLeft + cropRight >= width || cropTop + cropBottom >= height) { QString errorStr = QString("Rejecting invalid crop values: left: %1, right: %2, top: %3, bottom: %4, higher than height/width %5/%6").arg(cropLeft).arg(cropRight).arg(cropTop).arg(cropBottom).arg(height).arg(width); PyErr_SetString(PyExc_RuntimeError, qPrintable(errorStr)); return nullptr; } qimage = qimage.copy(cropLeft, cropTop, width - cropLeft - cropRight, height - cropTop - cropBottom); width = qimage.width(); height = qimage.height(); } QByteArray binaryImage; for (int i = 0; i<height; i++) { const QRgb *scanline = reinterpret_cast<const QRgb *>(qimage.scanLine(i)); const QRgb *end = scanline + qimage.width(); for (; scanline != end; scanline++) { binaryImage.append(!grayscale ? (char) qRed(scanline[0]) : (char) qGray(scanline[0])); binaryImage.append(!grayscale ? (char) qGreen(scanline[1]) : (char) qGray(scanline[1])); binaryImage.append(!grayscale ? (char) qBlue(scanline[2]) : (char) qGray(scanline[2])); } } PyList_SET_ITEM(result, i, Py_BuildValue("{s:i,s:i,s:O}", "imageWidth", width, "imageHeight", height, "imageData", PyByteArray_FromStringAndSize(binaryImage.constData(),binaryImage.size()))); } else { PyErr_SetString(PyExc_TypeError, reader.errorString().toUtf8().constData()); return nullptr; } } return result; } else { PyErr_SetString(PyExc_TypeError, reader.errorString().toUtf8().constData()); return nullptr; } } PyObject* EffectModule::wrapAbort(PyObject *self, PyObject *) { return Py_BuildValue("i", getEffect()->isInterruptionRequested() ? 1 : 0); } PyObject* EffectModule::wrapImageShow(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int imgId = -1; bool argsOk = (argCount == 0); if (argCount == 1 && PyArg_ParseTuple(args, "i", &imgId)) { argsOk = true; } if ( ! argsOk || (imgId>-1 && imgId >= getEffect()->_imageStack.size())) { return nullptr; } QImage * qimage = (imgId<0) ? &(getEffect()->_image) : &(getEffect()->_imageStack[imgId]); int width = qimage->width(); int height = qimage->height(); Image<ColorRgb> image(width, height); QByteArray binaryImage; for (int i = 0; i<height; ++i) { const QRgb * scanline = reinterpret_cast<const QRgb *>(qimage->scanLine(i)); for (int j = 0; j< width; ++j) { binaryImage.append((char) qRed(scanline[j])); binaryImage.append((char) qGreen(scanline[j])); binaryImage.append((char) qBlue(scanline[j])); } } memcpy(image.memptr(), binaryImage.data(), binaryImage.size()); emit getEffect()->setInputImage(getEffect()->_priority, image, getEffect()->getRemaining(), false); return Py_BuildValue(""); } PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); PyObject * bytearray = nullptr; int startRX = 0; int startRY = 0; int startX = 0; int startY = 0; int endX, width = getEffect()->_imageSize.width(); int endY, height = getEffect()->_imageSize.height(); int spread = 0; bool argsOK = false; if ( argCount == 10 && PyArg_ParseTuple(args, "iiiiiiiiOi", &startRX, &startRY, &width, &height, &startX, &startY, &endX, &endY, &bytearray, &spread) ) { argsOK = true; } if ( argCount == 6 && PyArg_ParseTuple(args, "iiiiOi", &startX, &startY, &endX, &endY, &bytearray, &spread) ) { argsOK = true; } if (argsOK) { if (PyByteArray_Check(bytearray)) { const int length = PyByteArray_Size(bytearray); const unsigned arrayItemLength = 5; if (length % arrayItemLength == 0) { QRect myQRect(startRX,startRY,width,height); QLinearGradient gradient(QPoint(startX,startY), QPoint(endX,endY)); char * data = PyByteArray_AS_STRING(bytearray); for (int idx=0; idx<length; idx+=arrayItemLength) { gradient.setColorAt( ((uint8_t)data[idx])/255.0, QColor( (uint8_t)(data[idx+1]), (uint8_t)(data[idx+2]), (uint8_t)(data[idx+3]), (uint8_t)(data[idx+4]) )); } gradient.setSpread(static_cast<QGradient::Spread>(spread)); getEffect()->_painter->fillRect(myQRect, gradient); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should multiple of 5"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "No bytearray properly defined"); return nullptr; } } return nullptr; } PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); PyObject * bytearray = nullptr; int centerX, centerY, angle; int startX = 0; int startY = 0; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); bool argsOK = false; if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiiO", &startX, &startY, &width, &height, &centerX, &centerY, &angle, &bytearray) ) { argsOK = true; } if ( argCount == 4 && PyArg_ParseTuple(args, "iiiO", &centerX, &centerY, &angle, &bytearray) ) { argsOK = true; } angle = qMax(qMin(angle,360),0); if (argsOK) { if (PyByteArray_Check(bytearray)) { const int length = PyByteArray_Size(bytearray); const unsigned arrayItemLength = 5; if (length % arrayItemLength == 0) { QRect myQRect(startX,startY,width,height); QConicalGradient gradient(QPoint(centerX,centerY), angle ); char * data = PyByteArray_AS_STRING(bytearray); for (int idx=0; idx<length; idx+=arrayItemLength) { gradient.setColorAt( ((uint8_t)data[idx])/255.0, QColor( (uint8_t)(data[idx+1]), (uint8_t)(data[idx+2]), (uint8_t)(data[idx+3]), (uint8_t)(data[idx+4]) )); } getEffect()->_painter->fillRect(myQRect, gradient); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should multiple of 5"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Argument 8 is not a bytearray"); return nullptr; } } return nullptr; } PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); PyObject * bytearray = nullptr; int centerX, centerY, radius, focalX, focalY, focalRadius, spread; int startX = 0; int startY = 0; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); bool argsOK = false; if ( argCount == 12 && PyArg_ParseTuple(args, "iiiiiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread) ) { argsOK = true; } if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &bytearray, &spread) ) { argsOK = true; focalX = centerX; focalY = centerY; focalRadius = radius; } if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiOi", &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread) ) { argsOK = true; } if ( argCount == 5 && PyArg_ParseTuple(args, "iiiOi", &centerX, &centerY, &radius, &bytearray, &spread) ) { argsOK = true; focalX = centerX; focalY = centerY; focalRadius = radius; } if (argsOK) { if (PyByteArray_Check(bytearray)) { int length = PyByteArray_Size(bytearray); if (length % 4 == 0) { QRect myQRect(startX,startY,width,height); QRadialGradient gradient(QPoint(centerX,centerY), qMax(radius,0) ); char * data = PyByteArray_AS_STRING(bytearray); for (int idx=0; idx<length; idx+=4) { gradient.setColorAt( ((uint8_t)data[idx])/255.0, QColor( (uint8_t)(data[idx+1]), (uint8_t)(data[idx+2]), (uint8_t)(data[idx+3]) )); } gradient.setSpread(static_cast<QGradient::Spread>(spread)); getEffect()->_painter->fillRect(myQRect, gradient); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should multiple of 4"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Last argument is not a bytearray"); return nullptr; } } return nullptr; } PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args) { PyObject * bytearray = nullptr; int argCount = PyTuple_Size(args); int r, g, b; int a = 255; bool argsOK = false; if ( argCount == 5 && PyArg_ParseTuple(args, "Oiiii", &bytearray, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 4 && PyArg_ParseTuple(args, "Oiii", &bytearray, &r, &g, &b) ) { argsOK = true; } if (argsOK) { if (PyByteArray_Check(bytearray)) { int length = PyByteArray_Size(bytearray); if (length % 2 == 0) { QVector <QPoint> points; char * data = PyByteArray_AS_STRING(bytearray); for (int idx=0; idx<length; idx+=2) { points.append(QPoint((int)(data[idx]),(int)(data[idx+1]))); } QPainter * painter = getEffect()->_painter; QPen oldPen = painter->pen(); QPen newPen(QColor(r,g,b,a)); painter->setPen(newPen); painter->setBrush(QBrush(QColor(r,g,b,a), Qt::SolidPattern)); painter->drawPolygon(points); painter->setPen(oldPen); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should multiple of 2"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Argument 1 is not a bytearray"); return nullptr; } } return nullptr; } PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args) { PyObject * bytearray = nullptr; QString brush; int argCount = PyTuple_Size(args); int radius, centerX, centerY; int startAngle = 0; int spanAngle = 360; int r = 0; int g = 0; int b = 0; int a = 255; bool argsOK = false; if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b) ) { argsOK = true; } if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiisO", &centerX, &centerY, &radius, &startAngle, &spanAngle, &brush, &bytearray) ) { argsOK = true; } if ( argCount == 5 && PyArg_ParseTuple(args, "iiisO", &centerX, &centerY, &radius, &brush, &bytearray) ) { argsOK = true; } if (argsOK) { QPainter * painter = getEffect()->_painter; startAngle = qMax(qMin(startAngle,360),0); spanAngle = qMax(qMin(spanAngle,360),-360); if( argCount == 7 || argCount == 5 ) { a = 0; if (PyByteArray_Check(bytearray)) { int length = PyByteArray_Size(bytearray); if (length % 5 == 0) { QConicalGradient gradient(QPoint(centerX,centerY), startAngle); char * data = PyByteArray_AS_STRING(bytearray); for (int idx=0; idx<length; idx+=5) { gradient.setColorAt( ((uint8_t)data[idx])/255.0, QColor( (uint8_t)(data[idx+1]), (uint8_t)(data[idx+2]), (uint8_t)(data[idx+3]), (uint8_t)(data[idx+4]) )); } painter->setBrush(gradient); Py_RETURN_NONE; } else { PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should multiple of 5"); return nullptr; } } else { PyErr_SetString(PyExc_RuntimeError, "Last argument is not a bytearray"); return nullptr; } } else { painter->setBrush(QBrush(QColor(r,g,b,a), Qt::SolidPattern)); } QPen oldPen = painter->pen(); QPen newPen(QColor(r,g,b,a)); painter->setPen(newPen); painter->drawPie(centerX - radius, centerY - radius, centerX + radius, centerY + radius, startAngle * 16, spanAngle * 16); painter->setPen(oldPen); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int r, g, b; int a = 255; int startX = 0; int startY = 0; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); bool argsOK = false; if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &startX, &startY, &width, &height, &r, &g, &b) ) { argsOK = true; } if ( argCount == 4 && PyArg_ParseTuple(args, "iiii",&r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 3 && PyArg_ParseTuple(args, "iii",&r, &g, &b) ) { argsOK = true; } if (argsOK) { QRect myQRect(startX,startY,width,height); getEffect()->_painter->fillRect(myQRect, QColor(r,g,b,a)); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int r, g, b; int a = 255; int startX = 0; int startY = 0; int thick = 1; int endX = getEffect()->_imageSize.width(); int endY = getEffect()->_imageSize.height(); bool argsOK = false; if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b) ) { argsOK = true; } if (argsOK) { QPainter * painter = getEffect()->_painter; QRect myQRect(startX, startY, endX, endY); QPen oldPen = painter->pen(); QPen newPen(QColor(r,g,b,a)); newPen.setWidth(thick); painter->setPen(newPen); painter->drawLine(startX, startY, endX, endY); painter->setPen(oldPen); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int r, g, b, x, y; int a = 255; int thick = 1; bool argsOK = false; if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &x, &y, &thick, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 6 && PyArg_ParseTuple(args, "iiiiii", &x, &y, &thick, &r, &g, &b) ) { argsOK = true; } if (argsOK) { QPainter * painter = getEffect()->_painter; QPen oldPen = painter->pen(); QPen newPen(QColor(r,g,b,a)); newPen.setWidth(thick); painter->setPen(newPen); painter->drawPoint(x, y); painter->setPen(oldPen); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int r, g, b; int a = 255; int startX = 0; int startY = 0; int thick = 1; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); bool argsOK = false; if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b, &a) ) { argsOK = true; } if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b) ) { argsOK = true; } if (argsOK) { QPainter * painter = getEffect()->_painter; QRect myQRect(startX,startY,width,height); QPen oldPen = painter->pen(); QPen newPen(QColor(r,g,b,a)); newPen.setWidth(thick); painter->setPen(newPen); painter->drawRect(startX, startY, width, height); painter->setPen(oldPen); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int r, g, b, x, y; if ( argCount == 5 && PyArg_ParseTuple(args, "iiiii", &x, &y, &r, &g, &b ) ) { getEffect()->_image.setPixel(x,y,qRgb(r,g,b)); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageGetPixel(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int x, y; if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &x, &y) ) { QRgb rgb = getEffect()->_image.pixel(x,y); return Py_BuildValue("iii",qRed(rgb),qGreen(rgb),qBlue(rgb)); } return nullptr; } PyObject* EffectModule::wrapImageSave(PyObject *self, PyObject *args) { QImage img(getEffect()->_image.copy()); getEffect()->_imageStack.append(img); return Py_BuildValue("i", getEffect()->_imageStack.size()-1); } PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int w, h; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &w, &h) ) { if (width<w || height<h) { delete getEffect()->_painter; getEffect()->_image = getEffect()->_image.scaled(qMax(width,w),qMax(height,h), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); getEffect()->_imageSize = getEffect()->_image.size(); getEffect()->_painter = new QPainter(&(getEffect()->_image)); } return Py_BuildValue("ii", getEffect()->_image.width(), getEffect()->_image.height()); } return nullptr; } PyObject* EffectModule::wrapImageWidth(PyObject *self, PyObject *args) { return Py_BuildValue("i", getEffect()->_imageSize.width()); } PyObject* EffectModule::wrapImageHeight(PyObject *self, PyObject *args) { return Py_BuildValue("i", getEffect()->_imageSize.height()); } PyObject* EffectModule::wrapImageCRotate(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); int angle; if ( argCount == 1 && PyArg_ParseTuple(args, "i", &angle ) ) { angle = qMax(qMin(angle,360),0); getEffect()->_painter->rotate(angle); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageCOffset(PyObject *self, PyObject *args) { int offsetX = 0; int offsetY = 0; int argCount = PyTuple_Size(args); if ( argCount == 2 ) { PyArg_ParseTuple(args, "ii", &offsetX, &offsetY ); } getEffect()->_painter->translate(QPoint(offsetX,offsetY)); Py_RETURN_NONE; } PyObject* EffectModule::wrapImageCShear(PyObject *self, PyObject *args) { int sh,sv; int argCount = PyTuple_Size(args); if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &sh, &sv )) { getEffect()->_painter->shear(sh,sv); Py_RETURN_NONE; } return nullptr; } PyObject* EffectModule::wrapImageResetT(PyObject *self, PyObject *args) { getEffect()->_painter->resetTransform(); Py_RETURN_NONE; }
27.698914
221
0.65405
keesg60
29534350b21e653d58a081bec6a6d2d994cf3c37
2,304
cpp
C++
hacclient/Sentinel.cpp
ChadSki/hacclient
f1471e1f74de13dbbc1ae6d92238939e010ff7d6
[ "MIT" ]
1
2020-05-02T16:42:30.000Z
2020-05-02T16:42:30.000Z
hacclient/Sentinel.cpp
ChadSki/hacclient
f1471e1f74de13dbbc1ae6d92238939e010ff7d6
[ "MIT" ]
null
null
null
hacclient/Sentinel.cpp
ChadSki/hacclient
f1471e1f74de13dbbc1ae6d92238939e010ff7d6
[ "MIT" ]
1
2020-03-31T08:46:31.000Z
2020-03-31T08:46:31.000Z
#include "Sentinel.h" #include "DebugHelper.h" #include <cstdint> void Sentinel::pingAnticheat() { OutputDebugString("Sentinel pinging!"); std::shared_ptr<Event> event(std::make_shared<Event>(PING_ANTICHEAT_THREAD)); broadcast(event); requestTime = GetTickCount(); outstandingRequests++; } void Sentinel::measureResponse() { outstandingRequests--; if((GetTickCount() - requestTime) > 5000) { OutputDebugString("Debugger found"); } else { OutputDebugString("Sentinel received response in time!"); } } void Sentinel::healthCheck() { if(outstandingRequests > 0 && (GetTickCount() - requestTime) > 5000) { OutputDebugString("Debugger 1 found"); } else if(outstandingRequests == 0) { pingAnticheat(); } if(SuspendThread(anticheat) == -1) { OutputDebugString("error"); } CONTEXT context; if(GetThreadContext(anticheat, &context) == 0) { OutputDebugString("error 2"); } if(SetThreadContext(anticheat, &context) == 0) { OutputDebugString("error 4"); } if(ResumeThread(anticheat) == -1) { OutputDebugString("error 3"); } } void Sentinel::setThreadHandle(std::shared_ptr<Event> event) { ThreadHandleEvent* e = static_cast<ThreadHandleEvent*>(event.get()); anticheat = e->acthread; } DWORD Sentinel::run() { exit = false; const int healthCheckFrequency = 5000; int lastHealthCheck = 0; std::shared_ptr<Event> event(std::make_shared<Event>(REQUEST_ANTICHEAT_THREAD_HANDLE)); broadcast(event); while(!exit) { WaitForSingleObject(eventSem, 5000); processQueue(); if(GetTickCount() - lastHealthCheck > healthCheckFrequency) { healthCheck(); lastHealthCheck = GetTickCount(); } } return 0; } void Sentinel::processQueue() { std::shared_ptr<Event> event; while(!events.empty()) { if(!events.try_pop(event)) { return; } switch(event->type) { case PONG_ANTICHEAT_THREAD: measureResponse(); break; case ANTICHEAT_THREAD_HANDLE: setThreadHandle(event); break; case THREAD_EXIT: exit = true; break; } } } void Sentinel::registerDispatcher(EventSubscriber* dispatcher) { this->dispatcher = dispatcher; std::vector<EVENTS> events; events.emplace_back(POST_MAP_LOAD); events.emplace_back(ANTICHEAT_THREAD_HANDLE); events.emplace_back(PONG_ANTICHEAT_THREAD); dispatcher->subscribe(this, events); }
22.588235
88
0.714844
ChadSki
29567775cc387e5e3c6daacc4a7f4b9a268cae89
4,512
cpp
C++
circe/gl/io/screen_quad.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
1
2021-09-17T18:12:47.000Z
2021-09-17T18:12:47.000Z
circe/gl/io/screen_quad.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
null
null
null
circe/gl/io/screen_quad.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
2
2021-09-17T18:13:02.000Z
2021-09-17T18:16:21.000Z
// Created by filipecn on 8/26/18. /* * Copyright (c) 2018 FilipeCN * * The MIT License (MIT) * * 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 "screen_quad.h" #include "buffer.h" #include <circe/gl/graphics/shader.h> #include <hermes/data_structures/raw_mesh.h> namespace circe::gl { ScreenQuad::ScreenQuad() { mesh_.meshDescriptor.elementSize = 3; mesh_.meshDescriptor.count = 2; mesh_.positionDescriptor.elementSize = 2; mesh_.positionDescriptor.count = 4; mesh_.texcoordDescriptor.elementSize = 2; mesh_.texcoordDescriptor.count = 4; mesh_.positions = std::vector<float>({-1, -1, 1, -1, 1, 1, -1, 1}); mesh_.texcoords = std::vector<float>({0, 0, 1, 0, 1, 1, 0, 1}); mesh_.indices.resize(6); mesh_.indices[0].positionIndex = mesh_.indices[0].texcoordIndex = 0; mesh_.indices[1].positionIndex = mesh_.indices[1].texcoordIndex = 1; mesh_.indices[2].positionIndex = mesh_.indices[2].texcoordIndex = 2; mesh_.indices[3].positionIndex = mesh_.indices[3].texcoordIndex = 0; mesh_.indices[4].positionIndex = mesh_.indices[4].texcoordIndex = 2; mesh_.indices[5].positionIndex = mesh_.indices[5].texcoordIndex = 3; mesh_.splitIndexData(); mesh_.buildInterleavedData(); const char *fs = "#version 440 core\n" "out vec4 outColor;" "in vec2 texCoord;" "layout (location = 0) uniform sampler2D tex;" "void main(){" " outColor = texture(tex, texCoord);}"; const char *vs = "#version 440 core\n" "layout (location = 0) in vec2 position;" "layout (location = 1) in vec2 texcoord;" "out vec2 texCoord;" "void main() {" " texCoord = texcoord;" " gl_Position = vec4(position, 0, 1);}"; const char *gs = nullptr; shader.reset(new ShaderProgram(vs, gs, fs)); shader->addVertexAttribute("position", 0); shader->addVertexAttribute("texcoord", 1); shader->addUniform("tex", 0); { glGenVertexArrays(1, &VAO); // bind the Vertex Array Object first, then bind and resize vertex buffer(s), // and then configure vertex attributes(s). glBindVertexArray(VAO); BufferDescriptor vd, id; create_buffer_description_from_mesh(mesh_, vd, id); vb_.reset(new GLVertexBuffer(&mesh_.interleavedData[0], vd)); ib_.reset(new GLIndexBuffer(&mesh_.positionsIndices[0], id)); vb_->locateAttributes(*shader.get()); // shader->registerVertexAttributes(vb_.get()); // note that this is allowed, the call to glVertexAttribPointer registered // VBO as the vertex attribute's bound vertex buffer object so afterwards we // can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // remember: do NOT unbind the EBO while a VAO is active as the bound // element buffer object IS stored in the VAO; keep the EBO bound. // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally // modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't // unbind VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); } } ScreenQuad::~ScreenQuad() = default; void ScreenQuad::render() { glBindVertexArray(VAO); shader->begin(); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); shader->end(); glBindVertexArray(0); } }
43.384615
81
0.687943
gui-works
2957e45352de22bb54945ce5789f315ee0569bd7
2,734
cpp
C++
C++/satisfiability-of-equality-equations.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/satisfiability-of-equality-equations.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/satisfiability-of-equality-equations.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: bool equationsPossible(vector<string>& equations) { UnionFind union_find(26); for (const auto& eqn : equations) { int x = eqn[0] - 'a'; int y = eqn[3] - 'a'; if (eqn[1] == '=') { union_find.union_set(x, y); } } for (const auto& eqn : equations) { int x = eqn[0] - 'a'; int y = eqn[3] - 'a'; if (eqn[1] == '!') { if (union_find.find_set(x) == union_find.find_set(y)) { return false; } } } return true; } private: class UnionFind { public: UnionFind(const int n) : set_(n) { iota(set_.begin(), set_.end(), 0); } int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } return set_[x]; } bool union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root == y_root) { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); return true; } private: vector<int> set_; }; }; // Time: O(n) // Space: O(1) class Solution2 { public: bool equationsPossible(vector<string>& equations) { vector<vector<int>> graph(26); for (const auto& eqn : equations) { int x = eqn[0] - 'a'; int y = eqn[3] - 'a'; if (eqn[1] == '!') { if (x == y) { return false; } } else { graph[x].emplace_back(y); graph[y].emplace_back(x); } } vector<int> color(26); for (int i = 0, c = 0; i < color.size(); ++i) { if (color[i]) { continue; } ++c; vector<int> stack = {c}; while (!stack.empty()) { int node = stack.back(); stack.pop_back(); for (const auto& nei : graph[node]) { if (!color[nei]) { color[nei] = c; stack.emplace_back(nei); } } } } for (const auto& eqn : equations) { if (eqn[1] != '!') { continue; } int x = eqn[0] - 'a'; int y = eqn[3] - 'a'; if (color[x] && color[x] == color[y]) { return false; } } return true; } };
25.792453
71
0.381858
jaiskid
295c18df9032415e30ff21a43f7bbc31a48922fc
16,058
cpp
C++
src/solvers/refinement/string_constraint_generator_indexof.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
null
null
null
src/solvers/refinement/string_constraint_generator_indexof.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
1
2019-02-05T16:18:25.000Z
2019-02-05T16:18:25.000Z
src/solvers/refinement/string_constraint_generator_indexof.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Generates string constraints for the family of indexOf and lastIndexOf java functions Author: Romain Brenguier, romain.brenguier@diffblue.com \*******************************************************************/ /// \file /// Generates string constraints for the family of indexOf and lastIndexOf java /// functions #include <solvers/refinement/string_refinement_invariant.h> #include <solvers/refinement/string_constraint_generator.h> /// Add axioms stating that the returned value is the index within `haystack` /// (`str`) of the first occurrence of `needle` (`c`) starting the search at /// `from_index`, or is `-1` if no such character occurs at or after position /// `from_index`. /// \todo Make argument names match whose of add_axioms_for_index_of_string /// /// These axioms are: /// 1. \f$-1 \le {\tt index} < |{\tt haystack}| \f$ /// 2. \f$ \lnot contains \Leftrightarrow {\tt index} = -1 \f$ /// 3. \f$ contains \Rightarrow {\tt from\_index} \le {\tt index} /// \land {\tt haystack}[{\tt index}] = {\tt needle} \f$ /// 4. \f$ \forall i \in [{\tt from\_index}, {\tt index}).\ contains /// \Rightarrow {\tt haystack}[i] \ne {\tt needle} \f$ /// 5. \f$ \forall m, n \in [{\tt from\_index}, |{\tt haystack}|) /// .\ \lnot contains \Rightarrow {\tt haystack}[m] \ne {\tt needle} /// \f$ /// \param str: an array of characters expression /// \param c: a character expression /// \param from_index: an integer expression /// \return integer expression `index` exprt string_constraint_generatort::add_axioms_for_index_of( const array_string_exprt &str, const exprt &c, const exprt &from_index) { const typet &index_type=str.length().type(); symbol_exprt index=fresh_exist_index("index_of", index_type); symbol_exprt contains=fresh_boolean("contains_in_index_of"); exprt minus1=from_integer(-1, index_type); and_exprt a1( binary_relation_exprt(index, ID_ge, minus1), binary_relation_exprt(index, ID_lt, str.length())); axioms.push_back(a1); equal_exprt a2(not_exprt(contains), equal_exprt(index, minus1)); axioms.push_back(a2); implies_exprt a3( contains, and_exprt( binary_relation_exprt(from_index, ID_le, index), equal_exprt(str[index], c))); axioms.push_back(a3); const auto zero = from_integer(0, index_type); const if_exprt lower_bound( binary_relation_exprt(from_index, ID_le, zero), zero, from_index); symbol_exprt n=fresh_univ_index("QA_index_of", index_type); string_constraintt a4( n, lower_bound, index, contains, not_exprt(equal_exprt(str[n], c))); axioms.push_back(a4); symbol_exprt m=fresh_univ_index("QA_index_of", index_type); string_constraintt a5( m, lower_bound, str.length(), not_exprt(contains), not_exprt(equal_exprt(str[m], c))); axioms.push_back(a5); return index; } /// Add axioms stating that the returned value `index` is the index within /// `haystack` of the first occurrence of `needle` starting the search at /// `from_index`, or `-1` if needle does not occur at or after position /// `from_index`. /// If needle is an empty string then the result is `from_index`. /// /// These axioms are: /// 1. \f$ contains \Rightarrow {\tt from\_index} \le \tt{index} /// \le |{\tt haystack}|-|{\tt needle} | \f$ /// 2. \f$ \lnot contains \Leftrightarrow {\tt index} = -1 \f$ /// 3. \f$ \forall n \in [0,|{\tt needle}|).\ contains /// \Rightarrow {\tt haystack}[n + {\tt index}] = {\tt needle}[n] \f$ /// 4. \f$ \forall n \in [{\tt from\_index}, {\tt index}).\ contains /// \Rightarrow (\exists m \in [0,|{\tt needle}|).\ {\tt haystack}[m+n] /// \ne {\tt needle}[m]]) \f$ /// 5. \f$ \forall n \in [{\tt from\_index},|{\tt haystack}|-|{\tt needle}|] /// .\ \lnot contains \Rightarrow (\exists m \in [0,|{\tt needle}|) /// .\ {\tt haystack}[m+n] \ne {\tt needle}[m]) \f$ /// 6. \f$ |{\tt needle}| = 0 \Rightarrow \tt{index} = from_index \f$ /// \param haystack: an array of character expression /// \param needle: an array of character expression /// \param from_index: an integer expression /// \return integer expression `index` representing the first index of `needle` /// in `haystack` exprt string_constraint_generatort::add_axioms_for_index_of_string( const array_string_exprt &haystack, const array_string_exprt &needle, const exprt &from_index) { const typet &index_type=haystack.length().type(); symbol_exprt offset=fresh_exist_index("index_of", index_type); symbol_exprt contains=fresh_boolean("contains_substring"); implies_exprt a1( contains, and_exprt( binary_relation_exprt(from_index, ID_le, offset), binary_relation_exprt( offset, ID_le, minus_exprt(haystack.length(), needle.length())))); axioms.push_back(a1); equal_exprt a2( not_exprt(contains), equal_exprt(offset, from_integer(-1, index_type))); axioms.push_back(a2); symbol_exprt qvar=fresh_univ_index("QA_index_of_string", index_type); string_constraintt a3( qvar, needle.length(), contains, equal_exprt(haystack[plus_exprt(qvar, offset)], needle[qvar])); axioms.push_back(a3); // string_not contains_constraintt are formulas of the form: // forall x in [lb,ub[. p(x) => exists y in [lb,ub[. s1[x+y] != s2[y] string_not_contains_constraintt a4( from_index, offset, contains, from_integer(0, index_type), needle.length(), haystack, needle); axioms.push_back(a4); string_not_contains_constraintt a5( from_index, plus_exprt( // Add 1 for inclusive upper bound. minus_exprt(haystack.length(), needle.length()), from_integer(1, index_type)), not_exprt(contains), from_integer(0, index_type), needle.length(), haystack, needle); axioms.push_back(a5); const implies_exprt a6( equal_exprt(needle.length(), from_integer(0, index_type)), equal_exprt(offset, from_index)); axioms.push_back(a6); return offset; } /// Add axioms stating that the returned value is the index within haystack of /// the last occurrence of needle starting the search backward at from_index (ie /// the index is smaller or equal to from_index), or -1 if needle does not occur /// before from_index. /// If `needle` is the empty string, the result is `from_index`. /// /// These axioms are: /// 1. \f$ contains \Rightarrow -1 \le {\tt index} /// \land {\tt index} \le {\tt from\_index} /// \land {\tt index} \le |{\tt haystack}| - |{\tt needle}| \f$ /// 2. \f$ \lnot contains \Leftrightarrow {\tt index}= -1 \f$ /// 3. \f$ \forall n \in [0, |{\tt needle}|).\ contains /// \Rightarrow {\tt haystack}[n+{\tt index}] = {\tt needle}[n] \f$ /// 4. \f$ \forall n \in [{\tt index}+1, /// min({\tt from\_index}, /// |{\tt haystack}| - |{\tt needle}|)] /// .\ contains \Rightarrow /// (\exists m \in [0,|{\tt needle}|) /// .\ {\tt haystack}[m+n] \ne {\tt needle}[m]]) \f$ /// 5. \f$ \forall n \in /// [0, min({\tt from\_index}, |{\tt haystack}| - |{\tt needle}|)] /// .\ \lnot contains \Rightarrow /// (\exists m \in [0,|{\tt needle}|) /// .\ {\tt haystack}[m+n] \ne {\tt needle}[m]) \f$ /// 6. \f$ |{\tt needle}| = 0 \Rightarrow index = from_index \f$ /// \param haystack: an array of characters expression /// \param needle: an array of characters expression /// \param from_index: integer expression /// \return integer expression `index` representing the last index of `needle` /// in `haystack` before or at `from_index`, or -1 if there is none exprt string_constraint_generatort::add_axioms_for_last_index_of_string( const array_string_exprt &haystack, const array_string_exprt &needle, const exprt &from_index) { const typet &index_type=haystack.length().type(); symbol_exprt offset=fresh_exist_index("index_of", index_type); symbol_exprt contains=fresh_boolean("contains_substring"); implies_exprt a1( contains, and_exprt( binary_relation_exprt(from_integer(-1, index_type), ID_le, offset), binary_relation_exprt( offset, ID_le, minus_exprt(haystack.length(), needle.length())), binary_relation_exprt(offset, ID_le, from_index))); axioms.push_back(a1); equal_exprt a2( not_exprt(contains), equal_exprt(offset, from_integer(-1, index_type))); axioms.push_back(a2); symbol_exprt qvar=fresh_univ_index("QA_index_of_string", index_type); equal_exprt constr3(haystack[plus_exprt(qvar, offset)], needle[qvar]); string_constraintt a3(qvar, needle.length(), contains, constr3); axioms.push_back(a3); // end_index is min(from_index, |str| - |substring|) minus_exprt length_diff(haystack.length(), needle.length()); if_exprt end_index( binary_relation_exprt(from_index, ID_le, length_diff), from_index, length_diff); string_not_contains_constraintt a4( plus_exprt(offset, from_integer(1, index_type)), plus_exprt(end_index, from_integer(1, index_type)), contains, from_integer(0, index_type), needle.length(), haystack, needle); axioms.push_back(a4); string_not_contains_constraintt a5( from_integer(0, index_type), plus_exprt(end_index, from_integer(1, index_type)), not_exprt(contains), from_integer(0, index_type), needle.length(), haystack, needle); axioms.push_back(a5); const implies_exprt a6( equal_exprt(needle.length(), from_integer(0, index_type)), equal_exprt(offset, from_index)); axioms.push_back(a6); return offset; } /// Index of the first occurence of a target inside the string /// /// If the target is a character: // NOLINTNEXTLINE /// \copybrief add_axioms_for_index_of(const array_string_exprt&,const exprt&,const exprt&) /// \link /// add_axioms_for_index_of(const array_string_exprt&,const exprt&,const exprt&) /// (More...) \endlink /// /// If the target is a refined_string: /// \copybrief string_constraint_generatort::add_axioms_for_index_of_string /// \link string_constraint_generatort::add_axioms_for_index_of_string (More...) /// \endlink /// \warning slow for string targets /// \param f: function application with arguments refined_string `haystack`, /// refined_string or character `needle`, and optional integer /// `from_index` with default value `0` /// \return integer expression exprt string_constraint_generatort::add_axioms_for_index_of( const function_application_exprt &f) { const function_application_exprt::argumentst &args=f.arguments(); PRECONDITION(args.size() == 2 || args.size() == 3); const array_string_exprt str = get_string_expr(args[0]); const exprt &c=args[1]; const typet &index_type = str.length().type(); const typet &char_type = str.content().type().subtype(); PRECONDITION(f.type() == index_type); const exprt from_index = args.size() == 2 ? from_integer(0, index_type) : args[2]; if(c.type().id()==ID_unsignedbv || c.type().id()==ID_signedbv) { return add_axioms_for_index_of( str, typecast_exprt(c, char_type), from_index); } else { INVARIANT( is_refined_string_type(c.type()), string_refinement_invariantt("c can only be a (un)signedbv or a refined " "string and the (un)signedbv case is already handled")); array_string_exprt sub = get_string_expr(c); return add_axioms_for_index_of_string(str, sub, from_index); } } /// Add axioms stating that the returned value is the index within `haystack` /// (`str`) of the last occurrence of `needle` (`c`) starting the search /// backward at `from_index`, or `-1` if no such character occurs at or before /// position `from_index`. /// \todo Change argument names to match add_axioms_for_last_index_of_string /// /// These axioms are : /// 1. \f$ -1 \le {\tt index} \le {\tt from\_index} /// \land {\tt index} < |{\tt haystack}| \f$ /// 2. \f$ {\tt index} = -1 \Leftrightarrow \lnot contains\f$ /// 3. \f$ contains \Rightarrow /// {\tt haystack}[{\tt index}] = {\tt needle} )\f$ /// 4. \f$ \forall n \in [{\tt index} +1, /// min({\tt from\_index}+1, |{\tt haystack}|)) /// .\ contains \Rightarrow {\tt haystack}[n] \ne {\tt needle} \f$ /// 5. \f$ \forall m \in [0, /// min({\tt from\_index}+1, |{\tt haystack}|)) /// .\ \lnot contains \Rightarrow {\tt haystack}[m] \ne {\tt needle}\f$ /// \param str: an array of characters expression /// \param c: a character expression /// \param from_index: an integer expression /// \return integer expression `index` representing the last index of `needle` /// in `haystack` before or at `from_index`, or `-1` if there is none exprt string_constraint_generatort::add_axioms_for_last_index_of( const array_string_exprt &str, const exprt &c, const exprt &from_index) { const typet &index_type = str.length().type(); const symbol_exprt index = fresh_exist_index("last_index_of", index_type); const symbol_exprt contains = fresh_boolean("contains_in_last_index_of"); const exprt minus1 = from_integer(-1, index_type); const and_exprt a1( binary_relation_exprt(index, ID_ge, minus1), binary_relation_exprt(index, ID_le, from_index), binary_relation_exprt(index, ID_lt, str.length())); axioms.push_back(a1); const notequal_exprt a2(contains, equal_exprt(index, minus1)); axioms.push_back(a2); const implies_exprt a3(contains, equal_exprt(str[index], c)); axioms.push_back(a3); const exprt index1 = from_integer(1, index_type); const exprt from_index_plus_one = plus_exprt_with_overflow_check(from_index, index1); const if_exprt end_index( binary_relation_exprt(from_index_plus_one, ID_le, str.length()), from_index_plus_one, str.length()); const symbol_exprt n = fresh_univ_index("QA_last_index_of1", index_type); const string_constraintt a4( n, plus_exprt(index, index1), end_index, contains, notequal_exprt(str[n], c)); axioms.push_back(a4); const symbol_exprt m = fresh_univ_index("QA_last_index_of2", index_type); const string_constraintt a5( m, end_index, not_exprt(contains), notequal_exprt(str[m], c)); axioms.push_back(a5); return index; } /// Index of the last occurence of a target inside the string /// /// If the target is a character: // NOLINTNEXTLINE /// \copybrief add_axioms_for_last_index_of(const array_string_exprt&,const exprt&,const exprt&) // NOLINTNEXTLINE /// \link add_axioms_for_last_index_of(const array_string_exprt&,const exprt&,const exprt&) /// (More...) \endlink /// /// If the target is a refined_string: /// \copybrief string_constraint_generatort::add_axioms_for_last_index_of_string /// \link string_constraint_generatort::add_axioms_for_last_index_of_string /// (More...) \endlink /// \warning slow for string targets /// \param f: function application with arguments refined_string `haystack`, /// refined_string or character `needle`, and optional integer /// `from_index` with default value `|haystack|-1` /// \return an integer expression exprt string_constraint_generatort::add_axioms_for_last_index_of( const function_application_exprt &f) { const function_application_exprt::argumentst &args=f.arguments(); PRECONDITION(args.size() == 2 || args.size() == 3); const array_string_exprt str = get_string_expr(args[0]); const exprt c = args[1]; const typet &index_type = str.length().type(); const typet &char_type = str.content().type().subtype(); PRECONDITION(f.type() == index_type); const exprt from_index = args.size() == 2 ? str.length() : args[2]; if(c.type().id()==ID_unsignedbv || c.type().id()==ID_signedbv) { return add_axioms_for_last_index_of( str, typecast_exprt(c, char_type), from_index); } else { const array_string_exprt sub = get_string_expr(c); return add_axioms_for_last_index_of_string(str, sub, from_index); } }
38.142518
96
0.675115
jeannielynnmoulton
29601cde5ad02783e2c0f0b430a603f4b63a84b8
4,641
cpp
C++
MJBATesting/src/main.cpp
AnthonyFuller/TonyTools
9746e53144783143e6820216d8e756abe30bd733
[ "MIT" ]
null
null
null
MJBATesting/src/main.cpp
AnthonyFuller/TonyTools
9746e53144783143e6820216d8e756abe30bd733
[ "MIT" ]
null
null
null
MJBATesting/src/main.cpp
AnthonyFuller/TonyTools
9746e53144783143e6820216d8e756abe30bd733
[ "MIT" ]
null
null
null
#include "main.h" struct ZNewTrajectory { uint32_t frames; uint32_t sampleFreq; }; struct Vector3 { float x; float y; float z; }; struct QuantizedQuaternion { uint16_t x; uint16_t y; uint16_t z; uint16_t w; }; struct Quaternion { float x; float y; float z; float w; Quaternion(QuantizedQuaternion quanQuat) { x = ((float)quanQuat.x / 32767) - 1; y = ((float)quanQuat.y / 32767) - 1; z = ((float)quanQuat.z / 32767) - 1; w = ((float)quanQuat.w / 32767) - 1; // Checking to make sure the final Quaternion is valid assert(roundf(x*x + y*y + z*z + w*w) == 1); } }; struct Transform { float x; float y; float z; float w; Transform(uint64_t data, Vector3 transScale) { // This is ugly as fuck x = (float)((int)(data >> 31) >> 11) * transScale.x; y = (float)((int)(data >> 10) >> 11) * transScale.y; z = (float)((int)((uint32_t)data << 11) >> 11) * transScale.z; w = 1.0; } }; struct BoneTransform { Quaternion m_rot; Transform m_trans; }; struct AnimDataHdr { float duration; uint32_t boneCount; ZNewTrajectory trajectory; uint32_t frames; float fps; uint32_t keyframes; uint32_t pad; uint32_t frameCount; uint16_t constBoneQuat; uint16_t constBoneTrans; Vector3 translationScale; bool hasBindPose; }; struct AnimDataOffsets { size_t quatBitArray; size_t transBitArray; size_t retargetBitArray; size_t constQuats; size_t quats; size_t bindPoseQuats; size_t constTrans; size_t trans; size_t bindPoseTrans; size_t end; }; AnimDataOffsets generateOffsets(AnimDataHdr hdr) { AnimDataOffsets offsets{}; size_t bindPoseBoneCount{}; if (hdr.hasBindPose) bindPoseBoneCount = 2 * hdr.boneCount; else bindPoseBoneCount = 0; offsets.quatBitArray = 0x38; offsets.transBitArray = (8 * ((hdr.boneCount + 63) >> 6)) + 0x38; offsets.retargetBitArray = offsets.transBitArray + (offsets.transBitArray - 0x38); offsets.constQuats = offsets.retargetBitArray + 8 * ((uint32_t)(bindPoseBoneCount + 63) >> 6); offsets.quats = offsets.constQuats + 8 * hdr.constBoneQuat; offsets.bindPoseQuats = offsets.quats + 8 * hdr.frameCount * (hdr.boneCount - hdr.constBoneQuat); offsets.constTrans = offsets.bindPoseQuats + 8 * bindPoseBoneCount; offsets.trans = offsets.constTrans + 8 * hdr.constBoneTrans; offsets.bindPoseTrans = offsets.trans + 8 * hdr.frameCount * (hdr.boneCount - hdr.constBoneTrans); offsets.end = offsets.bindPoseTrans + (8 * bindPoseBoneCount); return offsets; } std::vector<Quaternion> readQuantQuatArr(file_buffer &buff, int numOfQuat) { std::vector<Quaternion> quatArr; for (int i = 0; i < numOfQuat; i++) { QuantizedQuaternion quantQuat = buff.read<QuantizedQuaternion>(); Quaternion quat(quantQuat); quatArr.push_back(quat); } return quatArr; } std::vector<Transform> readQuantTransArr(file_buffer &buff, int numOfTrans, Vector3 transScale) { std::vector<Transform> transArr; for (int i = 0; i < numOfTrans; i++) { uint64_t quantTransData = buff.read<uint64_t>(); Transform trans(quantTransData, transScale); transArr.push_back(trans); } return transArr; } int main(int argc, char *argv[]) { file_buffer buff; buff.load(argv[1]); AnimDataHdr hdr = buff.read<AnimDataHdr>(); AnimDataOffsets offsets = generateOffsets(hdr); buff.index = offsets.constQuats; assert(buff.index == offsets.constQuats); std::vector<Quaternion> constQuats = readQuantQuatArr(buff, hdr.constBoneQuat); assert(buff.index == offsets.quats); std::vector<Quaternion> quats = readQuantQuatArr(buff, (offsets.bindPoseQuats - offsets.quats) / 8); assert(buff.index == offsets.bindPoseQuats); std::vector<Quaternion> bindPoseQuats = readQuantQuatArr(buff, (offsets.constTrans - offsets.bindPoseQuats) / 8); assert(buff.index == offsets.constTrans); std::vector<Transform> constTrans = readQuantTransArr(buff, hdr.constBoneTrans, hdr.translationScale); assert(buff.index == offsets.trans); std::vector<Transform> trans = readQuantTransArr(buff, (offsets.bindPoseTrans - offsets.trans) / 8, hdr.translationScale); assert(buff.index == offsets.bindPoseTrans); std::vector<Transform> bindPoseTrans = readQuantTransArr(buff, (offsets.end - offsets.bindPoseTrans) / 8, hdr.translationScale); assert(buff.index == offsets.end); LOG("Done!"); }
25.927374
132
0.662357
AnthonyFuller
2960525e598021fd446b3e6cf31a227ef95e9afa
2,268
cpp
C++
_project/test_mpi_support.cpp
IMTEK-Simulation/molecular_dynamics_course
ea730c2f6771338696221347a5af0c937a04206f
[ "CC-BY-4.0" ]
4
2021-07-04T19:44:58.000Z
2022-03-20T07:42:45.000Z
_project/test_mpi_support.cpp
IMTEK-Simulation/molecular_dynamics_course
ea730c2f6771338696221347a5af0c937a04206f
[ "CC-BY-4.0" ]
null
null
null
_project/test_mpi_support.cpp
IMTEK-Simulation/molecular_dynamics_course
ea730c2f6771338696221347a5af0c937a04206f
[ "CC-BY-4.0" ]
null
null
null
/* * Copyright 2021 Lars Pastewka * * ### MIT license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <gtest/gtest.h> #include "mpi_support.h" TEST(MPISupport, MPIType) { EXPECT_EQ(MPI::mpi_type<char>(), MPI_CHAR); EXPECT_EQ(MPI::mpi_type<short>(), MPI_SHORT); EXPECT_EQ(MPI::mpi_type<int>(), MPI_INT); EXPECT_EQ(MPI::mpi_type<long>(), MPI_LONG); EXPECT_EQ(MPI::mpi_type<long long>(), MPI_LONG_LONG_INT); EXPECT_EQ(MPI::mpi_type<unsigned char>(), MPI_UNSIGNED_CHAR); EXPECT_EQ(MPI::mpi_type<unsigned short>(), MPI_UNSIGNED_SHORT); EXPECT_EQ(MPI::mpi_type<unsigned int>(), MPI_UNSIGNED); EXPECT_EQ(MPI::mpi_type<unsigned long>(), MPI_UNSIGNED_LONG); EXPECT_EQ(MPI::mpi_type<float>(), MPI_FLOAT); EXPECT_EQ(MPI::mpi_type<double>(), MPI_DOUBLE); } TEST(MPISupport, Wrap) { EXPECT_EQ(wrap_to_interval(0, 7), 0); EXPECT_EQ(wrap_to_interval(1, 7), 1); EXPECT_EQ(wrap_to_interval(-1, 7), 6); EXPECT_EQ(wrap_to_distance(0, 7), 0); EXPECT_EQ(wrap_to_distance(1, 7), 1); EXPECT_EQ(wrap_to_distance(-1, 7), -1); EXPECT_EQ(wrap_to_distance(3, 7), 3); EXPECT_EQ(wrap_to_distance(-3, 7), -3); EXPECT_EQ(wrap_to_distance(4, 7), -3); EXPECT_EQ(wrap_to_distance(-4, 7), 3); }
41.236364
79
0.728395
IMTEK-Simulation
296239f37b6fd21ed2f86e5f429e4c4875f9f7bf
74,371
cpp
C++
src/nanosvg.cpp
CodeFinder2/nanosvg
a1d2a5a7f4723143a621ed7a2a38bafdf5066d1e
[ "Zlib" ]
null
null
null
src/nanosvg.cpp
CodeFinder2/nanosvg
a1d2a5a7f4723143a621ed7a2a38bafdf5066d1e
[ "Zlib" ]
null
null
null
src/nanosvg.cpp
CodeFinder2/nanosvg
a1d2a5a7f4723143a621ed7a2a38bafdf5066d1e
[ "Zlib" ]
null
null
null
#include "nanosvg/nanosvg.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #define NSVG_PI (3.14159265358979323846264338327f) #define NSVG_KAPPA90 (0.5522847493f) // Length proportional to radius of a cubic bezier handle for 90deg arcs. #define NSVG_ALIGN_MIN 0 #define NSVG_ALIGN_MID 1 #define NSVG_ALIGN_MAX 2 #define NSVG_ALIGN_NONE 0 #define NSVG_ALIGN_MEET 1 #define NSVG_ALIGN_SLICE 2 #define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) #define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16)) #ifdef _MSC_VER #pragma warning (disable: 4996) // Switch off security warnings #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings #ifdef __cplusplus #define NSVG_INLINE inline #else #define NSVG_INLINE #endif #else #define NSVG_INLINE inline #endif static int nsvg__isspace(char c) { return strchr(" \t\n\v\f\r", c) != 0; } static int nsvg__isdigit(char c) { return c >= '0' && c <= '9'; } static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; } static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; } // Simple XML parser #define NSVG_XML_TAG 1 #define NSVG_XML_CONTENT 2 #define NSVG_XML_MAX_ATTRIBS 256 static void nsvg__parseContent(char* s, void (*contentCb)(void* ud, const char* s), void* ud) { // Trim start white spaces while (*s && nsvg__isspace(*s)) s++; if (!*s) return; if (contentCb) (*contentCb)(ud, s); } static void nsvg__parseElement(char* s, void (*startelCb)(void* ud, const char* el, const char** attr), void (*endelCb)(void* ud, const char* el), void* ud) { const char* attr[NSVG_XML_MAX_ATTRIBS]; int nattr = 0; char* name; int start = 0; int end = 0; char quote; // Skip white space after the '<' while (*s && nsvg__isspace(*s)) s++; // Check if the tag is end tag if (*s == '/') { s++; end = 1; } else { start = 1; } // Skip comments, data and preprocessor stuff. if (!*s || *s == '?' || *s == '!') return; // Get tag name name = s; while (*s && !nsvg__isspace(*s)) s++; if (*s) { *s++ = '\0'; } // Get attribs while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) { char* name = NULL; char* value = NULL; // Skip white space before the attrib name while (*s && nsvg__isspace(*s)) s++; if (!*s) break; if (*s == '/') { end = 1; break; } name = s; // Find end of the attrib name. while (*s && !nsvg__isspace(*s) && *s != '=') s++; if (*s) { *s++ = '\0'; } // Skip until the beginning of the value. while (*s && *s != '\"' && *s != '\'') s++; if (!*s) break; quote = *s; s++; // Store value and find the end of it. value = s; while (*s && *s != quote) s++; if (*s) { *s++ = '\0'; } // Store only well formed attributes if (name && value) { attr[nattr++] = name; attr[nattr++] = value; } } // List terminator attr[nattr++] = 0; attr[nattr++] = 0; // Call callbacks. if (start && startelCb) (*startelCb)(ud, name, attr); if (end && endelCb) (*endelCb)(ud, name); } int nsvg__parseXML(char* input, void (*startelCb)(void* ud, const char* el, const char** attr), void (*endelCb)(void* ud, const char* el), void (*contentCb)(void* ud, const char* s), void* ud) { char* s = input; char* mark = s; int state = NSVG_XML_CONTENT; while (*s) { if (*s == '<' && state == NSVG_XML_CONTENT) { // Start of a tag *s++ = '\0'; nsvg__parseContent(mark, contentCb, ud); mark = s; state = NSVG_XML_TAG; } else if (*s == '>' && state == NSVG_XML_TAG) { // Start of a content or new tag. *s++ = '\0'; nsvg__parseElement(mark, startelCb, endelCb, ud); mark = s; state = NSVG_XML_CONTENT; } else { s++; } } return 1; } /* Simple SVG parser. */ #define NSVG_MAX_ATTR 128 enum NSVGgradientUnits { NSVG_USER_SPACE = 0, NSVG_OBJECT_SPACE = 1 }; #define NSVG_MAX_DASHES 8 enum NSVGunits { NSVG_UNITS_USER, NSVG_UNITS_PX, NSVG_UNITS_PT, NSVG_UNITS_PC, NSVG_UNITS_MM, NSVG_UNITS_CM, NSVG_UNITS_IN, NSVG_UNITS_PERCENT, NSVG_UNITS_EM, NSVG_UNITS_EX }; typedef struct NSVGcoordinate { float value; int units; } NSVGcoordinate; typedef struct NSVGlinearData { NSVGcoordinate x1, y1, x2, y2; } NSVGlinearData; typedef struct NSVGradialData { NSVGcoordinate cx, cy, r, fx, fy; } NSVGradialData; typedef struct NSVGgradientData { char id[64]; char ref[64]; char type; union { NSVGlinearData linear; NSVGradialData radial; }; char spread; char units; float xform[6]; int nstops; NSVGgradientStop* stops; struct NSVGgradientData* next; } NSVGgradientData; typedef struct NSVGattrib { char id[64]; float xform[6]; unsigned int fillColor; unsigned int strokeColor; float opacity; float fillOpacity; float strokeOpacity; char fillGradient[64]; char strokeGradient[64]; float strokeWidth; float strokeDashOffset; float strokeDashArray[NSVG_MAX_DASHES]; int strokeDashCount; char strokeLineJoin; char strokeLineCap; float miterLimit; char fillRule; float fontSize; unsigned int stopColor; float stopOpacity; float stopOffset; char hasFill; char hasStroke; char visible; } NSVGattrib; typedef struct NSVGparser { NSVGattrib attr[NSVG_MAX_ATTR]; int attrHead; float* pts; int npts; int cpts; NSVGpath* plist; NSVGimage* image; NSVGgradientData* gradients; NSVGshape* shapesTail; float viewMinx, viewMiny, viewWidth, viewHeight; int alignX, alignY, alignType; float dpi; char pathFlag; char defsFlag; } NSVGparser; static void nsvg__xformIdentity(float* t) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetTranslation(float* t, float tx, float ty) { t[0] = 1.0f; t[1] = 0.0f; t[2] = 0.0f; t[3] = 1.0f; t[4] = tx; t[5] = ty; } static void nsvg__xformSetScale(float* t, float sx, float sy) { t[0] = sx; t[1] = 0.0f; t[2] = 0.0f; t[3] = sy; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetSkewX(float* t, float a) { t[0] = 1.0f; t[1] = 0.0f; t[2] = tanf(a); t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetSkewY(float* t, float a) { t[0] = 1.0f; t[1] = tanf(a); t[2] = 0.0f; t[3] = 1.0f; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformSetRotation(float* t, float a) { float cs = cosf(a), sn = sinf(a); t[0] = cs; t[1] = sn; t[2] = -sn; t[3] = cs; t[4] = 0.0f; t[5] = 0.0f; } static void nsvg__xformMultiply(float* t, float* s) { float t0 = t[0] * s[0] + t[1] * s[2]; float t2 = t[2] * s[0] + t[3] * s[2]; float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; t[1] = t[0] * s[1] + t[1] * s[3]; t[3] = t[2] * s[1] + t[3] * s[3]; t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; t[0] = t0; t[2] = t2; t[4] = t4; } static void nsvg__xformInverse(float* inv, float* t) { double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; if (det > -1e-6 && det < 1e-6) { nsvg__xformIdentity(t); return; } invdet = 1.0 / det; inv[0] = (float)(t[3] * invdet); inv[2] = (float)(-t[2] * invdet); inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); inv[1] = (float)(-t[1] * invdet); inv[3] = (float)(t[0] * invdet); inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); } static void nsvg__xformPremultiply(float* t, float* s) { float s2[6]; memcpy(s2, s, sizeof(float)*6); nsvg__xformMultiply(s2, t); memcpy(t, s2, sizeof(float)*6); } static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t) { *dx = x*t[0] + y*t[2] + t[4]; *dy = x*t[1] + y*t[3] + t[5]; } static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t) { *dx = x*t[0] + y*t[2]; *dy = x*t[1] + y*t[3]; } #define NSVG_EPSILON (1e-12) static int nsvg__ptInBounds(float* pt, float* bounds) { return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3]; } static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3) { double it = 1.0-t; return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3; } static void nsvg__curveBounds(float* bounds, float* curve) { int i, j, count; double roots[2], a, b, c, b2ac, t, v; float* v0 = &curve[0]; float* v1 = &curve[2]; float* v2 = &curve[4]; float* v3 = &curve[6]; // Start the bounding box by end points bounds[0] = nsvg__minf(v0[0], v3[0]); bounds[1] = nsvg__minf(v0[1], v3[1]); bounds[2] = nsvg__maxf(v0[0], v3[0]); bounds[3] = nsvg__maxf(v0[1], v3[1]); // Bezier curve fits inside the convex hull of it's control points. // If control points are inside the bounds, we're done. if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds)) return; // Add bezier curve inflection points in X and Y. for (i = 0; i < 2; i++) { a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i]; b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i]; c = 3.0 * v1[i] - 3.0 * v0[i]; count = 0; if (fabs(a) < NSVG_EPSILON) { if (fabs(b) > NSVG_EPSILON) { t = -c / b; if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; } } else { b2ac = b*b - 4.0*c*a; if (b2ac > NSVG_EPSILON) { t = (-b + sqrt(b2ac)) / (2.0 * a); if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; t = (-b - sqrt(b2ac)) / (2.0 * a); if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) roots[count++] = t; } } for (j = 0; j < count; j++) { v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]); bounds[0+i] = nsvg__minf(bounds[0+i], (float)v); bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v); } } } static NSVGparser* nsvg__createParser() { NSVGparser* p; p = (NSVGparser*)malloc(sizeof(NSVGparser)); if (p == NULL) goto error; memset(p, 0, sizeof(NSVGparser)); p->image = (NSVGimage*)malloc(sizeof(NSVGimage)); if (p->image == NULL) goto error; memset(p->image, 0, sizeof(NSVGimage)); // Init style nsvg__xformIdentity(p->attr[0].xform); memset(p->attr[0].id, 0, sizeof p->attr[0].id); p->attr[0].fillColor = NSVG_RGB(0,0,0); p->attr[0].strokeColor = NSVG_RGB(0,0,0); p->attr[0].opacity = 1; p->attr[0].fillOpacity = 1; p->attr[0].strokeOpacity = 1; p->attr[0].stopOpacity = 1; p->attr[0].strokeWidth = 1; p->attr[0].strokeLineJoin = NSVG_JOIN_MITER; p->attr[0].strokeLineCap = NSVG_CAP_BUTT; p->attr[0].miterLimit = 4; p->attr[0].fillRule = NSVG_FILLRULE_NONZERO; p->attr[0].hasFill = 1; p->attr[0].visible = 1; return p; error: if (p) { if (p->image) free(p->image); free(p); } return NULL; } static void nsvg__deletePaths(NSVGpath* path) { while (path) { NSVGpath *next = path->next; if (path->pts != NULL) free(path->pts); free(path); path = next; } } static void nsvg__deletePaint(NSVGpaint* paint) { if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT) free(paint->gradient); } static void nsvg__deleteGradientData(NSVGgradientData* grad) { NSVGgradientData* next; while (grad != NULL) { next = grad->next; free(grad->stops); free(grad); grad = next; } } static void nsvg__deleteParser(NSVGparser* p) { if (p != NULL) { nsvg__deletePaths(p->plist); nsvg__deleteGradientData(p->gradients); nsvgDelete(p->image); free(p->pts); free(p); } } static void nsvg__resetPath(NSVGparser* p) { p->npts = 0; } static void nsvg__addPoint(NSVGparser* p, float x, float y) { if (p->npts+1 > p->cpts) { p->cpts = p->cpts ? p->cpts*2 : 8; p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float)); if (!p->pts) return; } p->pts[p->npts*2+0] = x; p->pts[p->npts*2+1] = y; p->npts++; } static void nsvg__moveTo(NSVGparser* p, float x, float y) { if (p->npts > 0) { p->pts[(p->npts-1)*2+0] = x; p->pts[(p->npts-1)*2+1] = y; } else { nsvg__addPoint(p, x, y); } } static void nsvg__lineTo(NSVGparser* p, float x, float y) { float px,py, dx,dy; if (p->npts > 0) { px = p->pts[(p->npts-1)*2+0]; py = p->pts[(p->npts-1)*2+1]; dx = x - px; dy = y - py; nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f); nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f); nsvg__addPoint(p, x, y); } } static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y) { if (p->npts > 0) { nsvg__addPoint(p, cpx1, cpy1); nsvg__addPoint(p, cpx2, cpy2); nsvg__addPoint(p, x, y); } } static NSVGattrib* nsvg__getAttr(NSVGparser* p) { return &p->attr[p->attrHead]; } static void nsvg__pushAttr(NSVGparser* p) { if (p->attrHead < NSVG_MAX_ATTR-1) { p->attrHead++; memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib)); } } static void nsvg__popAttr(NSVGparser* p) { if (p->attrHead > 0) p->attrHead--; } static float nsvg__actualOrigX(NSVGparser* p) { return p->viewMinx; } static float nsvg__actualOrigY(NSVGparser* p) { return p->viewMiny; } static float nsvg__actualWidth(NSVGparser* p) { return p->viewWidth; } static float nsvg__actualHeight(NSVGparser* p) { return p->viewHeight; } static float nsvg__actualLength(NSVGparser* p) { float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p); return sqrtf(w*w + h*h) / sqrtf(2.0f); } static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length) { NSVGattrib* attr = nsvg__getAttr(p); switch (c.units) { case NSVG_UNITS_USER: return c.value; case NSVG_UNITS_PX: return c.value; case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi; case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi; case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi; case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi; case NSVG_UNITS_IN: return c.value * p->dpi; case NSVG_UNITS_EM: return c.value * attr->fontSize; case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica. case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length; default: return c.value; } return c.value; } static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id) { NSVGgradientData* grad = p->gradients; if (id == NULL || *id == '\0') return NULL; while (grad != NULL) { if (strcmp(grad->id, id) == 0) return grad; grad = grad->next; } return NULL; } static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, char* paintType) { NSVGattrib* attr = nsvg__getAttr(p); NSVGgradientData* data = NULL; NSVGgradientData* ref = NULL; NSVGgradientStop* stops = NULL; NSVGgradient* grad; float ox, oy, sw, sh, sl; int nstops = 0; int refIter; data = nsvg__findGradientData(p, id); if (data == NULL) return NULL; // TODO: use ref to fill in all unset values too. ref = data; refIter = 0; while (ref != NULL) { NSVGgradientData* nextRef = NULL; if (stops == NULL && ref->stops != NULL) { stops = ref->stops; nstops = ref->nstops; break; } nextRef = nsvg__findGradientData(p, ref->ref); if (nextRef == ref) break; // prevent infite loops on malformed data ref = nextRef; refIter++; if (refIter > 32) break; // prevent infite loops on malformed data } if (stops == NULL) return NULL; grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1)); if (grad == NULL) return NULL; // The shape width and height. if (data->units == NSVG_OBJECT_SPACE) { ox = localBounds[0]; oy = localBounds[1]; sw = localBounds[2] - localBounds[0]; sh = localBounds[3] - localBounds[1]; } else { ox = nsvg__actualOrigX(p); oy = nsvg__actualOrigY(p); sw = nsvg__actualWidth(p); sh = nsvg__actualHeight(p); } sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f); if (data->type == NSVG_PAINT_LINEAR_GRADIENT) { float x1, y1, x2, y2, dx, dy; x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw); y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh); x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw); y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh); // Calculate transform aligned to the line dx = x2 - x1; dy = y2 - y1; grad->xform[0] = dy; grad->xform[1] = -dx; grad->xform[2] = dx; grad->xform[3] = dy; grad->xform[4] = x1; grad->xform[5] = y1; } else { float cx, cy, fx, fy, r; cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw); cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh); fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw); fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh); r = nsvg__convertToPixels(p, data->radial.r, 0, sl); // Calculate transform aligned to the circle grad->xform[0] = r; grad->xform[1] = 0; grad->xform[2] = 0; grad->xform[3] = r; grad->xform[4] = cx; grad->xform[5] = cy; grad->fx = fx / r; grad->fy = fy / r; } nsvg__xformMultiply(grad->xform, data->xform); nsvg__xformMultiply(grad->xform, attr->xform); grad->spread = data->spread; memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop)); grad->nstops = nstops; *paintType = data->type; return grad; } static float nsvg__getAverageScale(float* t) { float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); return (sx + sy) * 0.5f; } static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform) { NSVGpath* path; float curve[4*2], curveBounds[4]; int i, first = 1; for (path = shape->paths; path != NULL; path = path->next) { nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform); for (i = 0; i < path->npts-1; i += 3) { nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform); nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform); nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform); nsvg__curveBounds(curveBounds, curve); if (first) { bounds[0] = curveBounds[0]; bounds[1] = curveBounds[1]; bounds[2] = curveBounds[2]; bounds[3] = curveBounds[3]; first = 0; } else { bounds[0] = nsvg__minf(bounds[0], curveBounds[0]); bounds[1] = nsvg__minf(bounds[1], curveBounds[1]); bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]); bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]); } curve[0] = curve[6]; curve[1] = curve[7]; } } } static void nsvg__addShape(NSVGparser* p) { NSVGattrib* attr = nsvg__getAttr(p); float scale = 1.0f; NSVGshape* shape; NSVGpath* path; int i; if (p->plist == NULL) return; shape = (NSVGshape*)malloc(sizeof(NSVGshape)); if (shape == NULL) goto error; memset(shape, 0, sizeof(NSVGshape)); memcpy(shape->id, attr->id, sizeof shape->id); scale = nsvg__getAverageScale(attr->xform); shape->strokeWidth = attr->strokeWidth * scale; shape->strokeDashOffset = attr->strokeDashOffset * scale; shape->strokeDashCount = (char)attr->strokeDashCount; for (i = 0; i < attr->strokeDashCount; i++) shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale; shape->strokeLineJoin = attr->strokeLineJoin; shape->strokeLineCap = attr->strokeLineCap; shape->miterLimit = attr->miterLimit; shape->fillRule = attr->fillRule; shape->opacity = attr->opacity; shape->paths = p->plist; p->plist = NULL; // Calculate shape bounds shape->bounds[0] = shape->paths->bounds[0]; shape->bounds[1] = shape->paths->bounds[1]; shape->bounds[2] = shape->paths->bounds[2]; shape->bounds[3] = shape->paths->bounds[3]; for (path = shape->paths->next; path != NULL; path = path->next) { shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]); shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]); shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]); shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]); } // Set fill if (attr->hasFill == 0) { shape->fill.type = NSVG_PAINT_NONE; } else if (attr->hasFill == 1) { shape->fill.type = NSVG_PAINT_COLOR; shape->fill.color = attr->fillColor; shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24; } else if (attr->hasFill == 2) { float inv[6], localBounds[4]; nsvg__xformInverse(inv, attr->xform); nsvg__getLocalBounds(localBounds, shape, inv); shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type); if (shape->fill.gradient == NULL) { shape->fill.type = NSVG_PAINT_NONE; } } // Set stroke if (attr->hasStroke == 0) { shape->stroke.type = NSVG_PAINT_NONE; } else if (attr->hasStroke == 1) { shape->stroke.type = NSVG_PAINT_COLOR; shape->stroke.color = attr->strokeColor; shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24; } else if (attr->hasStroke == 2) { float inv[6], localBounds[4]; nsvg__xformInverse(inv, attr->xform); nsvg__getLocalBounds(localBounds, shape, inv); shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type); if (shape->stroke.gradient == NULL) shape->stroke.type = NSVG_PAINT_NONE; } // Set flags shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00); // Add to tail if (p->image->shapes == NULL) p->image->shapes = shape; else p->shapesTail->next = shape; p->shapesTail = shape; return; error: if (shape) free(shape); } static void nsvg__addPath(NSVGparser* p, char closed) { NSVGattrib* attr = nsvg__getAttr(p); NSVGpath* path = NULL; float bounds[4]; float* curve; int i; if (p->npts < 4) return; if (closed) nsvg__lineTo(p, p->pts[0], p->pts[1]); // Expect 1 + N*3 points (N = number of cubic bezier segments). if ((p->npts % 3) != 1) return; path = (NSVGpath*)malloc(sizeof(NSVGpath)); if (path == NULL) goto error; memset(path, 0, sizeof(NSVGpath)); path->pts = (float*)malloc(p->npts*2*sizeof(float)); if (path->pts == NULL) goto error; path->closed = closed; path->npts = p->npts; // Transform path. for (i = 0; i < p->npts; ++i) nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform); // Find bounds for (i = 0; i < path->npts-1; i += 3) { curve = &path->pts[i*2]; nsvg__curveBounds(bounds, curve); if (i == 0) { path->bounds[0] = bounds[0]; path->bounds[1] = bounds[1]; path->bounds[2] = bounds[2]; path->bounds[3] = bounds[3]; } else { path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]); path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]); path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]); path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]); } } path->next = p->plist; p->plist = path; return; error: if (path != NULL) { if (path->pts != NULL) free(path->pts); free(path); } } // We roll our own string to float because the std library one uses locale and messes things up. static double nsvg__atof(const char* s) { char* cur = (char*)s; char* end = NULL; double res = 0.0, sign = 1.0; long long intPart = 0, fracPart = 0; char hasIntPart = 0, hasFracPart = 0; // Parse optional sign if (*cur == '+') { cur++; } else if (*cur == '-') { sign = -1; cur++; } // Parse integer part if (nsvg__isdigit(*cur)) { // Parse digit sequence intPart = strtoll(cur, &end, 10); if (cur != end) { res = (double)intPart; hasIntPart = 1; cur = end; } } // Parse fractional part. if (*cur == '.') { cur++; // Skip '.' if (nsvg__isdigit(*cur)) { // Parse digit sequence fracPart = strtoll(cur, &end, 10); if (cur != end) { res += (double)fracPart / pow(10.0, (double)(end - cur)); hasFracPart = 1; cur = end; } } } // A valid number should have integer or fractional part. if (!hasIntPart && !hasFracPart) return 0.0; // Parse optional exponent if (*cur == 'e' || *cur == 'E') { long expPart = 0; cur++; // skip 'E' expPart = strtol(cur, &end, 10); // Parse digit sequence with sign if (cur != end) { res *= pow(10.0, (double)expPart); } } return res * sign; } static const char* nsvg__parseNumber(const char* s, char* it, const int size) { const int last = size-1; int i = 0; // sign if (*s == '-' || *s == '+') { if (i < last) it[i++] = *s; s++; } // integer part while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } if (*s == '.') { // decimal point if (i < last) it[i++] = *s; s++; // fraction part while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } } // exponent if ((*s == 'e' || *s == 'E') && (s[1] != 'm' && s[1] != 'x')) { if (i < last) it[i++] = *s; s++; if (*s == '-' || *s == '+') { if (i < last) it[i++] = *s; s++; } while (*s && nsvg__isdigit(*s)) { if (i < last) it[i++] = *s; s++; } } it[i] = '\0'; return s; } static const char* nsvg__getNextPathItem(const char* s, char* it) { it[0] = '\0'; // Skip white spaces and commas while (*s && (nsvg__isspace(*s) || *s == ',')) s++; if (!*s) return s; if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) { s = nsvg__parseNumber(s, it, 64); } else { // Parse command it[0] = *s++; it[1] = '\0'; return s; } return s; } static unsigned int nsvg__parseColorHex(const char* str) { unsigned int r=0, g=0, b=0; if (sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3 ) // 2 digit hex return NSVG_RGB(r, g, b); if (sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3 ) // 1 digit hex, e.g. #abc -> 0xccbbaa return NSVG_RGB(r*17, g*17, b*17); // same effect as (r<<4|r), (g<<4|g), .. return NSVG_RGB(128, 128, 128); } static unsigned int nsvg__parseColorRGB(const char* str) { unsigned int r=0, g=0, b=0; if (sscanf(str, "rgb(%u, %u, %u)", &r, &g, &b) == 3) // decimal integers return NSVG_RGB(r, g, b); if (sscanf(str, "rgb(%u%%, %u%%, %u%%)", &r, &g, &b) == 3) // decimal integer percentage return NSVG_RGB(r*255/100, g*255/100, b*255/100); return NSVG_RGB(128, 128, 128); } typedef struct NSVGNamedColor { const char* name; unsigned int color; } NSVGNamedColor; NSVGNamedColor nsvg__colors[] = { { "red", NSVG_RGB(255, 0, 0) }, { "green", NSVG_RGB( 0, 128, 0) }, { "blue", NSVG_RGB( 0, 0, 255) }, { "yellow", NSVG_RGB(255, 255, 0) }, { "cyan", NSVG_RGB( 0, 255, 255) }, { "magenta", NSVG_RGB(255, 0, 255) }, { "black", NSVG_RGB( 0, 0, 0) }, { "grey", NSVG_RGB(128, 128, 128) }, { "gray", NSVG_RGB(128, 128, 128) }, { "white", NSVG_RGB(255, 255, 255) }, #ifdef NANOSVG_ALL_COLOR_KEYWORDS { "aliceblue", NSVG_RGB(240, 248, 255) }, { "antiquewhite", NSVG_RGB(250, 235, 215) }, { "aqua", NSVG_RGB( 0, 255, 255) }, { "aquamarine", NSVG_RGB(127, 255, 212) }, { "azure", NSVG_RGB(240, 255, 255) }, { "beige", NSVG_RGB(245, 245, 220) }, { "bisque", NSVG_RGB(255, 228, 196) }, { "blanchedalmond", NSVG_RGB(255, 235, 205) }, { "blueviolet", NSVG_RGB(138, 43, 226) }, { "brown", NSVG_RGB(165, 42, 42) }, { "burlywood", NSVG_RGB(222, 184, 135) }, { "cadetblue", NSVG_RGB( 95, 158, 160) }, { "chartreuse", NSVG_RGB(127, 255, 0) }, { "chocolate", NSVG_RGB(210, 105, 30) }, { "coral", NSVG_RGB(255, 127, 80) }, { "cornflowerblue", NSVG_RGB(100, 149, 237) }, { "cornsilk", NSVG_RGB(255, 248, 220) }, { "crimson", NSVG_RGB(220, 20, 60) }, { "darkblue", NSVG_RGB( 0, 0, 139) }, { "darkcyan", NSVG_RGB( 0, 139, 139) }, { "darkgoldenrod", NSVG_RGB(184, 134, 11) }, { "darkgray", NSVG_RGB(169, 169, 169) }, { "darkgreen", NSVG_RGB( 0, 100, 0) }, { "darkgrey", NSVG_RGB(169, 169, 169) }, { "darkkhaki", NSVG_RGB(189, 183, 107) }, { "darkmagenta", NSVG_RGB(139, 0, 139) }, { "darkolivegreen", NSVG_RGB( 85, 107, 47) }, { "darkorange", NSVG_RGB(255, 140, 0) }, { "darkorchid", NSVG_RGB(153, 50, 204) }, { "darkred", NSVG_RGB(139, 0, 0) }, { "darksalmon", NSVG_RGB(233, 150, 122) }, { "darkseagreen", NSVG_RGB(143, 188, 143) }, { "darkslateblue", NSVG_RGB( 72, 61, 139) }, { "darkslategray", NSVG_RGB( 47, 79, 79) }, { "darkslategrey", NSVG_RGB( 47, 79, 79) }, { "darkturquoise", NSVG_RGB( 0, 206, 209) }, { "darkviolet", NSVG_RGB(148, 0, 211) }, { "deeppink", NSVG_RGB(255, 20, 147) }, { "deepskyblue", NSVG_RGB( 0, 191, 255) }, { "dimgray", NSVG_RGB(105, 105, 105) }, { "dimgrey", NSVG_RGB(105, 105, 105) }, { "dodgerblue", NSVG_RGB( 30, 144, 255) }, { "firebrick", NSVG_RGB(178, 34, 34) }, { "floralwhite", NSVG_RGB(255, 250, 240) }, { "forestgreen", NSVG_RGB( 34, 139, 34) }, { "fuchsia", NSVG_RGB(255, 0, 255) }, { "gainsboro", NSVG_RGB(220, 220, 220) }, { "ghostwhite", NSVG_RGB(248, 248, 255) }, { "gold", NSVG_RGB(255, 215, 0) }, { "goldenrod", NSVG_RGB(218, 165, 32) }, { "greenyellow", NSVG_RGB(173, 255, 47) }, { "honeydew", NSVG_RGB(240, 255, 240) }, { "hotpink", NSVG_RGB(255, 105, 180) }, { "indianred", NSVG_RGB(205, 92, 92) }, { "indigo", NSVG_RGB( 75, 0, 130) }, { "ivory", NSVG_RGB(255, 255, 240) }, { "khaki", NSVG_RGB(240, 230, 140) }, { "lavender", NSVG_RGB(230, 230, 250) }, { "lavenderblush", NSVG_RGB(255, 240, 245) }, { "lawngreen", NSVG_RGB(124, 252, 0) }, { "lemonchiffon", NSVG_RGB(255, 250, 205) }, { "lightblue", NSVG_RGB(173, 216, 230) }, { "lightcoral", NSVG_RGB(240, 128, 128) }, { "lightcyan", NSVG_RGB(224, 255, 255) }, { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) }, { "lightgray", NSVG_RGB(211, 211, 211) }, { "lightgreen", NSVG_RGB(144, 238, 144) }, { "lightgrey", NSVG_RGB(211, 211, 211) }, { "lightpink", NSVG_RGB(255, 182, 193) }, { "lightsalmon", NSVG_RGB(255, 160, 122) }, { "lightseagreen", NSVG_RGB( 32, 178, 170) }, { "lightskyblue", NSVG_RGB(135, 206, 250) }, { "lightslategray", NSVG_RGB(119, 136, 153) }, { "lightslategrey", NSVG_RGB(119, 136, 153) }, { "lightsteelblue", NSVG_RGB(176, 196, 222) }, { "lightyellow", NSVG_RGB(255, 255, 224) }, { "lime", NSVG_RGB( 0, 255, 0) }, { "limegreen", NSVG_RGB( 50, 205, 50) }, { "linen", NSVG_RGB(250, 240, 230) }, { "maroon", NSVG_RGB(128, 0, 0) }, { "mediumaquamarine", NSVG_RGB(102, 205, 170) }, { "mediumblue", NSVG_RGB( 0, 0, 205) }, { "mediumorchid", NSVG_RGB(186, 85, 211) }, { "mediumpurple", NSVG_RGB(147, 112, 219) }, { "mediumseagreen", NSVG_RGB( 60, 179, 113) }, { "mediumslateblue", NSVG_RGB(123, 104, 238) }, { "mediumspringgreen", NSVG_RGB( 0, 250, 154) }, { "mediumturquoise", NSVG_RGB( 72, 209, 204) }, { "mediumvioletred", NSVG_RGB(199, 21, 133) }, { "midnightblue", NSVG_RGB( 25, 25, 112) }, { "mintcream", NSVG_RGB(245, 255, 250) }, { "mistyrose", NSVG_RGB(255, 228, 225) }, { "moccasin", NSVG_RGB(255, 228, 181) }, { "navajowhite", NSVG_RGB(255, 222, 173) }, { "navy", NSVG_RGB( 0, 0, 128) }, { "oldlace", NSVG_RGB(253, 245, 230) }, { "olive", NSVG_RGB(128, 128, 0) }, { "olivedrab", NSVG_RGB(107, 142, 35) }, { "orange", NSVG_RGB(255, 165, 0) }, { "orangered", NSVG_RGB(255, 69, 0) }, { "orchid", NSVG_RGB(218, 112, 214) }, { "palegoldenrod", NSVG_RGB(238, 232, 170) }, { "palegreen", NSVG_RGB(152, 251, 152) }, { "paleturquoise", NSVG_RGB(175, 238, 238) }, { "palevioletred", NSVG_RGB(219, 112, 147) }, { "papayawhip", NSVG_RGB(255, 239, 213) }, { "peachpuff", NSVG_RGB(255, 218, 185) }, { "peru", NSVG_RGB(205, 133, 63) }, { "pink", NSVG_RGB(255, 192, 203) }, { "plum", NSVG_RGB(221, 160, 221) }, { "powderblue", NSVG_RGB(176, 224, 230) }, { "purple", NSVG_RGB(128, 0, 128) }, { "rosybrown", NSVG_RGB(188, 143, 143) }, { "royalblue", NSVG_RGB( 65, 105, 225) }, { "saddlebrown", NSVG_RGB(139, 69, 19) }, { "salmon", NSVG_RGB(250, 128, 114) }, { "sandybrown", NSVG_RGB(244, 164, 96) }, { "seagreen", NSVG_RGB( 46, 139, 87) }, { "seashell", NSVG_RGB(255, 245, 238) }, { "sienna", NSVG_RGB(160, 82, 45) }, { "silver", NSVG_RGB(192, 192, 192) }, { "skyblue", NSVG_RGB(135, 206, 235) }, { "slateblue", NSVG_RGB(106, 90, 205) }, { "slategray", NSVG_RGB(112, 128, 144) }, { "slategrey", NSVG_RGB(112, 128, 144) }, { "snow", NSVG_RGB(255, 250, 250) }, { "springgreen", NSVG_RGB( 0, 255, 127) }, { "steelblue", NSVG_RGB( 70, 130, 180) }, { "tan", NSVG_RGB(210, 180, 140) }, { "teal", NSVG_RGB( 0, 128, 128) }, { "thistle", NSVG_RGB(216, 191, 216) }, { "tomato", NSVG_RGB(255, 99, 71) }, { "turquoise", NSVG_RGB( 64, 224, 208) }, { "violet", NSVG_RGB(238, 130, 238) }, { "wheat", NSVG_RGB(245, 222, 179) }, { "whitesmoke", NSVG_RGB(245, 245, 245) }, { "yellowgreen", NSVG_RGB(154, 205, 50) }, #endif }; static unsigned int nsvg__parseColorName(const char* str) { int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor); for (i = 0; i < ncolors; i++) { if (strcmp(nsvg__colors[i].name, str) == 0) { return nsvg__colors[i].color; } } return NSVG_RGB(128, 128, 128); } static unsigned int nsvg__parseColor(const char* str) { size_t len = 0; while(*str == ' ') ++str; len = strlen(str); if (len >= 1 && *str == '#') return nsvg__parseColorHex(str); else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(') return nsvg__parseColorRGB(str); return nsvg__parseColorName(str); } static float nsvg__parseOpacity(const char* str) { float val = nsvg__atof(str); if (val < 0.0f) val = 0.0f; if (val > 1.0f) val = 1.0f; return val; } static float nsvg__parseMiterLimit(const char* str) { float val = nsvg__atof(str); if (val < 0.0f) val = 0.0f; return val; } static int nsvg__parseUnits(const char* units) { if (units[0] == 'p' && units[1] == 'x') return NSVG_UNITS_PX; else if (units[0] == 'p' && units[1] == 't') return NSVG_UNITS_PT; else if (units[0] == 'p' && units[1] == 'c') return NSVG_UNITS_PC; else if (units[0] == 'm' && units[1] == 'm') return NSVG_UNITS_MM; else if (units[0] == 'c' && units[1] == 'm') return NSVG_UNITS_CM; else if (units[0] == 'i' && units[1] == 'n') return NSVG_UNITS_IN; else if (units[0] == '%') return NSVG_UNITS_PERCENT; else if (units[0] == 'e' && units[1] == 'm') return NSVG_UNITS_EM; else if (units[0] == 'e' && units[1] == 'x') return NSVG_UNITS_EX; return NSVG_UNITS_USER; } static int nsvg__isCoordinate(const char* s) { // optional sign if (*s == '-' || *s == '+') s++; // must have at least one digit, or start by a dot return (nsvg__isdigit(*s) || *s == '.'); } static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str) { NSVGcoordinate coord = {0, NSVG_UNITS_USER}; char buf[64]; coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64)); coord.value = nsvg__atof(buf); return coord; } static NSVGcoordinate nsvg__coord(float v, int units) { NSVGcoordinate coord = {v, units}; return coord; } static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length) { NSVGcoordinate coord = nsvg__parseCoordinateRaw(str); return nsvg__convertToPixels(p, coord, orig, length); } static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na) { const char* end; const char* ptr; char it[64]; *na = 0; ptr = str; while (*ptr && *ptr != '(') ++ptr; if (*ptr == 0) return 1; end = ptr; while (*end && *end != ')') ++end; if (*end == 0) return 1; while (ptr < end) { if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) { if (*na >= maxNa) return 0; ptr = nsvg__parseNumber(ptr, it, 64); args[(*na)++] = (float)nsvg__atof(it); } else { ++ptr; } } return (int)(end - str); } static int nsvg__parseMatrix(float* xform, const char* str) { float t[6]; int na = 0; int len = nsvg__parseTransformArgs(str, t, 6, &na); if (na != 6) return len; memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseTranslate(float* xform, const char* str) { float args[2]; float t[6]; int na = 0; int len = nsvg__parseTransformArgs(str, args, 2, &na); if (na == 1) args[1] = 0.0; nsvg__xformSetTranslation(t, args[0], args[1]); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseScale(float* xform, const char* str) { float args[2]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 2, &na); if (na == 1) args[1] = args[0]; nsvg__xformSetScale(t, args[0], args[1]); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseSkewX(float* xform, const char* str) { float args[1]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 1, &na); nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseSkewY(float* xform, const char* str) { float args[1]; int na = 0; float t[6]; int len = nsvg__parseTransformArgs(str, args, 1, &na); nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI); memcpy(xform, t, sizeof(float)*6); return len; } static int nsvg__parseRotate(float* xform, const char* str) { float args[3]; int na = 0; float m[6]; float t[6]; int len = nsvg__parseTransformArgs(str, args, 3, &na); if (na == 1) args[1] = args[2] = 0.0f; nsvg__xformIdentity(m); if (na > 1) { nsvg__xformSetTranslation(t, -args[1], -args[2]); nsvg__xformMultiply(m, t); } nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI); nsvg__xformMultiply(m, t); if (na > 1) { nsvg__xformSetTranslation(t, args[1], args[2]); nsvg__xformMultiply(m, t); } memcpy(xform, m, sizeof(float)*6); return len; } static void nsvg__parseTransform(float* xform, const char* str) { float t[6]; int len; nsvg__xformIdentity(xform); while (*str) { if (strncmp(str, "matrix", 6) == 0) len = nsvg__parseMatrix(t, str); else if (strncmp(str, "translate", 9) == 0) len = nsvg__parseTranslate(t, str); else if (strncmp(str, "scale", 5) == 0) len = nsvg__parseScale(t, str); else if (strncmp(str, "rotate", 6) == 0) len = nsvg__parseRotate(t, str); else if (strncmp(str, "skewX", 5) == 0) len = nsvg__parseSkewX(t, str); else if (strncmp(str, "skewY", 5) == 0) len = nsvg__parseSkewY(t, str); else{ ++str; continue; } if (len != 0) { str += len; } else { ++str; continue; } nsvg__xformPremultiply(xform, t); } } static void nsvg__parseUrl(char* id, const char* str) { int i = 0; str += 4; // "url("; if (*str == '#') str++; while (i < 63 && *str != ')') { id[i] = *str++; i++; } id[i] = '\0'; } static char nsvg__parseLineCap(const char* str) { if (strcmp(str, "butt") == 0) return NSVG_CAP_BUTT; else if (strcmp(str, "round") == 0) return NSVG_CAP_ROUND; else if (strcmp(str, "square") == 0) return NSVG_CAP_SQUARE; // TODO: handle inherit. return NSVG_CAP_BUTT; } static char nsvg__parseLineJoin(const char* str) { if (strcmp(str, "miter") == 0) return NSVG_JOIN_MITER; else if (strcmp(str, "round") == 0) return NSVG_JOIN_ROUND; else if (strcmp(str, "bevel") == 0) return NSVG_JOIN_BEVEL; // TODO: handle inherit. return NSVG_JOIN_MITER; } static char nsvg__parseFillRule(const char* str) { if (strcmp(str, "nonzero") == 0) return NSVG_FILLRULE_NONZERO; else if (strcmp(str, "evenodd") == 0) return NSVG_FILLRULE_EVENODD; // TODO: handle inherit. return NSVG_FILLRULE_NONZERO; } static const char* nsvg__getNextDashItem(const char* s, char* it) { int n = 0; it[0] = '\0'; // Skip white spaces and commas while (*s && (nsvg__isspace(*s) || *s == ',')) s++; // Advance until whitespace, comma or end. while (*s && (!nsvg__isspace(*s) && *s != ',')) { if (n < 63) it[n++] = *s; s++; } it[n++] = '\0'; return s; } static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray) { char item[64]; int count = 0, i; float sum = 0.0f; // Handle "none" if (str[0] == 'n') return 0; // Parse dashes while (*str) { str = nsvg__getNextDashItem(str, item); if (!*item) break; if (count < NSVG_MAX_DASHES) strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p))); } for (i = 0; i < count; i++) sum += strokeDashArray[i]; if (sum <= 1e-6f) count = 0; return count; } static void nsvg__parseStyle(NSVGparser* p, const char* str); static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value) { float xform[6]; NSVGattrib* attr = nsvg__getAttr(p); if (!attr) return 0; if (strcmp(name, "style") == 0) { nsvg__parseStyle(p, value); } else if (strcmp(name, "display") == 0) { if (strcmp(value, "none") == 0) attr->visible = 0; // Don't reset ->visible on display:inline, one display:none hides the whole subtree } else if (strcmp(name, "fill") == 0) { if (strcmp(value, "none") == 0) { attr->hasFill = 0; } else if (strncmp(value, "url(", 4) == 0) { attr->hasFill = 2; nsvg__parseUrl(attr->fillGradient, value); } else { attr->hasFill = 1; attr->fillColor = nsvg__parseColor(value); } } else if (strcmp(name, "opacity") == 0) { attr->opacity = nsvg__parseOpacity(value); } else if (strcmp(name, "fill-opacity") == 0) { attr->fillOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "stroke") == 0) { if (strcmp(value, "none") == 0) { attr->hasStroke = 0; } else if (strncmp(value, "url(", 4) == 0) { attr->hasStroke = 2; nsvg__parseUrl(attr->strokeGradient, value); } else { attr->hasStroke = 1; attr->strokeColor = nsvg__parseColor(value); } } else if (strcmp(name, "stroke-width") == 0) { attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "stroke-dasharray") == 0) { attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray); } else if (strcmp(name, "stroke-dashoffset") == 0) { attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "stroke-opacity") == 0) { attr->strokeOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "stroke-linecap") == 0) { attr->strokeLineCap = nsvg__parseLineCap(value); } else if (strcmp(name, "stroke-linejoin") == 0) { attr->strokeLineJoin = nsvg__parseLineJoin(value); } else if (strcmp(name, "stroke-miterlimit") == 0) { attr->miterLimit = nsvg__parseMiterLimit(value); } else if (strcmp(name, "fill-rule") == 0) { attr->fillRule = nsvg__parseFillRule(value); } else if (strcmp(name, "font-size") == 0) { attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); } else if (strcmp(name, "transform") == 0) { nsvg__parseTransform(xform, value); nsvg__xformPremultiply(attr->xform, xform); } else if (strcmp(name, "stop-color") == 0) { attr->stopColor = nsvg__parseColor(value); } else if (strcmp(name, "stop-opacity") == 0) { attr->stopOpacity = nsvg__parseOpacity(value); } else if (strcmp(name, "offset") == 0) { attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f); } else if (strcmp(name, "id") == 0) { strncpy(attr->id, value, 63); attr->id[63] = '\0'; } else { return 0; } return 1; } static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end) { const char* str; const char* val; char name[512]; char value[512]; int n; str = start; while (str < end && *str != ':') ++str; val = str; // Right Trim while (str > start && (*str == ':' || nsvg__isspace(*str))) --str; ++str; n = (int)(str - start); if (n > 511) n = 511; if (n) memcpy(name, start, n); name[n] = 0; while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val; n = (int)(end - val); if (n > 511) n = 511; if (n) memcpy(value, val, n); value[n] = 0; return nsvg__parseAttr(p, name, value); } static void nsvg__parseStyle(NSVGparser* p, const char* str) { const char* start; const char* end; while (*str) { // Left Trim while(*str && nsvg__isspace(*str)) ++str; start = str; while(*str && *str != ';') ++str; end = str; // Right Trim while (end > start && (*end == ';' || nsvg__isspace(*end))) --end; ++end; nsvg__parseNameValue(p, start, end); if (*str) ++str; } } static void nsvg__parseAttribs(NSVGparser* p, const char** attr) { int i; for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "style") == 0) nsvg__parseStyle(p, attr[i + 1]); else nsvg__parseAttr(p, attr[i], attr[i + 1]); } } static int nsvg__getArgsPerElement(char cmd) { switch (cmd) { case 'v': case 'V': case 'h': case 'H': return 1; case 'm': case 'M': case 'l': case 'L': case 't': case 'T': return 2; case 'q': case 'Q': case 's': case 'S': return 4; case 'c': case 'C': return 6; case 'a': case 'A': return 7; case 'z': case 'Z': return 0; } return -1; } static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) { *cpx += args[0]; *cpy += args[1]; } else { *cpx = args[0]; *cpy = args[1]; } nsvg__moveTo(p, *cpx, *cpy); } static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) { *cpx += args[0]; *cpy += args[1]; } else { *cpx = args[0]; *cpy = args[1]; } nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) *cpx += args[0]; else *cpx = args[0]; nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { if (rel) *cpy += args[0]; else *cpy = args[0]; nsvg__lineTo(p, *cpx, *cpy); } static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x2, y2, cx1, cy1, cx2, cy2; if (rel) { cx1 = *cpx + args[0]; cy1 = *cpy + args[1]; cx2 = *cpx + args[2]; cy2 = *cpy + args[3]; x2 = *cpx + args[4]; y2 = *cpy + args[5]; } else { cx1 = args[0]; cy1 = args[1]; cx2 = args[2]; cy2 = args[3]; x2 = args[4]; y2 = args[5]; } nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx2; *cpy2 = cy2; *cpx = x2; *cpy = y2; } static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { cx2 = *cpx + args[0]; cy2 = *cpy + args[1]; x2 = *cpx + args[2]; y2 = *cpy + args[3]; } else { cx2 = args[0]; cy2 = args[1]; x2 = args[2]; y2 = args[3]; } cx1 = 2*x1 - *cpx2; cy1 = 2*y1 - *cpy2; nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx2; *cpy2 = cy2; *cpx = x2; *cpy = y2; } static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx, cy; float cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { cx = *cpx + args[0]; cy = *cpy + args[1]; x2 = *cpx + args[2]; y2 = *cpy + args[3]; } else { cx = args[0]; cy = args[1]; x2 = args[2]; y2 = args[3]; } // Convert to cubic bezier cx1 = x1 + 2.0f/3.0f*(cx - x1); cy1 = y1 + 2.0f/3.0f*(cy - y1); cx2 = x2 + 2.0f/3.0f*(cx - x2); cy2 = y2 + 2.0f/3.0f*(cy - y2); nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx; *cpy2 = cy; *cpx = x2; *cpy = y2; } static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy, float* cpx2, float* cpy2, float* args, int rel) { float x1, y1, x2, y2, cx, cy; float cx1, cy1, cx2, cy2; x1 = *cpx; y1 = *cpy; if (rel) { x2 = *cpx + args[0]; y2 = *cpy + args[1]; } else { x2 = args[0]; y2 = args[1]; } cx = 2*x1 - *cpx2; cy = 2*y1 - *cpy2; // Convert to cubix bezier cx1 = x1 + 2.0f/3.0f*(cx - x1); cy1 = y1 + 2.0f/3.0f*(cy - y1); cx2 = x2 + 2.0f/3.0f*(cx - x2); cy2 = y2 + 2.0f/3.0f*(cy - y2); nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); *cpx2 = cx; *cpy2 = cy; *cpx = x2; *cpy = y2; } static float nsvg__sqr(float x) { return x*x; } static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); } static float nsvg__vecrat(float ux, float uy, float vx, float vy) { return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy)); } static float nsvg__vecang(float ux, float uy, float vx, float vy) { float r = nsvg__vecrat(ux,uy, vx,vy); if (r < -1.0f) r = -1.0f; if (r > 1.0f) r = 1.0f; return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r); } static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) { // Ported from canvg (https://code.google.com/p/canvg/) float rx, ry, rotx; float x1, y1, x2, y2, cx, cy, dx, dy, d; float x1p, y1p, cxp, cyp, s, sa, sb; float ux, uy, vx, vy, a1, da; float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6]; float sinrx, cosrx; int fa, fs; int i, ndivs; float hda, kappa; rx = fabsf(args[0]); // y radius ry = fabsf(args[1]); // x radius rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction x1 = *cpx; // start point y1 = *cpy; if (rel) { // end point x2 = *cpx + args[5]; y2 = *cpy + args[6]; } else { x2 = args[5]; y2 = args[6]; } dx = x1 - x2; dy = y1 - y2; d = sqrtf(dx*dx + dy*dy); if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { // The arc degenerates to a line nsvg__lineTo(p, x2, y2); *cpx = x2; *cpy = y2; return; } sinrx = sinf(rotx); cosrx = cosf(rotx); // Convert to center point parameterization. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // 1) Compute x1', y1' x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f; y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f; d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry); if (d > 1) { d = sqrtf(d); rx *= d; ry *= d; } // 2) Compute cx', cy' s = 0.0f; sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p); sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p); if (sa < 0.0f) sa = 0.0f; if (sb > 0.0f) s = sqrtf(sa / sb); if (fa == fs) s = -s; cxp = s * rx * y1p / ry; cyp = s * -ry * x1p / rx; // 3) Compute cx,cy from cx',cy' cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp; cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp; // 4) Calculate theta1, and delta theta. ux = (x1p - cxp) / rx; uy = (y1p - cyp) / ry; vx = (-x1p - cxp) / rx; vy = (-y1p - cyp) / ry; a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle da = nsvg__vecang(ux,uy, vx,vy); // Delta angle // if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; // if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; if (fs == 0 && da > 0) da -= 2 * NSVG_PI; else if (fs == 1 && da < 0) da += 2 * NSVG_PI; // Approximate the arc using cubic spline segments. t[0] = cosrx; t[1] = sinrx; t[2] = -sinrx; t[3] = cosrx; t[4] = cx; t[5] = cy; // Split arc into max 90 degree segments. // The loop assumes an iteration per end point (including start and end), this +1. ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f); hda = (da / (float)ndivs) / 2.0f; // Fix for ticket #179: division by 0: avoid cotangens around 0 (infinite) if ((hda < 1e-3f) && (hda > -1e-3f)) hda *= 0.5f; else hda = (1.0f - cosf(hda)) / sinf(hda); kappa = fabsf(4.0f / 3.0f * hda); if (da < 0.0f) kappa = -kappa; for (i = 0; i <= ndivs; i++) { a = a1 + da * ((float)i/(float)ndivs); dx = cosf(a); dy = sinf(a); nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent if (i > 0) nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y); px = x; py = y; ptanx = tanx; ptany = tany; } *cpx = x2; *cpy = y2; } static void nsvg__parsePath(NSVGparser* p, const char** attr) { const char* s = NULL; char cmd = '\0'; float args[10]; int nargs; int rargs = 0; char initPoint; float cpx, cpy, cpx2, cpy2; const char* tmp[4]; char closedFlag; int i; char item[64]; for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "d") == 0) { s = attr[i + 1]; } else { tmp[0] = attr[i]; tmp[1] = attr[i + 1]; tmp[2] = 0; tmp[3] = 0; nsvg__parseAttribs(p, tmp); } } if (s) { nsvg__resetPath(p); cpx = 0; cpy = 0; cpx2 = 0; cpy2 = 0; initPoint = 0; closedFlag = 0; nargs = 0; while (*s) { s = nsvg__getNextPathItem(s, item); if (!*item) break; if (cmd != '\0' && nsvg__isCoordinate(item)) { if (nargs < 10) args[nargs++] = (float)nsvg__atof(item); if (nargs >= rargs) { switch (cmd) { case 'm': case 'M': nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0); // Moveto can be followed by multiple coordinate pairs, // which should be treated as linetos. cmd = (cmd == 'm') ? 'l' : 'L'; rargs = nsvg__getArgsPerElement(cmd); cpx2 = cpx; cpy2 = cpy; initPoint = 1; break; case 'l': case 'L': nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'H': case 'h': nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'V': case 'v': nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; case 'C': case 'c': nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0); break; case 'S': case 's': nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0); break; case 'Q': case 'q': nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0); break; case 'T': case 't': nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0); break; case 'A': case 'a': nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0); cpx2 = cpx; cpy2 = cpy; break; default: if (nargs >= 2) { cpx = args[nargs-2]; cpy = args[nargs-1]; cpx2 = cpx; cpy2 = cpy; } break; } nargs = 0; } } else { cmd = item[0]; if (cmd == 'M' || cmd == 'm') { // Commit path. if (p->npts > 0) nsvg__addPath(p, closedFlag); // Start new subpath. nsvg__resetPath(p); closedFlag = 0; nargs = 0; } else if (initPoint == 0) { // Do not allow other commands until initial point has been set (moveTo called once). cmd = '\0'; } if (cmd == 'Z' || cmd == 'z') { closedFlag = 1; // Commit path. if (p->npts > 0) { // Move current point to first point cpx = p->pts[0]; cpy = p->pts[1]; cpx2 = cpx; cpy2 = cpy; nsvg__addPath(p, closedFlag); } // Start new subpath. nsvg__resetPath(p); nsvg__moveTo(p, cpx, cpy); closedFlag = 0; nargs = 0; } rargs = nsvg__getArgsPerElement(cmd); if (rargs == -1) { // Command not recognized cmd = '\0'; rargs = 0; } } } // Commit path. if (p->npts) nsvg__addPath(p, closedFlag); } nsvg__addShape(p); } static void nsvg__parseRect(NSVGparser* p, const char** attr) { float x = 0.0f; float y = 0.0f; float w = 0.0f; float h = 0.0f; float rx = -1.0f; // marks not set float ry = -1.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)); if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)); if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); } } if (rx < 0.0f && ry > 0.0f) rx = ry; if (ry < 0.0f && rx > 0.0f) ry = rx; if (rx < 0.0f) rx = 0.0f; if (ry < 0.0f) ry = 0.0f; if (rx > w/2.0f) rx = w/2.0f; if (ry > h/2.0f) ry = h/2.0f; if (w != 0.0f && h != 0.0f) { nsvg__resetPath(p); if (rx < 0.00001f || ry < 0.0001f) { nsvg__moveTo(p, x, y); nsvg__lineTo(p, x+w, y); nsvg__lineTo(p, x+w, y+h); nsvg__lineTo(p, x, y+h); } else { // Rounded rectangle nsvg__moveTo(p, x+rx, y); nsvg__lineTo(p, x+w-rx, y); nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry); nsvg__lineTo(p, x+w, y+h-ry); nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h); nsvg__lineTo(p, x+rx, y+h); nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry); nsvg__lineTo(p, x, y+ry); nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y); } nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseCircle(NSVGparser* p, const char** attr) { float cx = 0.0f; float cy = 0.0f; float r = 0.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p))); } } if (r > 0.0f) { nsvg__resetPath(p); nsvg__moveTo(p, cx+r, cy); nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r); nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy); nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r); nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy); nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseEllipse(NSVGparser* p, const char** attr) { float cx = 0.0f; float cy = 0.0f; float rx = 0.0f; float ry = 0.0f; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); } } if (rx > 0.0f && ry > 0.0f) { nsvg__resetPath(p); nsvg__moveTo(p, cx+rx, cy); nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry); nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy); nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry); nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy); nsvg__addPath(p, 1); nsvg__addShape(p); } } static void nsvg__parseLine(NSVGparser* p, const char** attr) { float x1 = 0.0; float y1 = 0.0; float x2 = 0.0; float y2 = 0.0; int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); } } nsvg__resetPath(p); nsvg__moveTo(p, x1, y1); nsvg__lineTo(p, x2, y2); nsvg__addPath(p, 0); nsvg__addShape(p); } static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag) { int i; const char* s; float args[2]; int nargs, npts = 0; char item[64]; nsvg__resetPath(p); for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "points") == 0) { s = attr[i + 1]; nargs = 0; while (*s) { s = nsvg__getNextPathItem(s, item); args[nargs++] = (float)nsvg__atof(item); if (nargs >= 2) { if (npts == 0) nsvg__moveTo(p, args[0], args[1]); else nsvg__lineTo(p, args[0], args[1]); nargs = 0; npts++; } } } } } nsvg__addPath(p, (char)closeFlag); nsvg__addShape(p); } static void nsvg__parseSVG(NSVGparser* p, const char** attr) { int i; for (i = 0; attr[i]; i += 2) { if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "width") == 0) { p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); } else if (strcmp(attr[i], "height") == 0) { p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); } else if (strcmp(attr[i], "viewBox") == 0) { const char *s = attr[i + 1]; char buf[64]; s = nsvg__parseNumber(s, buf, 64); p->viewMinx = nsvg__atof(buf); while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; if (!*s) return; s = nsvg__parseNumber(s, buf, 64); p->viewMiny = nsvg__atof(buf); while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; if (!*s) return; s = nsvg__parseNumber(s, buf, 64); p->viewWidth = nsvg__atof(buf); while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; if (!*s) return; s = nsvg__parseNumber(s, buf, 64); p->viewHeight = nsvg__atof(buf); } else if (strcmp(attr[i], "preserveAspectRatio") == 0) { if (strstr(attr[i + 1], "none") != 0) { // No uniform scaling p->alignType = NSVG_ALIGN_NONE; } else { // Parse X align if (strstr(attr[i + 1], "xMin") != 0) p->alignX = NSVG_ALIGN_MIN; else if (strstr(attr[i + 1], "xMid") != 0) p->alignX = NSVG_ALIGN_MID; else if (strstr(attr[i + 1], "xMax") != 0) p->alignX = NSVG_ALIGN_MAX; // Parse X align if (strstr(attr[i + 1], "yMin") != 0) p->alignY = NSVG_ALIGN_MIN; else if (strstr(attr[i + 1], "yMid") != 0) p->alignY = NSVG_ALIGN_MID; else if (strstr(attr[i + 1], "yMax") != 0) p->alignY = NSVG_ALIGN_MAX; // Parse meet/slice p->alignType = NSVG_ALIGN_MEET; if (strstr(attr[i + 1], "slice") != 0) p->alignType = NSVG_ALIGN_SLICE; } } } } } static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type) { int i; NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData)); if (grad == NULL) return; memset(grad, 0, sizeof(NSVGgradientData)); grad->units = NSVG_OBJECT_SPACE; grad->type = type; if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) { grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT); grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) { grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); } nsvg__xformIdentity(grad->xform); for (i = 0; attr[i]; i += 2) { if (strcmp(attr[i], "id") == 0) { strncpy(grad->id, attr[i+1], 63); grad->id[63] = '\0'; } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { if (strcmp(attr[i], "gradientUnits") == 0) { if (strcmp(attr[i+1], "objectBoundingBox") == 0) grad->units = NSVG_OBJECT_SPACE; else grad->units = NSVG_USER_SPACE; } else if (strcmp(attr[i], "gradientTransform") == 0) { nsvg__parseTransform(grad->xform, attr[i + 1]); } else if (strcmp(attr[i], "cx") == 0) { grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "cy") == 0) { grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "r") == 0) { grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "fx") == 0) { grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "fy") == 0) { grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "x1") == 0) { grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "y1") == 0) { grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "x2") == 0) { grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "y2") == 0) { grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]); } else if (strcmp(attr[i], "spreadMethod") == 0) { if (strcmp(attr[i+1], "pad") == 0) grad->spread = NSVG_SPREAD_PAD; else if (strcmp(attr[i+1], "reflect") == 0) grad->spread = NSVG_SPREAD_REFLECT; else if (strcmp(attr[i+1], "repeat") == 0) grad->spread = NSVG_SPREAD_REPEAT; } else if (strcmp(attr[i], "xlink:href") == 0) { const char *href = attr[i+1]; strncpy(grad->ref, href+1, 62); grad->ref[62] = '\0'; } } } grad->next = p->gradients; p->gradients = grad; } static void nsvg__parseGradientStop(NSVGparser* p, const char** attr) { NSVGattrib* curAttr = nsvg__getAttr(p); NSVGgradientData* grad; NSVGgradientStop* stop; int i, idx; curAttr->stopOffset = 0; curAttr->stopColor = 0; curAttr->stopOpacity = 1.0f; for (i = 0; attr[i]; i += 2) { nsvg__parseAttr(p, attr[i], attr[i + 1]); } // Add stop to the last gradient. grad = p->gradients; if (grad == NULL) return; grad->nstops++; grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops); if (grad->stops == NULL) return; // Insert idx = grad->nstops-1; for (i = 0; i < grad->nstops-1; i++) { if (curAttr->stopOffset < grad->stops[i].offset) { idx = i; break; } } if (idx != grad->nstops-1) { for (i = grad->nstops-1; i > idx; i--) grad->stops[i] = grad->stops[i-1]; } stop = &grad->stops[idx]; stop->color = curAttr->stopColor; stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24; stop->offset = curAttr->stopOffset; } static void nsvg__startElement(void* ud, const char* el, const char** attr) { NSVGparser* p = (NSVGparser*)ud; if (p->defsFlag) { // Skip everything but gradients in defs if (strcmp(el, "linearGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); } else if (strcmp(el, "radialGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); } else if (strcmp(el, "stop") == 0) { nsvg__parseGradientStop(p, attr); } return; } if (strcmp(el, "g") == 0) { nsvg__pushAttr(p); nsvg__parseAttribs(p, attr); } else if (strcmp(el, "path") == 0) { if (p->pathFlag) // Do not allow nested paths. return; nsvg__pushAttr(p); nsvg__parsePath(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "rect") == 0) { nsvg__pushAttr(p); nsvg__parseRect(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "circle") == 0) { nsvg__pushAttr(p); nsvg__parseCircle(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "ellipse") == 0) { nsvg__pushAttr(p); nsvg__parseEllipse(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "line") == 0) { nsvg__pushAttr(p); nsvg__parseLine(p, attr); nsvg__popAttr(p); } else if (strcmp(el, "polyline") == 0) { nsvg__pushAttr(p); nsvg__parsePoly(p, attr, 0); nsvg__popAttr(p); } else if (strcmp(el, "polygon") == 0) { nsvg__pushAttr(p); nsvg__parsePoly(p, attr, 1); nsvg__popAttr(p); } else if (strcmp(el, "linearGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); } else if (strcmp(el, "radialGradient") == 0) { nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); } else if (strcmp(el, "stop") == 0) { nsvg__parseGradientStop(p, attr); } else if (strcmp(el, "defs") == 0) { p->defsFlag = 1; } else if (strcmp(el, "svg") == 0) { nsvg__parseSVG(p, attr); } } static void nsvg__endElement(void* ud, const char* el) { NSVGparser* p = (NSVGparser*)ud; if (strcmp(el, "g") == 0) { nsvg__popAttr(p); } else if (strcmp(el, "path") == 0) { p->pathFlag = 0; } else if (strcmp(el, "defs") == 0) { p->defsFlag = 0; } } static void nsvg__content(void* ud, const char* s) { NSVG_NOTUSED(ud); NSVG_NOTUSED(s); // empty } static void nsvg__imageBounds(NSVGparser* p, float* bounds) { NSVGshape* shape; shape = p->image->shapes; if (shape == NULL) { bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0; return; } bounds[0] = shape->bounds[0]; bounds[1] = shape->bounds[1]; bounds[2] = shape->bounds[2]; bounds[3] = shape->bounds[3]; for (shape = shape->next; shape != NULL; shape = shape->next) { bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]); bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]); bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]); bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]); } } static float nsvg__viewAlign(float content, float container, int type) { if (type == NSVG_ALIGN_MIN) return 0; else if (type == NSVG_ALIGN_MAX) return container - content; // mid return (container - content) * 0.5f; } static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy) { float t[6]; nsvg__xformSetTranslation(t, tx, ty); nsvg__xformMultiply (grad->xform, t); nsvg__xformSetScale(t, sx, sy); nsvg__xformMultiply (grad->xform, t); } static void nsvg__scaleToViewbox(NSVGparser* p, const char* units) { NSVGshape* shape; NSVGpath* path; float tx, ty, sx, sy, us, bounds[4], t[6], avgs; int i; float* pt; // Guess image size if not set completely. nsvg__imageBounds(p, bounds); if (p->viewWidth == 0) { if (p->image->width > 0) { p->viewWidth = p->image->width; } else { p->viewMinx = bounds[0]; p->viewWidth = bounds[2] - bounds[0]; } } if (p->viewHeight == 0) { if (p->image->height > 0) { p->viewHeight = p->image->height; } else { p->viewMiny = bounds[1]; p->viewHeight = bounds[3] - bounds[1]; } } if (p->image->width == 0) p->image->width = p->viewWidth; if (p->image->height == 0) p->image->height = p->viewHeight; tx = -p->viewMinx; ty = -p->viewMiny; sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0; sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0; // Unit scaling us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f); // Fix aspect ratio if (p->alignType == NSVG_ALIGN_MEET) { // fit whole image into viewbox sx = sy = nsvg__minf(sx, sy); tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; } else if (p->alignType == NSVG_ALIGN_SLICE) { // fill whole viewbox with image sx = sy = nsvg__maxf(sx, sy); tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; } // Transform sx *= us; sy *= us; avgs = (sx+sy) / 2.0f; for (shape = p->image->shapes; shape != NULL; shape = shape->next) { shape->bounds[0] = (shape->bounds[0] + tx) * sx; shape->bounds[1] = (shape->bounds[1] + ty) * sy; shape->bounds[2] = (shape->bounds[2] + tx) * sx; shape->bounds[3] = (shape->bounds[3] + ty) * sy; for (path = shape->paths; path != NULL; path = path->next) { path->bounds[0] = (path->bounds[0] + tx) * sx; path->bounds[1] = (path->bounds[1] + ty) * sy; path->bounds[2] = (path->bounds[2] + tx) * sx; path->bounds[3] = (path->bounds[3] + ty) * sy; for (i =0; i < path->npts; i++) { pt = &path->pts[i*2]; pt[0] = (pt[0] + tx) * sx; pt[1] = (pt[1] + ty) * sy; } } if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) { nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy); memcpy(t, shape->fill.gradient->xform, sizeof(float)*6); nsvg__xformInverse(shape->fill.gradient->xform, t); } if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) { nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy); memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6); nsvg__xformInverse(shape->stroke.gradient->xform, t); } shape->strokeWidth *= avgs; shape->strokeDashOffset *= avgs; for (i = 0; i < shape->strokeDashCount; i++) shape->strokeDashArray[i] *= avgs; } } NSVGimage* nsvgParse(char* input, const char* units, float dpi) { NSVGparser* p; NSVGimage* ret = 0; p = nsvg__createParser(); if (p == NULL) { return NULL; } p->dpi = dpi; nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); // Scale to viewBox nsvg__scaleToViewbox(p, units); ret = p->image; p->image = NULL; nsvg__deleteParser(p); return ret; } NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi) { FILE* fp = NULL; size_t size; char* data = NULL; NSVGimage* image = NULL; fp = fopen(filename, "rb"); if (!fp) goto error; fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); data = (char*)malloc(size+1); if (data == NULL) goto error; if (fread(data, 1, size, fp) != size) goto error; data[size] = '\0'; // Must be null terminated. fclose(fp); image = nsvgParse(data, units, dpi); free(data); return image; error: if (fp) fclose(fp); if (data) free(data); if (image) nsvgDelete(image); return NULL; } NSVGpath* nsvgDuplicatePath(NSVGpath* p) { NSVGpath* res = NULL; if (p == NULL) return NULL; res = (NSVGpath*)malloc(sizeof(NSVGpath)); if (res == NULL) goto error; memset(res, 0, sizeof(NSVGpath)); res->pts = (float*)malloc(p->npts*2*sizeof(float)); if (res->pts == NULL) goto error; memcpy(res->pts, p->pts, p->npts * sizeof(float) * 2); res->npts = p->npts; memcpy(res->bounds, p->bounds, sizeof(p->bounds)); res->closed = p->closed; return res; error: if (res != NULL) { free(res->pts); free(res); } return NULL; } void nsvgDelete(NSVGimage* image) { NSVGshape *snext, *shape; if (image == NULL) return; shape = image->shapes; while (shape != NULL) { snext = shape->next; nsvg__deletePaths(shape->paths); nsvg__deletePaint(&shape->fill); nsvg__deletePaint(&shape->stroke); free(shape); shape = snext; } free(image); }
26.344669
123
0.605115
CodeFinder2