blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
8927b414fd8eb8ae86bf7006631985679095a7be
d2b2f59e3ff929bc3c12fa9f32bac90ad5882958
/code/VirtualGrasp/GraphicsLibrary/Sampler.cpp
d8f4df6e3b7753b6091dc5a1424847d9c2bacb82
[]
no_license
jjcao/graspSaliency
27b33bd1c3f7f550a61b6cd3661fed2f315ec38a
7a2fef80c81aca3a808544a4c4de9fbd4d2c8421
refs/heads/master
2020-12-24T05:43:29.260536
2016-11-18T11:17:01
2016-11-18T11:17:01
73,456,937
0
0
null
null
null
null
UTF-8
C++
false
false
3,721
cpp
#include "Sampler.h" #include "SimpleDraw.h" #include "Stats.h" Sampler::Sampler(Mesh * srcMesh, SamplingMethod samplingMethod) { isReady = false; if(srcMesh == NULL) return; else mesh = srcMesh; method = samplingMethod; // Sample based on method selected if( method == RANDOM_BARYCENTRIC ) { // Compute all faces area faceAreas = Vector<double> (mesh->numberOfFaces()); faceProbability = Vector<double> (mesh->numberOfFaces()); totalMeshArea = 0; for(StdList<Face>::iterator f = mesh->face.begin(); f != mesh->face.end(); f++) { faceAreas[f->index] = f->area(); totalMeshArea += faceAreas[f->index]; } for(int i = 0; i < (int) faceAreas.size(); i++) faceProbability[i] = faceAreas[i] / totalMeshArea; interval = Vector<AreaFace>(mesh->numberOfFaces() + 1); interval[0] = AreaFace(0.0, mesh->faceIndexMap[0]); int i = 0; // Compute mesh area in a cumulative manner for(int j = 0; j < (int) faceAreas.size(); j++) { interval[i+1] = AreaFace(interval[i].area + faceProbability[j], mesh->faceIndexMap[j]); i++; } // For importance sampling clearBias(); } else if( method == FACE_CENTER ) { // No preparations needed.. } isReady = true; } SamplePoint Sampler::getSample() { SamplePoint sp; if( method == RANDOM_BARYCENTRIC ) { // r, random point in the area double r = uniform(); // Find corresponding face Vector<AreaFace>::iterator it = lower_bound(interval.begin(), interval.end(), AreaFace(Min(r,interval.back().area))); Face * face = it->f; // Add sample from that face double b[3]; RandomBaricentric(b); sp = SamplePoint( face->getBary(b[0], b[1]), *mesh->fn(face->index), 1.0, face->index, b[0], b[1]); } else if( method == FACE_CENTER ) { int fcount = mesh->numberOfFaces(); int randTriIndex = (int) (fcount * (((double)rand()) / (double)RAND_MAX)) ; if( randTriIndex >= fcount ) randTriIndex = fcount - 1; Face * tri = mesh->f( randTriIndex ); // Get triangle center and normal Vec triCenter = tri->center(); Vec triNor = *mesh->fn(randTriIndex); sp = SamplePoint(triCenter, triNor, tri->area(), tri->index); } return sp; } Vector<SamplePoint> Sampler::getSamples(int numberSamples) { Vector<SamplePoint> samples; for(int i = 0; i < numberSamples; i++) { samples.push_back( getSample() ); } return samples; } void Sampler::clearBias() { bias = faceProbability; } void Sampler::resampleWithBias() { isReady = false; // Fill with lowest bias double minBias = *min_element(bias.begin(), bias.end()); for(int i = 0; i < (int) bias.size(); i++) bias[i] = Max(bias[i], minBias); double totalNewArea = 0; for(int i = 0; i < (int) faceAreas.size(); i++) { faceAreas[i] = bias[i]; totalNewArea += faceAreas[i]; } for(int i = 0; i < (int) faceAreas.size(); i++) faceProbability[i] = faceAreas[i] / totalNewArea; interval = Vector<AreaFace>(mesh->numberOfFaces() + 1); interval[0] = AreaFace(0.0, mesh->faceIndexMap[0]); int i = 0; // Compute mesh area in a cumulative manner for(int j = 0; j < (int) faceAreas.size(); j++) { interval[i+1] = AreaFace(interval[i].area + faceProbability[j], mesh->faceIndexMap[j]); i++; } // Normalize new total mesh area double total = interval.back().area; for(int i = 0; i < (int)interval.size(); i++) interval[i].area /= total; isReady = true; } void Sampler::draw(const Vector<SamplePoint> & samples) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(4.0); glBegin(GL_POINTS); for(int i = 0; i < (int)samples.size(); i++) { const SamplePoint * p = &samples[i]; glColor4f(1,0,0, p->weight); glNormal3fv(p->n); glVertex3dv(p->pos); } glEnd(); }
[ "jjcao1231@gmail.com" ]
jjcao1231@gmail.com
9fdf3b930f6d9bf4b057b539cc9625bf1d8f58a2
812cdd1ec03a1588274cc1c7ab7d736829448197
/src/CplusPlus/main.cpp
f6d01b61dcc480822be0cac9af04c90fa330489a
[]
no_license
jrodriguez-v/ED2_BinarySearchTree_01
cf141e994ed02dd556c9c0a0e93d27b3ce2e3261
a70c9b6e63a3e6549e601e6bf885bfa214894090
refs/heads/master
2022-12-23T07:30:14.617317
2020-09-28T04:02:33
2020-09-28T04:02:33
297,547,006
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
#include <iostream> #include <UI.h> int main() { UI* ui = new UI(); ui->Start(); return 0; }
[ "jrodriguezv@ucenfotec.ac.cr" ]
jrodriguezv@ucenfotec.ac.cr
8c311afd1396ae7806c59eda77a0f8af21bf144a
600c1e74e04e79351fc49578200a50eaced8118c
/StoreAppLuaTest1/LuaTest.h
da7b00f2c429f91bdda5466c38e84f679b0853cb
[ "MIT" ]
permissive
sygh-JP/CompactLua
b21c0bbb4e72d6c8ed2d52e2c4c96070d7ac0f5f
768bbc0b7cfc6c4dc9330b051cf93967a197e909
refs/heads/master
2022-11-17T11:55:13.500246
2022-10-29T14:45:37
2022-10-29T14:45:37
86,248,692
1
1
null
null
null
null
UTF-8
C++
false
false
833
h
#pragma once delegate void WriteStringDelegate(Platform::String^ str); // Luabind のテスト用クラス。 // Lua ステートの RAII を兼ねる。 class MyLua { lua_State* m_lua; private: static WriteStringDelegate^ m_outputWriter; static WriteStringDelegate^ m_errorWriter; // property もしくは event にしたければ、ref クラス内に含める必要がある。 public: MyLua(); ~MyLua(); void Bind(); bool DoLuaScriptString(const char* script); bool DoLuaScriptString(const wchar_t* script); public: static void SetOutputWriter(WriteStringDelegate^ writer) { m_outputWriter = writer; } static void SetErrorWriter(WriteStringDelegate^ writer) { m_errorWriter = writer; } private: static void Print(const char* srcText); }; typedef std::shared_ptr<MyLua> TMyLuaPtr;
[ "whitekatyusha@yahoo.co.jp" ]
whitekatyusha@yahoo.co.jp
4415e2e1a4591efd44e9610f53608af24aa8100e
79eb22109a4be71753f1ebc32ad9f7e79d8f990b
/lattice/unitcell_xml.hpp
eb958b4362714ebe44f7795a9d14bba63cb6051e
[ "Apache-2.0" ]
permissive
todo-group/lattice
875a882823e9a1592e22c075bf978a92ef02a6b3
7183c386ab466ef8a57e5b26766c01e3b04114e8
refs/heads/master
2022-05-07T13:14:23.000659
2022-03-10T02:25:41
2022-03-10T02:25:41
193,005,518
4
3
Apache-2.0
2019-07-30T02:44:18
2019-06-21T00:48:43
C++
UTF-8
C++
false
false
5,692
hpp
/* Copyright (C) 2019-2022 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp> 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 LATTICE_UNITCELL_XML_HPP #define LATTICE_UNITCELL_XML_HPP #include <sstream> #include <string> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "unitcell.hpp" namespace lattice { using boost::property_tree::ptree; inline ptree& operator>>(ptree& pt, unitcell& cell) { std::size_t dim = 0; if (auto str = pt.get_optional<std::string>("<xmlattr>.dimension")) { dim = stoi(str.get()); } else { throw std::invalid_argument("attribute dimension does not found"); } cell = unitcell(dim); std::size_t ns = 0; if (auto str = pt.get_optional<std::string>("<xmlattr>.vertices")) ns = stoi(str.get()); for (auto& v : pt) { if (v.first == "VERTEX") { bool found_pos = false; coordinate_t pos = coordinate_t::Zero(dim); int tp = 0; for (auto& c : v.second) { if (c.first == "COORDINATE") { if (found_pos) throw std::invalid_argument("duplicated <COORDINATE> tag"); std::istringstream is(c.second.data()); std::string sin; for (std::size_t m = 0; m < dim; ++m) { is >> sin; pos(m) = stod(sin); } found_pos = true; } } if (auto str = v.second.get_optional<std::string>("<xmlattr>.type")) { tp = stoi(str.get()); } cell.add_site(pos, tp); } } if (cell.num_sites() > 0) { if (ns > 0 && cell.num_sites() != ns) throw std::invalid_argument("inconsistent number of sites"); } else { coordinate_t pos = coordinate_t::Zero(dim); for (std::size_t i = 0; i < ns; ++i) cell.add_site(pos, 0); } for (auto& e : pt) { if (e.first == "EDGE") { bool found_source = false, found_target = false; std::size_t source = 1, target = 1; // offset one offset_t source_offset = offset_t::Zero(dim), target_offset = offset_t::Zero(dim); int tp = 0; for (auto& st : e.second) { if (st.first == "SOURCE") { if (found_source) throw std::invalid_argument("duplicated <SOURCE> tag"); if (auto str = st.second.get_optional<std::string>("<xmlattr>.vertex")) source = stoi(str.get()); if (auto str = st.second.get_optional<std::string>("<xmlattr>.offset")) { std::istringstream is(str.get()); std::string sin; for (std::size_t m = 0; m < dim; ++m) { is >> sin; source_offset(m) = stod(sin); } } found_source = true; } else if (st.first == "TARGET") { if (found_target) throw std::invalid_argument("duplicated <TARGET> tag"); if (auto str = st.second.get_optional<std::string>("<xmlattr>.vertex")) target = stoi(str.get()); if (auto str = st.second.get_optional<std::string>("<xmlattr>.offset")) { std::istringstream is(str.get()); std::string sin; for (std::size_t m = 0; m < dim; ++m) { is >> sin; target_offset(m) = stod(sin); } } found_target = true; } } target_offset = target_offset - source_offset; if (auto str = e.second.get_optional<std::string>("<xmlattr>.type")) tp = stoi(str.get()); cell.add_bond(source - 1, target - 1, target_offset, tp); } } return pt; } inline ptree& write_xml(ptree& pt, const std::string& name, const unitcell& cell) { ptree& root = pt.add("UNITCELL", ""); root.put("<xmlattr>.name", name); root.put("<xmlattr>.dimension", cell.dimension()); root.put("<xmlattr>.vertices", cell.num_sites()); for (std::size_t s = 0; s < cell.num_sites(); ++s) { ptree& vertex = root.add("VERTEX", ""); vertex.put("<xmlattr>.type", cell.site(s).type); std::ostringstream os; os << std::setprecision(std::numeric_limits<double>::max_digits10); auto pos = cell.site(s).coordinate; for (std::size_t m = 0; m < cell.dimension(); ++m) os << (m ? " " : "") << pos(m); vertex.add("COORDINATE", os.str()); } for (std::size_t b = 0; b < cell.num_bonds(); ++b) { ptree& edge = root.add("EDGE", ""); edge.put("<xmlattr>.type", cell.bond(b).type); ptree& source = edge.add("SOURCE", ""); source.put("<xmlattr>.source", cell.bond(b).source + 1); ptree& target = edge.add("TARGET", ""); target.put("<xmlattr>.target", cell.bond(b).target + 1); std::ostringstream os; auto offset = cell.bond(b).target_offset; for (std::size_t m = 0; m < cell.dimension(); ++m) os << (m ? " " : "") << offset(m); target.put("<xmlattr>.offset", os.str()); } return pt; } inline bool read_xml(ptree& pt, const std::string& name, unitcell& cell) { for (auto& child : pt.get_child("LATTICES")) { if (child.first == "UNITCELL") { if (auto str = child.second.get_optional<std::string>("<xmlattr>.name")) { if (str.get() == name) { child.second >> cell; return true; } } } } return false; } } // end namespace lattice #endif
[ "wistaria@phys.s.u-tokyo.ac.jp" ]
wistaria@phys.s.u-tokyo.ac.jp
142ccf0482b1f7b35e661b7059081608981a3933
db257feeb047692577d51d0f4e3085ef90ec8710
/home_control_1/home_control/home_manage/luxdomotvedit.cpp
eea555f3f439b9749512e59f169d9062a1f1eb56
[]
no_license
yeefanwong/leelen_code
975cf11d378529177ef7c406684fae8df46e8fbe
a37685ad6062221b5032608c98447db227bd4070
refs/heads/master
2023-03-16T03:45:04.024954
2017-09-04T09:55:16
2017-09-04T09:55:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,817
cpp
#include "luxdomotvedit.h" #include"maindialog.h" #include"MyBuffer.h" extern MainDialog *g_pMainDlg; extern LMap_6410_Msg mLMap_6410_Msg; extern QMultiMap<QString,QDeclarativeEngine*> engines; LuxDomoTvEdit::LuxDomoTvEdit(QDeclarativeItem *parent) : QDeclarativeItem(parent) { listEngine=NULL; listItem=NULL; } LuxDomoTvEdit::~LuxDomoTvEdit() { resourceRelease(); } void LuxDomoTvEdit::componentComplete() { } void LuxDomoTvEdit::resourceRelease() { if(listEngine!=NULL) { listEngine->deleteLater(); listEngine=NULL; } if(listItem!=NULL) { listItem->deleteLater(); listItem=NULL; } } void LuxDomoTvEdit::init(QString type, QString deviceUid) { if(tr("roomScene")==type) { m_deviceElement=g_pMainDlg->m_pHomeControlDlg->m_pHomeScene->LoadingRoomSceneDeviceData(deviceUid); if(m_deviceElement.isNull()){ parentItem()->deleteLater(); } } else if(tr("homeScene")==type) { m_deviceElement=g_pMainDlg->m_pHomeControlDlg->m_pHomeScene->LoadingHomeSceneDeviceData(deviceUid); if(m_deviceElement.isNull()){ parentItem()->deleteLater(); } } MyMsgLog<<m_deviceElement.attribute("mode")<<m_deviceElement.attribute("value"); QString mode=m_deviceElement.attribute("mode"); if(mode!=tr("av")&&mode!=tr("tv")) { mode=tr("av"); m_deviceElement.setAttribute("mode",mode); } parentItem()->setProperty("mode",m_deviceElement.attribute("mode")); parentItem()->setProperty("volume",m_deviceElement.attribute("value")); } void LuxDomoTvEdit::close() { parentItem()->deleteLater(); } void LuxDomoTvEdit::showModeList() { resourceRelease(); QDeclarativeEngine *engine = new QDeclarativeEngine(parentItem()); QDeclarativeComponent component(engine, QUrl("qrc:/QML/content/LuxDomoListDialog.qml")); QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(component.create()); item->setParentItem(parentItem()); int pointX=parentItem()->property("pointX").toInt(); item->setWidth(mLMap_6410_Msg.screenW*7/40); item->setHeight(mLMap_6410_Msg.screenH/3); item->setX(mLMap_6410_Msg.screenW*7/40+pointX); item->setY(mLMap_6410_Msg.screenH*4/9); item->setProperty("dataType",tr("mode")); QMetaObject::invokeMethod(item,"clearModel",Qt::DirectConnection); QMetaObject::invokeMethod(item,"addModel",Qt::DirectConnection, Q_ARG(QVariant,tr("av"))); QMetaObject::invokeMethod(item,"addModel",Qt::DirectConnection, Q_ARG(QVariant,tr("tv"))); listEngine=NULL; listItem=NULL; } void LuxDomoTvEdit::showVolumeList() { resourceRelease(); QDeclarativeEngine *engine = new QDeclarativeEngine(parentItem()); QDeclarativeComponent component(engine, QUrl("qrc:/QML/content/LuxDomoListDialog.qml")); QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(component.create()); item->setParentItem(parentItem()); int pointX=parentItem()->property("pointX").toInt(); item->setWidth(mLMap_6410_Msg.screenW*7/40); item->setHeight(mLMap_6410_Msg.screenH/3); item->setX(mLMap_6410_Msg.screenW*7/40+pointX); item->setY(mLMap_6410_Msg.screenH*5/9); item->setProperty("dataType",tr("volume")); QMetaObject::invokeMethod(item,"clearModel",Qt::DirectConnection); for(int i=0;i<=10;i++) { QMetaObject::invokeMethod(item,"addModel",Qt::DirectConnection, Q_ARG(QVariant,QString::number(i*10))); } listEngine=NULL; listItem=NULL; } void LuxDomoTvEdit::save() { QString mode=parentItem()->property("mode").toString(); QString volume=parentItem()->property("volume").toString(); m_deviceElement.setAttribute("mode",mode); m_deviceElement.setAttribute("value",volume); parentItem()->deleteLater(); }
[ "yankaobi@sensenets.com" ]
yankaobi@sensenets.com
877793328f44d48b4f3b4e5f444077206737c2ab
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/include/ocidescriptors.h
7c69937eb613fa4aebb09da9182d0e5707cd88ca
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
2,929
h
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2001. All Rights Reserved. * * Contributor(s): * Dave Mackie dmackie@cisco.com */ #ifndef __OCIDESCRIPTORS_INCLUDED__ #define __OCIDESCRIPTORS_INCLUDED__ const u_int8_t MP4OCIDescrTagsStart = 0x40; const u_int8_t MP4ContentClassDescrTag = 0x40; const u_int8_t MP4KeywordDescrTag = 0x41; const u_int8_t MP4RatingDescrTag = 0x42; const u_int8_t MP4LanguageDescrTag = 0x43; const u_int8_t MP4ShortTextDescrTag = 0x44; const u_int8_t MP4ExpandedTextDescrTag = 0x45; const u_int8_t MP4ContentCreatorDescrTag = 0x46; const u_int8_t MP4ContentCreationDescrTag = 0x47; const u_int8_t MP4OCICreatorDescrTag = 0x48; const u_int8_t MP4OCICreationDescrTag = 0x49; const u_int8_t MP4SmpteCameraDescrTag = 0x4A; const u_int8_t MP4OCIDescrTagsEnd = 0x5F; class MP4ContentClassDescriptor : public MP4Descriptor { public: MP4ContentClassDescriptor(); void Read(MP4File* pFile); }; class MP4KeywordDescriptor : public MP4Descriptor { public: MP4KeywordDescriptor(); protected: void Mutate(); }; class MP4RatingDescriptor : public MP4Descriptor { public: MP4RatingDescriptor(); void Read(MP4File* pFile); }; class MP4LanguageDescriptor : public MP4Descriptor { public: MP4LanguageDescriptor(); }; class MP4ShortTextDescriptor : public MP4Descriptor { public: MP4ShortTextDescriptor(); protected: void Mutate(); }; class MP4ExpandedTextDescriptor : public MP4Descriptor { public: MP4ExpandedTextDescriptor(); protected: void Mutate(); }; class MP4CreatorDescriptor : public MP4Descriptor { public: MP4CreatorDescriptor(u_int8_t tag); }; class MP4CreationDescriptor : public MP4Descriptor { public: MP4CreationDescriptor(u_int8_t tag); }; class MP4SmpteCameraDescriptor : public MP4Descriptor { public: MP4SmpteCameraDescriptor(); }; class MP4UnknownOCIDescriptor : public MP4Descriptor { public: MP4UnknownOCIDescriptor(); void Read(MP4File* pFile); }; extern MP4Descriptor *CreateOCIDescriptor(u_int8_t tag); #endif /* __OCIDESCRIPTORS_INCLUDED__ */
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006
148bb9d9b4b0315b3cd4609ee41f00ab5d42e1e9
83cfe28f0ed65742cb602011929675a222df4bb6
/src/RigelModel/ModelBase.cpp
e2d8b85e5c7fc5f4c69e161edc1cd348257ba475
[]
no_license
RigelStudio/RigelGIS
362b14bd44ac4258761a9c00bcef70cc07687935
89b477bedce77313b282371c04abaaab17ba58d6
refs/heads/master
2021-01-22T09:55:17.477958
2019-12-16T14:27:31
2019-12-16T14:27:31
102,331,613
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,646
cpp
#include "ModelBase.h" #include "RigelCore/MEMath.h" #include "RigelCore/OECore.h" #include <osgEarth\GeoData> ModelBase::ModelBase() { m_pModelMT = new osg::MatrixTransform; m_pNodeMT = new osg::MatrixTransform; m_pModelMT->addChild(m_pNodeMT); addChild(m_pModelMT); m_pLogo = nullptr; } ModelBase::~ModelBase() { } void ModelBase::setScale(float scale) { //ÉèÖÃËõ·Å osg::Matrix sMat = osg::Matrix::scale(scale, scale, scale); osg::Matrix mat = m_pNodeMT->getMatrix(); m_pNodeMT->setMatrix(sMat * mat); } void ModelBase::setAngle(float angleX, float angleY, float angleZ) { // } void ModelBase::setAngle(osg::Vec3& rotate) { float radianX = osg::DegreesToRadians(rotate.x()); float radianY = osg::DegreesToRadians(rotate.y()); float radianZ = osg::DegreesToRadians(rotate.z()); osg::Quat quatX, quatY, quatZ; quatX = osg::Quat(radianX, osg::X_AXIS); quatY = osg::Quat(radianY, osg::Y_AXIS); quatZ = osg::Quat(radianZ, osg::Z_AXIS); auto quat = quatX * quatY * quatZ; osg::Matrixd matS = m_pNodeMT->getMatrix(); osg::Matrixd matR = osg::Matrixd::rotate(quat); m_pNodeMT->setMatrix(matS * matR); } Geo::ModelOption& ModelBase::getData() { return m_modelData; } void ModelBase::setSelected(bool isSelect) { //none } void ModelBase::setPosLLH(osg::Vec3d& llhPos) { GeoPoint point = GeoPoint(OECore::ins()->getMapSRS(), llhPos); setPosition(point); } void ModelBase::setPosLL(double x, double y) { auto geoPos = osgEarth::GeoPoint(OECore::ins()->getMapSRS(), x, y); setPosition(geoPos); } void ModelBase::setFont(std::string& strFont) { if (m_pLogo != nullptr) { m_pLogo->setFont(strFont); } }
[ "fonlylovey@163.com" ]
fonlylovey@163.com
4b5b360516398219112ba5a08950194d68ad14f1
93fe04273698cc72ecdebfb9af481ee1bbdd61d3
/Main.cpp
8907f6f45775fd1747dc0f054b4ddd1ee144aa14
[]
no_license
crystalDf/Principles-and-Practice-Using-Cpp-Chapter-07-CalculatorWithSqrt
45d55788ad280f71e9f4f8116a760ef8851f91bd
ecd303312e321ffd0f42fa3431f2d129b458da20
refs/heads/master
2023-03-18T21:15:39.573919
2021-03-06T15:54:23
2021-03-06T15:54:23
345,132,755
0
0
null
null
null
null
UTF-8
C++
false
false
9,109
cpp
# include "std_lib_facilities.h" const char number = '8'; const char quit = 'q'; const char print = ';'; const string prompt = "> "; const string result = "= "; const char name = 'a'; const char let = 'L'; const string declkey = "let"; const char my_sqrt = 'S'; const string sqrtkey = "sqrt"; class Token { public: char kind; double value; string name; Token(char ch) : kind { ch } { } Token(char ch, double val) : kind { ch }, value { val } { } Token(char ch, string n) : kind { ch }, name { n } { } }; class Token_stream { public: Token_stream() : full { false }, buffer { ' ' } { } Token get(); void putback(Token t); void ignore(char c); private: bool full; Token buffer; }; void Token_stream::putback(Token t) { if (full) { error("putback() into a full buffer"); } buffer = t; full = true; } Token Token_stream::get() { if (full) { full = false; return buffer; } char ch; std::cin >> ch; switch (ch) { case print: case quit: case '(': case ')': case '{': case '}': case '+': case '-': case '*': case '/': case '%': case '!': case '=': return Token { ch }; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { std::cin.putback(ch); double val; std::cin >> val; return Token { number, val }; } default: { if (isalpha(ch)) { string s; while (true) { s += ch; if (!std::cin.get(ch) || (!isalpha(ch) && !isdigit(ch))) { break; } } cin.putback(ch); if (s == declkey) { return Token { let }; } if (s == sqrtkey) { return Token { my_sqrt }; } return Token { name, s }; } error("Bad token"); return Token { ' ' }; } } } void Token_stream::ignore(char c) { if (full && c == buffer.kind) { full = false; return; } full = false; char ch; while (std::cin >> ch) { if (ch == c) { return; } } } class Variable { public: Variable(string var, double val) : name { var } , value { val } { } string name; double value; }; double expression(); double term(); double factorial(); double primary(); double get_factorial(double val); void calculate(); void clean_up_mess(); double get_value(string s); void set_value(string s, double d); double statement(); double declaration(); double define_name(string var, double val); bool is_declared(string var); double sqrt_pattern(); Token_stream ts; vector<Variable> var_table; int main() { try { define_name("pi", 3.1415926535); define_name("e", 2.7182818284); calculate(); keep_window_open(); } catch (exception& e) { std::cerr << e.what() << std::endl; keep_window_open(); return 1; } catch (...) { std::cerr << "exception" << std::endl; keep_window_open(); return 2; } } double expression() { double left = term(); Token t = ts.get(); while (true) { switch (t.kind) { case '+': { left += term(); t = ts.get(); break; } case '-': { left -= term(); t = ts.get(); break; } default: ts.putback(t); return left; } } } double term() { double left = factorial(); Token t = ts.get(); while (true) { switch (t.kind) { case '*': { left *= factorial(); t = ts.get(); break; } case '/': { double d = factorial(); if (!d) { error("divide by zero"); } left /= d; t = ts.get(); break; } case '%': { double d = factorial(); if (!d) { error("divide by zero"); } left = fmod(left, d); t = ts.get(); break; } default: ts.putback(t); return left; } } } double factorial() { double left = primary(); Token t = ts.get(); while (true) { switch (t.kind) { case '!': { left = get_factorial(left); t = ts.get(); break; } default: ts.putback(t); return left; } } } double primary() { Token t = ts.get(); switch (t.kind) { case '(': { double d = expression(); t = ts.get(); if (t.kind != ')') { error("')' expected"); } return d; } case '{': { double d = expression(); t = ts.get(); if (t.kind != '}') { error("'}' expected"); } return d; } case number: return t.value; case '-': return -primary(); case '+': return primary(); case name: return get_value(t.name); default: error("primary expected"); return 0; } } double get_factorial(double val) { int result = 1; for (int i = 1; i <= val; ++i) { result *= i; } return result; } void calculate() { while (std::cin) try { std::cout << prompt; Token t = ts.get(); while (t.kind == print) { t = ts.get(); } if (t.kind == quit) { return; } ts.putback(t); std::cout << result << statement() << std::endl; } catch (exception& e) { std::cerr << e.what() << std::endl; clean_up_mess(); } } void clean_up_mess() { ts.ignore(print); } double get_value(string s) { for (const Variable& v : var_table) { if (v.name == s) { return v.value; } } error("get: undefined variable", s); return 0; } void set_value(string s, double d) { for (Variable& v : var_table) { if (v.name == s) { v.value = d; return; } } error("set: undefined variable", s); } double statement() { Token t = ts.get(); switch (t.kind) { case let: return declaration(); case my_sqrt: return sqrt_pattern(); default: ts.putback(t); return expression(); } } double declaration() { Token t = ts.get(); if (t.kind != name) { error("name expected in declaration"); } string var_name = t.name; Token t2 = ts.get(); if (t2.kind != '=') { error("= missing in declaration of ", var_name); } double d = expression(); define_name(var_name, d); return d; } double define_name(string var, double val) { if (is_declared(var)) { error(var, " declared twice"); } var_table.push_back(Variable(var, val)); return val; } bool is_declared(string var) { for (const Variable& v : var_table) { if (v.name == var) { return true; } } return false; } double sqrt_pattern() { Token t = ts.get(); switch (t.kind) { case '(': { double d = expression(); t = ts.get(); if (t.kind != ')') { error("')' expected"); } return sqrt(d); } default: error("sqrt_pattern expected"); return 0; } }
[ "chendong333@gmail.com" ]
chendong333@gmail.com
efa5b52d7fac7a093489af5391fc2536fe1d272e
865831aacb3ba95de3f57a8c81c4ea8b6001a1a4
/src/ECS/EventDispatcher.cpp
61d85f2aed739676aceb64757a28108a259f206d
[ "MIT" ]
permissive
rodrigobmg/ECS-2
69c5a12a5b56c60ccc48745575eb56d4f76722e2
274b04960c411754c53dc64c1544277df57a1c9f
refs/heads/master
2020-07-02T22:32:53.246816
2019-05-22T09:04:29
2019-05-22T09:04:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
467
cpp
// Copyright (c) 2019 Ethan Margaillan <contact@ethan.jp>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/Ethan13310/ECS/master/LICENSE #include <ECS/EventDispatcher.hpp> void ecs::EventDispatcher::clearAll() { m_listeners.clear(); } void ecs::EventDispatcher::clear(Event::Id id) { for (auto it{ m_listeners.begin() }; it != m_listeners.end();) { if (it->second.id == id) { it = m_listeners.erase(it); } else { ++it; } } }
[ "ethan.margaillan@gmail.com" ]
ethan.margaillan@gmail.com
c51d931e6cc1de680f59e2271f104dbb7aa12ab6
39e38c0be28ce52f8e42d8329efcfcbbe5b24e84
/HOTEL/3.cpp
c2c21a324e58d642875136b0cfd3be2fe0e51660
[]
no_license
shailesh1001/CODECHEF
bba2460f3a8ee2f61537fd67c1ed6add22a8e135
450a54d3513987691f96c2935b74362a119ab1f9
refs/heads/master
2021-01-17T20:51:28.200912
2014-11-18T16:04:04
2014-11-18T16:04:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
cpp
//Author : pakhandi // using namespace std; #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<cmath> #include<cstring> #define wl(n) while(n--) #define fl(i,a,b) for(i=a; i<b; i++) #define rev(i,a,b) for(i=a; i>=b; i--) #define print(n) printf("%d\n", n) #define scan(n) scanf("%d", &n) #define MOD 1000000007 #define ll long long int int arr_start[105], arr_end[105], arr_new[210], arr_sum[210]; int main() { int i, j, cases, n, new_n; int count, flag, max_count; scan(cases); wl(cases) { max_count=0; count=0; scan(n); fl(i,0,n) scan(arr_start[i]); fl(i,0,n) scan(arr_end[i]); fl(i,0,n) arr_new[i]=arr_start[i]; j=0; new_n=2*n; fl(i,n,new_n) arr_new[i]=arr_end[j++]; sort(arr_new, arr_new+(2*n)); rev(i,new_n-1, 0) { flag=0; fl(j,0,n) { if(arr_new[i]==arr_start[j]) { arr_start[j]=-100; arr_sum[i]=1; flag=1; break; } } if(flag==0) arr_sum[i]=-1; } for(i=0; i<2*n; i++) { count=count+arr_sum[i]; if(count>max_count) max_count=count; } print(max_count); } return 0; }
[ "asimkprasad@gmail.com" ]
asimkprasad@gmail.com
8a4dd64f50c0e90382ed99b9c5b8858fe006e4d6
541e3f1c759452e67a5dbd561e8ed0ac25a9b095
/displays/NcursesDisplay.cpp
a459dad04a1be7660801b27fd7e67615e5438fff
[]
no_license
ethanquix/SystemMonitor
20dd6f7daa6f5e18b8471e5e5ca74298aaa8e894
925783b02caa55784d519cba1f033b5d100f4bae
refs/heads/master
2021-03-30T18:29:55.174965
2017-01-22T09:59:35
2017-01-22T09:59:35
79,708,972
0
0
null
null
null
null
UTF-8
C++
false
false
6,501
cpp
// // Created by szterg_r on 21/01/17. // #include <ncurses.h> #include <iostream> #include <unistd.h> #include <algorithm> #include <wordexp.h> #include "NcursesDisplay.hpp" #include "../core/Core.hpp" Display::NcursesDisplay::NcursesDisplay() { newterm(NULL, stdout, stdin); curs_set(0); _win = new NcursesWindow(0, 0, 0, 0); _colorPair = 0; start_color(); init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_MAGENTA, COLOR_WHITE); init_pair(3, COLOR_RED, COLOR_BLACK); init_pair(4, COLOR_BLUE, COLOR_WHITE); init_pair(5, COLOR_YELLOW, COLOR_RED); init_pair(6, COLOR_WHITE, COLOR_BLUE); init_pair(7, COLOR_GREEN, COLOR_WHITE); init_pair(8, COLOR_MAGENTA, COLOR_GREEN); reloadBoards(); } Display::NcursesDisplay::~NcursesDisplay() { delete _win; endwin(); } void Display::NcursesDisplay::reloadBoards() { Display::Board *_boards = Core::getInstance()->getBoards(); for (int i = 0; i < 2; ++i) { _boards[i].x = 1; _boards[i].y = 1 + i * (LINES / 2); _boards[i].width = (COLS - 2) / 2; _boards[i].height = (LINES - 2) / 2; } for (int i = 2; i < 4; ++i) { _boards[i].x = COLS / 2 + 2; _boards[i].y = 1 + (i - 2) * ((LINES - 2) / 4 + 1); _boards[i].width = (COLS - 2) / 2; _boards[i].height = (LINES - 2) / 4; } for (int i = 4; i < 6; ++i) { _boards[i].x = COLS / 2 + 2; _boards[i].y = 2 + 2 * (LINES - 2) / 4 + (i - 4) * ((LINES - 2) / 4 + 1); _boards[i].width = (COLS - 2) / 4; _boards[i].height = (LINES - 2) / 4; } for (int i = 6; i < 8; ++i) { _boards[i].x = COLS / 4 * 3 + 3; _boards[i].y = 2 + 2 * (LINES - 2) / 4 + (i - 6) * ((LINES - 2) / 4 + 1); _boards[i].width = (COLS - 2) / 4; _boards[i].height = (LINES - 2) / 4; } } void Display::NcursesDisplay::draw(const Display::Board &board, const std::pair<int, int> &pair, const std::vector<std::pair<int, int>> &vector, bool fill) { auto it = vector.end(); if ((int) vector.size() < board.width - 2) it = vector.begin(); else it -= (board.width - 2); auto max_elem = std::max_element(it, vector.end(), [](const std::pair<int, int> &left, const std::pair<int, int> &right) { return left.second < right.second; }); (void) pair; (void) fill; int max = (*max_elem).second; int div = 1; while (max / div > board.height - 2) div += 1; int x = board.x + 1; for (; it != vector.end(); ++it) { for (int i = 0; i < (*it).second / div; ++i) _win->print(x, board.y + board.height - 1 - i, "|"); _win->print(x++, board.y + board.height - 1 - (*it).second / div, "+"); } } void Display::NcursesDisplay::write(const Display::Board &board, const std::string &string) { _win->print(board.x, board.y, board.width, board.height, string); } void Display::NcursesDisplay::refresh() { _win->refresh(); ::refresh(); } void Display::NcursesDisplay::erase() { reloadBoards(); _win->applyColorPair(_colorPair + 1); _win->clear(); _win->verticalLine(0, COLS / 2, 1, LINES - 2); _win->horizontalLine(0, 1, LINES / 2, COLS - 2); _win->verticalLine(0, COLS / 4 * 3 + 1, LINES / 2 + 1, LINES / 2 - 2); _win->horizontalLine(0, COLS / 2 + 1, LINES / 4 * 3, COLS / 2 - 2); _win->horizontalLine(0, COLS / 2 + 1, LINES / 4, COLS / 2 - 2); } void Display::NcursesDisplay::handleResize() { } void Display::NcursesDisplay::processEvents() { int input = _win->getChar(); switch (input) { case 'q': case 27: Core::getInstance()->exitLoop(); break; case KEY_F(2): case KEY_F(3): case KEY_F(4): case KEY_F(5): case KEY_F(6): case KEY_F(7): case KEY_F(8): case KEY_F(9): { std::vector<std::string> modules = Core::getInstance()->getCachedModules(); modules.insert(modules.begin(), "Remove module"); NcursesWindow subwin(1, 1, COLS / 4, std::min(LINES - 2, (int) modules.size() + 2), false); int cur = 0; int key = 0; do { if (key == KEY_DOWN) cur = (cur == (int) modules.size() - 1) ? 0 : cur + 1; else if (key == KEY_UP) cur = (cur == 0) ? modules.size() - 1 : cur - 1; subwin.clear(); subwin.applyColorPair(_colorPair + 1); subwin.refresh(); int i = 1; for (auto it = modules.begin(); it != modules.end(); ++it) { if (i - 1 == cur) subwin.setAttribute(A_REVERSE); subwin.print(2, i++, (*it)); subwin.unsetAttribute(A_REVERSE); } subwin.refresh(); } while ((key = subwin.getChar()) != 'q' && key != 10); if (cur == 0) Core::getInstance()->disableModule(input - KEY_F(2)); else if (key != 'q') Core::getInstance()->enableModule(modules[cur], input - KEY_F(2)); } break; case 'n': Core::getInstance()->changeDisplay(true); break; case 't': ++_colorPair; _colorPair %= 8; _win->applyColorPair(_colorPair + 1); break; case 'p': NcursesWindow subwin(COLS / 4, LINES / 8, COLS / 2, 3, false); std::string in; echo(); subwin.clear(); subwin.applyColorPair(_colorPair + 1); subwin.print(1, 1, "Module path : "); subwin.refresh(); in = subwin.prompt(15, 1); if (in != "") { wordexp_t exp_result; if (wordexp(in.c_str(), &exp_result, 0) == 0) { Core::getInstance()->loadModule(exp_result.we_wordv[0]); wordfree(&exp_result); noecho(); break; } } } }
[ "dimitriwyzlic@gmail.com" ]
dimitriwyzlic@gmail.com
0938048e60aed74e187e33f8bca48b8c4c4bae71
58790459d953a3e4b6722ed3ee939f82d9de8c3e
/my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/Samples/DocSign/sources/DSHandler.cpp
5d339a631bd5feb61f220c923ff55478cf41cc7f
[]
no_license
tisn05/VS
bb84deb993eb18d43d8edaf81afb753afa3d3188
da56d392a518ba21edcb1a367b4b4378d65506f0
refs/heads/master
2020-09-25T05:49:31.713773
2016-08-22T01:22:16
2016-08-22T01:22:16
66,229,337
0
1
null
null
null
null
UTF-8
C++
false
false
28,198
cpp
/********************************************************************* ADOBE SYSTEMS INCORPORATED Copyright (C) 1998-2006 Adobe Systems Incorporated All rights reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. --------------------------------------------------------------------- DSHandler.cpp - Main Digital Signature callbacks and related routines. *********************************************************************/ #include "DocSign.h" #include "DSHandler.h" #include "DSEngine.h" #include "DSSigVal.h" ASAtom DSHandler::fHandlerName = ASAtomNull; PubSecHandlerRec DSHandler::fHandlerRec; bool DSHandler::fbHandlerIsInit = false; bool DSHandler::fbHandlerIsRegistered = false; // Precise bbox of Acrobat logo stream stmLogoLogo extern const ASFixedRect stmLogoBBox; // Stream data for Acrobat Logo extern const char* const stmLogoData; /************************************************************************* * Big red X ************************************************************************/ static ASFixedRect stmInvalidBBox = { fixedZero,fixedZero,0x00630000,0x00630000 }; static const char* const stmInvalidData = "% DSInvalid\n" "q\n" "0.1 0 0 0.1 5 0 cm\n" "0 J 0 j 4 M []0 d\n" "1 i \n" "1 G\n" "0 g\n" "69 181 m\n" "92 205 310 447 343 486 c\n" "291 542 126 730 99 763 c\n" "242 894 l\n" "282 842 417 668 468 607 c\n" "501 646 668 845 708 895 c\n" "843 768 l\n" "810 735 604 527 576 492 c\n" "614 451 822 221 851 187 c\n" "710 52 l\n" "677 92 486 330 451 370 c\n" "431 347 217 75 197 49 c\n" "69 181 l\n" "f\n" "0.44 G\n" "1 0 0 rg\n" "1.2 w\n" "50 232 m\n" "73 257 292 498 325 537 c\n" "273 594 108 782 80 814 c\n" "224 945 l\n" "264 893 398 719 450 658 c\n" "483 697 650 896 690 946 c\n" "825 820 l\n" "791 786 585 578 557 544 c\n" "595 502 803 272 832 239 c\n" "691 103 l\n" "659 143 467 381 433 421 c\n" "413 398 198 126 178 101 c\n" "50 232 l\n" "B\n" "Q"; /************************************************************************* * Yellow question mark ************************************************************************/ static ASFixedRect stmUnknownBBox = { fixedZero,fixedZero,0x00630000,0x00630000 }; static const char* const stmUnknownData = "% DSUnknown\n" "q\n" "1 G\n" "1 g\n" "0.1 0 0 0.1 9 0 cm\n" "0 J 0 j 4 M []0 d\n" "1 i \n" "0 g\n" "313 292 m\n" "313 404 325 453 432 529 c\n" "478 561 504 597 504 645 c\n" "504 736 440 760 391 760 c\n" "286 760 271 681 265 626 c\n" "265 625 l\n" "100 625 l\n" "100 828 253 898 381 898 c\n" "451 898 679 878 679 650 c\n" "679 555 628 499 538 435 c\n" "488 399 467 376 467 292 c\n" "313 292 l\n" "h\n" "308 214 170 -164 re\n" "f\n" "0.44 G\n" "1.2 w\n" "1 1 0.4 rg\n" "287 318 m\n" "287 430 299 479 406 555 c\n" "451 587 478 623 478 671 c\n" "478 762 414 786 365 786 c\n" "260 786 245 707 239 652 c\n" "239 651 l\n" "74 651 l\n" "74 854 227 924 355 924 c\n" "425 924 653 904 653 676 c\n" "653 581 602 525 512 461 c\n" "462 425 441 402 441 318 c\n" "287 318 l\n" "h\n" "282 240 170 -164 re\n" "B\n" "Q"; /************************************************************************* * Green check ************************************************************************/ static ASFixedRect stmDoubleValidBBox = { 0x00000000,0x00000000,0x03C39459,0x03E80000 }; static const char* const stmDoubleValidData = "% DSDoubleValid\n" "q\n" "0 J 0 j 4 M []0 d\n" "1.5 i \n" "1 g\n" "370 37 m\n" "0 401 l\n" "126 574 l\n" "365 289 l\n" "779 1000 l\n" "944 876 l\n" "h f\n" "0 g\n" "406 0 m\n" "55 349 l\n" "157 485 l\n" "396 200 l\n" "817 916 l\n" "963 808 l\n" "h f\n" "0 G\n" "0 0.7 0.23 rg\n" "15 w\n" "377 50 m\n" "25 399 l\n" "128 536 l\n" "367 251 l\n" "787 967 l\n" "934 859 l\n" "b\n" "Q"; /************************************************************************* * DSHandler::Register * Register this handler with PubSec ************************************************************************/ bool DSHandler::Register() { fHandlerName = ASAtomFromString( DOCSIGN_HANDLER_NAME ); ACROASSERT( !fbHandlerIsInit && !fbHandlerIsRegistered ); if( gPubSecHFT == NULL || gDigSigHFT == NULL || gAcroFormHFT == NULL || fbHandlerIsRegistered ) return false; if( !fbHandlerIsInit ) { memset( &fHandlerRec, 0, sizeof(fHandlerRec) ); DSEngine *psEngine = new DSEngine; if( !psEngine ) return false; fHandlerRec.size = sizeof(PubSecHandlerRec); fHandlerRec.engine = (PubSecEngine) psEngine; fHandlerRec.getBoolProperty = ASCallbackCreateProto(PSGetBoolPropertyProc, DSHandler::GetBoolProperty ); fHandlerRec.getAtomProperty = ASCallbackCreateProto(PSGetAtomPropertyProc, DSHandler::GetAtomProperty ); fHandlerRec.getTextProperty = ASCallbackCreateProto(PSGetTextPropertyProc, DSHandler::GetTextProperty ); fHandlerRec.getInt32Property = ASCallbackCreateProto(PSGetInt32PropertyProc, DSHandler::GetInt32Property ); fHandlerRec.newEngine = ASCallbackCreateProto(PSNewEngineProc, DSHandler::NewEngine ); fHandlerRec.destroyEngine = ASCallbackCreateProto(PSDestroyEngineProc, DSHandler::DestroyEngine ); fHandlerRec.sessionAcquire = ASCallbackCreateProto(PSSessionAcquireProc, DSHandler::SessionAcquire ); fHandlerRec.sessionRelease = ASCallbackCreateProto(PSSessionReleaseProc, DSHandler::SessionRelease ); fHandlerRec.sessionReady = ASCallbackCreateProto(PSSessionReadyProc, DSHandler::SessionReady ); fHandlerRec.performOperation = ASCallbackCreateProto(PSPerformOperationProc, DSHandler::PerformOperation ); fHandlerRec.sigGetSigProperties = ASCallbackCreateProto(PSSigGetSigPropertiesProc, DSHandler::SigGetSigProperties ); fHandlerRec.sigAuthenticate = ASCallbackCreateProto(PSSigAuthenticateProc, DSHandler::SigAuthenticate ); fHandlerRec.sigGetSigValue = ASCallbackCreateProto(PSSigGetSigValueProc, DSHandler::SigGetSigValue ); // Set up this callback if you want to have custom appearance fHandlerRec.sigCreateAPNXObj = ASCallbackCreateProto(PSSigCreateAPNXObjProc, DSHandler::SigCreateAPNXObj ); fHandlerRec.sigValidate = ASCallbackCreateProto(PSSigValidateProc, DSHandler::SigValidate ); fHandlerRec.sigValidateDialog = NULL; fHandlerRec.sigPropDialog = NULL; fHandlerRec.getLogo = ASCallbackCreateProto(PSGetLogoProc, DSHandler::GetLogo ); // SigVal methods fHandlerRec.sigValGetText = ASCallbackCreateProto(PSSigValGetTextProc, DSSigVal::GetText ); // Once you set up the PSSigCreateAPNXObjProc callback, you must set up this callback // in order to have the PSGetLogoProc callback invoked fHandlerRec.sigValGetAPLabel = ASCallbackCreateProto(PSSigValGetAPLabelProc, DSSigVal::GetAPLabel ); // Cert exchange methods fHandlerRec.exportData = ASCallbackCreateProto(PSExportDataProc, DSHandler::ExportData ); fHandlerRec.importData = NULL; // Encryption methods fHandlerRec.cryptOpenCMSEnvelope = ASCallbackCreateProto(PSOpenCMSEnvelopeProc, DSHandler::openCMSEnvelope); fHandlerRec.cryptGetImplicitRecipients = ASCallbackCreateProto(PSGetImplicitRecipientsProc, DSHandler::getImplicitRecipients); fbHandlerIsInit = true; } /* Register security handler. Note that ownership of this struct is retained by this plug-in */ ASBool bOk = PSRegisterHandler( gExtensionID, &fHandlerRec ); if( !bOk ) { // Destroy fHandlerRec Unregister(); } fbHandlerIsRegistered = true; return true; } // Will remove struct from PubSecHFTs list of handlers void DSHandler::Unregister() { if( fbHandlerIsInit ) { if( fbHandlerIsRegistered ) PSUnregisterHandler( &fHandlerRec ); fbHandlerIsRegistered = false; if( fHandlerRec.engine ) { DSEngine* psEngine = (DSEngine*) fHandlerRec.engine; delete psEngine; fHandlerRec.engine = NULL; } /* Destroy callbacks */ ASCallbackDestroy ( (void *)fHandlerRec.getBoolProperty ); ASCallbackDestroy ( (void *)fHandlerRec.getAtomProperty ); ASCallbackDestroy ( (void *)fHandlerRec.getTextProperty ); ASCallbackDestroy ( (void *)fHandlerRec.getInt32Property ); ASCallbackDestroy ( (void *)fHandlerRec.newEngine ); ASCallbackDestroy ( (void *)fHandlerRec.destroyEngine ); ASCallbackDestroy ( (void *)fHandlerRec.sessionAcquire ); ASCallbackDestroy ( (void *)fHandlerRec.sessionRelease ); ASCallbackDestroy ( (void *)fHandlerRec.sessionReady ); ASCallbackDestroy ( (void *)fHandlerRec.performOperation ); ASCallbackDestroy ( (void *)fHandlerRec.sigAuthenticate ); ASCallbackDestroy ( (void *)fHandlerRec.sigGetSigProperties ); ASCallbackDestroy ( (void *)fHandlerRec.sigGetSigValue ); ASCallbackDestroy ( (void *)fHandlerRec.sigValidate ); ASCallbackDestroy ( (void *)fHandlerRec.sigValidateDialog ); ASCallbackDestroy ( (void *)fHandlerRec.sigCreateAPNXObj ); ASCallbackDestroy ( (void *)fHandlerRec.getLogo ); ASCallbackDestroy ( (void *)fHandlerRec.sigValGetAPLabel); ASCallbackDestroy ( (void *)fHandlerRec.sigValGetText ); ASCallbackDestroy ( (void *)fHandlerRec.exportData ); ASCallbackDestroy ( (void *)fHandlerRec.cryptOpenCMSEnvelope ); ASCallbackDestroy ( (void *)fHandlerRec.cryptGetImplicitRecipients); memset( &fHandlerRec, 0, sizeof(fHandlerRec) ); } fbHandlerIsInit = false; } /************************************************************************* * Common wrapper for engine calls that throw exceptions ************************************************************************/ #define ErrorASText(a,b) ASTextFromPDText( "Error at File: " a " , Line: " #b ) #define PSTRY(myEng,inEng) DSRetCode retCode = kDSParameterError; \ DSEngine* myEng = (DSEngine*)inEng; \ if( !myEng ) myEng = (DSEngine*)fHandlerRec.engine; \ if( !myEng ) return retCode; \ try { #define PSCATCH } catch(...) { \ psEngine->putErrorText( ErrorASText( __FILE__, __LINE__ ) ); \ } return retCode; /************************************************************************* * Class DSHandler basic methods ************************************************************************/ ACCB1 DSRetCode ACCB2 DSHandler::SessionAcquire( PubSecEngine engine, PDDoc pdDoc, PSSessionOpType opType, ASText opText, ASCab cabParams, ASBool bUI ) { PSTRY(psEngine,engine) { retCode = psEngine->sessionAcquire( pdDoc, opType, opText, cabParams, bUI ? true : false ); } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::SessionRelease( PubSecEngine engine, PSSessionOpType opType ) { PSTRY(psEngine,engine) { retCode = psEngine->sessionRelease( opType ); } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::SessionReady( PubSecEngine engine, PSSessionOpType opType ) { PSTRY(psEngine,engine) { retCode = psEngine->sessionReady( opType ); } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::PerformOperation( PubSecEngine engine, PSPerformOpType type, const ASCab cabParams, ASBool bUI ) { DSRetCode retCode = kDSException; DSEngine* psEngine = (DSEngine*)engine; if( !psEngine ) psEngine = (DSEngine*)fHandlerRec.engine; if( !psEngine ) return retCode; try { retCode = psEngine->performOperation( type, cabParams, bUI ); if( ( retCode == kDSParameterError ) && ( cabParams == NULL ) ) retCode = kDSFalse; } catch(...) { psEngine->putErrorText( ErrorASText( __FILE__, __LINE__ ) ); } return retCode; } ACCB1 PubSecEngine ACCB2 DSHandler::NewEngine() { DSEngine* engine = new DSEngine; return (PubSecEngine) engine; } ACCB1 void ACCB2 DSHandler::DestroyEngine( PubSecEngine engine ) { if( engine ) { DSEngine* psEngine = (DSEngine*) engine; delete psEngine; } } ACCB1 ASBool ACCB2 DSHandler::GetBoolProperty( PubSecEngine engine, const char* szPropertyName, const ASBool defaultValue ) { // If engine ever put in DLL then move static responses here // (for example, response to PROP_PSENG_SignInvisible) bool retVal = defaultValue ? true : false; DSEngine* psEngine = (DSEngine*)engine; if( !psEngine ) psEngine = (DSEngine*)fHandlerRec.engine; if( psEngine && szPropertyName ) { try { if( szPropertyName ) { if( !strcmp( szPropertyName, PROP_PSENG_PDSignVisible ) ) { retVal = true; } else if( !strcmp( szPropertyName, PROP_PSENG_PDSignInvisible ) ) { retVal = true; } else if( !strcmp( szPropertyName, PROP_PSENG_PDSignAuthor ) ) { retVal = true; } else if( !strcmp( szPropertyName, PROP_PSENG_PDEncrypt ) ) { retVal = false; } else if( !strcmp( szPropertyName, PROP_PSENG_PDDecrypt ) ) { retVal = false; } else if( !strcmp( szPropertyName, PROP_PSENG_ExportContact ) ) { retVal = true; } else if( !strcmp( szPropertyName, PROP_PSENG_SignFormatPKCS1 ) ) { retVal = true; } else if( !strcmp( szPropertyName, PROP_PSENG_SignFormatPKCS7 ) ) { retVal = false; } else if( !strcmp( szPropertyName, PROP_PSENG_SignFormatPKCS1Digest ) ) { retVal = false; } else if( !strcmp( szPropertyName, PROP_PSENG_SignFormatPKCS7DetachedDigest ) ) { retVal = false; } else if( !strcmp( szPropertyName, PROP_PSENG_CosSign ) ) { retVal = true; } else if( !strcmp (szPropertyName, PROP_PSENG_PDSignCustomAP )) { retVal = true; } else { retVal = ((DSEngine*)psEngine)->getBoolProperty( szPropertyName, defaultValue ? true : false ); } } } catch (...) { }; } return retVal ? true : false; } ACCB1 ASAtom ACCB2 DSHandler::GetAtomProperty( PubSecEngine engine, const char* szPropertyName ) { // Note that we do not call engine unless we have to. // This allows possibility for engine code to be put in DLL that gets loaded later ASAtom retVal = ASAtomNull; if( szPropertyName ) { if( !strcmp( szPropertyName, PROP_PSENG_ASAtom_DigSigHandlerName ) ) retVal = fHandlerName; else if( !strcmp( szPropertyName, PROP_PSENG_ASAtom_PubSecHandlerName ) ) retVal = fHandlerName; } (void)engine; // Deliberately unused parameter engine. return retVal; } ACCB1 ASInt32 ACCB2 DSHandler::GetInt32Property( PubSecEngine engine, const char* szPropertyName, const ASInt32 defaultValue ) { ASInt32 retVal = defaultValue; if( szPropertyName ) { // First deal with handler generic properties, then call // engine for engine specific properities if( !strcmp( szPropertyName, PROP_PSENG_ASInt32_HandlerVersion ) ) { retVal = DOCSIGN_CURRENT_VERSION; } else { DSEngine* psEngine = (DSEngine*)engine; if( !psEngine ) psEngine = (DSEngine*)fHandlerRec.engine; if( psEngine ) { try { retVal = ((DSEngine*)psEngine)->getInt32Property( szPropertyName, defaultValue ); } catch (...) { }; } } } return retVal; } ACCB1 ASText ACCB2 DSHandler::GetTextProperty( PubSecEngine engine, const char* szPropertyName, const ASInt32 index ) { ASText retVal = NULL; if (!strcmp( szPropertyName, PROP_PSENG_ASAtom_PubSecHandlerName) ) { // Language independent Handler name retVal = ASTextFromPDText( DOCSIGN_HANDLER_NAME ); } else if (!strcmp( szPropertyName, PROP_PSENG_ASAtom_DigSigHandlerName) ) { retVal = ASTextFromPDText( DOCSIGN_HANDLER_NAME ); } else if (!strcmp( szPropertyName, PROP_PSENG_HandlerUIName) ) { // Language DEpendent handler name retVal = ASTextFromPDText( DOCSIGN_HANDLER_NAME ); } else { DSEngine* psEngine = (DSEngine*)engine; if( !psEngine ) psEngine = (DSEngine*)fHandlerRec.engine; if( psEngine ) { try { retVal = ((DSEngine*)psEngine)->getTextProperty( szPropertyName, index ); } catch (...) { }; } } return retVal; } /************************************************************************* * Encryption support routines ************************************************************************/ ACCB1 DSRetCode ACCB2 DSHandler::openCMSEnvelope ( PubSecEngine engine, ASUns8* inCMSEnvelope, ASUns32 inCMSEnvelopeSize, ASUns8** pOutData, ASUns32* pOutDataSize, ASBool inUIAllowed ) { PSTRY(psEngine, engine) { if(inCMSEnvelope != NULL && pOutData != NULL && pOutDataSize != NULL) retCode = psEngine->openCMSEnvelope(inCMSEnvelope, inCMSEnvelopeSize, pOutData, pOutDataSize, inUIAllowed); } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::getImplicitRecipients (PubSecEngine engine, ASCab outCertList, ASBool inUIAllowed ) { PSTRY(psEngine, engine) { if(outCertList != NULL) { psEngine->getImplicitRecipients(outCertList, inUIAllowed); retCode = kDSOk; } } PSCATCH; } /************************************************************************* * DigSigHFT routines ************************************************************************/ ACCB1 DSRetCode ACCB2 DSHandler::SigGetSigProperties( PubSecEngine engine, PSSigSigPropParams params ) { PSTRY(psEngine,engine) { if( params ) { psEngine->sigGetSigProperties( params); retCode = kDSOk; } } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::SigAuthenticate( PubSecEngine engine, const PDDoc pdDoc, ASCab inESParams, ASBool bUI ) { PSTRY(psEngine,engine) { retCode = psEngine->sigAuthenticate( pdDoc, inESParams, bUI ? true : false ); } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::SigGetSigValue( PubSecEngine engine, PSSigGetSigValueParams inOutParams ) { PSTRY(psEngine,engine) { if( inOutParams ) { psEngine->sigGetSigValue( inOutParams); retCode = kDSOk; } } PSCATCH; } ACCB1 DSRetCode ACCB2 DSHandler::SigValidate( PubSecEngine engine, PSSigValidateParams params ) { PSTRY(psEngine,engine) { if( params ) { psEngine->sigValidate( params ); retCode = kDSOk; } } PSCATCH; } /************************************************************************* * DSHandler::ExportData ************************************************************************/ ACCB1 DSRetCode ACCB2 DSHandler::ExportData( PubSecEngine engine, PSExportDataType dataType, ASCab outCab, ASBool bUI ) { PSTRY(psEngine,engine) { if( outCab ) { psEngine->exportData( dataType, outCab, bUI ? true : false ); retCode = kDSOk; } } PSCATCH; } /************************************************************************* * DSHander::SigCreateAPNXObj * Returns a signature appearance that is put into the /AP dictionry * /N entry. ************************************************************************/ ACCB1 DSRetCode ACCB2 DSHandler::SigCreateAPNXObj( PubSecEngine engine, CosObj *pOutXObj, PSSigPDDocParams docParams, PSAPSigType sigType ) { CosObj xObjArray[4]; // XObject Array for the apprearance layers ASFixedMatrix Matrix[4]; // XObject positions ASBool layerFlags[4]; // flags indicating whether the corresponding layers will be displayed PDDoc pdDoc = docParams->pdDoc; CosDoc cosDoc = PDDocGetCosDoc(pdDoc); PDAnnot pdAnnot = PDAnnotFromCosObj(docParams->sigAnnot); // set up AP // get border and background colors PDColorValueRec cBorder, cBgrd; AFPDWidgetGetAreaColors(pdAnnot, &cBorder, &cBgrd); // get widget border AFPDWidgetBorderRec border; AFPDWidgetGetBorder(pdAnnot, &border); // determine bbox dependent on rotation ASFixedRect annotRectRec; PDAnnotGetRect ( pdAnnot, &annotRectRec ); // get bbox width and height ASFixed width = annotRectRec.right - annotRectRec.left; ASFixed height = annotRectRec.top - annotRectRec.bottom; // get rotation AVDoc avDoc = AVDocFromPDDoc(pdDoc); AVPageView pgView = AVDocGetPageView(avDoc); PDPage pdPage = AVPageViewGetPage(pgView); PDRotate pdRotate = PDPageGetRotate(pdPage); // Compensate for rotation ASFixedRect bboxRec; switch(pdRotate) { case pdRotate90: case pdRotate270: DocSignFixedRect(&bboxRec, 0, 0, height, width); break; default: DocSignFixedRect(&bboxRec, 0, 0, width, height); break; } // layout individual layers (n0 is created from acroforms background info) // All but n2 layer can be NULL, which will cause defaults to be used. xObjArray[0] = CosNewNull(); // for n1 xObjArray[1] = CreateN2XObject(cosDoc, docParams->sigField, docParams->sigAnnot, &bboxRec); // for n2 xObjArray[2] = CosNewNull(); // for n3 xObjArray[3] = CosNewNull(); // for n4 //set ASFixedMatrixP of xObjects for(int i = 0; i < 4; i++) DocSignFixedMatrixSetIdentity( &Matrix[i] ); // set flag for each XObject // The flags indicates whether any of the layers are optional. // You must have n1 and n3 generated if you want your PSSigValGetAPLabelProc callback invoked layerFlags[0] = false; layerFlags[1] = false; layerFlags[2] = false; layerFlags[3] = true; // Create multi layered XObject DSAPCreateLayeredStreamExParamsRec params; memset(&params, 0x00, sizeof(DSAPCreateLayeredStreamExParamsRec)); params.XObjects = xObjArray; params.cosDoc = cosDoc; params.layerMatrices = Matrix; params.border = &border; params.cBorder = &cBorder; params.cBackGnd = &cBgrd; params.width = width; params.height = height; params.pdr = pdRotate; params.layerFlags = layerFlags; params.layerNNum = 4; CosObj tmpObj = DigSigAPCreateLayeredStreamEx(&params); *pOutXObj = DocSignStreamToXObject(tmpObj, NULL, NULL, true); return kDSOk; } /************************************************************************* * DSHandler::GetLogo * Returns string that is used to create signature background ************************************************************************/ ACCB1 void ACCB2 DSHandler::GetLogo( ASAtom label, const char* *pcLogo, const ASFixedRect* *pRect ) { if( pRect ) *pRect = NULL; if( pcLogo ) *pcLogo = NULL; if( label == DsSigValValid_K) { if( pRect ) *pRect = &stmDoubleValidBBox; if( pcLogo ) *pcLogo = stmDoubleValidData; } else if( label == DsSigValUnknown_K) { if( pRect) *pRect = &stmUnknownBBox; if( pcLogo ) *pcLogo = stmUnknownData; } else if ( label == DsSigValInvalid_K) { if( pRect) *pRect = &stmInvalidBBox; if( pcLogo ) *pcLogo = stmInvalidData; } } /************************************************************************* * Acrobat Logo ************************************************************************/ // Precise bbox of Acrobat logo stream stmLogoLogo const ASFixedRect stmLogoBBox = { 0, 0x00630000, 0x00630000, 0 }; // 0,0,99,99 // Stream data for Acrobat Logo const char* const stmLogoData = "% Acrobat Logo\n" "q\n" "0 J 0 j 4 M []0 d\n" "1 0 0 1 0 -1 cm\n" "1 0.85 0.85 rg\n" /* faded red */ "0 i\n" "96.1 24.7 m\n" "96.4 24.7 l\n" "96.8 24.7 97 24.6 97 24.3 c\n" "97 24 96.7 23.9 96.4 23.9 c\n" "96.1 23.9 l\n" "96.1 24.7 l\n" "94.1 23.7 m\n" "94.1 22.4 95.2 21.4 96.5 21.4 c\n" "98 21.4 99 22.4 99 23.7 c\n" "99 25.1 98 26.1 96.5 26.1 c\n" "95.2 26.1 94.1 25.1 94.1 23.7 c\n" "96.1 23.5 m\n" "96.4 23.5 l\n" "96.7 23.5 96.9 23.2 97 22.9 c\n" "97.1 22.4 l\n" "97.6 22.4 l\n" "97.5 22.9 l\n" "97.5 23.3 97.3 23.6 97 23.7 c\n" "97.3 23.8 97.6 23.9 97.6 24.3 c\n" "97.5 24.9 97.2 25.3 96.4 25.3 c\n" "95.6 25.3 l\n" "95.6 22.4 l\n" "96.1 22.4 l\n" "96.1 23.5 l\n" "94.6 23.7 m\n" "94.6 24.8 95.5 25.6 96.5 25.6 c\n" "97.7 25.6 98.4 24.8 98.4 23.7 c\n" "98.4 22.7 97.7 21.9 96.5 21.9 c\n" "95.5 21.9 94.6 22.7 94.6 23.7 c\n" "98.4 30.4 m\n" "98.7 31.1 99 31.4 99 32.1 c\n" "99 36 92.2 38 82.3 38 c\n" "78.9 38 74.8 37.6 70.3 37.3 c\n" "67.2 39 64.1 41 61.3 43.1 c\n" "54.2 49 49 58.5 45.9 68.1 c\n" "47.3 76 47.3 82.8 47.6 90.3 c\n" "46.9 86.9 46.2 81.4 44.6 73.2 c\n" "42.8 79.1 42.1 84.9 42.1 89.4 c\n" "42.1 90.3 42.1 96.5 44.2 97.9 c\n" "45.6 97.2 47.3 95.8 47.6 92.1 c\n" "49 98.5 46.6 98.5 42.8 98.5 c\n" "39.4 98.5 39.4 90.3 39.4 88.3 c\n" "39.4 85.5 39.8 82.1 40.4 78.6 c\n" "41 75.2 41.8 71.4 42.8 67.8 c\n" "42.8 62.3 16.8 1.2 2.7 1.2 c\n" "2.1 4.7 8.9 14.3 18.5 21.6 c\n" "4.8 14.3 0.8 6.1 0.8 2.6 c\n" "0.8 0.6 4.8 -0.1 5.1 -0.1 c\n" "9.9 -0.1 17.4 7.1 28.1 25.6 c\n" "39.8 29.7 55.1 32.7 68.8 34.1 c\n" "77.4 29.7 87 27 92.8 27 c\n" "95.9 27 97.6 27.7 98 29.3 c\n" "97.3 29 96.2 28.6 94.9 28.6 c\n" "90.4 28.6 82.5 31.1 74.7 34.8 c\n" "81.9 35.3 98.7 36 98.4 30.4 c\n" "28.1 25.9 m\n" "39.4 45.5 42.8 55.4 44.6 62.3 c\n" "51.4 45.2 60.3 39.4 65.1 36.6 c\n" "53.5 34.6 40.1 31.1 28.1 25.9 c\n" "h f\n" "Q"; /************************************************************************* * DSHander::CreateN2XObject * Returns an XObject for n2 ************************************************************************/ CosObj DSHandler::CreateN2XObject( CosDoc cosDoc, const CosObj sigField, const CosObj sigAnnot, const ASFixedRect* const pBBoxRec ) { const char * strText = "DocSign custom appearance text."; DSAPTextEntryRec inText; memset(&inText, 0x00, sizeof(DSAPTextEntryRec)); inText.next = NULL; inText.heightRatio = 0x00010000; // 100% inText.text = ASTextFromScriptText(strText, kASRomanScript); CosObj cosObj = DigSigAPCreateCompositeTextXObj(cosDoc, &inText, pBBoxRec, sigField, sigAnnot); return cosObj; } /************************************************************************* * DocSign support functions ************************************************************************/ void DSHandler::DocSignFixedRect(ASFixedRect *fr, ASFixed fxLeft, ASFixed fxBottom, ASFixed fxRight, ASFixed fxTop) { fr->left = fxLeft; fr->top = fxTop; fr->right = fxRight; fr->bottom = fxBottom; } CosObj DSHandler::DocSignStreamToXObject(CosObj strm, ASFixedMatrixP matrix, const ASFixedRect* const bbox, ASBool bUseOldObj) { CosDoc cosDoc; CosObj co; if(CosObjGetType(strm) != CosNull) { if(!bUseOldObj) strm = CosObjCopy(strm, CosObjGetDoc(strm), true); cosDoc = CosObjGetDoc(strm); co = CosStreamDict(strm); CosDictPut(co, Type_K, CosNewName(cosDoc, false, XObject_K)); CosDictPut(co, Subtype_K, CosNewName(cosDoc, false, Form_K)); CosDictPut(co, FormType_K, CosNewInteger(cosDoc, false, 1)); if(bbox) DocSignCosPutRect(cosDoc, co, BBox_K, bbox); if(!CosDictKnown(co, Matrix_K) || matrix) { if(matrix){ ASFixedMatrix fm; if(CosDictKnown(co, Matrix_K)) { ASFixedMatrix om; DocSignCosGetMatrix(co, Matrix_K, &om); ASFixedMatrixConcat(&fm, matrix, &om); } else fm = *matrix; DocSignCosPutMatrix(cosDoc, co, Matrix_K, &fm); } else { ASFixedMatrix fmId; DocSignFixedMatrixSetIdentity(&fmId); DocSignCosPutMatrix(cosDoc, co, Matrix_K, &fmId); } } } return strm; } void DSHandler::DocSignCosPutRect(CosDoc cd, CosObj coParent, ASAtom asaKey, const ASFixedRect *fr) { CosObj coRect; ACROASSERT(fr); coRect = CosNewArray(cd, false, 4); CosArrayPut(coRect, 0, CosNewFixed(cd, false, fr->left)); CosArrayPut(coRect, 1, CosNewFixed(cd, false, fr->bottom)); CosArrayPut(coRect, 2, CosNewFixed(cd, false, fr->right)); CosArrayPut(coRect, 3, CosNewFixed(cd, false, fr->top)); CosDictPut(coParent, asaKey, coRect); } void DSHandler::DocSignCosPutMatrix(CosDoc cd, CosObj coParent, ASAtom asaKey, const ASFixedMatrix *m) { CosObj coMatrix; ACROASSERT(m); coMatrix = CosNewArray(cd, false, 6); CosArrayPut(coMatrix, 0, CosNewFixed(cd, false, m->a)); CosArrayPut(coMatrix, 1, CosNewFixed(cd, false, m->b)); CosArrayPut(coMatrix, 2, CosNewFixed(cd, false, m->c)); CosArrayPut(coMatrix, 3, CosNewFixed(cd, false, m->d)); CosArrayPut(coMatrix, 4, CosNewFixed(cd, false, m->h)); CosArrayPut(coMatrix, 5, CosNewFixed(cd, false, m->v)); CosDictPut(coParent, asaKey, coMatrix); } void DSHandler::DocSignCosGetMatrix(CosObj coParent, ASAtom asaKey, ASFixedMatrix *m) { CosObj coMatrix; ACROASSERT(m); /* Set to identity matrix. */ DocSignFixedMatrixSetIdentity(m); coMatrix = CosDictGet(coParent, asaKey); if (CosObjGetType(coMatrix) == CosArray) { m->a = CosFixedValue(CosArrayGet(coMatrix, 0)); m->b = CosFixedValue(CosArrayGet(coMatrix, 1)); m->c = CosFixedValue(CosArrayGet(coMatrix, 2)); m->d = CosFixedValue(CosArrayGet(coMatrix, 3)); m->h = CosFixedValue(CosArrayGet(coMatrix, 4)); m->v = CosFixedValue(CosArrayGet(coMatrix, 5)); } } void DSHandler::DocSignFixedMatrixSet(ASFixedMatrix *fm, ASFixed a, ASFixed b, ASFixed c, ASFixed d, ASFixed h, ASFixed v) { if( fm ) { fm->a = a; fm->b = b; fm->c = c; fm->d = d; fm->h = h; fm->v = v; } }
[ "tisn05@gmail.com" ]
tisn05@gmail.com
cba3d843b03f9dd7cd210adf6479dfbfe46b6ccf
a756eed9030c5afa645436412d777a1774357c70
/CP/TESTING POINTERS.cpp
cf70147d716db8a2f514bd69e93167193863d1b7
[]
no_license
jainsourav43/DSA
fc92faa7f8e95151c8f0af4c69228d4db7e1e5ce
deb46f70a1968b44bb28389d01b35cb571a8c293
refs/heads/master
2021-05-25T09:13:42.418930
2020-06-30T07:36:56
2020-06-30T07:36:56
126,943,860
0
1
null
2020-06-30T07:36:57
2018-03-27T07:07:51
C++
UTF-8
C++
false
false
906
cpp
#include<iostream> using namespace std; #include<bits/stdc++.h> #define ll long long int main() { //code int t; cin>>t; while(t--) { string s; cin>>s; int i,len=s.length(),n=len,max1,st; int po,minv; vector<int> ans; int x=1; if(s[0]=='I') { ans.push_back(1); ans.push_back(2); minv=3; po=1; } else { ans.push_back(2); ans.push_back(1); minv=3; po=0; } for(i=1;i<len;i++) { if(s[i]=='I') { ans.push_back(minv); minv++; po=i+1; } else { ans.push_back(ans[i]); for(int j=po;j<=i;j++) { ans[j]++; } minv++; } } for(i=0;i<ans.size();i++) { cout<<ans[i]; } cout<<endl; } return 0; }
[ "jainsourav43@gmail.com" ]
jainsourav43@gmail.com
dba6b39425fc5f500154cf509318c068c4cf3bb4
7a92e39f0cbb62bf4e480ea33faa90f2dd9f42a4
/include/rectangle.h
73d12f9a8a2c87da72a79ddab7239361f0c8f11b
[ "MIT" ]
permissive
Ogravius/CarGame
e2c686866e27c2f5668be021f70138d00ee27a4a
af7329780e55e550dd787f6dd233bb7a079a7d84
refs/heads/master
2022-11-03T05:00:31.858626
2017-10-25T00:03:20
2017-10-25T00:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,826
h
#pragma once #define _USE_MATH_DEFINES #include <math.h> #include <SFML/Graphics.hpp> //!This class is used to create an abstract base class of the rectangle. class Rectangle : public sf::RectangleShape { protected: /*!Formula converting degrees to radians.*/ /**@brief (float)M_PI / 180.f; */ float fDegToRad; /*!Half extents needed to declare vertices.*/ sf::Vector2f halfExtents; /*!Local vertices of the rectangle.*/ std::vector<sf::Vertex> localVertices; /*!Global vertices of the rectangle.*/ std::vector<sf::Vertex> globalVertices; /*!Face normals of the rectangle.*/ std::vector<sf::Vector2f> normals; /*!One time setup of the local vertices.*/ void setupLocalVertices(); /*!One time setup of the global vertices including rotation.*/ void updateGlobalVertices(float rotation); public: /*!Initializer.*/ Rectangle(){}; /*!Constructor.*/ /**@param position = Position of the rectangle. @param dimensions = Size of the rectangle*/ Rectangle(const sf::Vector2f& position, const sf::Vector2f& dimensions); /*!Constructor.*/ /**@param position = Position of the rectangle. @param dimensions = Size of the rectangle. @param texture = Texture to load.*/ Rectangle(const sf::Vector2f& position, const sf::Vector2f& dimensions, const sf::Texture& texture); /*!Returns normals of said rectangle.*/ /**@return normals = Returns face normals of the rectangle.*/ std::vector<sf::Vector2f> getNormals() const; /*!Returns global vertices of said rectangle.*/ /**@return globalVertices = Returns global vertices of the rectangle.*/ std::vector<sf::Vertex> getGlobalVertices() const; /*!Updates face normals based on the given rotation.*/ /**@param rotation = Rotation needed so that normals can be updated whenever the rectangle rotates.*/ void updateNormals(float rotation); //!< };
[ "jerzysciechowski345@gmail.com" ]
jerzysciechowski345@gmail.com
bc52d369583938ea4250894863d8d4efc99b259e
a2badfee532cf096e9bd12b0892fdce3b49e54c8
/src/buildorders/9poolspeedlingmuta.cpp
d42f715babddd69d0c65ec6120fa2b5c01ddaa56
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
unghee/TorchCraftAI
5e5e9b218990db8042198a12aeef78651b49f67b
e6d596483d2a9a8b796765ed98097fcae39b6ac0
refs/heads/master
2022-04-16T12:12:10.289312
2020-04-20T02:55:22
2020-04-20T02:55:22
257,154,995
0
0
MIT
2020-04-20T02:51:19
2020-04-20T02:51:18
null
UTF-8
C++
false
false
3,480
cpp
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "base.h" #include "registry.h" namespace cherrypi { class ABBO9PoolSpeedLingMuta : public ABBOBase { public: using ABBOBase::ABBOBase; Position nextSunkenPos; bool waitForSpire = false; virtual void preBuild2(autobuild::BuildState& st) override { using namespace buildtypes; using namespace autobuild; postBlackboardKey(Blackboard::kMinScoutFrameKey, 0); bool attack = armySupply >= enemyArmySupply || !state_->unitsInfo().myUnitsOfType(Zerg_Mutalisk).empty(); postBlackboardKey("TacticsAttack", attack); nextSunkenPos = findSunkenPos(Zerg_Sunken_Colony); waitForSpire = false; if (armySupply >= enemyArmySupply) { if (!state_->unitsInfo().myUnitsOfType(Zerg_Spire).empty() && state_->unitsInfo().myCompletedUnitsOfType(Zerg_Spire).empty()) { int larvaTime = 342 * ((state_->unitsInfo().myUnitsOfType(Zerg_Hatchery).size() + state_->unitsInfo().myUnitsOfType(Zerg_Lair).size()) * 3 - state_->unitsInfo().myUnitsOfType(Zerg_Larva).size() + 1); for (Unit* u : state_->unitsInfo().myUnitsOfType(Zerg_Spire)) { if (u->remainingBuildTrainTime <= larvaTime) { waitForSpire = true; break; } } if (st.gas > st.minerals) { waitForSpire = true; } } } } virtual void buildStep2(autobuild::BuildState& st) override { using namespace buildtypes; using namespace autobuild; if (hasOrInProduction(st, Zerg_Creep_Colony)) { build(Zerg_Sunken_Colony); return; } if (waitForSpire) { build(Zerg_Mutalisk); buildN(Zerg_Drone, 12); return; } auto placeSunkens = [&](int n) { if (countPlusProduction(st, Zerg_Sunken_Colony) < n) { build(Zerg_Creep_Colony, nextSunkenPos); } }; if (countPlusProduction(st, Zerg_Sunken_Colony) && enemyArmySupply * 0.75 > armySupply) { placeSunkens(4); build(Zerg_Zergling); buildN(Zerg_Drone, 14); placeSunkens(3); } else { placeSunkens(2); build(Zerg_Zergling); } if (st.gas >= 100.0) { build(Metabolic_Boost); buildN(Zerg_Lair, 1); } int mutaCount = countPlusProduction(st, Zerg_Mutalisk); if (has(st, Zerg_Lair)) { build(Zerg_Mutalisk); if (enemyRace == +tc::BW::Race::Zerg && (mutaCount < 6 || enemyMutaliskCount >= mutaCount / 2)) { buildN(Zerg_Scourge, 1 + mutaCount / 2); } } if (enemyArmySupply > armySupply + countPlusProduction(st, Zerg_Sunken_Colony) * 3) { placeSunkens(4); } if (armySupply >= enemyArmySupply || countPlusProduction(st, Zerg_Sunken_Colony)) { buildN(Zerg_Drone, 11); if (enemyMutaliskCount > mutaCount && enemyMutaliskCount < 9) { buildN(Zerg_Scourge, std::min(enemyMutaliskCount + 2, 8)); } } if (st.frame < 15 * 60 * 4) { buildN(Zerg_Zergling, 6); } buildN(Zerg_Extractor, 1); if (countPlusProduction(st, Zerg_Spawning_Pool) == 0) { build(Zerg_Spawning_Pool); buildN(Zerg_Drone, 9); } } }; REGISTER_SUBCLASS_3(ABBOBase, ABBO9PoolSpeedLingMuta, UpcId, State*, Module*); } // namespace cherrypi
[ "danthe3rd@users.noreply.github.com" ]
danthe3rd@users.noreply.github.com
05e8b259cf8a932a63843ebd4140f90a8643ea9f
8b8402b10e860e2b0c9198a42d7e080b9682ee19
/three/main.cpp
0fa4232f5267ed4470cfa37827d4731515312a58
[]
no_license
CapSmollet/Deadline25.11.2019-23.59
7f20544e7a17090174ec0f62713e03dfbd17d346
959d4bd8de7c8b6ddc52a7347e8cc753b6818031
refs/heads/master
2020-09-17T06:15:28.234143
2019-11-29T23:11:19
2019-11-29T23:11:19
224,016,253
0
0
null
null
null
null
UTF-8
C++
false
false
1,434
cpp
/* Напишите эффективную функцию, выписывающую из массива длины n все элементы, у которых количество двоек в троичной записи меньше k. * Функция должна возвращать общее количество двоек в троичной записи всех чисел массива. В комментариях напишите, почему перебор - эффективный * Перебор эффективный, потому что не существует более эффективного */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int n, k, in; vector <int> vec; bool cmp(int a, int b) { if (a > b) return true; } int counter(int x) { int num = 0; while (x % 3 != x) { if (x % 3 == 2) num++; x /= 3; } if (x % 3 == 2) num++; return num; } int del_and_sum(vector <int>& x) { int sum = 0; sort(x.begin(), x.end(), cmp); int i = 0; while (x[i] >= k) { i++; } x.resize(i); for (int j = 0; j < i; j++) { sum += x[j]; } return sum; } int main() { cin >> n >> k; vec.resize(n); for (int i = 0; i < n; ++i) { cin >> in; vec[i] = counter(in); } cout << del_and_sum(vec); return 0; }
[ "muaxim@gmail.com" ]
muaxim@gmail.com
41ff0421995d0a091a9113f141c2b60b5de3ed15
1675ca738aeefa77827a9ded8543b3bb040cfd3d
/include/Card.h
63a65da1472cd6f0a1f2577a5b732eac252a277a
[ "MIT" ]
permissive
cottonke/solitaireSolver
cd38f2936b9bba563def1c588d97b6904d8f483b
6a32e6f075cf872479c2ff694ea9d6f5674469da
refs/heads/master
2021-01-10T22:58:57.760726
2016-10-10T02:53:41
2016-10-10T02:53:41
70,435,790
0
0
null
null
null
null
UTF-8
C++
false
false
1,359
h
#ifndef CARD_H #define CARD_H enum Suit : uint8_t { Spades = 0, Clubs, Hearts, Diamonds }; enum Value : uint8_t { Ace = 0, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }; class Card { public: Card(Suit s, Value v, bool faceUp = false): m_Suit(s), m_Value(v), m_IsFaceUp(faceUp) {}; virtual ~Card() {}; Card(const Card&) = default; Card& operator=(const Card&) = default; Card(Card&&) = default; Card& operator=(Card&&) = default; std::string getLongString() const; std::string getShortString() const; operator std::string() const { return getLongString(); } inline uint8_t getCardNum() const { return ((static_cast<uint8_t>(m_Suit) * 13) + (static_cast<uint8_t>(m_Value))); } inline void turnDown() { m_IsFaceUp = false; } inline void turnUp() { m_IsFaceUp = true; } inline void flip() { m_IsFaceUp = !m_IsFaceUp; } inline bool isFaceUp() const { return m_IsFaceUp; } inline Suit getSuit() const { return m_Suit; } inline Value getValue() const { return m_Value; } protected: private: Card() = delete; bool m_IsFaceUp; Suit m_Suit; Value m_Value; }; #endif
[ "cottonke@gmail.com" ]
cottonke@gmail.com
f47853eae25e5ec6b2c646df6da57eb541cdd06f
bd7d4c148df27f8be6649d313efb24f536b7cf34
/src/armnn/backends/NeonWorkloads/NeonPermuteWorkload.hpp
06b2dc692b391059def594d983cff749e9284bf4
[ "MIT" ]
permissive
codeaudit/armnn
701e126a11720760ee8209cc866aa095554696c2
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
refs/heads/master
2020-03-29T00:48:17.399665
2018-08-31T08:22:23
2018-08-31T08:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,318
hpp
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #pragma once #include "backends/Workload.hpp" #include "backends/WorkloadData.hpp" #include "backends/NeonWorkloadUtils.hpp" #include <armnn/TypesUtils.hpp> #include <arm_compute/runtime/NEON/functions/NEPermute.h> #include <string> namespace armnn { arm_compute::Status NeonPermuteWorkloadValidate(const TensorInfo& input, const TensorInfo& output, const PermuteDescriptor& descriptor); template <armnn::DataType... DataTypes> class NeonPermuteWorkload : public TypedWorkload<PermuteQueueDescriptor, DataTypes...> { public: static const std::string& GetName() { static const std::string name = std::string("NeonPermuteWorkload"); return name; } NeonPermuteWorkload(const PermuteQueueDescriptor& descriptor, const WorkloadInfo& info); void Execute() const override; private: using TypedWorkload<PermuteQueueDescriptor, DataTypes...>::m_Data; mutable arm_compute::NEPermute m_PermuteFunction; }; using NeonPermuteFloatWorkload = NeonPermuteWorkload<DataType::Float16, DataType::Float32>; using NeonPermuteUint8Workload = NeonPermuteWorkload<DataType::QuantisedAsymm8>; } // namespace armnn
[ "telmo.soares@arm.com" ]
telmo.soares@arm.com
d5eeace921796e21aa74e1d8cd257f3f9a7cbe88
147e5ff85d832109dfe1ca7f6de33d4b2c57e298
/src/item.cpp
2cfcebd3686df8f5b93e0ecffe40c6265012177e
[]
no_license
LeandroPerrotta/DarghosTFS04_86_v3
3b2cdd6bb23e67752a36a967e1757a29495109e2
8757fdf28e2e0df8173492a836d3e97d8acd5bde
refs/heads/master
2023-06-19T18:23:41.369859
2021-07-16T12:37:57
2021-07-16T12:37:57
386,521,291
0
0
null
null
null
null
UTF-8
C++
false
false
39,677
cpp
//////////////////////////////////////////////////////////////////////// // OpenTibia - an opensource roleplaying game //////////////////////////////////////////////////////////////////////// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //////////////////////////////////////////////////////////////////////// #include "otpch.h" #include <iostream> #include <iomanip> #include "item.h" #include "container.h" #include "depot.h" #include "teleport.h" #include "trashholder.h" #include "mailbox.h" #include "luascript.h" #include "combat.h" #include "house.h" #include "beds.h" #include "actions.h" #include "configmanager.h" #include "game.h" #include "movement.h" extern Game g_game; extern ConfigManager g_config; extern MoveEvents* g_moveEvents; Items Item::items; Item* Item::CreateItem(const uint16_t type, uint16_t amount/* = 0*/) { const ItemType& it = Item::items[type]; if(it.group == ITEM_GROUP_DEPRECATED) { #ifdef __DEBUG__ std::clog << "[Error - Item::CreateItem] Item " << it.id << " has been declared as deprecated" << std::endl; #endif return NULL; } if(!it.id) return NULL; Item* newItem = NULL; if(it.isDepot()) newItem = new Depot(type); else if(it.isContainer()) newItem = new Container(type); else if(it.isTeleport()) newItem = new Teleport(type); else if(it.isMagicField()) newItem = new MagicField(type); else if(it.isDoor()) newItem = new Door(type); else if(it.isTrashHolder()) newItem = new TrashHolder(type, it.magicEffect); else if(it.isMailbox()) newItem = new Mailbox(type); else if(it.isBed()) newItem = new BedItem(type); else if(it.id >= 2210 && it.id <= 2212) newItem = new Item(type - 3, amount); else if(it.id == 2215 || it.id == 2216) newItem = new Item(type - 2, amount); else if(it.id >= 2202 && it.id <= 2206) newItem = new Item(type - 37, amount); else if(it.id == 2640) newItem = new Item(6132, amount); else if(it.id == 6301) newItem = new Item(6300, amount); else newItem = new Item(type, amount); newItem->addRef(); return newItem; } Item* Item::CreateItem(PropStream& propStream) { uint16_t type; if(!propStream.getShort(type)) return NULL; return Item::CreateItem(items.getRandomizedItem(type), 0); } bool Item::loadItem(xmlNodePtr node, Container* parent) { if(xmlStrcmp(node->name, (const xmlChar*)"item")) return false; int32_t intValue; std::string strValue; Item* item = NULL; if(readXMLInteger(node, "id", intValue)) item = Item::CreateItem(intValue); if(!item) return false; if(readXMLString(node, "attributes", strValue)) { StringVec v, attr = explodeString(strValue, ";"); for(StringVec::iterator it = attr.begin(); it != attr.end(); ++it) { v = explodeString((*it), ","); if(v.size() < 2) continue; if(atoi(v[1].c_str()) || v[1] == "0") item->setAttribute(v[0], atoi(v[1].c_str())); else item->setAttribute(v[0], v[1]); } } //compatibility if(readXMLInteger(node, "subtype", intValue) || readXMLInteger(node, "subType", intValue)) item->setSubType(intValue); if(readXMLInteger(node, "actionId", intValue) || readXMLInteger(node, "actionid", intValue) || readXMLInteger(node, "aid", intValue)) item->setActionId(intValue); if(readXMLInteger(node, "uniqueId", intValue) || readXMLInteger(node, "uniqueid", intValue) || readXMLInteger(node, "uid", intValue)) item->setUniqueId(intValue); if(readXMLString(node, "text", strValue)) item->setText(strValue); if(item->getContainer()) loadContainer(node, item->getContainer()); if(parent) parent->addItem(item); return true; } bool Item::loadContainer(xmlNodePtr parentNode, Container* parent) { xmlNodePtr node = parentNode->children; while(node) { if(node->type != XML_ELEMENT_NODE) { node = node->next; continue; } if(!xmlStrcmp(node->name, (const xmlChar*)"item") && !loadItem(node, parent)) return false; node = node->next; } return true; } Item::Item(const uint16_t type, uint16_t amount/* = 0*/): ItemAttributes(), id(type) { raid = NULL; loadedFromMap = false; setItemCount(1); setDefaultDuration(); const ItemType& it = items[id]; if(it.isFluidContainer() || it.isSplash()) setFluidType(amount); else if(it.stackable) { if(amount) setItemCount(amount); else if(it.charges) setItemCount(it.charges); } else if(it.charges) setCharges(amount ? amount : it.charges); #ifdef __DARGHOS_CUSTOM__ if(it.wieldPosition == SLOT_HEAD) { int16_t durability = Items::helmetsDurability[it.m_rarity][it.m_quality]; setDurability(durability, durability); } else if(it.wieldPosition == SLOT_ARMOR) { int16_t durability = Items::chestsDurability[it.m_rarity][it.m_quality]; setDurability(durability, durability); } else if(it.wieldPosition == SLOT_LEGS) { int16_t durability = Items::legsDurability[it.m_rarity][it.m_quality]; setDurability(durability, durability); } else if(it.wieldPosition == SLOT_FEET) { int16_t durability = Items::feetsDurability[it.m_rarity][it.m_quality]; setDurability(durability, durability); } else if(it.weaponType == WEAPON_WAND) { int16_t durability = Items::lightItemsDurability[it.m_rarity]; setDurability(durability, durability); } else if((it.weaponType == WEAPON_AXE || it.weaponType == WEAPON_SWORD || it.weaponType == WEAPON_CLUB) && !(it.slotPosition & SLOTP_TWO_HAND)) { int16_t durability = Items::mediumItemsDurability[it.m_rarity]; setDurability(durability, durability); } else if(((it.weaponType == WEAPON_AXE || it.weaponType == WEAPON_SWORD || it.weaponType == WEAPON_CLUB) && (it.slotPosition & SLOTP_TWO_HAND)) || it.weaponType == WEAPON_SHIELD) { int16_t durability = Items::heavyItemsDurability[it.m_rarity]; setDurability(durability, durability); } else if(it.weaponType == WEAPON_DIST && (it.slotPosition & SLOTP_TWO_HAND)) { int16_t durability = Items::distanceDurability[it.m_rarity]; setDurability(durability, durability); } #endif } Item* Item::clone() const { Item* tmp = Item::CreateItem(id, count); if(!tmp) return NULL; if(!attributes || attributes->empty()) return tmp; tmp->createAttributes(); *tmp->attributes = *attributes; return tmp; } void Item::copyAttributes(Item* item) { if(item && item->attributes && !item->attributes->empty()) { createAttributes(); *attributes = *item->attributes; } eraseAttribute("decaying"); eraseAttribute("duration"); } void Item::onRemoved() { if(raid) { raid->unRef(); raid = NULL; } ScriptEnviroment::removeTempItem(this); if(getUniqueId()) ScriptEnviroment::removeUniqueThing(this); } void Item::setDefaultSubtype() { setItemCount(1); const ItemType& it = items[id]; if(it.charges) setCharges(it.charges); } void Item::setID(uint16_t newId) { const ItemType& it = Item::items[newId]; const ItemType& pit = Item::items[id]; id = newId; uint32_t newDuration = it.decayTime * 1000; if(!newDuration && !it.stopTime && it.decayTo == -1) { eraseAttribute("decaying"); eraseAttribute("duration"); } eraseAttribute("corpseowner"); if(newDuration > 0 && (!pit.stopTime || !hasIntegerAttribute("duration"))) { setDecaying(DECAYING_FALSE); setDuration(newDuration); } } bool Item::floorChange(FloorChange_t change/* = CHANGE_NONE*/) const { if(change < CHANGE_NONE) return Item::items[id].floorChange[change]; for(int32_t i = CHANGE_PRE_FIRST; i < CHANGE_LAST; ++i) { if(Item::items[id].floorChange[i]) return true; } return false; } Player* Item::getHoldingPlayer() { Cylinder* p = getParent(); while(p) { if(p->getCreature()) return p->getCreature()->getPlayer(); p = p->getParent(); } return NULL; } const Player* Item::getHoldingPlayer() const { return const_cast<Item*>(this)->getHoldingPlayer(); } uint16_t Item::getSubType() const { const ItemType& it = items[id]; if(it.isFluidContainer() || it.isSplash()) return getFluidType(); if(it.charges) return getCharges(); return count; } void Item::setSubType(uint16_t n) { const ItemType& it = items[id]; if(it.isFluidContainer() || it.isSplash()) setFluidType(n); else if(it.charges) setCharges(n); else count = n; } Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) { switch(attr) { case ATTR_COUNT: { uint8_t _count; if(!propStream.getByte(_count)) return ATTR_READ_ERROR; setSubType((uint16_t)_count); break; } case ATTR_ACTION_ID: { uint16_t aid; if(!propStream.getShort(aid)) return ATTR_READ_ERROR; setAttribute("aid", aid); break; } case ATTR_UNIQUE_ID: { uint16_t uid; if(!propStream.getShort(uid)) return ATTR_READ_ERROR; setUniqueId(uid); break; } case ATTR_NAME: { std::string name; if(!propStream.getString(name)) return ATTR_READ_ERROR; setAttribute("name", name); break; } case ATTR_PLURALNAME: { std::string name; if(!propStream.getString(name)) return ATTR_READ_ERROR; setAttribute("pluralname", name); break; } case ATTR_ARTICLE: { std::string article; if(!propStream.getString(article)) return ATTR_READ_ERROR; setAttribute("article", article); break; } case ATTR_ATTACK: { int32_t attack; if(!propStream.getLong((uint32_t&)attack)) return ATTR_READ_ERROR; setAttribute("attack", attack); break; } case ATTR_EXTRAATTACK: { int32_t attack; if(!propStream.getLong((uint32_t&)attack)) return ATTR_READ_ERROR; setAttribute("extraattack", attack); break; } case ATTR_DEFENSE: { int32_t defense; if(!propStream.getLong((uint32_t&)defense)) return ATTR_READ_ERROR; setAttribute("defense", defense); break; } case ATTR_EXTRADEFENSE: { int32_t defense; if(!propStream.getLong((uint32_t&)defense)) return ATTR_READ_ERROR; setAttribute("extradefense", defense); break; } case ATTR_ARMOR: { int32_t armor; if(!propStream.getLong((uint32_t&)armor)) return ATTR_READ_ERROR; setAttribute("armor", armor); break; } case ATTR_ATTACKSPEED: { int32_t attackSpeed; if(!propStream.getLong((uint32_t&)attackSpeed)) return ATTR_READ_ERROR; setAttribute("attackspeed", attackSpeed); break; } case ATTR_HITCHANCE: { int32_t hitChance; if(!propStream.getLong((uint32_t&)hitChance)) return ATTR_READ_ERROR; setAttribute("hitchance", hitChance); break; } case ATTR_SCRIPTPROTECTED: { uint8_t protection; if(!propStream.getByte(protection)) return ATTR_READ_ERROR; setAttribute("scriptprotected", protection != 0); break; } case ATTR_DUALWIELD: { uint8_t wield; if(!propStream.getByte(wield)) return ATTR_READ_ERROR; setAttribute("dualwield", wield != 0); break; } case ATTR_TEXT: { std::string text; if(!propStream.getString(text)) return ATTR_READ_ERROR; setAttribute("text", text); break; } case ATTR_WRITTENDATE: { int32_t date; if(!propStream.getLong((uint32_t&)date)) return ATTR_READ_ERROR; setAttribute("date", date); break; } case ATTR_WRITTENBY: { std::string writer; if(!propStream.getString(writer)) return ATTR_READ_ERROR; setAttribute("writer", writer); break; } case ATTR_DESC: { std::string text; if(!propStream.getString(text)) return ATTR_READ_ERROR; setAttribute("description", text); break; } case ATTR_RUNE_CHARGES: { uint8_t charges; if(!propStream.getByte(charges)) return ATTR_READ_ERROR; setSubType((uint16_t)charges); break; } case ATTR_CHARGES: { uint16_t charges; if(!propStream.getShort(charges)) return ATTR_READ_ERROR; setSubType(charges); break; } case ATTR_DURATION: { int32_t duration; if(!propStream.getLong((uint32_t&)duration)) return ATTR_READ_ERROR; setAttribute("duration", duration); break; } case ATTR_DECAYING_STATE: { uint8_t state; if(!propStream.getByte(state)) return ATTR_READ_ERROR; if((ItemDecayState_t)state != DECAYING_FALSE) setAttribute("decaying", (int32_t)DECAYING_PENDING); break; } //these should be handled through derived classes //if these are called then something has changed in the items.otb since the map was saved //just read the values //Depot class case ATTR_DEPOT_ID: { uint16_t depot; if(!propStream.getShort(depot)) return ATTR_READ_ERROR; break; } //Door class case ATTR_HOUSEDOORID: { uint8_t door; if(!propStream.getByte(door)) return ATTR_READ_ERROR; break; } //Teleport class case ATTR_TELE_DEST: { TeleportDest* dest; if(!propStream.getStruct(dest)) return ATTR_READ_ERROR; break; } //Bed class case ATTR_SLEEPERGUID: { uint32_t sleeper; if(!propStream.getLong(sleeper)) return ATTR_READ_ERROR; break; } case ATTR_SLEEPSTART: { uint32_t sleepStart; if(!propStream.getLong(sleepStart)) return ATTR_READ_ERROR; break; } //Container class case ATTR_CONTAINER_ITEMS: { uint32_t _count; propStream.getLong(_count); return ATTR_READ_ERROR; } //ItemAttributes class case ATTR_ATTRIBUTE_MAP: { bool unique = hasIntegerAttribute("uid"), ret = unserializeMap(propStream); if(!unique && hasIntegerAttribute("uid")) // unfortunately we have to do this ScriptEnviroment::addUniqueThing(this); // this attribute has a custom behavior as well if(getDecaying() != DECAYING_FALSE) setDecaying(DECAYING_PENDING); if(ret) break; } default: return ATTR_READ_ERROR; } return ATTR_READ_CONTINUE; } bool Item::unserializeAttr(PropStream& propStream) { uint8_t attrType = ATTR_END; while(propStream.getByte(attrType) && attrType != ATTR_END) { switch(readAttr((AttrTypes_t)attrType, propStream)) { case ATTR_READ_ERROR: return false; case ATTR_READ_END: return true; default: break; } } return true; } bool Item::serializeAttr(PropWriteStream& propWriteStream) const { if(isStackable() || isFluidContainer() || isSplash()) { propWriteStream.addByte(ATTR_COUNT); propWriteStream.addByte((uint8_t)getSubType()); } if(attributes && !attributes->empty()) { propWriteStream.addByte(ATTR_ATTRIBUTE_MAP); serializeMap(propWriteStream); } return true; } bool Item::hasProperty(enum ITEMPROPERTY prop) const { const ItemType& it = items[id]; switch(prop) { case BLOCKSOLID: if(it.blockSolid) return true; break; case MOVEABLE: if(it.moveable && (!loadedFromMap || (!getUniqueId() && (!getActionId() || !getContainer())))) return true; break; case HASHEIGHT: if(it.hasHeight) return true; break; case BLOCKPROJECTILE: if(it.blockProjectile) return true; break; case BLOCKPATH: if(it.blockPathFind) return true; break; case ISVERTICAL: if(it.isVertical) return true; break; case ISHORIZONTAL: if(it.isHorizontal) return true; break; case IMMOVABLEBLOCKSOLID: if(it.blockSolid && (!it.moveable || (loadedFromMap && (getUniqueId() || (getActionId() && getContainer()))))) return true; break; case IMMOVABLEBLOCKPATH: if(it.blockPathFind && (!it.moveable || (loadedFromMap && (getUniqueId() || (getActionId() && getContainer()))))) return true; break; case SUPPORTHANGABLE: if(it.isHorizontal || it.isVertical) return true; break; case IMMOVABLENOFIELDBLOCKPATH: if(!it.isMagicField() && it.blockPathFind && (!it.moveable || (loadedFromMap && (getUniqueId() || (getActionId() && getContainer()))))) return true; break; case NOFIELDBLOCKPATH: if(!it.isMagicField() && it.blockPathFind) return true; break; case FLOORCHANGEDOWN: if(it.floorChange[CHANGE_DOWN]) return true; break; case FLOORCHANGEUP: for(uint16_t i = CHANGE_FIRST; i <= CHANGE_PRE_LAST; i++) { if(it.floorChange[i]) return true; } break; default: break; } return false; } double Item::getWeight() const { if(isStackable()) return items[id].weight * std::max((int32_t)1, (int32_t)count); return items[id].weight; } std::string Item::getDescription(const ItemType& it, int32_t lookDistance, const Item* item/* = NULL*/, int32_t subType/* = -1*/, bool addArticle/* = true*/) { std::stringstream s; s << getNameDescription(it, item, subType, addArticle); if(item) subType = item->getSubType(); bool dot = true; if(it.isRune()) { if(!it.runeSpellName.empty()) s << "(\"" << it.runeSpellName << "\")"; if(it.runeLevel > 0 || it.runeMagLevel > 0 || (it.vocationString != "" && it.wieldInfo == 0)) { s << "." << std::endl << "It can only be used"; if(it.vocationString != "" && it.wieldInfo == 0) s << " by " << it.vocationString; bool begin = true; if(it.runeLevel > 0) { begin = false; s << " with level " << it.runeLevel; } if(it.runeMagLevel > 0) { begin = false; s << " " << (begin ? "with" : "and") << " magic level " << it.runeMagLevel; } if(!begin) s << " or higher"; } } else if(it.weaponType != WEAPON_NONE) { bool begin = true; if(it.weaponType == WEAPON_DIST && it.ammoType != AMMO_NONE) { begin = false; s << " (Range:" << int32_t(item ? item->getShootRange() : it.shootRange); if(it.attack || it.extraAttack || (item && (item->getAttack() || item->getExtraAttack()))) { s << ", Atk " << std::showpos << int32_t(item ? item->getAttack() : it.attack); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; } if(it.hitChance != -1 || (item && item->getHitChance() != -1)) s << ", Hit% " << std::showpos << (item ? item->getHitChance() : it.hitChance) << std::noshowpos; #ifdef __DARGHOS_CUSTOM__ if(it.m_criticalChance > 0 || (item && item->getCriticalChance() > 0)) s << ", Crit% " << std::showpos << (item ? item->getCriticalChance() : it.m_criticalChance) << std::noshowpos; #endif } else if(it.weaponType != WEAPON_AMMO && it.weaponType != WEAPON_WAND) { if(it.attack || it.extraAttack || (item && (item->getAttack() || item->getExtraAttack()))) { begin = false; s << " (Atk:"; if(it.abilities.elementType != COMBAT_NONE && it.decayTo < 1) { s << std::max((int32_t)0, int32_t((item ? item->getAttack() : it.attack) - it.abilities.elementDamage)); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; s << " physical + " << it.abilities.elementDamage << " " << getCombatName(it.abilities.elementType); } else { s << int32_t(item ? item->getAttack() : it.attack); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; } } if(it.defense || it.extraDefense || (item && (item->getDefense() || item->getExtraDefense()))) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "Def:" << int32_t(item ? item->getDefense() : it.defense); if(it.extraDefense || (item && item->getExtraDefense())) s << " " << std::showpos << int32_t(item ? item->getExtraDefense() : it.extraDefense) << std::noshowpos; } #ifdef __DARGHOS_CUSTOM__ if(it.m_criticalChance > 0 || (item && item->getCriticalChance() > 0)) s << ", Crit% " << std::showpos << (item ? item->getCriticalChance() : it.m_criticalChance) << std::noshowpos; #endif } for(uint16_t i = SKILL_FIRST; i <= SKILL_LAST; i++) { if(!it.abilities.skills[i]) continue; if(begin) { begin = false; s << " ("; } else s << ", "; s << getSkillName(i) << " " << std::showpos << (int32_t)it.abilities.skills[i] << std::noshowpos; } if(it.abilities.stats[STAT_MAGICLEVEL]) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "magic level " << std::showpos << (int32_t)it.abilities.stats[STAT_MAGICLEVEL] << std::noshowpos; } #ifdef __DARGHOS_CUSTOM__ if(it.m_maxDurability > 0 || (item && item->getMaxDurability() > 0)) { if(begin) { begin = false; s << " ("; } else s << ", "; if(item) s << "Dur: " << item->getDurability() << "/" << item->getMaxDurability() << std::noshowpos; else s << "Dur: " << it.m_durability << "/" << it.m_maxDurability << std::noshowpos; } #endif // TODO: we should find some better way of completing this int32_t show = it.abilities.absorb[COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.absorb[i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.absorb[i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection "; } else s << ", "; s << getCombatName((CombatType_t)i) << " " << std::showpos << it.abilities.absorb[i] << std::noshowpos << "%"; } } else { if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection all " << std::showpos << show << std::noshowpos << "%"; } // TODO: same case as absorbs... show = it.abilities.reflect[REFLECT_CHANCE][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_CHANCE][i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.reflect[REFLECT_CHANCE][i] || !it.abilities.reflect[REFLECT_PERCENT][i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "reflect: "; } else s << ", "; s << it.abilities.reflect[REFLECT_CHANCE][i] << "% for "; if(it.abilities.reflect[REFLECT_PERCENT][i] > 99) s << "whole"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 75) s << "huge"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 50) s << "medium"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 25) s << "small"; else s << "tiny"; s << getCombatName((CombatType_t)i); } if(!tmp) s << " damage"; } else { if(begin) { begin = false; s << " ("; } else s << ", "; int32_t tmp = it.abilities.reflect[REFLECT_PERCENT][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_PERCENT][i] == tmp) continue; tmp = 0; break; } s << "reflect: " << show << "% for "; if(tmp) { if(tmp > 99) s << "whole"; else if(tmp >= 75) s << "huge"; else if(tmp >= 50) s << "medium"; else if(tmp >= 25) s << "small"; else s << "tiny"; } else s << "mixed"; s << " damage"; } if(it.abilities.speed) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "speed " << std::showpos << (int32_t)(it.abilities.speed / 2) << std::noshowpos; } if(it.abilities.invisible) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "invisibility"; } if(it.abilities.regeneration) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "faster regeneration"; } if(it.abilities.manaShield) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "mana shield"; } if(hasBitSet(CONDITION_DRUNK, it.abilities.conditionSuppressions)) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "hard drinking"; } if(it.dualWield || (item && item->isDualWield())) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "dual wielding"; } if(!begin) s << ")"; } else if(it.armor || (item && item->getArmor()) || it.showAttributes) { int32_t tmp = it.armor; if(item) tmp = item->getArmor(); bool begin = true; if(tmp) { s << " (Arm:" << tmp; begin = false; } for(uint16_t i = SKILL_FIRST; i <= SKILL_LAST; i++) { if(!it.abilities.skills[i]) continue; if(begin) { begin = false; s << " ("; } else s << ", "; s << getSkillName(i) << " " << std::showpos << (int32_t)it.abilities.skills[i] << std::noshowpos; } if(it.abilities.stats[STAT_MAGICLEVEL]) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "magic level " << std::showpos << (int32_t)it.abilities.stats[STAT_MAGICLEVEL] << std::noshowpos; } #ifdef __DARGHOS_CUSTOM__ if(it.m_criticalChance > 0 || (item && item->getCriticalChance() > 0)) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "crit% " << std::showpos << (item ? item->getCriticalChance() : it.m_criticalChance) << std::noshowpos; } if(it.m_maxDurability > 0 || (item && item->getMaxDurability() > 0)) { if(begin) { begin = false; s << " ("; } else s << ", "; if(item) s << "Dur: " << item->getDurability() << "/" << item->getMaxDurability() << std::noshowpos; else s << "Dur: " << it.m_durability << "/" << it.m_maxDurability << std::noshowpos; } #endif // TODO: we should find some better way of completing this int32_t show = it.abilities.absorb[COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.absorb[i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.absorb[i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection "; } else s << ", "; s << getCombatName((CombatType_t)i) << " " << std::showpos << it.abilities.absorb[i] << std::noshowpos << "%"; } } else { if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection all " << std::showpos << show << std::noshowpos << "%"; } #ifdef __DARGHOS_CUSTOM__ if(it.abilities.fieldAbsorb.size() > 0) { for(Absorb_t::const_iterator tmp_it = it.abilities.fieldAbsorb.begin(); tmp_it != it.abilities.fieldAbsorb.end(); tmp_it++) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection " << getCombatName((*tmp_it).first) << " field: " << (*tmp_it).second << "%"; } } #endif // TODO: same case as absorbs... show = it.abilities.reflect[REFLECT_CHANCE][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_CHANCE][i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.reflect[REFLECT_CHANCE][i] || !it.abilities.reflect[REFLECT_PERCENT][i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "reflect: "; } else s << ", "; s << it.abilities.reflect[REFLECT_CHANCE][i] << "% for "; if(it.abilities.reflect[REFLECT_PERCENT][i] > 99) s << "whole"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 75) s << "huge"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 50) s << "medium"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 25) s << "small"; else s << "tiny"; s << getCombatName((CombatType_t)i); } if(!tmp) s << " damage"; } else { if(begin) { begin = false; s << " ("; } else s << ", "; int32_t tmp = it.abilities.reflect[REFLECT_PERCENT][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_PERCENT][i] == tmp) continue; tmp = 0; break; } s << "reflect: " << show << "% for "; if(tmp) { if(tmp > 99) s << "whole"; else if(tmp >= 75) s << "huge"; else if(tmp >= 50) s << "medium"; else if(tmp >= 25) s << "small"; else s << "tiny"; } else s << "mixed"; s << " damage"; } if(it.abilities.speed) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "speed " << std::showpos << (int32_t)(it.abilities.speed / 2) << std::noshowpos; } if(it.abilities.invisible) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "invisibility"; } if(it.abilities.regeneration) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "faster regeneration"; } if(it.abilities.manaShield) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "mana shield"; } if(hasBitSet(CONDITION_DRUNK, it.abilities.conditionSuppressions)) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "hard drinking"; } if(!begin) s << ")"; } #ifdef __DARGHOS_CUSTOM__ else if(it.m_criticalChance > 0 || (item && item->getCriticalChance() > 0)) s << "(Crit% " << std::showpos << (item ? item->getCriticalChance() : it.m_criticalChance) << std::noshowpos << ")"; #endif else if(it.isContainer()) s << " (Vol:" << (int32_t)it.maxItems << ")"; else if(it.isKey()) s << " (Key:" << (item ? (int32_t)item->getActionId() : 0) << ")"; else if(it.isFluidContainer()) { if(subType > 0) s << " of " << (items[subType].name.length() ? items[subType].name : "unknown"); else s << ". It is empty"; } else if(it.isSplash()) { s << " of "; if(subType > 0 && items[subType].name.length()) s << items[subType].name; else s << "unknown"; } else if(it.allowDistRead) { s << "." << std::endl; if(item && !item->getText().empty()) { if(lookDistance <= 4) { if(!item->getWriter().empty()) { s << item->getWriter() << " wrote"; time_t date = item->getDate(); if(date > 0) s << " on " << formatDate(date); s << ": "; } else s << "You read: "; std::string text = item->getText(); s << text; char end = *text.rbegin(); if(end == '?' || end == '!' || end == '.') dot = false; } else s << "You are too far away to read it"; } else s << "Nothing is written on it"; } else if(it.levelDoor && item && item->getActionId() >= (int32_t)it.levelDoor && item->getActionId() <= ((int32_t)it.levelDoor + g_config.getNumber(ConfigManager::MAXIMUM_DOOR_LEVEL))) s << " for level " << item->getActionId() - it.levelDoor; if(it.showCharges) s << " that has " << subType << " charge" << (subType != 1 ? "s" : "") << " left"; if(it.showDuration) { if(item && item->hasIntegerAttribute("duration")) { int32_t duration = item->getDuration() / 1000; s << " that will expire in "; if(duration >= 86400) { uint16_t days = duration / 86400; uint16_t hours = (duration % 86400) / 3600; s << days << " day" << (days > 1 ? "s" : ""); if(hours > 0) s << " and " << hours << " hour" << (hours > 1 ? "s" : ""); } else if(duration >= 3600) { uint16_t hours = duration / 3600; uint16_t minutes = (duration % 3600) / 60; s << hours << " hour" << (hours > 1 ? "s" : ""); if(hours > 0) s << " and " << minutes << " minute" << (minutes > 1 ? "s" : ""); } else if(duration >= 60) { uint16_t minutes = duration / 60; uint16_t seconds = duration % 60; s << minutes << " minute" << (minutes > 1 ? "s" : ""); if(seconds > 0) s << " and " << seconds << " second" << (seconds > 1 ? "s" : ""); } else s << duration << " second" << (duration > 1 ? "s" : ""); } else s << " that is brand-new"; } if(dot) s << "."; if(it.wieldInfo) { s << std::endl << "It can only be wielded properly by "; if(it.wieldInfo & WIELDINFO_PREMIUM) s << "premium "; if(it.wieldInfo & WIELDINFO_VOCREQ) s << it.vocationString; else s << "players"; if(it.wieldInfo & WIELDINFO_LEVEL) s << " of level " << (int32_t)it.minReqLevel << " or higher"; if(it.wieldInfo & WIELDINFO_MAGLV) { if(it.wieldInfo & WIELDINFO_LEVEL) s << " and"; else s << " of"; s << " magic level " << (int32_t)it.minReqMagicLevel << " or higher"; } s << "."; } if(lookDistance <= 1 && it.pickupable) { std::string tmp; if(!item) tmp = getWeightDescription(it.weight, it.stackable && it.showCount, subType); else tmp = item->getWeightDescription(); if(!tmp.empty()) s << std::endl << tmp; } if(it.abilities.elementType != COMBAT_NONE && it.decayTo > 0) { s << std::endl << "It is temporarily enchanted with " << getCombatName(it.abilities.elementType) << " ("; s << std::max((int32_t)0, int32_t((item ? item->getAttack() : it.attack) - it.abilities.elementDamage)); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; s << " physical + " << it.abilities.elementDamage << " " << getCombatName(it.abilities.elementType) << " damage)."; } std::string str; if(item && !item->getSpecialDescription().empty()) str = item->getSpecialDescription(); else if(!it.description.empty() && lookDistance <= 1) str = it.description; if(str.empty()) return s.str(); if(str.find("|PLAYERNAME|") != std::string::npos) { std::string tmp = "You"; if(item) { if(const Player* player = item->getHoldingPlayer()) tmp = player->getName(); } replaceString(str, "|PLAYERNAME|", tmp); } if(str.find("|TIME|") != std::string::npos || str.find("|DATE|") != std::string::npos || str.find( "|DAY|") != std::string::npos || str.find("|MONTH|") != std::string::npos || str.find( "|YEAR|") != std::string::npos || str.find("|HOUR|") != std::string::npos || str.find( "|MINUTES|") != std::string::npos || str.find("|SECONDS|") != std::string::npos || str.find("|WEEKDAY|") != std::string::npos || str.find("|YEARDAY|") != std::string::npos) { time_t now = time(NULL); tm* ts = localtime(&now); std::stringstream ss; ss << ts->tm_sec; replaceString(str, "|SECONDS|", ss.str()); ss.str(""); ss << ts->tm_min; replaceString(str, "|MINUTES|", ss.str()); ss.str(""); ss << ts->tm_hour; replaceString(str, "|HOUR|", ss.str()); ss.str(""); ss << ts->tm_mday; replaceString(str, "|DAY|", ss.str()); ss.str(""); ss << (ts->tm_mon + 1); replaceString(str, "|MONTH|", ss.str()); ss.str(""); ss << (ts->tm_year + 1900); replaceString(str, "|YEAR|", ss.str()); ss.str(""); ss << ts->tm_wday; replaceString(str, "|WEEKDAY|", ss.str()); ss.str(""); ss << ts->tm_yday; replaceString(str, "|YEARDAY|", ss.str()); ss.str(""); ss << ts->tm_hour << ":" << ts->tm_min << ":" << ts->tm_sec; replaceString(str, "|TIME|", ss.str()); ss.str(""); replaceString(str, "|DATE|", formatDateEx(now)); } s << std::endl << str; return s.str(); } std::string Item::getNameDescription(const ItemType& it, const Item* item/* = NULL*/, int32_t subType/* = -1*/, bool addArticle/* = true*/) { if(item) subType = item->getSubType(); std::stringstream s; if(it.name.length() || (item && item->getName().length())) { if(subType > 1 && it.stackable && it.showCount) s << subType << " " << (item ? item->getPluralName() : it.pluralName); else { if(addArticle) { if(item && !item->getArticle().empty()) s << item->getArticle() << " "; else if(!it.article.empty()) s << it.article << " "; } s << (item ? item->getName() : it.name); } } else s << "an item of type " << it.id << ", please report it to gamemaster"; return s.str(); } std::string Item::getWeightDescription(double weight, bool stackable, uint32_t count/* = 1*/) { if(weight <= 0) return ""; std::stringstream s; if(stackable && count > 1) s << "They weigh " << std::fixed << std::setprecision(2) << weight << " oz."; else s << "It weighs " << std::fixed << std::setprecision(2) << weight << " oz."; return s.str(); } void Item::setActionId(int32_t aid, bool callEvent/* = true*/) { Tile* tile = NULL; if(callEvent) tile = getTile(); if(tile && getActionId()) g_moveEvents->onRemoveTileItem(tile, this); setAttribute("aid", aid); if(tile) g_moveEvents->onAddTileItem(tile, this); } void Item::resetActionId(bool callEvent/* = true*/) { if(!getActionId()) return; Tile* tile = NULL; if(callEvent) tile = getTile(); eraseAttribute("aid"); if(tile) g_moveEvents->onAddTileItem(tile, this); } void Item::setUniqueId(int32_t uid) { if(getUniqueId()) return; setAttribute("uid", uid); ScriptEnviroment::addUniqueThing(this); } bool Item::canDecay() { if(isRemoved()) return false; if(loadedFromMap && (getUniqueId() || (getActionId() && getContainer()))) return false; const ItemType& it = Item::items[id]; return it.decayTo >= 0 && it.decayTime; } void Item::getLight(LightInfo& lightInfo) { const ItemType& it = items[id]; lightInfo.color = it.lightColor; lightInfo.level = it.lightLevel; } void Item::__startDecaying() { g_game.startDecay(this); } #ifdef __DARGHOS_CUSTOM__ void Item::onWear(bool onDeath/* = false*/, bool withSkull/* = false*/) { if(getMaxDurability() <= 0) return; int16_t durabilityWear = 1; bool wearDurability = false; if(!onDeath) { if(random_range(1, 100000) <= g_config.getNumber(ConfigManager::ITEM_DURABILITY_LOSS_CHANCE)) wearDurability = true; } else { if(!withSkull) durabilityWear = std::floor(getMaxDurability() * (float)(g_config.getNumber(ConfigManager::ON_DEATH_ITEM_DURABILITY_WEAR_PERCENT) / 100.)); else durabilityWear = std::floor(getMaxDurability() * (float)(g_config.getNumber(ConfigManager::WITH_SKULL_ITEM_DURABILITY_WEAR_PERCENT) / 100.)); wearDurability = true; } if(wearDurability) { setDurability(std::max(0, getDurability() - durabilityWear), getMaxDurability()); } if(getDurability() == 0) { Player* player = getHoldingPlayer(); if(player) { Item* item = NULL; if(item = player->getInventoryItem(SLOT_BACKPACK)) { g_game.internalMoveItem(NULL, getParent(), item->getContainer(), INDEX_WHEREEVER, this, getItemCount(), NULL); } } } } #endif
[ "leandro_perrotta@hotmail.com" ]
leandro_perrotta@hotmail.com
661122244f7be880bdfc3b3324aa62efc6d42776
4c0568bcb1a7345482052dffedbd1b544cf432cf
/ResourceUnpack/ResourceUnpack.cpp
565f9a87989c931bb3879859ef6a4af69f987202
[]
no_license
CBE7F1F65/aab67be7d1ea40a0bd5beca3a5dc1ebc
d8a4daf93caa9dd03628eaf89859e41f12214006
a60f4e173f79e5fb232378f3d2e00882dfd8feef
refs/heads/master
2021-01-22T02:53:08.710769
2013-03-07T00:15:45
2013-03-07T00:15:45
32,192,709
1
0
null
null
null
null
GB18030
C++
false
false
1,539
cpp
// ResourceUnpack.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "ResourceUnpack.h" #include "ResourceUnpackDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CResourceUnpackApp BEGIN_MESSAGE_MAP(CResourceUnpackApp, CWinApp) ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() // CResourceUnpackApp 构造 CResourceUnpackApp::CResourceUnpackApp() { // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CResourceUnpackApp 对象 CResourceUnpackApp theApp; // CResourceUnpackApp 初始化 BOOL CResourceUnpackApp::InitInstance() { CWinApp::InitInstance(); AfxEnableControlContainer(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("")); CResourceUnpackDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此放置处理何时用“确定”来关闭 //对话框的代码 } else if (nResponse == IDCANCEL) { // TODO: 在此放置处理何时用“取消”来关闭 //对话框的代码 } // 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序, // 而不是启动应用程序的消息泵。 return FALSE; }
[ "CBE7F1F65@d27205ec-b7ea-c6cd-419b-f32fc6026ca2" ]
CBE7F1F65@d27205ec-b7ea-c6cd-419b-f32fc6026ca2
8efd9715c69bdce3619b8e90eac704e5d45e2616
29ec01acd91e6427e6d1bd4e54539267c05811b4
/include/json_spirit/writer_options.h
c1ce929ebd09486075d64e758bc33d56d93838f3
[]
no_license
danielfiskvik/ThinkWSS
d77e34a0c520b0650bc120c5bb6de18b45369bf8
d4c1a5b3415d62277e4a96f89e02a850e1973b10
refs/heads/master
2016-09-05T18:10:35.182615
2015-01-11T02:30:06
2015-01-11T02:30:06
29,072,752
0
1
null
null
null
null
UTF-8
C++
false
false
1,058
h
#ifndef WRITER_OPTIONS_H #define WRITER_OPTIONS_H // Copyright John W. Wilkinson 2007 - 2011 // Distributed under the MIT License, see accompanying file LICENSE.txt // json spirit version 4.05 #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif namespace json_spirit { enum Output_options { pretty_print = 0x01, // Add whitespace to format the output nicely. raw_utf8 = 0x02, // This prevents non-printable characters from being escapted using "\uNNNN" notation. // Note, this is an extension to the JSON standard. It disables the escaping of // non-printable characters allowing UTF-8 sequences held in 8 bit char strings // to pass through unaltered. remove_trailing_zeros = 0x04, // NOTE: this is no longer meaningful, but used to output e.g. "1.200000000000000" as "1.2" single_line_arrays = 0x08, // pretty printing except that arrays printed on single lines unless they contain // composite elements, i.e. objects or arrays }; } #endif
[ "daniel@daniel-Lenovo-Y50-70" ]
daniel@daniel-Lenovo-Y50-70
3e916f5afc3fd8ad3a72102232cf43310fab48a6
38318b27527be5531b64eee6786c29702377b17b
/union_find.hpp
9a14ced507df62af1cd635612fb7e6abb079c519
[]
no_license
OskarPetto/graphfruit
5c6fb907d49a9ab519e92e2a814b8592c0855353
9d174310441d366e20c9c040ccfd0f2b78fbd0c5
refs/heads/master
2021-08-28T17:23:26.860358
2017-12-12T22:41:41
2017-12-12T22:41:41
103,444,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
hpp
/* * A union find implementation using weighted quick-union and path compression. * @author Oskar Petto * @version 13.09.2017 * first version */ #ifndef UNION_FIND_HPP #define UNION_FIND_HPP #include <cstddef> #include <vector> namespace graphfruit { class union_find { public: /* * Constructors */ explicit union_find(std::size_t n); union_find(const union_find& other) = default; union_find(union_find &&) noexcept = default; union_find& operator=(const union_find& other) = default; union_find& operator=(union_find&& other) = default; ~union_find() = default; /* * Removes all elements from the structure. * Complexity: O(1) */ void clear(); /* * Uses one-pass path compression to find the root of the set containing x. * Complexity: O(log(n)) */ std::size_t set_find(std::size_t x); /* * Uses union by rank to merge the sets of x and y. * Complexity: */ void set_union(std::size_t x, std::size_t y); private: struct elem { std::size_t parent; unsigned int rank; }; std::vector<elem> id; }; } #endif //UNION_FIND_HPP
[ "OskarPetto@users.noreply.github.com" ]
OskarPetto@users.noreply.github.com
003edac98bf6cf5209d1389e0d533eae10b56422
9b6eced5d80668bd4328a8f3d1f75c97f04f5e08
/bthci/hci2implementations/qdps/symbian/src/hcisymbianqdp.cpp
671c31e888c4f349ac02ee003b6a55641fd6c783
[]
no_license
SymbianSource/oss.FCL.sf.os.bt
3ca94a01740ac84a6a35718ad3063884ea885738
ba9e7d24a7fa29d6dd93808867c28bffa2206bae
refs/heads/master
2021-01-18T23:42:06.315016
2010-10-14T10:30:12
2010-10-14T10:30:12
72,765,157
1
0
null
null
null
null
UTF-8
C++
false
false
17,509
cpp
// Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // /** @file @internalComponent */ #include "hcisymbianqdp.h" #include "hcieventmodifiable.h" #include <bluetooth/hcicommandqitem.h> #include <bluetooth/hci/hciopcodes.h> #include <bluetooth/hci/hciconsts.h> #include <bluetooth/hci/command.h> #include <bluetooth/hci/event.h> #include <bluetooth/hci/commandcompleteevent.h> #include <bluetooth/hci/disconnectioncompleteevent.h> #include <bluetooth/hci/readclockoffsetevent.h> #include <bluetooth/hci/authenticationcompleteevent.h> #include <bluetooth/hci/readlocalversioninfocompleteevent.h> #include <bluetooth/hci/writelinkpolicysettingscommand.h> #include <bluetooth/hci/readlinkpolicysettingscommand.h> #include <bluetooth/hci/readlmphandlecommand.h> #include <bluetooth/hci/rolediscoverycommand.h> #include <bluetooth/hci/sniffsubratingcommand.h> #include <bluetooth/hci/flushcommand.h> #include <bluetooth/hci/readautomaticflushtimeoutcommand.h> #include <bluetooth/hci/writeautomaticflushtimeoutcommand.h> #include <bluetooth/hci/readtransmitpowerlevelcommand.h> #include <bluetooth/hci/readlinksupervisiontimeoutcommand.h> #include <bluetooth/hci/writelinksupervisiontimeoutcommand.h> #include <bluetooth/hci/readfailedcontactcountercommand.h> #include <bluetooth/hci/resetfailedcontactcountercommand.h> #include <bluetooth/hci/readlinkqualitycommand.h> #include <bluetooth/hci/readrssicommand.h> #include <bluetooth/hci/readafhchannelmapcommand.h> #include <bluetooth/hci/readclockcommand.h> #include <bluetooth/logger.h> #ifdef __FLOG_ACTIVE _LIT8(KLogComponent, LOG_COMPONENT_QDP_SYMBIAN); #endif #ifdef _DEBUG PANICCATEGORY("qdpsymbia"); #endif // _DEBUG void AppendConnectionHandle(TDes8& aDes, THCIConnectionHandle aConnectionHandle) { LOG_STATIC_FUNC THCIConnHandle connHandle = aConnectionHandle.ConnHandle(); LOG1(_L8("Appending connection handle = 0x%04x"), connHandle); TUint8 val[2] = {connHandle & 0xff, connHandle >> 8}; aDes.Append(val, 2); } /*static*/ CHCISymbianQdp* CHCISymbianQdp::NewL() { LOG_STATIC_FUNC CHCISymbianQdp* self = new (ELeave) CHCISymbianQdp(); return self; } // Private constructor. CHCISymbianQdp::CHCISymbianQdp() { LOG_FUNC } TAny* CHCISymbianQdp::Interface(TUid aUid) { TAny* ret = NULL; switch(aUid.iUid) { case KHCICmdQueueDecisionInterfaceUid: ret = reinterpret_cast<TAny*>(static_cast<MHCICmdQueueDecisionInterface*>(this)); break; case KHCICmdQueueDecisionEventModifierInterfaceUid: ret = reinterpret_cast<TAny*>(static_cast<MHCICmdQueueEventModifierInterface*>(this)); break; case KHCICmdQueueUtilityUserUid: ret = reinterpret_cast<TAny*>(static_cast<MHCICmdQueueUtilityUser*>(this)); break; default: break; }; return ret; } // MHCICmdQueueDecisionInterface TBool CHCISymbianQdp::MhcqdiDoesCommandRequireWorkaround(const CHCICommandQItem& /* aParent */) { LOG_FUNC // No Workarounds required. return EFalse; } CHCICommandQItem* CHCISymbianQdp::MhcqdiGetPreChildCommand(const CHCICommandQItem& /* aParent */, const CHCICommandQItem* /* aPreviousWorkaroundCmd */, const THCIEventBase* /*aPreviousCmdResult*/) { LOG_FUNC // No Workarounds required (see MhcqdiDoesCommandRequireWorkaround), should never be called. return NULL; } CHCICommandQItem* CHCISymbianQdp::MhcqdiGetPostChildCommand(const CHCICommandQItem& /* aParent */, const CHCICommandQItem* /* aPreviousPostChild */, const THCIEventBase* /*aPreviousCmdResult*/) { LOG_FUNC // No Workarounds required (see MhcqdiDoesCommandRequireWorkaround), should never be called. return NULL; } THCIEventBase* CHCISymbianQdp::MhcqdiGetFakedUnsolicitedEvent(const CHCICommandQItem& /*aParent*/, const THCIEventBase* /*aPreviousFakedEvent*/) { LOG_FUNC // No Workarounds required (see MhcqdiDoesCommandRequireWorkaround), should never be called. return NULL; } void CHCISymbianQdp::MhcqdiCommandAboutToBeDeleted(const CHCICommandQItem& /*aDyingCmd*/) { LOG_FUNC // Notification function. No need to do anything. } TInt CHCISymbianQdp::MhcqdiCanSend(CHCICommandQItem& /*aCommand*/, const TDblQue<const CHCICommandQItem>& aSentCommands) { LOG_FUNC #ifdef SERIAL_LOW_POWER_MODE_REQUESTS if (!aSentCommands.IsEmpty()) { THCIOpcode opcode = aSentCommands.Last()->Command().Opcode(); // The following commands are blocked to avoid ambiguity in matching mode change // events. This ensures they are issued serially to the controller to prevent any confusion. // Note: This workaround currently resides in this Symbian QDP, but may require further // modification or placement depending on target hardware characteristics. This workaround // may not be required for all controllers. if(opcode == KHoldModeOpcode || opcode == KSniffModeOpcode || opcode == KExitSniffModeOpcode || opcode == KSwitchRoleOpcode || opcode == KParkModeOpcode || opcode == KExitParkModeOpcode) { return EBlock; } } #endif // SERIAL_LOW_POWER_MODE_REQUESTS // if no other issue then allow command queue to proceed return EContinue; } TUint CHCISymbianQdp::MhcqdiTimeoutRequired(const CHCICommandQItem& /* aCmdAboutToBeSent */) { LOG_FUNC // No timeout required. return MHCICmdQueueDecisionInterface::KNoTimeoutRequired; } void CHCISymbianQdp::MhcqdiMatchedEventReceived(const THCIEventBase& aEvent, const CHCICommandQItem& /*aRelatedCommand*/) { LOG_FUNC // Cache the HCI version number of the controller. This allows // us to ignore errors from specific versions of controllers if(aEvent.EventCode() == ECommandCompleteEvent && THCICommandCompleteEvent::Cast(aEvent).CommandOpcode() == KReadLocalVersionInfoOpcode) { const TReadLocalVersionInfoCompleteEvent& readLocalVersionCompleteEvent = TReadLocalVersionInfoCompleteEvent::Cast(aEvent); iHCIVersion = readLocalVersionCompleteEvent.Version(); } } void CHCISymbianQdp::MhcqemiMatchedEventReceived(THCIEventBase& aEvent, const CHCICommandQItem& aRelatedCommand) { LOG_FUNC #ifdef IGNORE_INVALID_HCI_PARAMETER_ERROR_ON_SET_EVENT_MASK_ON_VERSION_1_1 FixIgnoreInvalidHciParameterErrorOnSetEventMaskOnVersion1_1(aEvent); #endif // IGNORE_INVALID_HCI_PARAMETER_ERROR_ON_SET_EVENT_MASK_ON_VERSION_1_1 #ifdef FAKE_COMPLETION_EVENTS_ON_DISCONNECTION FixFakeCompletionEventsOnDisconnection(aEvent); #endif // FAKE_COMPLETION_EVENTS_ON_DISCONNECTION #ifdef ADD_CONNECTION_HANDLE_FOR_TRUNCATED_INVALID_CONNECTION_HANDLE_ERROR_EVENTS FixAddConnectionHandleForTruncatedInvalidConnectionHandleErrorEvents(aEvent, &aRelatedCommand); #endif // ADD_CONNECTION_HANDLE_FOR_TRUNCATED_INVALID_CONNECTION_HANDLE_ERROR_EVENTS // Don't forget to call the non-modifiable version of this function too MhcqdiMatchedEventReceived(aEvent, aRelatedCommand); } MHCICmdQueueDecisionInterface::TCommandErroredAction CHCISymbianQdp::MhcqdiMatchedErrorEventReceived(const THCIEventBase& /*aErrorEvent*/, const CHCICommandQItem& /*aRelatedCommand*/) { LOG_FUNC // Never resend. return MHCICmdQueueDecisionInterface::EContinueWithError; } void CHCISymbianQdp::MhcqdiUnmatchedEventReceived(const THCIEventBase& /*aEvent*/) { LOG_FUNC // Notification function. No need to do anything. } void CHCISymbianQdp::FixIgnoreInvalidHciParameterErrorOnSetEventMaskOnVersion1_1(THCIEventBase& aEvent) { LOG_FUNC // Some controllers supporting Bluetooth 1.1 return an EInvalidHCIParameter error // when SetEventMask is called. We still want to call SetEventMask and catch any actual // error in the stack (since it means that stack start up has failed). // In this case, stack start-up is fine, just ignore the returned EInvalidHCIParameter if(aEvent.ErrorCode() == EInvalidHCIParameter && aEvent.EventCode() == ECommandCompleteEvent && KSetEventMaskOpcode == THCICommandCompleteEvent::Cast(aEvent).CommandOpcode() && iHCIVersion == EHWHCIv1_1) { LOG(_L8("Ignoring Invalid HCI Parameter error for Set Event Mask")); THCIEventModifiable& event = static_cast<THCIEventModifiable&>(aEvent); event.SetErrorCode(EOK); } } void CHCISymbianQdp::FixFakeCompletionEventsOnDisconnection(THCIEventBase& aEvent) { LOG_FUNC // Some controllers fail to follow the HCI specification w.r.t. events on disconnection. // The specification indicates outstanding data on a connection handle to be considered // removed when a disconnection occurs. Events however are not guarded by such text // and should always be returned (with an appropriate error code). // The command queue expects these events (as it is programmed to the spec) so if a // controller fails to perform the task, we have to make up the shortfall. Currently // the following events are the ones that fail to be generated in the controllers. // This issue has been observed with: // // * Authentication_Complete // * Read_Clock_Offset if(aEvent.EventCode() == EDisconnectionCompleteEvent) { const TDisconnectionCompleteEvent& disconnEvent = TDisconnectionCompleteEvent::Cast(aEvent); THCIConnectionHandle handle = disconnEvent.ConnectionHandle(); THCIErrorCode reason = static_cast<THCIErrorCode>(disconnEvent.Reason()); if(iProvider->FindOutstandingCommand(KAuthenticationRequestedOpcode)) { LOG(_L8("Injecting Authentication Complete Event")); TAuthenticationCompleteEvent authenticationCompleteEvent(reason, handle, iEventModBuffer); iProvider->InjectEvent(authenticationCompleteEvent); } if(iProvider->FindOutstandingCommand(KReadClockOffsetOpcode)) { LOG(_L8("Injecting Read Clock Offset Complete Event")); THCIClockOffset clockOffset = 0; TReadClockOffsetEvent readClockOffsetEvent(reason, handle, clockOffset, iEventModBuffer); iProvider->InjectEvent(readClockOffsetEvent); } } } /** Utility template class for FixAddConnectionHandleForTruncatedInvalidConnectionHandleErrorEvents function. */ template<class XCommandCompleteCommandClass> struct AttemptToFixCommandCompleteEvent { static void CheckAndFix(THCICommandCompleteEvent& aEvent, const CHCICommandQItem* aRelatedCommand, TDes8& aNewBuffer, TInt aCorrectSize, TInt aExpectedSizeMissing) { LOG_STATIC_FUNC THCIEventModifiable& event = static_cast<THCIEventModifiable&>(static_cast<THCIEventBase&>(aEvent)); // Check to see if the data is truncated - only apply the fix if it is if(event.EventData().Length() == (aCorrectSize-aExpectedSizeMissing)) { // This is actually a best effort guess that the connection handle is missing. Fixing this isn't simple because // we need a bigger buffer than we may have - so we have to create our own backing buffer for the event. LOG1(_L8("Modifying Command Complete event (opcode = 0x%04x) to add Connection Handle"), aEvent.CommandOpcode()); aNewBuffer.FillZ(aCorrectSize); // ensure buffer is clean aNewBuffer.Copy(event.EventData()); if(aRelatedCommand) { const XCommandCompleteCommandClass& cmd = static_cast<const XCommandCompleteCommandClass&>(aRelatedCommand->Command()); AppendConnectionHandle(aNewBuffer, cmd.ConnectionHandle()); } else { // we have no connection handle to insert in, so pick one that can // never be valid. AppendConnectionHandle(aNewBuffer, KInvalidConnectionHandle); } aNewBuffer.SetLength(aCorrectSize); event.EventData().Set(aNewBuffer); // update event to point to new buffer } // Ensure that now the event is correct. ASSERT_DEBUG(event.EventData().Length() == aCorrectSize); } }; void CHCISymbianQdp::FixAddConnectionHandleForTruncatedInvalidConnectionHandleErrorEvents(THCIEventBase& aEvent, const CHCICommandQItem* aRelatedCommand) { LOG_FUNC // Some controllers do not follow the HCI specification in that they do not always return // an event of the correct size - in this case controllers omit a connection handle field when // erroring with "invalid connection handle" error code. One can argue about this but the // command queue is designed with the spec in mind so just adjust the events as appropriate. // // Notably command complete events are the events with issues; if a command status is used // then the error code is communicated without any other parameters, and the resulting events will // not generally be generated (see FixFakeCompletionEventsOnDisconnection). // Current events that have observed (^) this issue (or could potentially have this issue (*)) are: // // ^ Command_Complete (Write_Link_Policy_Settings) // ^ Command_Complete (Read_Link_Policy_Settings) // * Command_Complete (Read_LMP_Handle) // ^ Command_Complete (Role_Discovery) // ^ Command_Complete (Sniff_Subrating) // * Command_Complete (Flush) // * Command_Complete (Read_Auto_Flush_Timeout) // * Command_Complete (Write_Auto_Flush_Timeout) // * Command_Complete (Read_Transmit_Power_Level) // * Command_Complete (Read_Link_Supervision_Timeout) // * Command_Complete (Write_Link_Supervision_Timeout) // * Command_Complete (Read_Failed_Contact_Counter) // * Command_Complete (Reset_Failed_Contact_Counter) // * Command_Complete (Read_Link_Quality) // * Command_Complete (Read_RSSI) // * Command_Complete (Read_AFH_Channel_Map) // * Command_Complete (Read_Clock) // // Only those actually observed as issues are included - the others are commented out for reference if(aEvent.ErrorCode() == ENoConnection) { if(aEvent.EventCode() == ECommandCompleteEvent) { THCICommandCompleteEvent& completeEvent = THCICommandCompleteEvent::Cast(aEvent); // Macro to make the code more concise #define _CHECK_AND_FIX(_COMMAND_NAME, _CORRECT_SIZE, _MISSING_SIZE) \ case K##_COMMAND_NAME##Opcode:\ AttemptToFixCommandCompleteEvent<C##_COMMAND_NAME##Command>::CheckAndFix(completeEvent, aRelatedCommand, iEventModBuffer, (_CORRECT_SIZE), (_MISSING_SIZE));\ break switch(completeEvent.CommandOpcode()) { _CHECK_AND_FIX(WriteLinkPolicySettings, 8, sizeof(THCIConnHandle)); _CHECK_AND_FIX(ReadLinkPolicySettings, 10, sizeof(THCIConnHandle) + sizeof(TUint16)); _CHECK_AND_FIX(RoleDiscovery, 9, sizeof(THCIConnHandle) + sizeof(TUint8)); _CHECK_AND_FIX(SniffSubrating, 8, sizeof(THCIConnHandle)); // These below are included as they potentially could have the same problem, // however in practice this issue has not been observed. // _CHECK_AND_FIX(ReadLMPHandle, 13, sizeof(THCIConnHandle) + sizeof(TUint8) + sizeof(TUint32)); // _CHECK_AND_FIX(Flush, 8, sizeof(THCIConnHandle) + sizeof(TUint8) + sizeof(TUint32)); // _CHECK_AND_FIX(ReadAutomaticFlushTimeout, 10, sizeof(THCIConnHandle) + sizeof(TUint16)); // _CHECK_AND_FIX(WriteAutomaticFlushTimeout, 8, sizeof(THCIConnHandle)); // _CHECK_AND_FIX(ReadTransmitPowerLevel, 9, sizeof(THCIConnHandle) + sizeof(TUint8)); // _CHECK_AND_FIX(ReadLinkSupervisionTimeout, 10, sizeof(THCIConnHandle) + sizeof(TUint16)); // _CHECK_AND_FIX(WriteLinkSupervisionTimeout, 8, sizeof(THCIConnHandle)); // _CHECK_AND_FIX(ReadFailedContactCounter, 10, sizeof(THCIConnHandle) + sizeof(TUint16)); // _CHECK_AND_FIX(ResetFailedContactCounter, 8, sizeof(THCIConnHandle)); // _CHECK_AND_FIX(ReadLinkQuality, 9, sizeof(THCIConnHandle)); // _CHECK_AND_FIX(ReadRSSI, 9, sizeof(THCIConnHandle) + sizeof(TUint8)); // _CHECK_AND_FIX(ReadAFHChannelMap, 19, sizeof(THCIConnHandle) + sizeof(TUint8) + 10); // _CHECK_AND_FIX(ReadClock, 14, sizeof(THCIConnHandle) + sizeof(TUint32) + sizeof(TUint16)); default: // just ignore break; } #undef _CHECK_AND_FIX } } } void CHCISymbianQdp::MhcqemiUnmatchedEventReceived(THCIEventBase& aEvent) { LOG_FUNC #ifdef FAKE_COMPLETION_EVENTS_ON_DISCONNECTION FixFakeCompletionEventsOnDisconnection(aEvent); #endif // FAKE_COMPLETION_EVENTS_ON_DISCONNECTION MhcqdiUnmatchedEventReceived(aEvent); } MHCICmdQueueDecisionInterface::TCommandTimedOutAction CHCISymbianQdp::MhcqdiCommandTimedOut(const CHCICommandQItem& /*aCommand*/, const TDblQue<const CHCICommandQItem>& /*aSentCommands*/, TUint /*aCurrentCommandCredits*/, TUint& aCreditsToBeRefunded) { LOG_FUNC // No Timeout ever set, should never be called. aCreditsToBeRefunded = KHCIDefaultCmdCredits; return EContinueWithTimeoutEvent; } void CHCISymbianQdp::MhcqdiSetPhysicalLinksState(const MPhysicalLinksState& /*aPhysicalLinkState*/) { LOG_FUNC } void CHCISymbianQdp::MhcqdiSetHardResetInitiator(const MHardResetInitiator& /*aHardResetInitiator*/) { LOG_FUNC } void CHCISymbianQdp::MhcqdiSetHCICommandQueue(MHCICommandQueue& /*aHCICommandQueue*/) { LOG_FUNC } void CHCISymbianQdp::MhcqdiSetTimeouts(TUint /*aQueueStarvationTimeout*/, TUint /*aMaxHciCommandTimeout*/) { LOG_FUNC } TUint CHCISymbianQdp::MhcqdiReset() { LOG_FUNC // Return the initial number of command credits for the queue. return KHCIDefaultCmdCredits; } void CHCISymbianQdp::MhcquuSetUtilitiesProvider(MHCICmdQueueUtilities& aProvider) { LOG_FUNC iProvider = &aProvider; }
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
1504b13d1e8ff8d15f16848597a9d14f7261b736
613ea8f52d144343895654cf81090f6afd730f9a
/Level-1/Recursion-1/CheckPalindrome.cpp
018035d4672a4d12e95d89dde2fe0fd7079223cb
[]
no_license
2505shivang/CodingNinjaDS-AlgoSolutions
e74509f302f5328649ce66264975f4616c819db7
48522e2c9ba820663d88d45fafc77419fc546222
refs/heads/main
2023-06-14T21:11:28.282346
2021-07-03T17:47:16
2021-07-03T17:47:16
382,556,549
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
bool helper(char input[],int start, int end){ if(start>=end){ return true; } bool smallans = helper(input,start+1,end-1); if(smallans==true){ if(input[start]==input[end]){ return true; } } return false; } bool checkPalindrome(char input[]) { int i=0; while(input[i]!='\0'){ i++; } return helper(input, 0, i-1); }
[ "2505shivang@gmail.com" ]
2505shivang@gmail.com
9519fb4f7e4ccc7d1e5108f1b72094f52b168bae
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/30/655.c
761d07add011a63d3accb818914696902ac33e54
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
256
c
int main() { int n,i,a,b,c,x,sum=0; scanf("%d",&n); for(i=1;i<=n;i++) { b=(i%10); a=((i-b)/10); if(b==0) b=1; b=b%7; a=a%7; if(i<10) a=1; c=i%7; if(a*b*c==0) continue; sum+=i*i; } printf("%d\n",sum); return 0; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
3305e071bd4e0f4f6638545fb286d59aec217792
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/hackathon/hanchuan/sscope/FlyCapture2/gtk/include/glibmm-2.4/glibmm/private/spawn_p.h
262bdc7ed48c8d2414e4ffaabcd24ea77e08fcd8
[ "MIT" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
145
h
// -*- c++ -*- // Generated by gtkmmproc -- DO NOT MODIFY! #ifndef _GLIBMM_SPAWN_P_H #define _GLIBMM_SPAWN_P_H #endif /* _GLIBMM_SPAWN_P_H */
[ "hanchuan.peng@gmail.com" ]
hanchuan.peng@gmail.com
06df96492ce6f4cda89ab2c33a87901b41288b56
7886017da9fd6be3c794f310c63d60bde36c4b9c
/src/bot/robot.hpp
1c0e441c971cb5d6342e899e7f2c6bef52a0127c
[ "MIT" ]
permissive
btowle/botventure
a8a162a79f23f77a074d3225bcc7bf41c2d8d493
d54de7bfe19947f7cf541a9859ff3a4339cb8897
refs/heads/master
2021-01-10T12:54:37.545103
2015-06-11T04:23:27
2015-06-11T04:23:27
36,896,473
1
1
null
null
null
null
UTF-8
C++
false
false
1,688
hpp
#ifndef bot_robot_ #define bot_robot_ #ifdef RAKE_COMPILATION #include "defaults.hpp" #include "messagereader.hpp" #include "messagewriter.hpp" #include "map2d.hpp" #include "mob.hpp" #else #include "network/defaults.hpp" #include "network/messagereader.hpp" #include "network/messagewriter.hpp" #include "world/map2d.hpp" #include "world/mob.hpp" #endif //RAKE_COMPILATION #include <string> #include "Poco/Net/StreamSocket.h" #include "Poco/Net/SocketAddress.h" #include "Poco/Net/SocketStream.h" namespace Botventure{ namespace Bot{ typedef Messages::Direction Direction; class Robot{ public: Robot() : address("localhost", Network::Defaults::Port), socket(address), sstream(socket), mReader(sstream), mWriter(sstream){ socket.setReceiveTimeout(5000000); socket.setSendTimeout(5000000); } bool Connect(); bool Disconnect(); bool IsConnected(); bool IsPlaying(); bool IsWinner(); int GetTurn(); World::Map2D GetMap(); std::vector<World::Mob> GetEnemies(); World::Mob GetPlayer(); bool Move(Direction direction); bool Attack(Direction direction); bool Wait(); private: bool DoAction(Messages::ActionType actionType, Direction direction); bool RequestMap(); bool GetNextTurn(); Poco::Net::SocketAddress address; Poco::Net::StreamSocket socket; Poco::Net::SocketStream sstream; Network::MessageReader mReader; Network::MessageWriter mWriter; int currentTurn = 0; bool playing = true; bool winner = false; bool connected = false; int mapTurn = -1; World::Map2D map; int enemiesTurn = -1; std::vector<World::Mob> enemies; int playerTurn = -1; World::Mob player; }; } } #endif
[ "thebriantowle@gmail.com" ]
thebriantowle@gmail.com
ae9caa5b7ef4538f8665ab1f0ddc3d8a7f68ff6b
882d3591752a93792bd8c734dd91b1e5439c5ffe
/common-c-library/third_party/json/json/reader.h
5d007e16420773800a870e89b35311a3a493239f
[]
no_license
KingsleyYau/LiveClient
f4d4d2ae23cbad565668b1c4d9cd849ea5ca2231
cdd2694ddb4f1933bef40c5da3cc7d1de8249ae2
refs/heads/master
2022-10-15T13:01:57.566157
2022-09-22T07:37:05
2022-09-22T07:37:05
93,734,517
27
14
null
null
null
null
UTF-8
C++
false
false
6,900
h
#ifndef CPPTL_JSON_READER_H_INCLUDED # define CPPTL_JSON_READER_H_INCLUDED # include "features.h" # include "value.h" # include <deque> # include <stack> # include <string> # include <iostream> namespace Json { /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value. * */ class JSON_API Reader { public: typedef char Char; typedef const Char *Location; /** \brief Constructs a Reader allowing all features * for parsing. */ Reader(); /** \brief Constructs a Reader allowing the specified feature set * for parsing. */ Reader( const Features &features ); /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document. * \param document UTF-8 encoded string containing the document to read. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param collectComments \c true to collect comment and allow writing them back during * serialization, \c false to discard comments. * This parameter is ignored if Features::allowComments_ * is \c false. * \return \c true if the document was successfully parsed, \c false if an error occurred. */ bool parse( const std::string &document, Value &root, bool collectComments = true ); /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document. * \param document UTF-8 encoded string containing the document to read. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param collectComments \c true to collect comment and allow writing them back during * serialization, \c false to discard comments. * This parameter is ignored if Features::allowComments_ * is \c false. * \return \c true if the document was successfully parsed, \c false if an error occurred. */ bool parse( const char *beginDoc, const char *endDoc, Value &root, bool collectComments = true ); /// \brief Parse from input stream. /// \see Json::operator>>(std::istream&, Json::Value&). bool parse( std::istream &is, Value &root, bool collectComments = true ); /** \brief Returns a user friendly string that list errors in the parsed document. * \return Formatted error message with the list of errors with their location in * the parsed document. An empty string is returned if no error occurred * during parsing. */ std::string getFormatedErrorMessages() const; private: enum TokenType { tokenEndOfStream = 0, tokenObjectBegin, tokenObjectEnd, tokenArrayBegin, tokenArrayEnd, tokenString, tokenNumber, tokenTrue, tokenFalse, tokenNull, tokenArraySeparator, tokenMemberSeparator, tokenComment, tokenError }; class Token { public: TokenType type_; Location start_; Location end_; }; class ErrorInfo { public: Token token_; std::string message_; Location extra_; }; typedef std::deque<ErrorInfo> Errors; bool expectToken( TokenType type, Token &token, const char *message ); bool readToken( Token &token ); void skipSpaces(); bool match( Location pattern, int patternLength ); bool readComment(); bool readCStyleComment(); bool readCppStyleComment(); bool readString(); void readNumber(); bool readValue(); bool readObject( Token &token ); bool readArray( Token &token ); bool decodeNumber( Token &token ); bool decodeString( Token &token ); bool decodeString( Token &token, std::string &decoded ); bool decodeDouble( Token &token ); // 在decodeNumber的判断中,如果超过uint的最大值而且有没有double的符号(.,e),就调用decodeLong(之前是调用decodeDouble)alex,2019-09-18 bool decodeLong( Token &token ); bool decodeUnicodeCodePoint( Token &token, Location &current, Location end, unsigned int &unicode ); bool decodeUnicodeEscapeSequence( Token &token, Location &current, Location end, unsigned int &unicode ); bool addError( const std::string &message, Token &token, Location extra = 0 ); bool recoverFromError( TokenType skipUntilToken ); bool addErrorAndRecover( const std::string &message, Token &token, TokenType skipUntilToken ); void skipUntilSpace(); Value &currentValue(); Char getNextChar(); void getLocationLineAndColumn( Location location, int &line, int &column ) const; std::string getLocationLineAndColumn( Location location ) const; void addComment( Location begin, Location end, CommentPlacement placement ); void skipCommentTokens( Token &token ); typedef std::stack<Value *> Nodes; Nodes nodes_; Errors errors_; std::string document_; Location begin_; Location end_; Location current_; Location lastValueEnd_; Value *lastValue_; std::string commentsBefore_; Features features_; bool collectComments_; }; /** \brief Read from 'sin' into 'root'. Always keep comments from the input JSON. This can be used to read a file into a particular sub-object. For example: \code Json::Value root; cin >> root["dir"]["file"]; cout << root; \endcode Result: \verbatim { "dir": { "file": { // The input stream JSON would be nested here. } } } \endverbatim \throw std::exception on parse error. \see Json::operator<<() */ std::istream& operator>>( std::istream&, Value& ); } // namespace Json #endif // CPPTL_JSON_READER_H_INCLUDED
[ "Kingsleyyau@gmail.com" ]
Kingsleyyau@gmail.com
f53de0187d2b712df3ea843863bcf741664d7d6c
44156824b84d26202338b3ca899da374dd43061b
/main.cpp
1fef651c14be72b0fd53470e1e9b3dd897436473
[]
no_license
xyficu/flifilterwheelqt
0f6e1185534215cb67cc9039b1d6a494f52438f8
ef24121619ef5a5cbf4ffdf46125517954656e83
refs/heads/master
2016-09-05T14:59:23.608170
2015-02-08T12:39:42
2015-02-08T12:39:42
27,922,574
0
0
null
2015-01-15T13:37:07
2014-12-12T13:59:59
C++
UTF-8
C++
false
false
192
cpp
#include "mainwindow.h" #include <QApplication> #include "cfwtcp.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
[ "xyficu@gmail.com" ]
xyficu@gmail.com
9ddf79cf2cdec7285c245cb2f2e527e386d45a2b
ba12c564b85a45f7f67043733eff6d392b522a70
/Manager.h
ec8d3994457081e65e4f6374a42ebac768ac2452
[]
no_license
XiaoFan-UCR-CompEngr/TestingBugs
be8e5f0c220fd56985ebe33958a27dcec44a4681
c6f9feae490589527f83d5fef34e1ac4f8e01207
refs/heads/main
2023-02-02T23:51:21.898584
2020-12-09T21:41:37
2020-12-09T21:41:37
320,083,085
0
0
null
null
null
null
UTF-8
C++
false
false
2,249
h
// // Created by 范笑 on 11/25/20. // #ifndef FINAL_PROJECT_XFAN029_HZHAN265_JIANGSHAN_MANAGER_H #define FINAL_PROJECT_XFAN029_HZHAN265_JIANGSHAN_MANAGER_H #include "Employee.h" class Manager : public Employee { public: Manager() { name=""; department=""; address=""; id = 0; salary=0; } Manager(string n,string dep,string addr,int ID,int sala) { name=n; department=dep; address=addr; id = ID; salary=sala; } Manager(string n,string dep,string addr,int ID,int sala,Employee* inputCEO) { name=n; department=dep; address=addr; id = ID; salary=sala; myCEO = inputCEO; } virtual void setName(string name) { this->name = name; } virtual void setId(int id) { this->id = id;} virtual void setSalary(int salary) { this->salary = salary; } virtual void setDepartment(string department) { this->department = department; } virtual void setAddress(string address) { this->address = address; } virtual string getName() { return name; } virtual string getDepartment() { return department; } virtual string getAddress() { return address; } virtual int getSalary() { return salary; } virtual int getID() { return id; } Employee * getCEO() { if(myCEO != nullptr) return myCEO; else return nullptr; } void setCEO(Employee* inputCEO) { myCEO = inputCEO; } virtual void display() override { cout<<"Manager Name: "<<getName()<<endl; cout<<"Department: "<<getDepartment()<<endl; cout<<"address: "<<getAddress()<<endl; cout<<"salary: "<<getSalary()<<endl; cout<<"ID: "<<getID()<<endl; if(getCEO() != nullptr) {cout<<"My CEO is "<<getCEO()->getName()<<endl;} else {cout<<"No CEO now"<<endl;} } virtual ~Manager(){} private: string name; string department; string address; int id; int salary; Employee* myCEO; }; #endif //FINAL_PROJECT_XFAN029_HZHAN265_JIANGSHAN_MANAGER_H
[ "72422851+XiaoFan-UCR-CompEngr@users.noreply.github.com" ]
72422851+XiaoFan-UCR-CompEngr@users.noreply.github.com
c0bb70b3f55851de4b18181e11c0f4b5e1eb08e6
2b027e4b2043a17471282b008f205dd2ac221281
/src/S605th/src/BabyFeed/qwt/qwt_compass_rose.h
19a79f6391bb8ccb66fab9611377f57adc11e89a
[]
no_license
hmiguellima/babyfeed
cd93bcfd7e62b5429089b42b2804fad4588b73c1
162ecf24c742dedd5e856638db3bcb1ba187063e
refs/heads/master
2020-04-07T16:25:37.174103
2019-02-17T16:33:16
2019-02-17T16:33:16
158,528,732
0
0
null
null
null
null
UTF-8
C++
false
false
2,200
h
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #ifndef QWT_COMPASS_ROSE_H #define QWT_COMPASS_ROSE_H 1 #include "qwt_global.h" #include <qpalette.h> class QPainter; /*! \brief Abstract base class for a compass rose */ class QWT_EXPORT QwtCompassRose { public: //! Destructor virtual ~QwtCompassRose() {}; //! Assign a palette virtual void setPalette( const QPalette &p ) { d_palette = p; } //! \return Current palette const QPalette &palette() const { return d_palette; } /*! Draw the rose \param painter Painter \param center Center point \param radius Radius of the rose \param north Position \param colorGroup Color group */ virtual void draw( QPainter *painter, const QPoint &center, int radius, double north, QPalette::ColorGroup colorGroup = QPalette::Active ) const = 0; private: QPalette d_palette; }; /*! \brief A simple rose for QwtCompass */ class QWT_EXPORT QwtSimpleCompassRose: public QwtCompassRose { public: QwtSimpleCompassRose( int numThorns = 8, int numThornLevels = -1 ); virtual ~QwtSimpleCompassRose(); void setWidth( double w ); double width() const; void setNumThorns( int count ); int numThorns() const; void setNumThornLevels( int count ); int numThornLevels() const; void setShrinkFactor( double factor ); double shrinkFactor() const; virtual void draw( QPainter *, const QPoint &center, int radius, double north, QPalette::ColorGroup = QPalette::Active ) const; static void drawRose( QPainter *, const QPalette &, const QPoint &center, int radius, double origin, double width, int numThorns, int numThornLevels, double shrinkFactor ); private: class PrivateData; PrivateData *d_data; }; #endif
[ "hugo.lima@sky.uk" ]
hugo.lima@sky.uk
3d070a89f37a0c5127cfbc47e90e8819a3ef8f9f
2f2e648c40b04322d9c103cd41519280aed83353
/src/daemon/executor.h
f2ec568814a7ea5ee1fd97142c3ba84edaf3ce35
[ "BSD-3-Clause" ]
permissive
equisde/sevabit-last
17243c2c49c0eca6a5aeacf49e81d074cc16c90a
0dee59dbed1b4fb2dbc10844cf430af1bfbb1736
refs/heads/master
2020-04-08T21:34:23.856736
2018-11-30T07:12:08
2018-11-30T07:12:08
159,749,645
1
0
null
null
null
null
UTF-8
C++
false
false
2,466
h
// Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The SevaBit Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include "daemon/daemon.h" #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <string> #undef LOKI_DEFAULT_LOG_CATEGORY #define LOKI_DEFAULT_LOG_CATEGORY "daemon" namespace daemonize { class t_executor final { public: typedef ::daemonize::t_daemon t_daemon; static std::string const NAME; static void init_options( boost::program_options::options_description & configurable_options ); std::string const & name(); t_daemon create_daemon( boost::program_options::variables_map const & vm ); bool run_non_interactive( boost::program_options::variables_map const & vm ); bool run_interactive( boost::program_options::variables_map const & vm ); }; }
[ "manxo369@gmail.com" ]
manxo369@gmail.com
24593518a4454645f08d1975f21d7e5c96f3e96a
05fb91eb3373f35e8d1c0bbf0e77a9704409645d
/sysroot/src/nova-kernel/libcpp/internal/stack.h
4cd64dc14fe514182ed1dc90b8a730dc390159b3
[]
no_license
sethamcbee/nova
33473fa961a5b6239f4052c968a4d57259f1777a
385c33644e3eb21d7fc159fdf6fc429180d149ee
refs/heads/master
2022-03-06T14:33:10.536997
2022-02-07T23:33:05
2022-02-07T23:33:05
151,373,180
1
0
null
null
null
null
UTF-8
C++
false
false
1,019
h
/** * @file stack.h * @author Seth McBee * @date 2019-9-24 */ #pragma once #include <globals.h> #include <deque> namespace std { template <class T, class Container = deque<T>> class stack { public: using value_type = T; using container_type = Container; using reference = value_type&; using const_reference = const value_type&; using size_type = size_t; /** Constructors. **/ explicit stack(const container_type& c) : data(c) {} explicit stack(container_type&& c = container_type()) : data(c) {} /** Member functions. **/ bool empty() const { return data.size() == 0; } size_type size() const { return data.size(); } reference top() { return data.back(); } const_reference top() const { return data.back(); } void push(const_reference e) { data.push_back(e); } void pop() { data.pop_back(); } private: container_type data; }; }
[ "sethamcbee@gmail.com" ]
sethamcbee@gmail.com
8ab0e52d5dd130f07f187e43c780da54a2ef2a94
f25a834f9b7063b313eb8c9967d78e9c923bdd51
/066-PulsOne/solution.cpp
4d539516fe5b60ae7ed10a971bad9c9ca2ec44c2
[]
no_license
siyinm/LeetCodePractice
64fce78ec375134a10c963b2285b50aa0831183d
b28d86dc8c9a62eabfc1f4a2de1a802c7c5b8fcc
refs/heads/master
2021-07-10T05:05:46.304087
2021-01-04T19:29:39
2021-01-04T19:29:39
227,295,952
2
1
null
null
null
null
UTF-8
C++
false
false
461
cpp
class Solution { public: vector<int> plusOne(vector<int>& digits) { int flag = 1; for (int i = digits.size()-1;i>=0;i--){ if (digits[i]!= 9 && flag) { digits[i]+=1; flag = 0; break; } if (digits[i] == 9 && flag){ digits[i] = 0; } } if (flag == 1) digits.insert(digits.begin(), 1); return digits; } };
[ "msy1827@126.com" ]
msy1827@126.com
c0248177ad56ac219dcd84f1badbe6795a24a113
638e9ba3a37e7e91dfea15e9de6b6d4696dce06d
/teamProject/source/COwnhalfManager.cpp
d7e27701cbf17aec2d05bde20fec642adbc15f58
[ "MIT" ]
permissive
shimizuz/RacingBattle
b516eae6688ecedd44bac9cd66414d90cec03c2e
9ae8c0b213219a173de3edaf1e70738b5b988fc8
refs/heads/master
2022-06-13T08:34:38.423590
2015-02-25T08:26:05
2015-02-25T08:26:05
26,419,788
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,050
cpp
//============================================================================== // // 陣地マネージャ // Author : Masahiro Yamaguchi // // 陣地のマネージャクラスです。 // マネージャといってもほぼマネージングしないんですけどね。 // //============================================================================== //============================================================================== //ヘッダーインクルード //============================================================================== #include "COwnhalfManager.h" #include "COwnhalf.h" #include <assert.h> #include <cmath> #include <d3dx9.h> //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // const //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ namespace { const float kInitDistance = 30.0f; } //============================================================================== // コンストラクタ //============================================================================== COwnhalfManager::COwnhalfManager() { for (int i = 0; i < kNumOwnhalfs; ++i) { m_pOwnhalfs[i] = nullptr; } for (int i = 0; i < kNumOwnhalfs; ++i) { m_pOwnhalfs[i] = new COwnhalf(); m_pOwnhalfs[i]->Init(5.0f,5.0f); } float angle = 0; for (int i = 0; i < kNumOwnhalfs; ++i) { CVector pos ( sinf(angle) * kInitDistance, 1.0f, cosf(angle) * kInitDistance); m_pOwnhalfs[i]->SetPosition(pos); angle += D3DX_PI * 0.5f; } } //============================================================================== // デストラクタ //============================================================================== COwnhalfManager::~COwnhalfManager() { } //============================================================================== // 範囲チェック //============================================================================== void COwnhalfManager::_CheckRange(int id) { assert(id < kNumOwnhalfs && "アーウ範囲外だぞ"); } //eof
[ "maxwel.masa@gmail.com" ]
maxwel.masa@gmail.com
877fa7c27a57527949401d8e0784fbec237527b9
ed384d8fa2203e649803d165e8ccf3e08c014be6
/第2章类对象所占的内存空间/classObject/2_8程序的优化_编译器层面.cpp
37f306cf25a68e36569e619cab5231845dcb80bb
[]
no_license
easyzoom/cPlusPlus-object-Model
dd9d5ad969f7392e4f676d55f04440c9202fcd73
c9e90586bf13884f59fbdf6224ccf9d2b417a1eb
refs/heads/master
2023-07-14T02:03:27.901548
2020-05-25T01:57:28
2020-05-25T01:57:28
null
0
0
null
null
null
null
GB18030
C++
false
false
2,319
cpp
#include<iostream> #include<cstdlib> #include<functional> #include <vector> #include <algorithm> #include <ctime> using namespace std; class CTemValue { public: int value1; int value2; public: CTemValue(int v1 = 0, int v2 = 0) :value1(v1), value2(v2)//构造函数 { cout << "调用了构造函数" << endl; cout << "value1=" << value1 << endl; cout << "value2=" << value2 << endl; } CTemValue(const CTemValue &ct) :value1(ct.value1), value2(ct.value2) { cout << "调用了拷贝构造函数" << endl; } virtual ~CTemValue() { cout << "调用了析构函数" << endl; } }; //开发者视角 CTemValue DoubleMyself(CTemValue&t) { //(1)开发者层面 //测试执行1000000次的使用时间,未实现 clock_t start, end; start = clock();//返回执行到这里的时间,毫秒 //测试代码 end = clock(); CTemValue tem; tem.value1 = t.value1 * 2; tem.value2 = t.value2 * 2; return tem;//生成一个临时对象,然后调用拷贝构造函数把tem对象拷贝到主调函数的内存空间。 //优化后 //return CTemValue(t.value1 * 2, t.value2 * 2);//生成一个临时对象直接返回 } //编译器视角 void DoubleMyself(CTemValue&obj, CTemValue&t) { obj.CTemValue::CTemValue(t.value1 * 2, t.value2 * 2); return; } int main(void) { CTemValue ts1(10, 20); //CTemValue ts2=DoubleMyself(ts1);//使用一个对象来接收,就会少一个析构函数 DoubleMyself(ts1); /* * 编译器视角 * CTemValue ts1; * ts1.CTemValue::CTemValue(10,20); * CTemValue temObj; * DoubleMyself(temObj,ts1); */ system("pause"); return 0; } /* *在linux平台执行这个代码 * (1)编译器层面 * linux下面的g++编译器会对针对返回临时值进行优化,NRV优化(named Return Value) * ROV优化(return Value Optimization) * 关闭优化: * g++ -fno-elide-constructors 文件名.cpp -o 生成文件名字 * (2)在Windows平台,项目属性右击--“属性”--“c/c++”--"优化" * “代码生成”--“基本运行时检查”--“默认值” * (4)优化说明: * 1.编译器是否真正优化了需要做测试 * 2.当代码很复杂,编译器会放弃优化 * 3.不要过度优化,过度优化可能导致程序错误,如你向在构造函数里面实现某些功能,但是被优化掉没有执行。 * * (5) * (6)(7) */
[ "baiqianlong@126.com" ]
baiqianlong@126.com
72988cf780c022e8383ebf6a5ced5fcd093c8420
b04baa5011362f9088a60f63e759be288359c7f1
/cs32/lab06/main2.cpp
b20d81cf30bb3ff27c095b704f84734b4c007ce6
[]
no_license
nickkpoon/CS
64ca939aa1ecf9e318fbc8c1a402983a10b1c0fc
c3827ca115ba0560cf0c085952be97a48929b5b0
refs/heads/master
2021-01-10T22:22:54.535762
2015-06-04T13:48:07
2015-06-04T13:48:07
36,873,012
0
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
// main2.cpp - tests optional and homework parts of Vec3 class // depends on working parts of the "Overloading operators in C++" lab #include <iostream> #include "vec.h" using namespace std; int main(int argc, char *argv[]) { Vec3 vec_0; const Vec3 vec_1(5.5, 6.6, 7.7); cout << "Input three doubles: "; cin >> vec_0; cout << "Input vector: " << vec_0 << endl; cout << "Constant vector: " << vec_1 << endl; // For testing the three optional, "After lab-work" items: /* Uncomment the following 2 lines when * is overloaded for double on left*/ //cout << "Simple multiplication: " << (8 * vec_0) << endl; //cout << "More multiplication: " << (3 * vec_0 * 2) << endl; /* Uncomment the following 2 lines when binary - is overloaded */ //cout << "Input vector - const vector: " << (vec_0 - vec_1) << endl; //cout << "More subtraction: " << (vec_0 - vec_1 - vec_0 - vec_1) << endl; /* Uncomment the following 3 lines when *= is overloaded*/ //vec_0 *= 2; //cout << "Input vector after *= 2: " << vec_0 << endl; //cout << "Last result *=.5: " << (vec_0 *= .5) << endl; // For testing the three homework items (actually five functions): /* Uncomment the following 2 lines when += is overloaded*/ cout << "Input vec += constant vec: " << (vec_0 += vec_1) << endl; cout << " Verify still changed: " << vec_0 << endl; /* Uncomment the following 4 lines when both versions of ++ overloaded */ cout << "++(Last vec) : " << ++vec_0 << endl; cout << " Verify same: " << vec_0 << endl; cout << "(Last vec)++ : " << vec_0++ << endl; cout << " Verify diff: " << vec_0 << endl; /* Uncomment the following 3 lines when both versions of [] overloaded */ cout << "Constant's data: " << vec_1[0] << " " << vec_1[1] << " " << vec_1[2] << endl; vec_0[0] = vec_0[1] = vec_0[2] = 77.77; cout << "Final vec: " << vec_0 << endl; }
[ "nickkpoon@gmail.com" ]
nickkpoon@gmail.com
8fd4dcbcf49949e52b884cff8b278f14f4f6ffc3
7a7ee8cca53e90f3876c5467162cb0eb9b3bcf9d
/Engine/LogicBricks/gkMessageSensor.cpp
613372acaeeca30c65d1aa578a8b7a64389d7695
[]
no_license
cnsuhao/gamekit
1a7818426c5235330417c84d927f26e2cc14616d
7f898af29bb19ccb0995e39276a01a3adf0169a0
refs/heads/master
2021-05-26T20:06:36.266706
2012-05-20T17:00:26
2012-05-20T17:00:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,856
cpp
/* ------------------------------------------------------------------------------- This file is part of OgreKit. http://gamekit.googlecode.com/ Copyright (c) 2006-2010 Xavier T. Contributor(s): none yet. ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "gkMessageSensor.h" #include "gkLogicManager.h" #include "gkLogicDispatcher.h" gkMessageSensor::gkMessageSensor(gkGameObject* object, gkLogicLink* link, const gkString& name) : gkLogicSensor(object, link, name) { m_listener = new gkMessageManager::GenericMessageListener("",object->getName(),""); m_listener->setAcceptEmptyTo(true); gkMessageManager::getSingleton().addListener(m_listener); m_dispatchType = DIS_CONSTANT; connect(); } gkMessageSensor::~gkMessageSensor() { gkMessageManager::getSingleton().removeListener(m_listener); delete m_listener; m_messages.clear(); } gkLogicBrick* gkMessageSensor::clone(gkLogicLink* link, gkGameObject* dest) { gkMessageSensor* sens = new gkMessageSensor(*this); sens->cloneImpl(link, dest); sens->m_listener = new gkMessageManager::GenericMessageListener("", "", m_listener->m_subjectFilter); gkMessageManager::getSingleton().addListener(sens->m_listener); return sens; } bool gkMessageSensor::query(void) { bool ret = false; m_messages.clear(); if (m_listener->m_messages.size() > 0 ) { ret = true; // We copy the massages so that Logic scripts can retrieve messages recieved between each logic step utArrayIterator<utArray<gkMessageManager::Message> > iter(m_listener->m_messages); while (iter.hasMoreElements()) { gkMessageManager::Message m = iter.peekNext(); if (m.m_to=="" || m.m_to == m_object->getName()) { m_messages.push_back(m); } iter.getNext(); } } m_listener->emptyMessages(); return ret; }
[ "exeqtor@gmail.com" ]
exeqtor@gmail.com
99f2bc872591cd6e08021b27d0c32fc03f7dc9bb
5961bacb57bb7830044a2c1dedead099a1d7c2bb
/tensorflow_serving/core/caching_manager.h
f0cf3b9ed692b022aa745058a506bb954a6f57ae
[ "Apache-2.0" ]
permissive
amadu80/serving
eb9fbb743c91e2070f1577bb9defaa5b19a4d87a
9769786fdc0b500d6d62c93c27533ddccce7c16c
refs/heads/master
2021-01-17T20:52:40.857288
2016-05-18T22:42:35
2016-05-18T22:42:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,517
h
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 TENSORFLOW_SERVING_CORE_CACHING_MANAGER_H_ #define TENSORFLOW_SERVING_CORE_CACHING_MANAGER_H_ #include <map> #include <memory> #include <string> #include <vector> #include "tensorflow_serving/core/basic_manager.h" #include "tensorflow_serving/core/manager.h" namespace tensorflow { namespace serving { // A manager that manages and loads servables on-demand. Upon receiving the // request for a servable name and optional version, the manager checks if it // already has the requested servable loaded. If not, it initiates the load // operation and then serves the request. // // The manager blocks on the load operation and returns the handle when the // servable has been loaded, or upon error. // // TODO(b/25449742): Add support for evictions of loaded servables from the // caching-manager. class CachingManager : public Manager { public: struct Options { // The resource tracker to use while managing servable resources. Optional. // If left as nullptr, we do not validate servable resource usage. std::unique_ptr<ResourceTracker> resource_tracker; // The number of threads in the thread-pool used to load and unload // servables. // // If set as 0, we don't use a thread-pool, and the {Load,Unload}Servable() // methods block. uint32 num_load_unload_threads = 0; // EventBus to publish servable state changes. This is optional, if unset, // we don't publish. EventBus<ServableState>* servable_event_bus = nullptr; // Maximum number of times we retry loading a servable, after the first // failure, before we give up. If set to 0, a load is attempted only once. uint32 max_num_load_retries = 5; // The interval, in microseconds, between each servable load retry. If set // negative, we don't wait. // Default: 1 minute. int64 load_retry_interval_micros = 1LL * 60 * 1000 * 1000; // The environment to use for starting threads in the thread-pool. Env* env = Env::Default(); }; // An abstraction for a loader-factory to map from a servable request to the // corresponding loader. class LoaderFactory { public: virtual ~LoaderFactory() = default; // Creates servable data consisting of the loader corresponding to the // servable-id. virtual Status CreateLoader( const ServableId& servable_id, std::unique_ptr<ServableData<std::unique_ptr<Loader>>>* loader_data) = 0; // Returns the latest version corresponding to the servable name. virtual int64 GetLatestVersion(const string& servable_name) const = 0; }; static Status Create(Options options, std::unique_ptr<LoaderFactory> loader_factory, std::unique_ptr<CachingManager>* caching_manager); ~CachingManager() override; std::map<ServableId, std::unique_ptr<UntypedServableHandle>> GetAvailableUntypedServableHandles() const override; std::vector<ServableId> ListAvailableServableIds() const override; private: CachingManager(std::unique_ptr<LoaderFactory> loader_factory, std::unique_ptr<BasicManager> basic_manager); // Returns the untyped handle for the servable request. // // Semantics related to a ServableRequest for "latest": // The manager forwards the "latest" request to the loader-factory, which // emits its notion of the "latest" version. This is then managed and loaded // by the manager, if not already available, and a handle to it is returned. Status GetUntypedServableHandle( const ServableRequest& request, std::unique_ptr<UntypedServableHandle>* handle) override; // Returns the untyped handle for a servable-id. Status GetUntypedServableHandleForId( const ServableId& servable_id, std::unique_ptr<UntypedServableHandle>* handle); // Load the servable corresponding to the servable-id. For multiple concurrent // requests for the same servable-id, enforces that exactly one thread // performs the load operation using the wrapped basic-manager. All other // requests block until the load completes and then trivially succeed. Status LoadServable(const ServableId& servable_id) LOCKS_EXCLUDED(load_mutex_map_mu_); std::unique_ptr<LoaderFactory> loader_factory_; std::unique_ptr<BasicManager> basic_manager_; // Used to protect access to the load_mutex_map_. mutable mutex load_mutex_map_mu_; // Map of servable-id to a mutex, which is required to synchronize calls to // load the servable using the wrapped basic-manager. // TODO(b/28445976): Add support for garbage-collection of map entries. std::map<ServableId, std::unique_ptr<mutex>> load_mutex_map_ GUARDED_BY(load_mutex_map_mu_); TF_DISALLOW_COPY_AND_ASSIGN(CachingManager); }; } // namespace serving } // namespace tensorflow #endif // TENSORFLOW_SERVING_CORE_CACHING_MANAGER_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
16b2de8e4ef8dccf3e563801c02953e9089733c1
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/inetsrv/msmq/src/lib/mp/lib/envusrheader.cpp
9bf7f27aab3d63cc99ea96bb91884652a91f9c8f
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
762
cpp
/*++ Copyright (c) 1995-97 Microsoft Corporation Module Name: envbody.cpp Abstract: Implementing serialization of the user supplied header to the SRMP envelop Author: Gil Shafriri(gilsh) 24-APRIL-01 --*/ #include <libpch.h> #include <qmpkt.h> #include "envcommon.h" #include "envusrheader.h" using namespace std; std::wostream& operator<<(std::wostream& wstr, const UserHeaderElement& UserHeader) { if(!UserHeader.m_pkt.IsSoapIncluded() ) return wstr; const WCHAR* pUserHeader = UserHeader.m_pkt.GetPointerToSoapHeader(); if(pUserHeader == NULL) return wstr; ASSERT(UserHeader.m_pkt.GetSoapHeaderLengthInWCHARs() == wcslen(pUserHeader) +1); return wstr<<pUserHeader; }
[ "112426112@qq.com" ]
112426112@qq.com
0e6ffa4de3b60b5e2d0c09e33fa70472bf1343e0
4d1ceea7ad28e2128e0f46418384d7c88dadaa49
/ProjectFoil/Source/ProjectFoil/ProjectFoilGameMode.cpp
c059958a5dad57b72ec0f9742efb3a72e0e2ee6b
[]
no_license
wanted28496/PreojectFoil
47b36cc72f44192cebe40783d8f9e85b82024e11
b2b8eddce64ab81b3c028a1ad00f9133aec92ce2
refs/heads/master
2022-02-17T23:14:52.252996
2019-08-29T06:30:14
2019-08-29T06:30:14
203,440,851
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "ProjectFoilGameMode.h" #include "ProjectFoilHUD.h" #include "ProjectFoilCharacter.h" #include "UObject/ConstructorHelpers.h" AProjectFoilGameMode::AProjectFoilGameMode() : Super() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnClassFinder(TEXT("/Game/FirstPersonCPP/Blueprints/FirstPersonCharacter")); DefaultPawnClass = PlayerPawnClassFinder.Class; // use our custom HUD class //HUDClass = AProjectFoilHUD::StaticClass(); }
[ "mit.doshi557@gmail.com" ]
mit.doshi557@gmail.com
264de6fc2777525f29648e48500c03cad4a19f82
48bc8be51c7e78d563f219bb80f8ec5e6e9743c6
/imgui/imgui_draw.cpp
beda8a5b9f0f40d9e5bb7ab870ed20a384354f48
[]
no_license
entropian/Simple2DParticles
c27d73a5277b14c226dfa659fcd35cebf4acb75f
a7b96901ad882a3d0081d475de9e514961bc0dc3
refs/heads/master
2020-04-07T15:39:33.730469
2019-10-11T04:21:21
2019-10-11T04:21:21
158,494,970
1
0
null
null
null
null
UTF-8
C++
false
false
102,499
cpp
// ImGui library v1.46 WIP // Drawing and font code // Contains implementation for // - ImDrawList // - ImDrawData // - ImFontAtlas // - ImFont // - Default font data #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui_internal.h" #include <stdio.h> // vsnprintf, sscanf, printf #include <new> // new (ptr) #ifndef alloca #if _WIN32 #include <malloc.h> // alloca #else #include <alloca.h> // alloca #endif #endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #define snprintf _snprintf #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #endif //------------------------------------------------------------------------- // STB libraries implementation //------------------------------------------------------------------------- //#define IMGUI_STB_NAMESPACE ImGuiStb //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION #ifdef IMGUI_STB_NAMESPACE namespace IMGUI_STB_NAMESPACE { #endif #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #endif #define STBRP_ASSERT(x) IM_ASSERT(x) #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION #define STBRP_STATIC #define STB_RECT_PACK_IMPLEMENTATION #endif #include "stb_rect_pack.h" #define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) #define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) #define STBTT_assert(x) IM_ASSERT(x) #ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #else #define STBTT_DEF extern #endif #include "stb_truetype.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef _MSC_VER #pragma warning (pop) #endif #ifdef IMGUI_STB_NAMESPACE } // namespace ImGuiStb using namespace IMGUI_STB_NAMESPACE; #endif //----------------------------------------------------------------------------- // ImDrawList //----------------------------------------------------------------------------- static ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift void ImDrawList::Clear() { CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.resize(0); _TextureIdStack.resize(0); _Path.resize(0); _ChannelsCurrent = 0; _ChannelsCount = 1; // NB: Do not clear channels so our allocations are re-used after the first frame. } void ImDrawList::ClearFreeMemory() { CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.clear(); _TextureIdStack.clear(); _Path.clear(); _ChannelsCurrent = 0; _ChannelsCount = 1; for (int i = 0; i < _Channels.Size; i++) { if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again _Channels[i].CmdBuffer.clear(); _Channels[i].IdxBuffer.clear(); } _Channels.clear(); } void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; draw_cmd.ClipRect = _ClipRectStack.Size ? _ClipRectStack.back() : GNullClipRect; draw_cmd.TextureId = _TextureIdStack.Size ? _TextureIdStack.back() : NULL; IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); CmdBuffer.push_back(draw_cmd); } void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) { AddDrawCmd(); current_cmd = &CmdBuffer.back(); } current_cmd->UserCallback = callback; current_cmd->UserCallbackData = callback_data; // Force a new command after us (we function this way so that the most common calls AddLine, AddRect, etc. always have a command to add to without doing any check). AddDrawCmd(); } void ImDrawList::UpdateClipRect() { ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; if (!current_cmd || (current_cmd->ElemCount != 0) || current_cmd->UserCallback != NULL) { AddDrawCmd(); } else { ImVec4 current_clip_rect = _ClipRectStack.Size ? _ClipRectStack.back() : GNullClipRect; if (CmdBuffer.Size >= 2 && ImLengthSqr(CmdBuffer.Data[CmdBuffer.Size-2].ClipRect - current_clip_rect) < 0.00001f) CmdBuffer.pop_back(); else current_cmd->ClipRect = current_clip_rect; } } // Scissoring. The values in clip_rect are x1, y1, x2, y2. void ImDrawList::PushClipRect(const ImVec4& clip_rect) { _ClipRectStack.push_back(clip_rect); UpdateClipRect(); } void ImDrawList::PushClipRectFullScreen() { PushClipRect(GNullClipRect); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiState from here? //ImGuiState& g = *GImGui; //PushClipRect(GetVisibleRect()); } void ImDrawList::PopClipRect() { IM_ASSERT(_ClipRectStack.Size > 0); _ClipRectStack.pop_back(); UpdateClipRect(); } void ImDrawList::UpdateTextureID() { ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; const ImTextureID texture_id = _TextureIdStack.Size ? _TextureIdStack.back() : NULL; if (!current_cmd || (current_cmd->ElemCount != 0 && current_cmd->TextureId != texture_id) || current_cmd->UserCallback != NULL) AddDrawCmd(); else current_cmd->TextureId = texture_id; } void ImDrawList::PushTextureID(const ImTextureID& texture_id) { _TextureIdStack.push_back(texture_id); UpdateTextureID(); } void ImDrawList::PopTextureID() { IM_ASSERT(_TextureIdStack.Size > 0); _TextureIdStack.pop_back(); UpdateTextureID(); } void ImDrawList::ChannelsSplit(int channels_count) { IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) _Channels.resize(channels_count); _ChannelsCount = channels_count; // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer memset(&_Channels[0], 0, sizeof(ImDrawChannel)); for (int i = 1; i < channels_count; i++) { if (i >= old_channels_count) { new(&_Channels[i]) ImDrawChannel(); } else { _Channels[i].CmdBuffer.resize(0); _Channels[i].IdxBuffer.resize(0); } if (_Channels[i].CmdBuffer.Size == 0) { ImDrawCmd draw_cmd; draw_cmd.ClipRect = _ClipRectStack.back(); draw_cmd.TextureId = _TextureIdStack.back(); _Channels[i].CmdBuffer.push_back(draw_cmd); } } } void ImDrawList::ChannelsMerge() { // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. if (_ChannelsCount <= 1) return; ChannelsSetCurrent(0); if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) CmdBuffer.pop_back(); int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; for (int i = 1; i < _ChannelsCount; i++) { ImDrawChannel& ch = _Channels[i]; if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) ch.CmdBuffer.pop_back(); new_cmd_buffer_count += ch.CmdBuffer.Size; new_idx_buffer_count += ch.IdxBuffer.Size; } CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; for (int i = 1; i < _ChannelsCount; i++) { ImDrawChannel& ch = _Channels[i]; if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } } AddDrawCmd(); _ChannelsCount = 1; } void ImDrawList::ChannelsSetCurrent(int idx) { if (_ChannelsCurrent == idx) return; memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); _ChannelsCurrent = idx; memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; } // NB: this can be called with negative count for removing primitives (as long as the result does not underflow) void ImDrawList::PrimReserve(int idx_count, int vtx_count) { ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; draw_cmd.ElemCount += idx_count; int vtx_buffer_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_size + vtx_count); _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size; int idx_buffer_size = IdxBuffer.Size; IdxBuffer.resize(idx_buffer_size + idx_count); _IdxWritePtr = IdxBuffer.Data + idx_buffer_size; } void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { const ImVec2 uv = GImGui->FontTexUvWhitePixel; const ImVec2 b(c.x, a.y); const ImVec2 d(a.x, c.y); _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _VtxCurrentIdx += 4; _IdxWritePtr += 6; } void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) { const ImVec2 b(c.x, a.y); const ImVec2 d(a.x, c.y); const ImVec2 uv_b(uv_c.x, uv_a.y); const ImVec2 uv_d(uv_a.x, uv_c.y); _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _VtxCurrentIdx += 4; _IdxWritePtr += 6; } // TODO: Thickness anti-aliased lines cap are missing their AA fringe. void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased) { if (points_count < 2) return; const ImVec2 uv = GImGui->FontTexUvWhitePixel; anti_aliased &= GImGui->Style.AntiAliasedLines; //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug int count = points_count; if (!closed) count = points_count-1; const bool thick_line = thickness > 1.0f; if (anti_aliased) { // Anti-aliased stroke const float AA_SIZE = 1.0f; const ImU32 col_trans = col & 0x00ffffff; const int idx_count = thick_line ? count*18 : count*12; const int vtx_count = thick_line ? points_count*4 : points_count*3; PrimReserve(idx_count, vtx_count); // Temporary buffer ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); ImVec2* temp_points = temp_normals + points_count; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; ImVec2 diff = points[i2] - points[i1]; diff *= ImInvLength(diff, 1.0f); temp_normals[i1].x = diff.y; temp_normals[i1].y = -diff.x; } if (!closed) temp_normals[points_count-1] = temp_normals[points_count-2]; if (!thick_line) { if (!closed) { temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; // Average normals ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; float dmr2 = dm.x*dm.x + dm.y*dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; if (scale > 100.0f) scale = 100.0f; dm *= scale; } dm *= AA_SIZE; temp_points[i2*2+0] = points[i2] + dm; temp_points[i2*2+1] = points[i2] - dm; // Add indexes _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); _IdxWritePtr += 12; idx1 = idx2; } // Add vertexes for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; _VtxWritePtr += 3; } } else { const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; if (!closed) { temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; // Average normals ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; float dmr2 = dm.x*dm.x + dm.y*dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; if (scale > 100.0f) scale = 100.0f; dm *= scale; } ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); ImVec2 dm_in = dm * half_inner_thickness; temp_points[i2*4+0] = points[i2] + dm_out; temp_points[i2*4+1] = points[i2] + dm_in; temp_points[i2*4+2] = points[i2] - dm_in; temp_points[i2*4+3] = points[i2] - dm_out; // Add indexes _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); _IdxWritePtr += 18; idx1 = idx2; } // Add vertexes for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; _VtxWritePtr += 4; } } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { // Non Anti-aliased Stroke const int idx_count = count*6; const int vtx_count = count*4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; const ImVec2& p1 = points[i1]; const ImVec2& p2 = points[i2]; ImVec2 diff = p2 - p1; diff *= ImInvLength(diff, 1.0f); const float dx = diff.x * (thickness * 0.5f); const float dy = diff.y * (thickness * 0.5f); _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); _IdxWritePtr += 6; _VtxCurrentIdx += 4; } } } void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased) { const ImVec2 uv = GImGui->FontTexUvWhitePixel; anti_aliased &= GImGui->Style.AntiAliasedShapes; //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug if (anti_aliased) { // Anti-aliased Fill const float AA_SIZE = 1.0f; const ImU32 col_trans = col & 0x00ffffff; const int idx_count = (points_count-2)*3 + points_count*6; const int vtx_count = (points_count*2); PrimReserve(idx_count, vtx_count); // Add indexes for fill unsigned int vtx_inner_idx = _VtxCurrentIdx; unsigned int vtx_outer_idx = _VtxCurrentIdx+1; for (int i = 2; i < points_count; i++) { _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); _IdxWritePtr += 3; } // Compute normals ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; const ImVec2& p1 = points[i1]; ImVec2 diff = p1 - p0; diff *= ImInvLength(diff, 1.0f); temp_normals[i0].x = diff.y; temp_normals[i0].y = -diff.x; } for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { // Average normals const ImVec2& n0 = temp_normals[i0]; const ImVec2& n1 = temp_normals[i1]; ImVec2 dm = (n0 + n1) * 0.5f; float dmr2 = dm.x*dm.x + dm.y*dm.y; if (dmr2 > 0.000001f) { float scale = 1.0f / dmr2; if (scale > 100.0f) scale = 100.0f; dm *= scale; } dm *= AA_SIZE * 0.5f; // Add vertices _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer _VtxWritePtr += 2; // Add indexes for fringes _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr += 6; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { // Non Anti-aliased Fill const int idx_count = (points_count-2)*3; const int vtx_count = points_count; PrimReserve(idx_count, vtx_count); for (int i = 0; i < vtx_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; _VtxWritePtr++; } for (int i = 2; i < points_count; i++) { _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); _IdxWritePtr += 3; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; } } void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax) { static ImVec2 circle_vtx[12]; static bool circle_vtx_builds = false; const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx); if (!circle_vtx_builds) { for (int i = 0; i < circle_vtx_count; i++) { const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI; circle_vtx[i].x = cosf(a); circle_vtx[i].y = sinf(a); } circle_vtx_builds = true; } if (amin > amax) return; if (radius == 0.0f) { _Path.push_back(centre); } else { _Path.reserve(_Path.Size + (amax - amin + 1)); for (int a = amin; a <= amax; a++) { const ImVec2& c = circle_vtx[a % circle_vtx_count]; _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); } } } void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments) { if (radius == 0.0f) _Path.push_back(centre); _Path.reserve(_Path.Size + (num_segments + 1)); for (int i = 0; i <= num_segments; i++) { const float a = amin + ((float)i / (float)num_segments) * (amax - amin); _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); } } static void PathBezierToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) { float dx = x4 - x1; float dy = y4 - y1; float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) { path->push_back(ImVec2(x4, y4)); } else if (level < 10) { float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); } } void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) { ImVec2 p1 = _Path.back(); if (num_segments == 0) { // Auto-tessellated PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0); } else { float t_step = 1.0f / (float)num_segments; for (int i_step = 1; i_step <= num_segments; i_step++) { float t = t_step * i_step; float u = 1.0f - t; float w1 = u*u*u; float w2 = 3*u*u*t; float w3 = 3*u*t*t; float w4 = t*t*t; _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); } } } void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) { float r = rounding; r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f); r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f); if (r <= 0.0f || rounding_corners == 0) { PathLineTo(a); PathLineTo(ImVec2(b.x,a.y)); PathLineTo(b); PathLineTo(ImVec2(a.x,b.y)); } else { const float r0 = (rounding_corners & 1) ? r : 0.0f; const float r1 = (rounding_corners & 2) ? r : 0.0f; const float r2 = (rounding_corners & 4) ? r : 0.0f; const float r3 = (rounding_corners & 8) ? r : 0.0f; PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9); PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12); PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3); PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6); } } void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) { if ((col >> 24) == 0) return; PathLineTo(a + ImVec2(0.5f,0.5f)); PathLineTo(b + ImVec2(0.5f,0.5f)); PathStroke(col, false, thickness); } void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) { if ((col >> 24) == 0) return; PathRect(a + ImVec2(0.5f,0.5f), b + ImVec2(0.5f,0.5f), rounding, rounding_corners); PathStroke(col, true); } void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) { if ((col >> 24) == 0) return; if (rounding > 0.0f) { PathRect(a, b, rounding, rounding_corners); PathFill(col); } else { PrimReserve(6, 4); PrimRect(a, b, col); } } void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) { if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) >> 24) == 0) return; const ImVec2 uv = GImGui->FontTexUvWhitePixel; PrimReserve(6, 4); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); PrimWriteVtx(a, uv, col_upr_left); PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); PrimWriteVtx(c, uv, col_bot_right); PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); } void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) { if ((col >> 24) == 0) return; PathLineTo(a); PathLineTo(b); PathLineTo(c); PathFill(col); } void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments) { if ((col >> 24) == 0) return; const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(centre, radius, 0.0f, a_max, num_segments); PathStroke(col, true); } void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) { if ((col >> 24) == 0) return; const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(centre, radius, 0.0f, a_max, num_segments); PathFill(col); } void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) { if ((col >> 24) == 0) return; PathLineTo(pos0); PathBezierCurveTo(cp0, cp1, pos1, num_segments); PathStroke(col, false, thickness); } void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) { if ((col >> 24) == 0) return; if (text_end == NULL) text_end = text_begin + strlen(text_begin); if (text_begin == text_end) return; IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. // reserve vertices for worse case (over-reserving is useful and easily amortized) const int char_count = (int)(text_end - text_begin); const int vtx_count_max = char_count * 4; const int idx_count_max = char_count * 6; const int vtx_begin = VtxBuffer.Size; const int idx_begin = IdxBuffer.Size; PrimReserve(idx_count_max, vtx_count_max); ImVec4 clip_rect = _ClipRectStack.back(); if (cpu_fine_clip_rect) { clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); } font->RenderText(font_size, pos, col, clip_rect, text_begin, text_end, this, wrap_width, cpu_fine_clip_rect != NULL); // give back unused vertices // FIXME-OPT: clean this up VtxBuffer.resize((int)(_VtxWritePtr - VtxBuffer.Data)); IdxBuffer.resize((int)(_IdxWritePtr - IdxBuffer.Data)); int vtx_unused = vtx_count_max - (VtxBuffer.Size - vtx_begin); int idx_unused = idx_count_max - (IdxBuffer.Size - idx_begin); CmdBuffer.back().ElemCount -= idx_unused; _VtxWritePtr -= vtx_unused; _IdxWritePtr -= idx_unused; _VtxCurrentIdx = (ImDrawIdx)VtxBuffer.Size; } // This is one of the few function breaking the encapsulation of ImDrawLst, but it is just so useful. void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) { if ((col >> 24) == 0) return; AddText(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end); } void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) { if ((col >> 24) == 0) return; // FIXME-OPT: This is wasting draw calls. const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); if (push_texture_id) PushTextureID(user_texture_id); PrimReserve(6, 4); PrimRectUV(a, b, uv0, uv1, col); if (push_texture_id) PopTextureID(); } //----------------------------------------------------------------------------- // ImDrawData //----------------------------------------------------------------------------- // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! void ImDrawData::DeIndexAllBuffers() { ImVector<ImDrawVert> new_vtx_buffer; TotalVtxCount = TotalIdxCount = 0; for (int i = 0; i < CmdListsCount; i++) { ImDrawList* cmd_list = CmdLists[i]; if (cmd_list->IdxBuffer.empty()) continue; new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; cmd_list->VtxBuffer.swap(new_vtx_buffer); cmd_list->IdxBuffer.resize(0); TotalVtxCount += cmd_list->VtxBuffer.Size; } } // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. void ImDrawData::ScaleClipRects(const ImVec2& scale) { for (int i = 0; i < CmdListsCount; i++) { ImDrawList* cmd_list = CmdLists[i]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); } } } //----------------------------------------------------------------------------- // ImFontAtlas //----------------------------------------------------------------------------- ImFontConfig::ImFontConfig() { FontData = NULL; FontDataSize = 0; FontDataOwnedByAtlas = true; FontNo = 0; SizePixels = 0.0f; OversampleH = 3; OversampleV = 1; PixelSnapH = false; GlyphExtraSpacing = ImVec2(0.0f, 0.0f); GlyphRanges = NULL; MergeMode = false; MergeGlyphCenterV = false; DstFont = NULL; memset(Name, 0, sizeof(Name)); } ImFontAtlas::ImFontAtlas() { TexID = NULL; TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; TexWidth = TexHeight = TexDesiredWidth = 0; TexUvWhitePixel = ImVec2(0, 0); } ImFontAtlas::~ImFontAtlas() { Clear(); } void ImFontAtlas::ClearInputData() { for (int i = 0; i < ConfigData.Size; i++) if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) { ImGui::MemFree(ConfigData[i].FontData); ConfigData[i].FontData = NULL; } // When clearing this we lose access to the font name and other information used to build the font. for (int i = 0; i < Fonts.Size; i++) if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) { Fonts[i]->ConfigData = NULL; Fonts[i]->ConfigDataCount = 0; } ConfigData.clear(); } void ImFontAtlas::ClearTexData() { if (TexPixelsAlpha8) ImGui::MemFree(TexPixelsAlpha8); if (TexPixelsRGBA32) ImGui::MemFree(TexPixelsRGBA32); TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; } void ImFontAtlas::ClearFonts() { for (int i = 0; i < Fonts.Size; i++) { Fonts[i]->~ImFont(); ImGui::MemFree(Fonts[i]); } Fonts.clear(); } void ImFontAtlas::Clear() { ClearInputData(); ClearTexData(); ClearFonts(); } void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Build atlas on demand if (TexPixelsAlpha8 == NULL) { if (ConfigData.empty()) AddFontDefault(); Build(); } *out_pixels = TexPixelsAlpha8; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; } void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Convert to RGBA32 format on demand // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp if (!TexPixelsRGBA32) { unsigned char* pixels; GetTexDataAsAlpha8(&pixels, NULL, NULL); TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); const unsigned char* src = pixels; unsigned int* dst = TexPixelsRGBA32; for (int n = TexWidth * TexHeight; n > 0; n--) *dst++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF; } *out_pixels = (unsigned char*)TexPixelsRGBA32; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; } ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); IM_ASSERT(font_cfg->SizePixels > 0.0f); // Create new font if (!font_cfg->MergeMode) { ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); new (font) ImFont(); Fonts.push_back(font); } ConfigData.push_back(*font_cfg); ImFontConfig& new_font_cfg = ConfigData.back(); new_font_cfg.DstFont = Fonts.back(); if (!new_font_cfg.FontDataOwnedByAtlas) { new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); new_font_cfg.FontDataOwnedByAtlas = true; memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } // Invalidate texture ClearTexData(); return Fonts.back(); } // Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder) static unsigned int stb_decompress_length(unsigned char *input); static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); static const char* GetDefaultCompressedFontDataTTFBase85(); static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } static void Decode85(const unsigned char* src, unsigned char* dst) { while (*src) { unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianess. src += 5; dst += 4; } } // Load embedded ProggyClean.ttf at size 13, disable oversampling ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) { ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (!font_cfg_template) { font_cfg.OversampleH = font_cfg.OversampleV = 1; font_cfg.PixelSnapH = true; } if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "<default>"); const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault()); return font; } ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { int data_size = 0; void* data = ImLoadFileToMemory(filename, "rb", &data_size, 0); if (!data) { IM_ASSERT(0); // Could not load file. return NULL; } ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (font_cfg.Name[0] == '\0') { // Store a short copy of filename into into the font name for convenience const char* p; for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p); } return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); } // NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); font_cfg.FontData = ttf_data; font_cfg.FontDataSize = ttf_size; font_cfg.SizePixels = size_pixels; if (glyph_ranges) font_cfg.GlyphRanges = glyph_ranges; return AddFont(&font_cfg); } ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); font_cfg.FontDataOwnedByAtlas = true; return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, font_cfg_template, glyph_ranges); } ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; void* compressed_ttf = ImGui::MemAlloc(compressed_ttf_size); Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); ImGui::MemFree(compressed_ttf); return font; } bool ImFontAtlas::Build() { IM_ASSERT(ConfigData.Size > 0); TexID = NULL; TexWidth = TexHeight = 0; TexUvWhitePixel = ImVec2(0, 0); ClearTexData(); struct ImFontTempBuildData { stbtt_fontinfo FontInfo; stbrp_rect* Rects; stbtt_pack_range* Ranges; int RangesCount; }; ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData)); // Initialize font information early (so we can error without any cleanup) + count glyphs int total_glyph_count = 0; int total_glyph_range_count = 0; for (int input_i = 0; input_i < ConfigData.Size; input_i++) { ImFontConfig& cfg = ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this)); const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); IM_ASSERT(font_offset >= 0); if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) return false; // Count glyphs if (!cfg.GlyphRanges) cfg.GlyphRanges = GetGlyphRangesDefault(); for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) { total_glyph_count += (in_range[1] - in_range[0]) + 1; total_glyph_range_count++; } } // Start packing TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512; // Width doesn't actually matters much but some API/GPU have texture size limitations, and increasing width can decrease height. TexHeight = 0; const int max_tex_height = 1024*32; stbtt_pack_context spc; stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). ImVector<stbrp_rect> extra_rects; RenderCustomTexData(0, &extra_rects); stbtt_PackSetOversampling(&spc, 1, 1); stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size); for (int i = 0; i < extra_rects.Size; i++) if (extra_rects[i].was_packed) TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) for (int input_i = 0; input_i < ConfigData.Size; input_i++) { ImFontConfig& cfg = ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; // Setup ranges int glyph_count = 0; int glyph_ranges_count = 0; for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) { glyph_count += (in_range[1] - in_range[0]) + 1; glyph_ranges_count++; } tmp.Ranges = buf_ranges + buf_ranges_n; tmp.RangesCount = glyph_ranges_count; buf_ranges_n += glyph_ranges_count; for (int i = 0; i < glyph_ranges_count; i++) { const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; stbtt_pack_range& range = tmp.Ranges[i]; range.font_size = cfg.SizePixels; range.first_unicode_codepoint_in_range = in_range[0]; range.num_chars = (in_range[1] - in_range[0]) + 1; range.chardata_for_range = buf_packedchars + buf_packedchars_n; buf_packedchars_n += range.num_chars; } // Pack tmp.Rects = buf_rects + buf_rects_n; buf_rects_n += glyph_count; stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); // Extend texture height for (int i = 0; i < n; i++) if (tmp.Rects[i].was_packed) TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); } IM_ASSERT(buf_rects_n == total_glyph_count); IM_ASSERT(buf_packedchars_n == total_glyph_count); IM_ASSERT(buf_ranges_n == total_glyph_range_count); // Create texture TexHeight = ImUpperPowerOfTwo(TexHeight); TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); spc.pixels = TexPixelsAlpha8; spc.height = TexHeight; // Second pass: render characters for (int input_i = 0; input_i < ConfigData.Size; input_i++) { ImFontConfig& cfg = ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); tmp.Rects = NULL; } // End packing stbtt_PackEnd(&spc); ImGui::MemFree(buf_rects); buf_rects = NULL; // Third pass: setup ImFont and glyphs for runtime for (int input_i = 0; input_i < ConfigData.Size; input_i++) { ImFontConfig& cfg = ConfigData[input_i]; ImFontTempBuildData& tmp = tmp_array[input_i]; ImFont* dst_font = cfg.DstFont; float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); float ascent = unscaled_ascent * font_scale; float descent = unscaled_descent * font_scale; if (!cfg.MergeMode) { dst_font->ContainerAtlas = this; dst_font->ConfigData = &cfg; dst_font->ConfigDataCount = 0; dst_font->FontSize = cfg.SizePixels; dst_font->Ascent = ascent; dst_font->Descent = descent; dst_font->Glyphs.resize(0); } dst_font->ConfigDataCount++; float off_y = (cfg.MergeMode && cfg.MergeGlyphCenterV) ? (ascent - dst_font->Ascent) * 0.5f : 0.0f; dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable() for (int i = 0; i < tmp.RangesCount; i++) { stbtt_pack_range& range = tmp.Ranges[i]; for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) { const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) continue; const int codepoint = range.first_unicode_codepoint_in_range + char_idx; if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint)) continue; stbtt_aligned_quad q; float dummy_x = 0.0f, dummy_y = 0.0f; stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1); ImFont::Glyph& glyph = dst_font->Glyphs.back(); glyph.Codepoint = (ImWchar)codepoint; glyph.X0 = q.x0; glyph.Y0 = q.y0; glyph.X1 = q.x1; glyph.Y1 = q.y1; glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1; glyph.Y0 += (float)(int)(dst_font->Ascent + off_y + 0.5f); glyph.Y1 += (float)(int)(dst_font->Ascent + off_y + 0.5f); glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance if (cfg.PixelSnapH) glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f); } } cfg.DstFont->BuildLookupTable(); } // Cleanup temporaries ImGui::MemFree(buf_packedchars); ImGui::MemFree(buf_ranges); ImGui::MemFree(tmp_array); // Render into our custom data block RenderCustomTexData(1, &extra_rects); return true; } void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) { // A work of art lies ahead! (. = white layer, X = black layer, others are blank) // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. const int TEX_DATA_W = 90; const int TEX_DATA_H = 27; const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" "..- -X.....X- X.X - X.X -X.....X - X.....X" "--- -XXX.XXX- X...X - X...X -X....X - X....X" "X - X.X - X.....X - X.....X -X...X - X...X" "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" "X..X - X.X - X.X - X.X -XX X.X - X.X XX" "X...X - X.X - X.X - XX X.X XX - X.X - X.X " "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" "X.X X..X - -X.......X- X.......X - XX XX - " "XX X..X - - X.....X - X.....X - X.X X.X - " " X..X - X...X - X...X - X..X X..X - " " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " "------------ - X - X -X.....................X- " " ----------------------------------- X...XXXXXXXXXXXXX...X - " " - X..X X..X - " " - X.X X.X - " " - XX XX - " }; ImVector<stbrp_rect>& rects = *(ImVector<stbrp_rect>*)p_rects; if (pass == 0) { // Request rectangles stbrp_rect r; memset(&r, 0, sizeof(r)); r.w = (TEX_DATA_W*2)+1; r.h = TEX_DATA_H+1; rects.push_back(r); } else if (pass == 1) { // Render/copy pixels const stbrp_rect& r = rects[0]; for (int y = 0, n = 0; y < TEX_DATA_H; y++) for (int x = 0; x < TEX_DATA_W; x++, n++) { const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; const int offset1 = offset0 + 1 + TEX_DATA_W; TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; } const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y); // Setup mouse cursors const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = { // Pos ........ Size ......... Offset ...... { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE }; for (int type = 0; type < ImGuiMouseCursor_Count_; type++) { ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); const ImVec2 size = cursor_datas[type][1]; cursor_data.Type = type; cursor_data.Size = size; cursor_data.HotOffset = cursor_datas[type][2]; cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; pos.x += TEX_DATA_W+1; cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; } } } // Retrieve list of range (2 int per range, values are inclusive) const ImWchar* ImFontAtlas::GetGlyphRangesDefault() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesKorean() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3131, 0x3163, // Korean alphabets 0xAC00, 0xD79D, // Korean characters 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesChinese() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF, // Half-width characters 0x4e00, 0x9FAF, // CJK Ideograms 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() { // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. // This encoding helps us reduce the source code size. static const short offsets_from_0x4E00[] = { -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, }; static int ranges_unpacked = false; static ImWchar ranges[8 + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF, // Half-width characters }; if (!ranges_unpacked) { // Unpack int codepoint = 0x4e00; ImWchar* dst = &ranges[8]; for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); dst[0] = 0; ranges_unpacked = true; } return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement 0x2DE0, 0x2DFF, // Cyrillic Extended-A 0xA640, 0xA69F, // Cyrillic Extended-B 0, }; return &ranges[0]; } //----------------------------------------------------------------------------- // ImFont //----------------------------------------------------------------------------- ImFont::ImFont() { Scale = 1.0f; FallbackChar = (ImWchar)'?'; Clear(); } ImFont::~ImFont() { // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. // If you want to delete fonts you need to do it between Render() and NewFrame(). // FIXME-CLEANUP /* ImGuiState& g = *GImGui; if (g.Font == this) g.Font = NULL; */ Clear(); } void ImFont::Clear() { FontSize = 0.0f; DisplayOffset = ImVec2(0.0f, 1.0f); ConfigData = NULL; ConfigDataCount = 0; Ascent = Descent = 0.0f; ContainerAtlas = NULL; Glyphs.clear(); FallbackGlyph = NULL; FallbackXAdvance = 0.0f; IndexXAdvance.clear(); IndexLookup.clear(); } void ImFont::BuildLookupTable() { int max_codepoint = 0; for (int i = 0; i != Glyphs.Size; i++) max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); IndexXAdvance.clear(); IndexXAdvance.resize(max_codepoint + 1); IndexLookup.clear(); IndexLookup.resize(max_codepoint + 1); for (int i = 0; i < max_codepoint + 1; i++) { IndexXAdvance[i] = -1.0f; IndexLookup[i] = -1; } for (int i = 0; i < Glyphs.Size; i++) { int codepoint = (int)Glyphs[i].Codepoint; IndexXAdvance[codepoint] = Glyphs[i].XAdvance; IndexLookup[codepoint] = i; } // Create a glyph to handle TAB // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) if (FindGlyph((unsigned short)' ')) { if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times Glyphs.resize(Glyphs.Size + 1); ImFont::Glyph& tab_glyph = Glyphs.back(); tab_glyph = *FindGlyph((unsigned short)' '); tab_glyph.Codepoint = '\t'; tab_glyph.XAdvance *= 4; IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; IndexLookup[(int)tab_glyph.Codepoint] = (int)(Glyphs.Size-1); } FallbackGlyph = NULL; FallbackGlyph = FindGlyph(FallbackChar); FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; for (int i = 0; i < max_codepoint + 1; i++) if (IndexXAdvance[i] < 0.0f) IndexXAdvance[i] = FallbackXAdvance; } void ImFont::SetFallbackChar(ImWchar c) { FallbackChar = c; BuildLookupTable(); } const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const { if (c < IndexLookup.Size) { const int i = IndexLookup[c]; if (i != -1) return &Glyphs[i]; } return FallbackGlyph; } const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const { // Simple word-wrapping for English, not full-featured. Please submit failing cases! // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" // ^ ^ ^ ^ ^__ ^ ^ // List of hardcoded separators: .,;!?'" // Skip extra blanks after a line returns (that includes not counting them in width computation) // e.g. "Hello world" --> "Hello" "World" // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; const char* word_end = text; const char* prev_word_end = NULL; bool inside_word = true; const char* s = text; while (s < text_end) { unsigned int c = (unsigned int)*s; const char* next_s; if (c < 0x80) next_s = s + 1; else next_s = s + ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; if (c < 32) { if (c == '\n') { line_width = word_width = blank_width = 0.0f; inside_word = true; s = next_s; continue; } if (c == '\r') { s = next_s; continue; } } const float char_width = ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] * scale : FallbackXAdvance; if (ImCharIsSpace(c)) { if (inside_word) { line_width += blank_width; blank_width = 0.0f; } blank_width += char_width; inside_word = false; } else { word_width += char_width; if (inside_word) { word_end = next_s; } else { prev_word_end = word_end; line_width += word_width + blank_width; word_width = blank_width = 0.0f; } // Allow wrapping after punctuation. inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); } // We ignore blank width at the end of the line (they can be skipped) if (line_width + word_width >= wrap_width) { // Words that cannot possibly fit within an entire line will be cut anywhere. if (word_width < wrap_width) s = prev_word_end ? prev_word_end : word_end; break; } s = next_s; } return s; } ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const { if (!text_end) text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; const float scale = size / FontSize; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; const char* s = text_begin; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { if (text_size.x < line_width) text_size.x = line_width; text_size.y += line_height; line_width = 0.0f; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source const char* prev_s = s; unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; } if (c < 32) { if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; continue; } if (c == '\r') continue; } const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; if (line_width + char_width >= max_width) { s = prev_s; break; } line_width += char_width; } if (text_size.x < line_width) text_size.x = line_width; if (line_width > 0 || text_size.y == 0.0f) text_size.y += line_height; if (remaining) *remaining = s; return text_size; } void ImFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, ImDrawList* draw_list, float wrap_width, bool cpu_fine_clip) const { if (!text_end) text_end = text_begin + strlen(text_begin); // Align to be pixel perfect pos.x = (float)(int)pos.x + DisplayOffset.x; pos.y = (float)(int)pos.y + DisplayOffset.y; float x = pos.x; float y = pos.y; if (y > clip_rect.w) return; const float scale = size / FontSize; const float line_height = FontSize * scale; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; ImDrawVert* vtx_write = draw_list->_VtxWritePtr; ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; const char* s = text_begin; if (!word_wrap_enabled && y + line_height < clip_rect.y) while (s < text_end && *s != '\n') // Fast-forward to next line s++; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { x = pos.x; y += line_height; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; } if (c < 32) { if (c == '\n') { x = pos.x; y += line_height; if (y > clip_rect.w) break; if (!word_wrap_enabled && y + line_height < clip_rect.y) while (s < text_end && *s != '\n') // Fast-forward to next line s++; continue; } if (c == '\r') continue; } float char_width = 0.0f; if (const Glyph* glyph = FindGlyph((unsigned short)c)) { char_width = glyph->XAdvance * scale; // Clipping on Y is more likely if (c != ' ' && c != '\t') { // We don't do a second finer clipping test on the Y axis (TODO: do some measurement see if it is worth it, probably not) float y1 = (float)(y + glyph->Y0 * scale); float y2 = (float)(y + glyph->Y1 * scale); float x1 = (float)(x + glyph->X0 * scale); float x2 = (float)(x + glyph->X1 * scale); if (x1 <= clip_rect.z && x2 >= clip_rect.x) { // Render a character float u1 = glyph->U0; float v1 = glyph->V0; float u2 = glyph->U1; float v2 = glyph->V1; // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) { if (x1 < clip_rect.x) { u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); x1 = clip_rect.x; } if (y1 < clip_rect.y) { v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); y1 = clip_rect.y; } if (x2 > clip_rect.z) { u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); x2 = clip_rect.z; } if (y2 > clip_rect.w) { v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); y2 = clip_rect.w; } if (y1 >= y2) { x += char_width; continue; } } // NB: we are not calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. // inlined: { idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; vtx_write += 4; vtx_current_idx += 4; idx_write += 6; } } } } x += char_width; } draw_list->_VtxWritePtr = vtx_write; draw_list->_VtxCurrentIdx = vtx_current_idx; draw_list->_IdxWritePtr = idx_write; } //----------------------------------------------------------------------------- // DEFAULT FONT DATA //----------------------------------------------------------------------------- // Compressed with stb_compress() then converted to a C array. // Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. // Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h //----------------------------------------------------------------------------- static unsigned int stb_decompress_length(unsigned char *input) { return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; } static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; static unsigned char *stb__dout; static void stb__match(unsigned char *data, unsigned int length) { // INVERSE of memmove... write each byte before copying the next... IM_ASSERT (stb__dout + length <= stb__barrier); if (stb__dout + length > stb__barrier) { stb__dout += length; return; } if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } while (length--) *stb__dout++ = *data++; } static void stb__lit(unsigned char *data, unsigned int length) { IM_ASSERT (stb__dout + length <= stb__barrier); if (stb__dout + length > stb__barrier) { stb__dout += length; return; } if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } memcpy(stb__dout, data, length); stb__dout += length; } #define stb__in2(x) ((i[x] << 8) + i[(x)+1]) #define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) #define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) static unsigned char *stb_decompress_token(unsigned char *i) { if (*i >= 0x20) { // use fewer if's for cases that expand small if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); } else { // more ifs for cases that expand large, since overhead is amortized if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; } return i; } static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) { const unsigned long ADLER_MOD = 65521; unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; unsigned long blocklen, i; blocklen = buflen % 5552; while (buflen) { for (i=0; i + 7 < blocklen; i += 8) { s1 += buffer[0], s2 += s1; s1 += buffer[1], s2 += s1; s1 += buffer[2], s2 += s1; s1 += buffer[3], s2 += s1; s1 += buffer[4], s2 += s1; s1 += buffer[5], s2 += s1; s1 += buffer[6], s2 += s1; s1 += buffer[7], s2 += s1; buffer += 8; } for (; i < blocklen; ++i) s1 += *buffer++, s2 += s1; s1 %= ADLER_MOD, s2 %= ADLER_MOD; buflen -= blocklen; blocklen = 5552; } return (unsigned int)(s2 << 16) + (unsigned int)s1; } static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) { unsigned int olen; if (stb__in4(0) != 0x57bC0000) return 0; if (stb__in4(4) != 0) return 0; // error! stream is > 4GB olen = stb_decompress_length(i); stb__barrier2 = i; stb__barrier3 = i+length; stb__barrier = output + olen; stb__barrier4 = output; i += 16; stb__dout = output; for (;;) { unsigned char *old_i = i; i = stb_decompress_token(i); if (i == old_i) { if (*i == 0x05 && i[1] == 0xfa) { IM_ASSERT(stb__dout == output + olen); if (stb__dout != output + olen) return 0; if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) return 0; return olen; } else { IM_ASSERT(0); /* NOTREACHED */ return 0; } } IM_ASSERT(stb__dout <= output + olen); if (stb__dout > output + olen) return 0; } } //----------------------------------------------------------------------------- // ProggyClean.ttf // Copyright (c) 2004, 2005 Tristan Grimmer // MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) // Download and more information at http://upperbounds.net //----------------------------------------------------------------------------- // File: 'ProggyClean.ttf' (41208 bytes) // Exported using binary_to_compressed_c.cpp //----------------------------------------------------------------------------- static const char proggy_clean_ttf_compressed_data_base85[11980+1] = "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" "2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#" "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL" "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N" "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N" "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)" "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX" "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." "x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G" "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)" "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L" "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#" "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)(" "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h" "o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-" "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-" "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO" "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL(" "$/V,;(kXZejWO`<[5??ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<" "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?" "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;" ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" "D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" "bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-" "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" "sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7" ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@" "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" "@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#" "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#" "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0" "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD" ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+" "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*" "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7" ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A" "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7" "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT" "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M" ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>" "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%" "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-" "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY" "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-" "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`" "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/" "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V" "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK" "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa" ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>" "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#" "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$" "MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO" "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>" "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#" "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" "/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#" "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#" "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; static const char* GetDefaultCompressedFontDataTTFBase85() { return proggy_clean_ttf_compressed_data_base85; }
[ "KH2010G@gmail.com" ]
KH2010G@gmail.com
fd6c4500b308c1efa8ce798ae43b0ad492adfbad
f5c368f37731839b6ab3ed0a0555c02e0d6a4c95
/DpLib/DpDXUtils.h
024c50e69a8239ba3f4adac138f341de9d74d6f2
[]
no_license
mi2think/DoPixel
c9f85993c44a124c7fdea233efb1bcfc26c27738
b95cd294e7e94ea2ce30cbb99524842ac2980c29
refs/heads/master
2021-01-22T07:35:45.852536
2016-05-31T08:26:53
2016-05-31T08:26:53
24,449,336
1
0
null
null
null
null
UTF-8
C++
false
false
1,213
h
/******************************************************************** created: 2016/01/07 created: 7:1:2016 22:31 filename: D:\OneDrive\3D\DpLib\DpLib\DpDXUtils.h file path: D:\OneDrive\3D\DpLib\DpLib file base: DpDXUtils file ext: h author: mi2think@gmail.com purpose: DX Utils *********************************************************************/ #ifndef __DP_DX_UTILS_H__ #define __DP_DX_UTILS_H__ #include "DoPixel.h" #include <windows.h> #include <d3dx9.h> #include <dxerr.h> namespace dopixel { // error checker class DXErrorChecker { public: DXErrorChecker(const char* file, int line); ~DXErrorChecker(); DXErrorChecker& operator=(HRESULT hr); private: const char* file_; int line_; HRESULT hr_; }; #define CHECK_HR DXErrorChecker(__FILE__, __LINE__) extern IDirect3D9* g_pD3D; extern IDirect3DDevice9* g_pD3DD; // utils // setup IDirect3D9* SetupD3D(); IDirect3DDevice9* SetupD3DDevice(HWND hwnd, int width, int height, bool wndmode); void DestoryDirectX(); // format const char* D3DFormat2String(D3DFORMAT format); // default display mode void ShowDisplayMode(); void ShowAdapterCount(); // default identifier void ShowAdapterIdentifier(); } #endif
[ "mi2think@gmail.com" ]
mi2think@gmail.com
af9f33e32fc4a3dce8db6a0deb07e7e6b8c73e15
fca8dfee4a80188502b9cad2c7df3c17f167c6ec
/src/liboptix/sutil/OptixMeshImpl.h
8eae205d45ff7157ec4b90ee1e07303a7cc4693c
[]
no_license
tal-chan/mitsuba-optix
c0226f1f2f6018aa4047436b584a614a98298f3d
eee068698aac5746042f9c9f1f9302d610744c0d
refs/heads/master
2021-01-22T10:21:23.441061
2015-06-26T13:13:12
2015-06-26T13:13:12
38,111,336
1
0
null
null
null
null
UTF-8
C++
false
false
6,600
h
/* * Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property and proprietary * rights in and to this software, related documentation and any modifications thereto. * Any use, reproduction, disclosure or distribution of this software and related * documentation without an express license agreement from NVIDIA Corporation is strictly * prohibited. * * TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* * AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, * INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY * SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT * LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF * BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGES */ #ifndef __samples_util_optix_mesh_impl_h__ #define __samples_util_optix_mesh_impl_h__ #include "MeshBase.h" #include "OptixMeshClasses.h" #include <optixu/optixpp_namespace.h> #include <optixu/optixu_aabb_namespace.h> #include <optixu/optixu_matrix_namespace.h> #include <string> //----------------------------------------------------------------------------- // // OptixMeshImpl class declaration // //----------------------------------------------------------------------------- class OptixMeshImpl : public MeshBase { public: typedef MeshBase Base; OptixMeshImpl( optix::Context context, // Context for RT object creation optix::GeometryGroup geometrygroup, // Empty geom group to hold model const char* ASBuilder = "Sbvh", const char* ASTraverser = "Bvh", const char* ASRefine = "0", bool large_geom = false ); // Reorder geom data for page fault minimization OptixMeshImpl( optix::Context context, // Context for RT object creation optix::GeometryGroup geometrygroup, // empty geom group to hold model optix::Material default_material, // default OptiX material to assign const char* ASBuilder = "Sbvh", const char* ASTraverser = "Bvh", const char* ASRefine = "0", bool large_geom = false ); // Reorder geom data for page fault minimization virtual ~OptixMeshImpl(); /// Not intended for use, throws an Exception to override base class method. virtual void loadModel( const std::string& filename ); void beginLoad( const std::string& filename ); void finalizeLoad(); void setDefaultIntersectionProgram( optix::Program inx_program ); optix::Program getDefaultIntersectionProgram() const; void setDefaultBoundingBoxProgram( optix::Program bbox_program ); optix::Program getDefaultBoundingBoxProgram() const; void setDefaultOptixMaterial( optix::Material material ); optix::Material getDefaultOptixMaterial() const; void setDefaultMaterialParams( const MeshMaterialParams& params ); const MeshMaterialParams& getDefaultMaterialParams() const; OptixMeshClasses::GroupGeometryInfo& getGroupGeometryInfo( const std::string& group_name ); const OptixMeshClasses::GroupGeometryInfo& getGroupGeometryInfo( const std::string& group_name ) const; void setOptixMaterial( int i, optix::Material material ); const optix::Material& getOptixMaterial( int i ) const; optix::Aabb getSceneBBox() const; optix::Buffer getLightBuffer() const; const optix::Matrix4x4& getLoadingTransform() const; void setLoadingTransform( const optix::Matrix4x4& transform ); virtual void addMaterial(); int getGroupMaterialNumber(const MeshGroup& group) const; void setOptixInstanceMatParams( optix::GeometryInstance gi, const MeshMaterialParams& params ) const; protected: virtual void preProcess(); virtual void allocateData(); virtual void startWritingData(); virtual void postProcess(); virtual void finishWritingData(); private: typedef std::map<std::string, OptixMeshClasses::GroupGeometryInfo> GroupGeometryInfoMap; void createGeometries(); void mapPoolBuffers(); void unmapPoolBuffers(); void mapGroupBuffers(); void unmapGroupBuffers(); void mapAllBuffers(); void unmapAllBuffers(); void processGeometriesAfterLoad(); void createGeoInstancesAndOptixGroup(); void createLightBuffer(); void transformVerticesAndNormals(); void initDefaultOptixMaterial(); void initDefaultIntersectProgram(); void initDefaultBBoxProgram(); std::string getTextureMapPath( const std::string& filename ) const; optix::Buffer getGeoVindexBuffer( optix::Geometry geo ); void setGeoVindexBuffer( optix::Geometry geo, optix::Buffer buf ); optix::Buffer getGeoNindexBuffer( optix::Geometry geo ); void setGeoNindexBuffer( optix::Geometry geo, optix::Buffer buf ); optix::Buffer getGeoTindexBuffer( optix::Geometry geo ); void setGeoTindexBuffer( optix::Geometry geo, optix::Buffer buf ); optix::Buffer getGeoMaterialBuffer( optix::Geometry geo ); void setGeoMaterialBuffer( optix::Geometry geo, optix::Buffer buf ); optix::Context m_context; optix::GeometryGroup m_geometrygroup; optix::Buffer m_vbuffer; optix::Buffer m_nbuffer; optix::Buffer m_tbuffer; MeshMaterialParams m_default_material_params; optix::Material m_default_optix_material; optix::Program m_default_intersect_program; optix::Program m_default_bbox_program; optix::Buffer m_light_buffer; const char* m_ASBuilder; const char* m_ASTraverser; const char* m_ASRefine; bool m_large_geom; optix::Aabb m_aabb; std::vector<optix::Material> m_optix_materials; GroupGeometryInfoMap m_group_infos; optix::Matrix4x4 m_loading_transform; bool m_materials_provided; bool m_currently_loading; // Implementation functors struct InitGroupsDefaultIntersectFunctor; struct CreateGeometriesFunctor; struct MapGroupBuffersFunctor; struct UnmapGroupBuffersFunctor; struct ProcessGeometriesAfterLoadFunctor; struct CreateGeometryInstancesFunctor; struct CreateLightBufferFunctor; }; #endif // __samples_util_optix_mesh_impl_h__
[ "chantal.j.ding@gmail.com" ]
chantal.j.ding@gmail.com
dc9c6d8b3a57dec757607617ea65eb4924d5d7fb
ec8906b348a2c39ab53e7444547fef681bb58776
/Cpp/3/Q121.cpp
cc1606622b64e732a29b6a96ef82eac782295bde
[]
no_license
NingmengLLL/Homework
a654d780c6ed72c96d4d7c60fcfa2589b0127f4d
e0d8a799e21ed0d25135b0bc3051443fc85adf3a
refs/heads/master
2020-04-02T13:10:48.319418
2018-10-24T09:00:27
2018-10-24T09:00:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
cpp
#include <iostream> #include <string> using namespace std; class Student { public: int id; string name; int age; double weight; double calculus; double english; double cpp; double gpa() { return (calculus * 4 + english * 4 + cpp * 3) / 11.0 / 20; } bool operator<(Student& other) { return this->gpa() < other.gpa(); } bool operator==(Student& other) { return this->gpa() == other.gpa(); } friend istream& operator>>(istream&, Student&); }; istream& operator>>(istream& in, Student& student) { in >> student.id >> student.name >> student.age >> student.weight >> student.calculus >> student.english >> student.cpp; return in; } bool operator<(string& str1, string& str2) { int length1 = str1.length(); int length2 = str2.length(); for (int i = 0; i < length1; i++){ if (i >= length2) { return false; } if (str1[i] < str2[i]) { return true; } else if (str1[i] > str2[i]){ return false; } } if (length1 == length2) { return false; } return true; } template <class T> int compare(T o1, T o2) { if (o1 < o2){ return -1; } else if (o1 == o2) { return 0; } else { return 1; } } int main() { Student s1, s2; cin >> s1 >> s2; cout << compare<string>(s1.name, s2.name) << " " << compare<int>(s1.age, s2.age) << " " << compare<double>(s1.weight, s2.weight) << " " << compare<Student>(s1, s2); }
[ "smallda@outlook.com" ]
smallda@outlook.com
da1f17d07b0c09021a3f1804953c8381c5220f73
81024c4396f19152dce8a490967bac44c0dba99c
/cing/libraries/mac/xcode/OgreSDK/include/OGRE/Plugins/ParticleFX/OgreLinearForceAffector.h
4d510d5fc997463482817e2efea877a3f0b96b93
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CingProject/Cing
ca8c44377705d1f3b744141809ae486a8cc640aa
1e4f83fe76e69bad57e07b48d2c54813e9a3a1c2
refs/heads/master
2020-04-05T23:41:10.838562
2014-05-05T17:30:46
2014-05-05T17:30:46
1,756,756
7
7
null
2014-05-05T17:30:33
2011-05-16T18:11:33
C++
UTF-8
C++
false
false
4,579
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __LinearForceAffector_H__ #define __LinearForceAffector_H__ #include "OgreParticleFXPrerequisites.h" #include "OgreParticleAffector.h" #include "OgreVector3.h" namespace Ogre { /** This class defines a ParticleAffector which applies a linear force to particles in a system. @remarks This affector (see ParticleAffector) applies a linear force, such as gravity, to a particle system. This force can be applied in 2 ways: by taking the average of the particle's current momentum and the force vector, or by adding the force vector to the current particle's momentum. @par The former approach is self-stabilising i.e. once a particle's momentum is equal to the force vector, no further change is made to it's momentum. It also results in a non-linear acceleration of particles. The latter approach is simpler and applies a constant acceleration to particles. However, it is not self-stabilising and can lead to perpetually increasing particle velocities. You choose the approach by calling the setForceApplication method. */ class _OgreParticleFXExport LinearForceAffector : public ParticleAffector { public: /** Command object for force vector (see ParamCommand).*/ class CmdForceVector : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /** Command object for force application (see ParamCommand).*/ class CmdForceApp : public ParamCommand { public: String doGet(const void* target) const; void doSet(void* target, const String& val); }; /// Choice of how to apply the force vector to particles enum ForceApplication { /// Take the average of the force vector and the particle momentum FA_AVERAGE, /// Add the force vector to the particle momentum FA_ADD }; /// Default constructor LinearForceAffector(ParticleSystem* psys); /** See ParticleAffector. */ void _affectParticles(ParticleSystem* pSystem, Real timeElapsed); /** Sets the force vector to apply to the particles in a system. */ void setForceVector(const Vector3& force); /** Gets the force vector to apply to the particles in a system. */ Vector3 getForceVector(void) const; /** Sets how the force vector is applied to a particle. @remarks The default is FA_ADD. @param fa A member of the ForceApplication enum. */ void setForceApplication(ForceApplication fa); /** Retrieves how the force vector is applied to a particle. @param fa A member of the ForceApplication enum. */ ForceApplication getForceApplication(void) const; /// Command objects static CmdForceVector msForceVectorCmd; static CmdForceApp msForceAppCmd; protected: /// Force vector Vector3 mForceVector; /// How to apply force ForceApplication mForceApplication; }; } #endif
[ "sroske@gmail.com" ]
sroske@gmail.com
3837ef36c42415960aeb75647bee65450eac6fd2
4c76ef7d5800e8dc801d0e7193238f31333b1b16
/Max_Heap.cpp
b109deb3047748e08f30fa69c5518a4b66ef8f0a
[]
no_license
archana77archana/Heap
bc3edb526e9bf6967cd6b39f9eda1ae9db6e2939
9e7aa4e24612dea1d39dc29f0d47b405e407820c
refs/heads/master
2021-01-20T12:04:49.708242
2014-05-05T12:29:46
2014-05-05T12:29:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,231
cpp
#include "Max_Heap.h" #include <cassert> #include <iomanip> #include <cmath> using std::endl; using std::swap; //using std::floor; using std::setw; /*Creates a heap, provided the ranges*/ //template<class T> //Max_Heap<T>::Max_Heap(typename vector<T>::iterator v_begin, // typename vector<T>::iterator v_end) //{ /*Making sure that there is atleast one element in the vector*/ // assert((v_end - v_begin) > 0); /*Starting index = 1 Index location is left free*/ // data.push_back(0); // size_t v_size = v_end - v_begin; // for(vector<T>::iterator itr = v_begin; itr != v_end; itr++) // { // data.push_back(*itr); // } // heap_size = v_size; /*Heapifying using Floyd's heap creation algorithm*/ // make_heap(); //} template<class T> void Max_Heap<T>::make_heap() { if(data.size() <= 1) return; else for(size_t i = (data.size()/2); i >= 1; i--) { heapify_down(i); } } template<class T> void Max_Heap<T>::heapify_down(size_t index) { /*comparing node with children*/ assert(index <= heap_size); /*left -> 2i*/ size_t left = (index << 1); /*right -> 2i + 1*/ size_t right = (index << 1) + 1; size_t largest = index; if((left <= heap_size) && (data[left] > data[largest])) { largest = left; } if((right <= heap_size) && (data[right] > data[largest])) { largest = right; } if(largest != index) { swap(data[index], data[largest]); heapify_down(largest); } } template<class T> Max_Heap<T>::Max_Heap(vector<T> v) { /*Making sure that there is atleast one element*/ assert(v.size() > 0); /*Starting index = 1 index 0 is left free*/ data.push_back(0); size_t v_size = v.end() - v.begin(); for(typename vector<T>::iterator itr = v.begin(); itr != v.end(); itr++) { data.push_back(*itr); } heap_size = v_size; make_heap(); } template<class T> void Max_Heap<T>::heapify_up(size_t index) { assert(index <= heap_size); size_t parent = index/2; if(data[index] > data[parent]) { swap(data[index], data[parent]); heapify_up(parent); } return; } template<class T> void Max_Heap<T>::push_heap(T value) { data.push_back(value); heap_size++; heapify_up(heap_size); return; } template<class T> void Max_Heap<T>::pop_heap() { assert(!empty()); /*If only one element left in the heap*/ if(heap_size == 1) { heap_size = 0; data.clear(); } /*More than one element*/ else { data[1] = data[heap_size]; --heap_size; data.pop_back(); heapify_down(1); } } template<class T> void Max_Heap<T>::levelorder_traversal(ostream &out = cout) const { for(size_t i = 1; i < data.size(); i++) { out << data[i] << " "; } out << endl; } template<class T> void Max_Heap<T>::print_tree(ostream &out = cout) { out << endl; size_t h = height(); vector<size_t> spaces; spaces.push_back(0); for(size_t i = 0; i <= h; i++) { spaces.push_back((spaces[i] + 1) * 2); } reverse(spaces.begin(), spaces.end()); for(size_t i = 0; i < spaces.size(); i++) { out << spaces[i] << " "; } out << endl; size_t counter = 1; /*No. of levels*/ for(size_t i = 0; i <= h; i++) { /*No. of nodes in one level*/ for(size_t k = 0; k < pow(2.0, i*1.0); k++) { if(counter > heap_size) break; /*Print space before no.*/ for(size_t j = 0; j < spaces[i]; j++) { out << ' '; } /*Print no.*/ out << setw(3) << data[counter++]; /*Print space before no.*/ for(size_t j = 0; j < spaces[i] + 1; j++) { out << ' '; } } out << endl; if(counter > heap_size) break; /*Printing arrows*/ size_t count_1 = spaces[i], count_2 = 0, count_3 = 1; /*No. of lines*/ for(size_t j = 0; j < spaces[i]/2; j++) { /*No. of arrows per level*/ for(size_t k = 0; k < pow(2.0, i * 1.0); k++) { /*Spaces before left arrow*/ for(size_t l = 0; l < count_1 - count_3; l++) { out << ' '; } /*Left arrow*/ out << "/"; /*Spaces between left and right arrows*/ for(size_t l = 0; l < 3 + count_2; l++) { out << ' '; } /*Right arrow*/ out << "\\"; for(size_t l = 0; l < count_1 - count_3; l++) { out << ' '; } /*Extra one space*/ out << ' '; } cout << endl; count_2 += 2; count_3++; } } out << endl; }
[ "kcarchana77@gmail.com" ]
kcarchana77@gmail.com
e2cdabc7fb5fb0478af9c6a7418eade276f3389e
d39bd302aaaaeac11959eadb885f18f93f23d5af
/ConsoleRPG/Character.cpp
6fff322157436bba309b984ff949ded766320712
[]
no_license
ABitulescu/Game
22082b24e092ae467b5db8d12e7672d69d404d06
b106047f4759f2624b438b096103303b885223c2
refs/heads/master
2022-10-08T22:02:29.822084
2020-06-08T17:19:52
2020-06-08T17:19:52
264,880,928
0
0
null
null
null
null
UTF-8
C++
false
false
5,161
cpp
#include "Character.h" Character::Character() { this->distanceTravelled = 0; this->gold = 0; this->name = ""; this->level = 1; this->exp = 0; this->expNext = 0; this->strengh = 0; this->vitality = 0; this->dexterity = 0; this->intelligence = 0; this->hp = 0; this->hpMax = 0; this->stamina = 0; this->staminaMax = 0; this->damageMin = 0; this->damageMax = 0; this->defence = 0; this->accuracy = 0; this->luck = 0; this->statPoints = 0; this->skillPoints = 0; } Character::Character(string name, int distanceTravelled, int gold, int level, int exp, int strengh, int vitality, int dexterity, int intelligence, int hp, int stamina, int statPoints, int skillPoints) { this->distanceTravelled = distanceTravelled; this->gold = gold; this->name = name; this->level = level; this->exp = exp; this->expNext = 0; this->strengh = strengh; this->vitality = vitality; this->dexterity = dexterity; this->intelligence = intelligence; this->hp = hp; this->hpMax = 0; this->stamina = stamina; this->staminaMax = 0; this->damageMin = 0; this->damageMax = 0; this->defence = 0; this->accuracy = 0; this->luck = 0; this->statPoints = statPoints; this->skillPoints = skillPoints; this->updateStats(); } Character::~Character() { } //Functions void Character::initialize(const string name) { this->distanceTravelled = 0; this->gold = 100; this->name = name; this->level = 1; this->exp = 0; this->expNext = static_cast<int> ((50 / 3) * ((pow(level, 3) - 6 * pow(level, 2)) + 17 * level - 12)) + 100; this->strengh = 5; this->vitality = 5; this->dexterity = 5; this->intelligence = 5; this->hpMax = (this->vitality * 2) + (this->strengh/2); this->hp = hpMax; this->staminaMax = this->vitality + (this->strengh/2) + (this->dexterity/3); this->stamina = this->staminaMax; this->damageMin = this->strengh; this->damageMax = this->strengh + 2; this->defence = this->dexterity + (this->intelligence/2); this->accuracy = this->dexterity / 2; this->luck = this->intelligence; this->statPoints = 0; this->skillPoints = 0; } void Character::printStats() const { cout << "= Character Sheet =" << endl; cout << "= Name: " << this->name << endl; cout << "= Level: " << this->level << endl; cout << "= Exp: " << this->exp << endl; cout << "= Exp to Next Level: " << this->expNext << endl; cout << endl; cout << "= Strengh: " << this->strengh << endl; cout << "= Vitality: " << this->vitality << endl; cout << "= Dexterity: " << this->dexterity << endl; cout << "= Intelligence: " << this->intelligence << endl; cout << endl; cout << "= Hp: " << this->hp << " / " << this->hpMax << endl; cout << "= Stamina: " << this->stamina <<" / " << this->staminaMax << endl; cout << "= Damage: " << this->damageMin << " - " <<this->damageMax << endl; cout << "= Defence: " << this->defence << endl; cout << "= Accuracy: " << this->accuracy << endl; cout << "= Luck: " << this->luck << endl; cout << endl; } void Character::updateStats() { this->expNext = static_cast<int> ((50 / 3) * ((pow(level, 3) - 6 * pow(level, 2)) + 17 * level - 12)) + 100; this->hpMax = (this->vitality * 2) + (this->strengh / 2); this->staminaMax = this->vitality + (this->strengh / 2) + (this->dexterity / 3); this->damageMin = this->strengh; this->damageMax = this->strengh + 2; this->defence = this->dexterity + (this->intelligence / 2); this->accuracy = this->dexterity / 2; this->luck = this->intelligence; } void Character::addToStat(int stat, int value) { if (this->statPoints < value) { cout << "You don't have any stat points to assign!" << "\n"; } else { switch (stat) { case 0: this->strengh += value; cout << "Added 1 point to strengh" << "\n"; break; case 1: this->vitality += value; cout << "Added 1 point to vitality" << "\n"; break; case 2: this->dexterity += value; cout << "Added 1 point to dexterity" << "\n"; break; case 3: this->intelligence += value; cout << "Added 1 point to intelligence" << "\n"; break; default: cout << "Your choice is not a Stat option" << "\n"; break; } this->statPoints -= value; } } void Character::levelUp() { if (this->exp >= this->expNext) { this->exp -= this->expNext; this->level++; this->expNext = static_cast<int> ((50 / 3) * ((pow(level, 3) - 6 * pow(level, 2)) + 17 * level - 12)) + 100; this->statPoints++; this->skillPoints++; this->updateStats(); cout << "You are now Level " << this->level << "!" << "\n\n"; } else { cout << "You need more EXP! \n\n"; } } string Character::getAsString() const //for saving the character { return name + " " + to_string(distanceTravelled) + " " + to_string(gold) + " " + to_string(level) + " " + to_string(exp) + " " + to_string(strengh) + " " + to_string(vitality) + " " + to_string(dexterity) + " " + to_string(intelligence) + " " + to_string(hp) + " " + to_string(stamina) + " " + to_string(statPoints) + " " + to_string(skillPoints) + " "; } void Character::takeDamage(const int damage) { this->hp -= damage; if (this->hp <= 0) { this->hp = 0; } }
[ "40036459+ABitulescu@users.noreply.github.com" ]
40036459+ABitulescu@users.noreply.github.com
fa337b2b6f6c645b2d4d62b26dce193a86ad0fc2
c2a4d5d8f15e289463d5e0cf58fdae9db776416b
/caffe_3d/src/caffe/layers/scale_layer.cpp
f1629bad4e3e57258068893ffb73da386d5eeb83
[ "MIT", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
wzmsltw/ECO-efficient-video-understanding
412310c114f58765cf775df8e141d3adcb69aa58
465e3af0c187d8f6c77651a5c6ad599bb4cfc466
refs/heads/master
2020-03-24T19:56:55.212935
2018-07-30T16:26:31
2018-07-30T16:26:31
142,951,813
2
1
MIT
2018-07-31T02:28:09
2018-07-31T02:28:09
null
UTF-8
C++
false
false
9,117
cpp
#include <algorithm> #include <vector> #include "caffe/filler.hpp" #include "caffe/layer_factory.hpp" #include "caffe/common_layers.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void ScaleLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const ScaleParameter& param = this->layer_param_.scale_param(); if (bottom.size() == 1 && this->blobs_.size() > 0) { LOG(INFO) << "Skipping parameter initialization"; } else if (bottom.size() == 1) { // scale is a learned parameter; initialize it axis_ = bottom[0]->CanonicalAxisIndex(param.axis()); const int num_axes = param.num_axes(); CHECK_GE(num_axes, -1) << "num_axes must be non-negative, " << "or -1 to extend to the end of bottom[0]"; if (num_axes >= 0) { CHECK_GE(bottom[0]->num_axes(), axis_ + num_axes) << "scale blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis_; } this->blobs_.resize(1); const vector<int>::const_iterator& shape_start = bottom[0]->shape().begin() + axis_; const vector<int>::const_iterator& shape_end = (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes); vector<int> scale_shape(shape_start, shape_end); this->blobs_[0].reset(new Blob<Dtype>(scale_shape)); FillerParameter filler_param(param.filler()); if (!param.has_filler()) { // Default to unit (1) filler for identity operation. filler_param.set_type("constant"); filler_param.set_value(1); } shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(filler_param)); filler->Fill(this->blobs_[0].get()); } if (param.bias_term()) { LayerParameter layer_param(this->layer_param_); layer_param.set_type("Bias"); BiasParameter* bias_param = layer_param.mutable_bias_param(); bias_param->set_axis(param.axis()); if (bottom.size() > 1) { bias_param->set_num_axes(bottom[1]->num_axes()); } else { bias_param->set_num_axes(param.num_axes()); } bias_param->mutable_filler()->CopyFrom(param.bias_filler()); bias_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); bias_bottom_vec_.resize(1); bias_bottom_vec_[0] = bottom[0]; bias_layer_->SetUp(bias_bottom_vec_, top); bias_param_id_ = this->blobs_.size(); this->blobs_.resize(bias_param_id_ + 1); this->blobs_[bias_param_id_] = bias_layer_->blobs()[0]; bias_propagate_down_.resize(1, false); } this->param_propagate_down_.resize(this->blobs_.size(), true); } template <typename Dtype> void ScaleLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const ScaleParameter& param = this->layer_param_.scale_param(); Blob<Dtype>* scale = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get(); // Always set axis_ == 0 in special case where scale is a scalar // (num_axes == 0). Mathematically equivalent for any choice of axis_, so the // actual setting can be safely ignored; and computation is most efficient // with axis_ == 0 and (therefore) outer_dim_ == 1. (Setting axis_ to // bottom[0]->num_axes() - 1, giving inner_dim_ == 1, would be equally // performant.) axis_ = (scale->num_axes() == 0) ? 0 : bottom[0]->CanonicalAxisIndex(param.axis()); CHECK_GE(bottom[0]->num_axes(), axis_ + scale->num_axes()) << "scale blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis_; for (int i = 0; i < scale->num_axes(); ++i) { CHECK_EQ(bottom[0]->shape(axis_ + i), scale->shape(i)) << "dimension mismatch between bottom[0]->shape(" << axis_ + i << ") and scale->shape(" << i << ")"; } outer_dim_ = bottom[0]->count(0, axis_); scale_dim_ = scale->count(); inner_dim_ = bottom[0]->count(axis_ + scale->num_axes()); if (bottom[0] == top[0]) { // in-place computation temp_.ReshapeLike(*bottom[0]); } else { top[0]->ReshapeLike(*bottom[0]); } sum_result_.Reshape(vector<int>(1, outer_dim_ * scale_dim_)); const int sum_mult_size = std::max(outer_dim_, inner_dim_); sum_multiplier_.Reshape(vector<int>(1, sum_mult_size)); if (sum_multiplier_.cpu_data()[sum_mult_size - 1] != Dtype(1)) { caffe_set(sum_mult_size, Dtype(1), sum_multiplier_.mutable_cpu_data()); } if (bias_layer_) { bias_bottom_vec_[0] = top[0]; bias_layer_->Reshape(bias_bottom_vec_, top); } } template <typename Dtype> void ScaleLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); if (bottom[0] == top[0]) { // In-place computation; need to store bottom data before overwriting it. // Note that this is only necessary for Backward; we could skip this if not // doing Backward, but Caffe currently provides no way of knowing whether // we'll need to do Backward at the time of the Forward call. caffe_copy(bottom[0]->count(), bottom[0]->cpu_data(), temp_.mutable_cpu_data()); } const Dtype* scale_data = ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); for (int n = 0; n < outer_dim_; ++n) { for (int d = 0; d < scale_dim_; ++d) { const Dtype factor = scale_data[d]; caffe_cpu_scale(inner_dim_, factor, bottom_data, top_data); bottom_data += inner_dim_; top_data += inner_dim_; } } if (bias_layer_) { bias_layer_->Forward(bias_bottom_vec_, top); } } template <typename Dtype> void ScaleLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (bias_layer_ && this->param_propagate_down_[this->param_propagate_down_.size() - 1]) { bias_layer_->Backward(top, bias_propagate_down_, bias_bottom_vec_); } const bool scale_param = (bottom.size() == 1); Blob<Dtype>* scale = scale_param ? this->blobs_[0].get() : bottom[1]; if ((!scale_param && propagate_down[1]) || (scale_param && this->param_propagate_down_[0])) { const Dtype* top_diff = top[0]->cpu_diff(); const bool in_place = (bottom[0] == top[0]); const Dtype* bottom_data = (in_place ? &temp_ : bottom[0])->cpu_data(); // Hack: store big eltwise product in bottom[0] diff, except in the special // case where this layer itself does the eltwise product, in which case we // can store it directly in the scale diff, and we're done. // If we're computing in-place (and not doing eltwise computation), this // hack doesn't work and we store the product in temp_. const bool is_eltwise = (bottom[0]->count() == scale->count()); Dtype* product = (is_eltwise ? scale->mutable_cpu_diff() : (in_place ? temp_.mutable_cpu_data() : bottom[0]->mutable_cpu_diff())); caffe_mul(top[0]->count(), top_diff, bottom_data, product); if (!is_eltwise) { Dtype* sum_result = NULL; if (inner_dim_ == 1) { sum_result = product; } else if (sum_result_.count() == 1) { const Dtype* sum_mult = sum_multiplier_.cpu_data(); Dtype* scale_diff = scale->mutable_cpu_diff(); if (scale_param) { Dtype result = caffe_cpu_dot(inner_dim_, product, sum_mult); *scale_diff += result; } else { *scale_diff = caffe_cpu_dot(inner_dim_, product, sum_mult); } } else { const Dtype* sum_mult = sum_multiplier_.cpu_data(); sum_result = (outer_dim_ == 1) ? scale->mutable_cpu_diff() : sum_result_.mutable_cpu_data(); caffe_cpu_gemv(CblasNoTrans, sum_result_.count(), inner_dim_, Dtype(1), product, sum_mult, Dtype(0), sum_result); } if (outer_dim_ != 1) { const Dtype* sum_mult = sum_multiplier_.cpu_data(); Dtype* scale_diff = scale->mutable_cpu_diff(); if (scale_dim_ == 1) { if (scale_param) { Dtype result = caffe_cpu_dot(outer_dim_, sum_mult, sum_result); *scale_diff += result; } else { *scale_diff = caffe_cpu_dot(outer_dim_, sum_mult, sum_result); } } else { caffe_cpu_gemv(CblasTrans, outer_dim_, scale_dim_, Dtype(1), sum_result, sum_mult, Dtype(scale_param), scale_diff); } } } } if (propagate_down[0]) { const Dtype* top_diff = top[0]->cpu_diff(); const Dtype* scale_data = scale->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); for (int n = 0; n < outer_dim_; ++n) { for (int d = 0; d < scale_dim_; ++d) { const Dtype factor = scale_data[d]; caffe_cpu_scale(inner_dim_, factor, top_diff, bottom_diff); bottom_diff += inner_dim_; top_diff += inner_dim_; } } } } #ifdef CPU_ONLY STUB_GPU(ScaleLayer); #endif INSTANTIATE_CLASS(ScaleLayer); REGISTER_LAYER_CLASS(Scale); } // namespace caffe
[ "zolfagha@bret.informatik.uni-freiburg.de" ]
zolfagha@bret.informatik.uni-freiburg.de
3f0be02f4ea08d511b3c74cc9bb0fcf28d6afe93
e94c4a5d830c4a5657679e23dc87f2ea0fa80e62
/AcceleratedC++/Chapter1/TestString.cpp
0369c6017ccf86fd7531c9f979b70bd8a368ca12
[ "MIT" ]
permissive
brianaguirre/SampleCodingInterviews
d559c1f83d3e96886b36d10d627ea14ff4bb4a3a
d5ef5b675695ded20bf3a6d0f009a23fc289b9ba
refs/heads/master
2021-01-12T12:27:54.258226
2016-11-18T04:13:38
2016-11-18T04:13:38
72,501,519
0
0
null
null
null
null
UTF-8
C++
false
false
3,381
cpp
// // TestString.cpp // Chapter1 // // Created by Brian Aguirre on 11/14/2016. // Copyright © Brian Aguirre. All rights reserved. // // Testing string = and string() #include <iostream> #include <string> int main(){ std::string s; // empty string std::string t = s; // string t contains copy of characters in s char c = '*'; int n = 10; std::string z(n, c); // string z contains 10 characters of the word Hello std::cout << z << std::endl; // 1-1 const std::string hello = "Hello"; const std::string message = hello + ", world" + "!"; //Compiles // Why? // Compiles because you're following the rules of concatinating a string lit and a string object. // The left-associative property of + makes it so that hello + ", world" is processed first. // 1-2 const std::string exclam = "!"; // const std::string message1 = "Hello" + ", world" + exclam; //Fails // Why? // Because of left-associative property: s.t. ("Hello" + ", world") + exclam. // Cannnot + two string literals because they're an array of chars. // So it's like adding to pointers together: const char* s1 + const char* s2. // Doesn't make sense. We can fix this by adding () arround ", world" + exclam // const std::string exclam = "!"; // const std::string message1 = "Hello" + (", world" + exclam); // 1-3 { const std::string s = "a string"; std::cout << s << std::endl; } { const std::string s = "another string"; std::cout << s << std::endl; } // Valid because the scope is limited by the {}. // So s soon as s is printed in the first statement, that variable is destroyed and memory is freed up for another variable. // In this case that variable has the same name, but that's still valid. // 1-4 { const std::string s = "a string"; std::cout << s << std::endl; { const std::string s = "another string"; std::cout << s << std::endl; }; } // Yes. Still valid, since scope is different due toe defining second string object s under second set of {} // We can use same name for variables if their scopes are different in C++. // 1-5 { std::string s = "a string"; { std::string x = s + ", really"; std::cout << s << std::endl; } // std::cout << x << std::endl; } // Not a valid program. String object x is referenced outside of its scope. Which makes it so that the compiler thinks it's undefined. // Solution: Either define x within the first set of brackets as an empty string, and then modify it within the second set of {} // { // std::string s = "a string"; // std::string x; // { // x = s + ", really"; // std::cout << s << std::endl; // } // std::cout << x << std::endl; // } // 1-6 std::cout << "What is your name?"; std::string name; std::cin >> name; std::cout << "Hello, " << name << std::endl << "And what is yours? "; std::cin >> name; std::cout << "Hello, " << name << "; nice to meet you too!" << std::endl; // When writing two inputs at once, the program splits the strings by the space between it. // Since it stops the cin when finding a whitespace, it just takes in the following one and loads it for the second cin >> name // This refers back to the concept of flushing the buffer when explicitly told to do so. return 0; }
[ "brian.n.aguirre@gmail.com" ]
brian.n.aguirre@gmail.com
505c0b0d834fc74487244bb091eae07e2c14d751
8f2eaa1918118e0e749733fbc31a46291c88cbe5
/examples/main.cpp
4f65d2b8b51988801a73f486a2ff903fd4cf4227
[]
no_license
heathkd/embedded-cplusplus
52c55f4e70000c196b4a4ec4a13a6e247ebc681f
ee6fcf911d56b0c0e7898fa7e563f2c01be96871
refs/heads/master
2021-05-07T00:32:52.861009
2017-11-07T04:13:56
2017-11-07T04:13:56
110,162,690
0
0
null
2017-11-09T20:27:39
2017-11-09T20:27:39
null
UTF-8
C++
false
false
354
cpp
/** * @file test.cpp * @brief a file to run the code outside of testing framework * * This file should never be committed and should be emptied after use. If * you want to add an example, make a file of your wlib feature and then commit that * * @author Deep Dhillon * @date November 05, 2017 * @bug No known bugs */ int main(){ }
[ "jeffniu22@gmail.com" ]
jeffniu22@gmail.com
d19721dd85cf05a22fb1573b853bb9acdddac364
f32d05dc32431e44c1805005b98d8b6262ebae9a
/util/workq.cpp
0923c483f8c17f88a62145fbd03e179340e53324
[]
no_license
jogger0703/buildim
d19475801acc68125201b87fa768e2d814367a74
f99dfe9c2fee057501364c1eb08accb962b5644f
refs/heads/master
2016-09-05T12:15:34.918832
2014-09-11T09:42:05
2014-09-11T09:42:52
null
0
0
null
null
null
null
GB18030
C++
false
false
3,289
cpp
#include "workq.h" // WorkQ::WorkQ(void) { valid = 0; InitializeCriticalSection(&cs); } WorkQ::~WorkQ(void) { DeleteCriticalSection(&cs); } ////////////////////////////////////////////////////////////////////////// /* * 初始化线程池 * max:线程池的最大容量 * worker_count:最大并发数 * timeout:超时粒度 * func_do:处理函数 * 成功返回0,失败返回错误码 */ int WorkQ::init(int max, int paiallel, int timeout, FUNC_CALLBACK func_do) { if (!func_do || max <= 0 || paiallel <= 0) return WQ_BADPRA; this->max_work = max; this->max_worker_count = paiallel; this->timeout = timeout; this->func = func_do; this->cur_work = this->cur_worker_count = 0; this->first = this->last = NULL; this->quit = 0; this->valid = 1; return WQ_OK; } /* * 销毁线程池 * 成功返回0,失败返回错误码 */ int WorkQ::destroy(void) { if (!valid) return WQ_INVAL; lock(); quit = 1; valid = 0; unlock(); // 等待所有线程退出 // 如果等待超过2秒,不再等待 int waited = 2000; while (cur_worker_count > 0 && waited > 0) { Sleep(50); waited -= 50; } return WQ_OK; } /* * 向线程池中添加任务 * data:数据 * 成功返回0,失败返回错误码 */ int WorkQ::add_work(void* data) { workq_ele_t* new_ele = NULL; if (!valid) return WQ_INVAL; if (cur_work >= max_work) return WQ_FULL; if (quit) return WQ_QUIT; new_ele = new workq_ele_t(); if (!new_ele) return WQ_NOMEM; new_ele->data = data; new_ele->next = NULL; /* 因为需要更改成员变量,加锁 */ lock(); if (!first) first = new_ele; else last->next = new_ele; last = new_ele; cur_work++; /* 解锁 */ unlock(); // 如果有空闲线程,无需创建新线程 if (idle > 0) return WQ_OK; if (cur_worker_count < max_worker_count) { HANDLE fd = ::CreateThread(0, 0, thread_do_it, this, 0, NULL); if (!fd) { return WQ_ERROR; } cur_worker_count++; } return WQ_OK; } /* * 调整线程并行数量 */ int WorkQ::modify_paiallel(int max) { if (max <= 0) return WQ_BADPRA; lock(); max_worker_count = max; unlock(); return WQ_OK; } /* * 线程函数 */ DWORD WorkQ::thread_do_it(void* arg) { WorkQ* wq = (WorkQ*)arg; workq_ele_t* ele = NULL; while (!wq->quit) { // 完工标识,表示所有任务都完成了 int all_done = 0; while (!wq->first && !wq->quit) { if (!all_done) wq->idle++; // 防止线程空转 Sleep(50); all_done = 1; // 如果工人数太多,自觉退出 if (wq->cur_worker_count > wq->max_worker_count) break; } // 有活干了,自觉减去空闲数 wq->idle--; // 如果工人数太多,自觉退出 if (wq->cur_worker_count > wq->max_worker_count) break; /* 拿到任务以后,将任务弹出队首和/或队尾 */ wq->lock(); ele = wq->first; if (!ele) continue; wq->first = ele->next; if (wq->last == ele) wq->last = NULL; wq->cur_work--; wq->unlock(); // 工作 wq->func(ele->data); delete ele; ele = NULL; } // 离开工人队列 wq->cur_worker_count--; return 0; } ////////////////////////////////////////////////////////////////////////// void WorkQ::lock() { EnterCriticalSection(&cs); } void WorkQ::unlock() { LeaveCriticalSection(&cs); }
[ "zhaoxueqian@eyou.net" ]
zhaoxueqian@eyou.net
d08996fd5c1a44d1cf2be5d5097264b900b99a25
10f96321263014ce31623e1799b2ba7181a528e6
/GLSL_Lighting/source/glApplication.h
483c14bed9103eaa2aa35baf0a3b84af2a2a4828
[ "BSD-3-Clause" ]
permissive
ganadist/OpenGL_Study
7511dbf421df79e843c83f1393918ffa83833f86
c5dc93b0a980a442ed1c6b4fda7a771bf836844f
refs/heads/master
2016-09-05T14:25:09.377840
2012-08-06T00:32:36
2012-08-06T00:32:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,656
h
//***************************************************************************** // Application Class // //(c) 2003-2006 by Martin Christen. All Rights reserved. //******************************************************************************/ #ifndef GL_APPLICATION_H #define GL_APPLICATION_H //! \defgroup app Application #include <list> namespace cwc { //! \ingroup app class glApplication { public: glApplication(void); virtual ~glApplication(void); //! OnInit is called when application starts. This is for example a good place to create (main) windows. virtual void OnInit() {}; //! OnExit is called when application terminates. virtual void OnExit() {}; //! Return Name of Application or 0 if undefined. char* GetAppName(){return 0;} //! Set Name of Application void SetAppName(char* sAppName); //! Starts Application (OnInit() -> MainLoop() -> OnExit()) void run(); //! The mainloop of the application, override if you want to specify your own, which is not recommended in // most cases and may not even work properly with all implementations! [Basically reserved for future use] virtual bool MainLoop(); //! ShowConsole is for Windows only: Show a console where cout/printf etc are redirected. This should not be used // for productive applications, but is "nice to have" when developing certain small applications. void ShowConsole(); protected: static std::list<glApplication*> _gAppInstances; }; } #endif
[ "ganadist@gmail.com" ]
ganadist@gmail.com
3af831f0134221bb94995cad0b0d5e58d8363c28
68da090ac539f6b49c9330b05e1aef9d9773157d
/src/driver/driver-machine.h
505c179eed3ecc473bec8c7a609c1f7ab90f9de1
[]
no_license
TallDave67/state-machine
64f939036dce8532585078deb7540de1b0d2e485
2203d1d042268cbdecb81087c99cb10eda4c7369
refs/heads/main
2023-06-12T02:19:29.459307
2021-07-04T15:08:26
2021-07-04T15:08:26
382,861,364
0
0
null
null
null
null
UTF-8
C++
false
false
528
h
#ifndef _DRIVER_MACHINE_H_ #define _DRIVER_MACHINE_H_ #include "manager-state.h" #include "manager-transition.h" #include "manager-event.h" namespace Driver { class Machine { public: Machine(Manager::State & _manager_state, Manager::Transition & _manager_transition, Manager::Event & _manager_event); ~Machine(); void run(); private: Manager::State & manager_state; Manager::Transition & manager_transition; Manager::Event & manager_event; }; } #endif
[ "david.bellis1967@gmail.com" ]
david.bellis1967@gmail.com
255355aab9a42f0fad4223ae1fe85023b9fcd4fc
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/windows/directx/dxg/d3dx8/mesh/skinmesh.h
2fc8aed1a5d00d05b1a97d161b2839d3f3dd1f87
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,507
h
#pragma once #ifndef __SKINMESH_H__ #define __SKINMESH_H__ /*////////////////////////////////////////////////////////////////////////////// // // File: skinmesh.h // // Copyright (C) 2000 Microsoft Corporation. All Rights Reserved. // // //////////////////////////////////////////////////////////////////////////////*/ #include "tri3mesh.h" class CBone { public: DWORD m_numWeights; DWORD* m_pVertIndices; float* m_pWeights; CBone(); ~CBone(); }; typedef CBone* LPBONE; // Defines for CD3DXSkinMesh::m_DataValid enum { D3DXSM_VERTINFL = 1, D3DXSM_FACEINFL = 2, D3DXSM_VERTDATA = 4, }; class CD3DXSkinMesh : public ID3DXSkinMesh { public: HRESULT WINAPI QueryInterface(REFIID iid, LPVOID *ppv); ULONG WINAPI AddRef(); ULONG WINAPI Release(); STDMETHOD(GetDevice)(THIS_ LPDIRECT3DDEVICE8* ppDevice); STDMETHOD(GetVertexBuffer)(THIS_ LPDIRECT3DVERTEXBUFFER8* ppVB); STDMETHOD(GetIndexBuffer)(THIS_ LPDIRECT3DINDEXBUFFER8* ppIB); STDMETHOD(LockVertexBuffer)(THIS_ DWORD flags, BYTE** ppData); STDMETHOD(UnlockVertexBuffer)(THIS); STDMETHOD(LockIndexBuffer)(THIS_ DWORD flags, BYTE** ppData); STDMETHOD(UnlockIndexBuffer)(THIS); STDMETHOD(LockAttributeBuffer)(THIS_ DWORD flags, DWORD** ppData); STDMETHOD(UnlockAttributeBuffer)(THIS); STDMETHOD_(DWORD, GetNumBones)(THIS); STDMETHOD(GetOriginalMesh)(THIS_ LPD3DXMESH* ppMesh); STDMETHOD_(DWORD, GetNumFaces)(THIS); STDMETHOD_(DWORD, GetNumVertices)(THIS); STDMETHOD_(DWORD, GetFVF)(THIS); STDMETHOD(GetDeclaration)(THIS_ DWORD Declaration[MAX_FVF_DECL_SIZE]); STDMETHOD_(DWORD, GetOptions)(THIS); HRESULT WINAPI SetBoneInfluence(DWORD bone, DWORD numInfluences, CONST DWORD* vertices, CONST float* weights); DWORD WINAPI GetNumBoneInfluences(DWORD bone); HRESULT WINAPI GetBoneInfluence(DWORD bone, DWORD* vertices, float* weights); STDMETHOD(GetMaxVertexInfluences)(THIS_ DWORD* maxVertexInfluences); STDMETHOD(GetMaxFaceInfluences)(THIS_ DWORD* maxFaceInfluences); HRESULT WINAPI GenerateSkinnedMesh(DWORD options, FLOAT fMinWeight, CONST LPDWORD rgiAdjacencyIn, LPDWORD rgiAdjacencyOut, LPD3DXMESH* ppMesh); HRESULT WINAPI UpdateSkinnedMesh(CONST D3DXMATRIX* pBoneTransforms, LPD3DXMESH pMesh); HRESULT WINAPI ConvertToBlendedMesh(DWORD options, CONST LPDWORD pAdjacencyIn, LPDWORD pAdjacencyOut, DWORD* pNumBoneCombinations, LPD3DXBUFFER* ppBoneCombinationTable, LPD3DXMESH* ppMesh); HRESULT WINAPI ConvertToIndexedBlendedMesh(DWORD options, CONST LPDWORD pAdjacencyIn, DWORD paletteSize, LPDWORD pAdjacencyOut, DWORD* pNumBoneCombinations, LPD3DXBUFFER* ppBoneCombinationTable, LPD3DXMESH* ppMesh); CD3DXSkinMesh(); ~CD3DXSkinMesh(); HRESULT Init(DWORD numFaces, DWORD numVertices, DWORD numBones, DWORD options, DWORD fvf, LPDIRECT3DDEVICE8 pD3DDevice); HRESULT Init(LPD3DXMESH pMesh, LPBONE pBones, DWORD numBones); HRESULT Init(LPD3DXMESH pMesh, DWORD numBones); HRESULT Init(DWORD numBones); HRESULT CalcVertexSkinData(); HRESULT TruncVertexSkinData(DWORD truncVertInfl, LPDWORD pAdjacencyIn); void CalcNumAttributes(LPDWORD pAttrMask, LPDWORD pAttrBits); private: // Changes with SetBoneInfluence or GenerateSkinnedMesh CBone* m_pBones; DWORD m_numBones; DWORD m_maxVertInfl; DWORD* m_vertInfl; DWORD* m_vertMatId; float* m_vertMatWeight; // Changes with SetMesh GXTri3Mesh<tp16BitIndex> *m_pMesh; DWORD m_numAttrib; // Changes with either SetBoneInfluence or SetMesh DWORD m_matidShift; DWORD m_maxFaceInfl; DWORD m_DataValid; // Invariants to SetBoneInfluence and SetMesh DWORD m_refCnt; D3DXMATRIX** m_pBoneMatrix; DWORD m_faceClamp; // max infl per face in output mesh. Any more infl in the input are ignored BOOL m_bMixedDevice; // Calculated during GenerateSkinnedMesh float* m_rgfCodes; bool m_bChangedWeights; float m_fMinWeight; // Helper functions HRESULT GenerateCodes(); // reallocates & recalculates m_rgfCodes }; #endif //__SKINMESH_H__
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
7e20c6f52a15775c61ed9dec8201d7bb9bf62cd6
8a542c8145f5fc52faa5937afd65052f5a27ebf9
/lib/util/WaveletCompressorUtil.cpp
7d621db0f8e89e15316f3275400492d0abde197c
[ "BSD-2-Clause-Views" ]
permissive
sogorkis/wavelet-compressor
2507aa34c02558e851532011bb31e150db473939
966b2ef3a750dfdb7cfbe482c60acb714a561bc2
refs/heads/master
2021-01-19T00:46:36.154847
2013-11-24T04:52:14
2013-11-24T04:52:14
14,655,786
1
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
/* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ #include <util/WaveletCompressorUtil.h> #include <cstdio> #include <cstdlib> #include <cstdarg> #include <cmath> #include <limits> bool verbose = false; void setVerbose(bool value) { verbose = value; } void info(const char *format, ...) { if(verbose) { va_list args; va_start(args,format); printf("INFO: "); vprintf(format, args); printf("\n"); va_end(args); } } void fail(const char *format, ...) { va_list args; va_start(args,format); printf("FAIL: "); vprintf(format, args); printf("\n"); va_end(args); exit(1); } void debug(const char *format, ...) { #ifdef DEBUG va_list args; va_start(args,format); printf("DEBUG: "); vprintf(format, args); printf("\n"); va_end(args); #endif }
[ "s.ogorkis@gmail.com" ]
s.ogorkis@gmail.com
72bdb66667effcee3b395dc4fcf826b7ca60da61
0d2683fc825a1b329fe93cf1974d884f58c9f95f
/src/instapaper/qtinstapaperauth_p.h
d77eec8afafeb6bfc8d758f84b8f775c746d1940
[]
no_license
Ahamtech/PaperClip
4de2ff73dffca387f59cdb23b1fb007c44f7f363
c4af5e638edf3aeb6144f49a47e770affca6a994
refs/heads/master
2021-05-02T09:49:14.163114
2017-02-05T19:00:13
2017-02-05T19:00:13
49,139,328
2
1
null
null
null
null
UTF-8
C++
false
false
1,730
h
/* * QtInstapaper - A Instapaper.com library for Qt * * Copyright (c) 2014 Zoltán Benke (benecore@devpda.net) * http://devpda.net * * 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. */ #ifndef QTINSTAPAPERAUTH_P_H #define QTINSTAPAPERAUTH_P_H #include "qtinstapaperauth.h" class QTINSTAPAPERSHARED_EXPORT QtInstapaperAuthPrivate { public: QtInstapaperAuthPrivate(); virtual ~QtInstapaperAuthPrivate(); QtInstapaperAuth::RequestType requestType; QString consumerKey; QString consumerSecret; QString scope; QUrl callbackUrl; QString oauthToken; QString oauthTokenSecret; QString oauthVerifier; }; #endif // QTINSTAPAPERAUTH_P_H
[ "kanishkablack@gmx.com" ]
kanishkablack@gmx.com
05ede9fb89f790a35272bbe286cb269370bb19c5
7e1107c4995489a26c4007e41b53ea8d00ab2134
/game/code/meta/spheretriggervolume.h
ec643ccc3a148373294f06877f14ee90fb914da4
[]
no_license
Svxy/The-Simpsons-Hit-and-Run
83837eb2bfb79d5ddb008346313aad42cd39f10d
eb4b3404aa00220d659e532151dab13d642c17a3
refs/heads/main
2023-07-14T07:19:13.324803
2023-05-31T21:31:32
2023-05-31T21:31:32
647,840,572
591
45
null
null
null
null
UTF-8
C++
false
false
3,046
h
//============================================================================= // Copyright (C) 2002 Radical Entertainment Ltd. All rights reserved. // // File: spheretriggervolume.h // // Description: Sphere Trigger Volume class // // History: 03/04/2002 + Created -- Cary Brisebois // //============================================================================= #ifndef SPHERETRIGGERVOLUME_H #define SPHERETRIGGERVOLUME_H //======================================== // Nested Includes //======================================== #include <radmath/radmath.hpp> #ifndef WORLD_BUILDER #include <meta/triggervolume.h> #else #include "triggervolume.h" #endif //======================================== // Forward References //======================================== //============================================================================= // // Synopsis: Blahblahblah // //============================================================================= class SphereTriggerVolume : public TriggerVolume { public: SphereTriggerVolume(); SphereTriggerVolume( const rmt::Vector& centre, float radius ); virtual ~SphereTriggerVolume(); // Intersection information bool Contains( const rmt::Vector& point, float epsilon = 0.00f ) const; // Intersection of bounding box with trigger volume. //p1 - p4 are the four corners of the box. bool IntersectsBox( const rmt::Vector& p1, const rmt::Vector& p2, const rmt::Vector& p3, const rmt::Vector& p4 ) const; virtual bool IntersectsBox( const rmt::Box3D& box ); bool IntersectsSphere( const rmt::Vector& position, float radius ) const; bool IntersectLine( const rmt::Vector& p1, const rmt::Vector& p2 ) const; // Bounding box bool GetBoundingBox( rmt::Vector& p1, rmt::Vector& p2 ) const; float GetSphereRadius() const; void SetSphereRadius( float radius ); virtual Type GetType() const; ////////////////////////////////////////////////////////////////////////// // tDrawable interface ////////////////////////////////////////////////////////////////////////// void GetBoundingBox(rmt::Box3D* box); void GetBoundingSphere(rmt::Sphere* sphere); protected: virtual void InitPoints(); virtual void CalcPoints(); private: bool IntersectLineSphere( const rmt::Vector& lineOrig, const rmt::Vector& lineDir ) const; // For sphere type float mRadius; //Prevent wasteful constructor creation. SphereTriggerVolume( const SphereTriggerVolume& spheretriggervolume ); SphereTriggerVolume& operator=( const SphereTriggerVolume& spheretriggervolume ); }; inline float SphereTriggerVolume::GetSphereRadius() const { return( mRadius ); } inline void SphereTriggerVolume::SetSphereRadius( float radius ) { mRadius = radius; } #endif //SPHERETRIGGERVOLUME_H
[ "aidan61605@gmail.com" ]
aidan61605@gmail.com
08fbdff518bff3a305c537200aa0a02a07699883
a7645998ee14dc93742925580b8509ac0eb72452
/2_4_texteditor/maintexteditor.h
395ebfc99fe52b5e679129aad2ab25abf0d38a56
[]
no_license
Jay-enhanced/QTLearn
97d19a539c4896fb37e7897d3a40a56546f13d42
9432e23e7230b7e03dbdc64749d6c3b7369bce53
refs/heads/master
2023-02-03T01:09:45.862700
2020-12-27T08:24:26
2020-12-27T08:24:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
#ifndef MAINTEXTEDITOR_H #define MAINTEXTEDITOR_H #include <QMainWindow> #include <QLabel> #include <QProgressBar> #include <QSpinBox> #include <QFontComboBox> namespace Ui { class MainTextEditor; } class MainTextEditor : public QMainWindow { Q_OBJECT public: explicit MainTextEditor(QWidget *parent = nullptr); ~MainTextEditor(); private slots: void on_actionBold_triggered(bool checked); void on_actionItalic_triggered(bool checked); void on_actionUnderline_triggered(bool checked); void on_textEdit_copyAvailable(bool b); void on_textEdit_selectionChanged(); void on_spinBoxFontSize_valueChanged(int aFontSize); void on_comboFont_currentIndexChanged(const QString &arg1); private: Ui::MainTextEditor *ui; QLabel *fLabCurFile; QProgressBar *progressBar1; QSpinBox *spinFontSize; QFontComboBox *comboFont; void initUI(void); void initSignalSlots(); }; #endif // MAINTEXTEDITOR_H
[ "woshihemingjie@outlook.com" ]
woshihemingjie@outlook.com
ff455a8a9a8bec36a4d7849b0098fb3773114d8a
e0d9e44a383fc159ac5405180235780c78964eba
/src/old/gui/GuiInteractionDelegate.h
7f5a4a087c422e7d5ec3904c67563c4e86389ffb
[]
no_license
stefanhendriks/googlecode-dune2themaker
123819c2dd5616d11bf813f22b5034be7bc7311c
82b946e436f169e1480d35d217ba270d528a9321
refs/heads/master
2021-05-28T10:42:59.990730
2015-04-09T07:34:29
2015-04-09T07:34:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
670
h
/** * The GuiInteractionDelegate is responsible for interaction with the user. GuiWindow's pass down the interaction * to the concrete GuiInteractionDelegate classes. * * This is purely used as minimum interface so you are obliged to pass a delegate class at most abstract levels. * */ #ifndef GUIDELEGATE_H_ #define GUIDELEGATE_H_ #include "GuiElement.h" class GuiInteractionDelegate { public: GuiInteractionDelegate() {}; virtual ~GuiInteractionDelegate() = 0; // this function must be implemented by each concrete delegate class virtual void interact(GuiElement * guiElementCallingDelegate) = 0; }; #endif /* GUIDELEGATE_H_ */
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151
74319218bfdf537fe7d4c8839c1d257209705374
03b392459336e6bd02db655368ab69cea0f54db3
/include/base_video.hpp
4c78890d071ba7ac0f23d1fe50c4a3d3b1d087cf
[]
no_license
wivj4zm4fpg0/large_scale_data_processing
a70f86c0a83fe987a81a52d1636bedcc66116875
b34ae093327cb9ba95c2079c3a4da1560ac4f95e
refs/heads/master
2020-03-28T06:35:48.321714
2018-10-29T21:05:08
2018-10-29T21:05:08
147,846,168
0
0
null
null
null
null
UTF-8
C++
false
false
278
hpp
#ifndef _INCLUDE_BASE_ #define _INCLUDE_BASE_ #include "make_directory.hpp" class Base_Video { private: char** argv; public: virtual void processing(string &input_path, string &output_path) = 0; void large_scale_data_processing(); Base_Video(char** argv); }; #endif
[ "nzswlrkad8cw@gmail.com" ]
nzswlrkad8cw@gmail.com
a4b1ae53ac66f66dad9d1a9becfaefb94b2a414f
a3e738f0854a34fab1e0606ddda2dc955a091374
/Práctica 4/Práctica 4 Ingeniería de los Computadores - Grupo 2/COVARIANZA_V1_P4/generaMatrix.cc
327cd9bf1acddf2603ce561d1354363e594ee9f0
[]
no_license
Reyeselda95/IC
40502baafd481436fd82b286192ffa3babb15f12
47c36c45f7e90eec0cc9733366a7592549cf0793
refs/heads/master
2020-06-14T13:25:58.618493
2017-07-18T00:38:18
2017-07-18T00:38:18
75,176,895
0
3
null
null
null
null
UTF-8
C++
false
false
1,380
cc
#include <iostream> /* rand example: guess the number */ #include <stdio.h> /* printf, scanf, puts, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> using namespace std; int main () { int num; int estatura=150; int pierna=90; int pie=30; int brazo=60; int espalda=40; int craneo=50; int peso=55; int neg; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ int i=0; int j=0; while(j<3){ while(i<1000000){ neg=rand()%2; if(neg==0) neg=-1; num=estatura+(rand()%50)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=pierna+(rand()%30)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=brazo+(rand()%30)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=espalda+(rand()%20)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=craneo+(rand()%15)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=pie+(rand()%20)*neg; cout << num<< " "; neg=rand()%2; if(neg==0) neg=-1; num=peso+(rand()%40)*neg; cout << num<< endl; i++; } j++; i=0; cout << endl; } return 0; }
[ "el_reyes_95@hotmail.com" ]
el_reyes_95@hotmail.com
4fe0119c72160ec1b96f32f9c8344c946626ce2e
ced0044646a4271afadc9d5aecb0cebe34051d4a
/Source/example_ue4/UReuseListSp.h
362c4a11293ea0cf70df086599e33c60e1342d50
[]
no_license
asdlei99/example_ue4
dd4cf53b360cb29222c52a640a6249d99eaf0730
cbbc63e917900a63cb3802dbd3d90f916650f41b
refs/heads/master
2022-04-12T11:19:19.581619
2020-03-13T11:49:56
2020-03-13T11:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,268
h
// Fill out your copyright notice in the Description page of Project Settings. /************************************************************************** Author: levingong Date: 2019-6-15 Description: 支持item任意大小的重用列表 **************************************************************************/ #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" #include "Runtime/SlateCore/Public/Styling/SlateTypes.h" #include "UReuseListSp.generated.h" /** * */ class UScrollBox; class USizeBox; class UCanvasPanel; UENUM(BlueprintType) enum class EReuseListSpStyle : uint8 { Vertical, Horizontal, }; UENUM(BlueprintType) enum class EReuseListSpNotFullAlignStyle : uint8 { Start, Middle, End, }; UCLASS() class EXAMPLE_UE4_API UReuseListSp : public UUserWidget { GENERATED_BODY() public: DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnUpdateItemDelegate, UUserWidget*, Widget, int32, Idx); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnPreUpdateItemDelegate, int32, Idx); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnCreateItemDelegate, UUserWidget*, Widget); UReuseListSp(const FObjectInitializer& ObjectInitializer); UPROPERTY(BlueprintAssignable) FOnUpdateItemDelegate OnUpdateItem; UPROPERTY(BlueprintAssignable) FOnPreUpdateItemDelegate OnPreUpdateItem; UPROPERTY(BlueprintAssignable) FOnCreateItemDelegate OnCreateItem; UFUNCTION(BlueprintCallable) void Reload(int32 __ItemCount); UFUNCTION(BlueprintCallable) void Refresh(); UFUNCTION(BlueprintCallable) void RefreshOne(int32 __Idx); UFUNCTION(BlueprintCallable) void ScrollToStart(); UFUNCTION(BlueprintCallable) void ScrollToEnd(); UFUNCTION(BlueprintCallable) void SetScrollOffset(float NewScrollOffset); UFUNCTION(BlueprintCallable) float GetScrollOffset() const; UFUNCTION(BlueprintCallable) const FVector2D& GetViewSize() const { return ViewSize; } UFUNCTION(BlueprintCallable) const FVector2D& GetContentSize() const { return ContentSize; } UFUNCTION(BlueprintCallable) void JumpByIdx(int32 __Idx); UFUNCTION(BlueprintCallable) void Clear() { Reload(0); } UFUNCTION(BlueprintCallable) void Reset(TSubclassOf<UUserWidget> __ItemClass, EReuseListSpStyle __Style, int32 __ItemSize, int32 __ItemPadding); UFUNCTION(BlueprintCallable) void ClearSpecialSize(); UFUNCTION(BlueprintCallable) void AddSpecialSize(int32 __Idx, int32 __Size); UFUNCTION(BlueprintCallable) void SetCurItemClass(const FString& StrName); UFUNCTION(BlueprintCallable) void ResetCurItemClassToDefault(); protected: bool Initialize(); UPROPERTY(EditAnywhere, Category = Property) FScrollBoxStyle ScrollBoxStyle; UPROPERTY(EditAnywhere, Category = Property) FScrollBarStyle ScrollBarStyle; UPROPERTY(EditAnywhere, Category = Property) ESlateVisibility ScrollBarVisibility; UPROPERTY(EditAnywhere, Category = Property) FVector2D ScrollBarThickness; UPROPERTY(EditAnywhere, Category = Property, meta = (ClampMin = "0")) int32 ItemSize; UPROPERTY(EditAnywhere, Category = Property, meta = (ClampMin = "0")) int32 ItemPadding; UPROPERTY(EditAnywhere, Category = Property) EReuseListSpStyle Style; UPROPERTY(EditAnywhere, Category = Property) TSubclassOf<UUserWidget> ItemClass; UPROPERTY(EditAnywhere, Category = Property) TMap<FString, TSubclassOf<UUserWidget> > OtherItemClass; UPROPERTY(EditAnywhere, Category = Property, meta = (ClampMin = "0")) int32 PreviewCount; UPROPERTY(EditAnywhere, Category = Property) EReuseListSpNotFullAlignStyle NotFullAlignStyle; UPROPERTY(EditAnywhere, Category = Property) bool NotFullScrollBoxHitTestInvisible; UPROPERTY(EditAnywhere, Category = Property) bool AutoAdjustItemSize; UPROPERTY(EditAnywhere, Category = Property, meta = (ClampMin = "1")) int32 ItemPoolMaxNum; void NativeConstruct(); void NativeTick(const FGeometry& MyGeometry, float InDeltaTime); #if WITH_EDITOR void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent); #endif void OnWidgetRebuilt(); void InitWidgetPtr(); void ScrollUpdate(float __Offset); void UpdateContentSize(TWeakObjectPtr<UWidget> widget); void RemoveNotUsed(int32 BIdx, int32 EIdx); void DoReload(); TWeakObjectPtr<UUserWidget> NewItem(); void ReleaseItem(TWeakObjectPtr<UUserWidget> __Item); void ReleaseAllItem(); void DoJump(); float GetAlignSpace(); void ComputeScrollBoxHitTest(); void FillArrOffset(); int32 GetItemSize(int32 idx); void AdjustItem(); void AdjustItemWidgetSize(); void AdjustScrollOffset(); bool IsVertical() const; bool IsInvalidParam() const; float GetViewSpan() const { return (IsVertical() ? ViewSize.Y : ViewSize.X); } float GetContentSpan() const { return (IsVertical() ? ContentSize.Y : ContentSize.X); } void ClearCache(); void SyncProp(); void OnEditReload(); TWeakObjectPtr<UScrollBox> ScrollBoxList; TWeakObjectPtr<UCanvasPanel> CanvasPanelBg; TWeakObjectPtr<USizeBox> SizeBoxBg; TWeakObjectPtr<UCanvasPanel> CanvasPanelList; FVector2D ViewSize; FVector2D ContentSize; int32 ItemCount; int32 MaxPos; TSubclassOf<UUserWidget> CurItemClass; TMap<int32, TWeakObjectPtr<UUserWidget> > ItemMap; TMap<TSubclassOf<UUserWidget>, TArray<TWeakObjectPtr<UUserWidget> > > ItemPool; TArray<int32> ArrOffset; TMap<int32, int32> SpecialSizeMap; int32 JumpIdx; int32 CurJumpOffsetIdx; float LastOffset; bool NeedJump; bool NeedFillArrOffset; bool NeedAdjustItemWidgetSize; int32 NeedAdjustScrollOffset; int32 NeedReloadAdjustScrollOffset; int32 ReloadAdjustBIdx; int32 ReloadAdjustBIdxOffset; int32 NeedAdjustItem; }; DECLARE_LOG_CATEGORY_EXTERN(LogUReuseListSp, Verbose, All);
[ "gxj21720@126.com" ]
gxj21720@126.com
90bd43f8f7d1803df31123f37b3541bbbf5e9357
ee76147a967e323b8f2858996815d7fa5ed37419
/source/loonyland2/display.h
24c09ac77aaa47f011da6aee98dbc1d99e70c1b4
[ "MIT" ]
permissive
glennneiger/HamSandwich
4622bffdfaa1911fd051029264a43b61e018a91f
bc1878de81797a72c18d476ad2d274e7fd604244
refs/heads/master
2020-05-31T14:05:37.106953
2019-06-04T23:30:36
2019-06-04T23:30:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,988
h
#ifndef DISPLAY_H #define DISPLAY_H #include "mgldraw.h" #include "jamulspr.h" #include "jamulfont.h" #include "cossin.h" #include "map.h" #include "tile.h" #pragma pack(1) /* This file handles all screen displaying. It's a go-between so that you don't have to pass the mgldraw object everywhere, and also handles the display list and camera, so everything is drawn in sorted order (or not drawn). */ #define MAX_DISPLAY_OBJS 1024 #define DISPLAY_XBORDER 256 #define DISPLAY_YBORDER 256 //display object flags #define DISPLAY_DRAWME 1 #define DISPLAY_SHADOW 2 #define DISPLAY_WALLTILE 4 #define DISPLAY_ROOFTILE 8 #define DISPLAY_PARTICLE 16 #define DISPLAY_GHOST 32 #define DISPLAY_GLOW 64 #define DISPLAY_TRANSTILE 128 #define DISPLAY_LIGHTNING 256 #define DISPLAY_CIRCLEPART 512 // circle particle #define DISPLAY_OFFCOLOR 1024 #define DISPLAY_RINGPART 2048 // ring particle #define DISPLAY_BOTTOM 4096 // sort it to the bottom, in with the shadows (it's on the floor) #define DISPLAY_NUMBER 8192 // render a printed number #define DISPLAY_CLOCK 16384 // add clock hands! typedef struct displayObj_t { int x,y,z,z2; sprite_t *spr; word hue; int bright; word flags; int prev,next; char light[9]; } displayObj_t; class DisplayList { public: DisplayList(void); ~DisplayList(void); bool DrawSprite(int x,int y,int z,int z2,word hue,int bright,sprite_t *spr,word flags); void ClearList(void); void Render(void); private: void HookIn(int me); int GetOpenSlot(void); displayObj_t dispObj[MAX_DISPLAY_OBJS]; int head,nextfree; }; bool InitDisplay(MGLDraw *mainmgl); void ExitDisplay(void); byte *GetDisplayScreen(void); void DrawMouseCursor(int x,int y); void PutCamera(int x,int y); void GetCamera(int *x,int *y); // call this once per gameloop, with the X and Y of the object you want the camera to track void UpdateCamera(int x,int y,byte facing,Map *map); void Print(int x,int y,char *s,char bright,byte font); void CenterPrint(int x,int y,char *s,char bright,byte font); void RightPrint(int x,int y,char *s,char bright,byte font); void PrintColor(int x,int y,char *s,byte color,char bright,byte font); void PrintGlow(int x,int y,char *s,char bright,byte font); void CenterPrintGlow(int x,int y,char *s,char bright,byte font); void CenterPrintColor(int x,int y,char *s,byte color,char bright,byte font); void CenterPrintDark(int x,int y,const char *s,byte font); void RightPrintColor(int x,int y,char *s,byte color,char bright,byte font); void RightPrintGlow(int x,int y,char *s,char bright,byte font); void RightPrintDark(int x,int y,char *s,byte font); void PrintDark(int x,int y,char *s,byte font); void PrintRectBlack(int x,int y,int x2,int y2,char *s,byte height,int bright,byte font); void PrintDarkAdj(int x,int y,char *s,char bright,byte font); void PrintRectBlack2(int x,int y,int x2,int y2,char *s,byte height,byte font); void RenderItAll(world_t *world,Map *map,byte flags); int GetStrLength(char *s,byte f); void SprDraw(int x,int y,int z,byte hue,char bright,sprite_t *spr,word flags); void OffSprDraw(int x,int y,int z,byte hue,byte hue2,char bright,sprite_t *spr,word flags); void WallDraw(int x,int y,word wall,word floor,char *light,word flags); void RoofDraw(int x,int y,word roof,char *light,word flags); void ParticleDraw(int x,int y,int z,byte type,byte size,word flags); void LightningDraw(int x,int y,int x2,int y2,byte bright,char range); void PlotPixel(int x,int y,byte c,byte *scrn,int pitch); void NumberDraw(int x,int y,int z,byte type,byte color,short num,word flags); void MakeItFlip(void); void DrawBox(int x,int y,int x2,int y2,byte c); void DrawFillBox(int x,int y,int x2,int y2,byte c); void DrawDebugBox(int x,int y,int x2,int y2); void ShakeScreen(byte howlong); void ShowImageOrFlic(char *str); void FilmWiggle(byte howlong); MGLDraw *GetDisplayMGL(void); byte GetGamma(void); void SetGamma(byte g); void DarkenScreen(byte dark); void DrawLine(int x,int y,int x2,int y2,byte col); #endif
[ "tad@platymuus.com" ]
tad@platymuus.com
2e0b1e81da8d89bf019382c08bae3026e7036237
b4e465c4c6a46e812829bd013ac7f6031a9e2e1f
/StoreManager/source/ItemManager.cpp
5fc0bd5722bc5e6936448c169ecb2d8efafde531
[]
no_license
Sushant-Chavan/StoreManager
27f1b3a09e4b19601c31838bff5fc9c4f4d6a027
75354bd94705e90b42482af06128157cc1cdbc06
refs/heads/master
2020-04-11T21:59:02.143950
2014-10-30T18:32:56
2014-10-30T18:32:56
26,060,962
1
1
null
null
null
null
UTF-8
C++
false
false
2,807
cpp
#include "ItemManager.h" itemManager::itemManager() { itemMap = new std::map<unsigned int, item*>; } void itemManager::addItem(const char* itemName, unsigned int itemCode, float quantity, unsigned int price) { item* newItem = new item; newItem->setItemName(itemName); newItem->setItemCode(itemCode); newItem->setItemQuantity(quantity); newItem->setItemPrice(price); itemMap->insert( std::pair<unsigned int, item*>(itemCode, newItem) ); } void itemManager::addItem(item& Item) { item* newItem = new item; newItem->setItemName(Item.getItemName().c_str()); newItem->setItemCode(Item.getItemCode()); newItem->setItemQuantity(Item.getItemQuantity()); newItem->setItemPrice(Item.getItemPrice()); itemMap->insert( std::pair<unsigned int, item*>(Item.getItemCode(), newItem) ); } void itemManager::removeItem(unsigned int itemCode) { std::map<unsigned int, item*>::iterator itr; itr = itemMap->find(itemCode); if(itr != itemMap->end()) { itemMap->erase(itr); std::cout << "Item with code " << itemCode << " erased!" << std::endl; } else { std::cout << "Item with code " << itemCode << " not found!" << std::endl; } } item itemManager::getItem(unsigned int itemCode) { std::map<unsigned int, item*>::iterator itr; itr = itemMap->find(itemCode); item newItem; if(itr != itemMap->end()) { newItem = *(itr->second); } return newItem; } item itemManager::getMappedItem(unsigned int positionInMap) { std::map<unsigned int, item*>::iterator itr = itemMap->begin(); for (unsigned int i = 0; i < positionInMap; i++) { itr++; } item newItem; if (itr != itemMap->end()) { newItem = *(itr->second); } return newItem; } void itemManager::displayAllItemCodes() { std::map<unsigned int, item*>::iterator itr; std::cout << "Item codes of Items currently present with the item Manager : " << std::endl; for(itr = itemMap->begin(); itr != itemMap->end(); itr++) { std::cout << itr->second->getItemCode() << std::endl; } } void itemManager::displayAllItemNames() { std::map<unsigned int, item*>::iterator itr; std::cout << "Item Names of Items currently present with the item Manager : " << std::endl; for(itr = itemMap->begin(); itr != itemMap->end(); itr++) { std::cout << itr->second->getItemName() << std::endl; } } void itemManager::displayAllItemDetails() { std::map<unsigned int, item*>::iterator itr; std::cout << "Details of Items currently present with the item Manager : " << std::endl; for(itr = itemMap->begin(); itr != itemMap->end(); itr++) { itr->second->displayDetails(); std::cout << std::endl; } } bool itemManager::itemPresent(unsigned int itemCode) { bool retval = false; std::map<unsigned int, item*>::iterator itr; itr = itemMap->find(itemCode); if(itr != itemMap->end()) { retval = true; } return retval; }
[ "suvich15@rediffmail.com" ]
suvich15@rediffmail.com
87815329ad51d97bad5059f533c1cf90c6878509
44d5ddeb77c4560af99f718fbc0a47de86a60fbd
/C++/Examples/C++/boost/25. PropertyTree/25.3. Accessing data with a translator.cpp
c05f4c66ff09654423fa5fefd1dd9914d910749c
[]
no_license
tuandat64/rpw
f55c707f52d0a4b02fdbda59bd295e0dd5206f3c
be3d40ee52d487e83df20f6757c228d638c12d77
refs/heads/master
2023-03-05T15:14:13.308877
2021-02-18T08:37:09
2021-02-18T08:37:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
#include "stdafx.h" //Chapter 25. Boost.PropertyTree - Example 25.3. Accessing data with a translator @ https://theboostcpplibraries.com/boost.propertytree #include <boost/property_tree/ptree.hpp> #include <boost/optional.hpp> #include <iostream> using namespace std; #include <cstdlib> struct string_to_int_translator { typedef string internal_type; typedef int external_type; boost::optional<int> get_value(const string& s) { char* c; long l = strtol(s.c_str(), &c, 10); return boost::make_optional(c != s.c_str(), static_cast<int>(l)); } }; int main() { typedef boost::property_tree::iptree ptree; ptree pt; pt.put(ptree::path_type{ "C:\\Windows\\System", '\\' }, "20 files"); pt.put(ptree::path_type{ "C:\\Windows\\Cursors", '\\' }, "50 files"); string_to_int_translator tr; int files = pt.get<int>(ptree::path_type{ "c:\\windows\\system", '\\' }, tr) + pt.get<int>(ptree::path_type{ "c:\\windows\\cursors", '\\' }, tr); cout << files << '\n'; }
[ "apkretov@hotmail.com" ]
apkretov@hotmail.com
3c083def648c21c7cb139671e98b87e2b967acd6
190e614f7722b8c95a3bb76b2f702ab55ed942e6
/PressureEngineCore/Src/Graphics/Models/TexturedModel.h
49df61a7138fd0be73d3151a47d3a90df2cc060c
[ "MIT" ]
permissive
templeblock/PressureEngine
ec11ffe99bcf5e8811fd21ec5e8bccbde4219e39
6b023165fcaecb267e13cf5532ea26a8da3f1450
refs/heads/master
2020-04-17T07:15:57.032285
2019-01-06T12:29:57
2019-01-06T12:29:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
h
#pragma once #include "../Models/RawModel.h" #include "../Textures/ModelTexture.h" #include "../../DllExport.h" namespace Pressure { class PRESSURE_API TexturedModel { private: RawModel m_RawModel; ModelTexture m_Texture; public: TexturedModel(RawModel model, ModelTexture texture) : m_RawModel(model), m_Texture(texture) { } inline RawModel getRawModel() const { return m_RawModel; } inline ModelTexture getTexture() const { return m_Texture; } inline bool operator==(const TexturedModel& other) const { return m_RawModel.getVertexArray().getID() == other.m_RawModel.getVertexArray().getID() && m_Texture.getID() == m_Texture.getID(); } }; } // Needed for comparisons when used as key in std::unordered_map. namespace std { template <> struct hash<Pressure::TexturedModel> { size_t operator()(const Pressure::TexturedModel& m) const { size_t res = 17; res = res * 31 + hash<unsigned int>()(m.getRawModel().getVertexArray().getID()); res = res * 31 + hash<unsigned int>()(m.getTexture().getID()); return res; } }; }
[ "olli.larsson@hotmail.com" ]
olli.larsson@hotmail.com
02b1b923ce9f924e4cd74d7b519d7d668a4b0919
6fd4564eea09aa91c1c9f60fdddece7e3d2e1cd5
/previous Practiced/sticker thief .cpp
a6f0834a5fccc064e72b463e005f0f45a70bc27c
[]
no_license
itechsubhan/data-structures
61783cc8440307dd9c89f17cfc32f8bf6ba32eb6
e64b2fd483099077f8468a9983d7431689e81371
refs/heads/master
2023-09-03T02:45:19.372706
2021-11-19T11:59:44
2021-11-19T11:59:44
429,775,143
0
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
#include <bits/stdc++.h> using namespace std; void solve() { int n,t=1,i,j,k; dp[0] = arr[0]; dp[1] = max(arr[0], arr[1]); int temp; // Iterate from i = 2 to n. for(int i = 2; i < n; i++) { // maximum value till ith house will be // maximum of (i-1)th house without including current house // and inculuding ith house + maxVlue till (i-2)th house. dp[i] = max(dp[i-1], dp[i-2] + arr[i]); } // return last value which will be the final Answer return dp[n-1]; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt","w", stdout); #endif solve(); }
[ "subhanitech63@gmail.com" ]
subhanitech63@gmail.com
951d87a76bf58b5ae39191d486022eea26d4ead3
70022f7e5ac4c229e412b51db248fdd08a0a5b28
/src/examples/cpp/call_passed_indirectly_to_call.cpp
c31ee8f6fc44c9081f445b77085de9525d85b1bd
[]
no_license
agrippa/chimes
6465fc48f118154e9d42fbd26d6b87a7dce7c5e9
695bb5bb54efbcd61469acda79b6ba6532e2d1d9
refs/heads/master
2020-12-25T14:02:17.752481
2016-07-04T02:20:59
2016-07-04T02:20:59
23,259,130
0
1
null
null
null
null
UTF-8
C++
false
false
240
cpp
#include <checkpoint.h> #include <assert.h> int foo(int *a, int s) { *a = s; } int bar() { return 6; } int main(int argc, char **argv) { int b; foo(&b, bar() + 9); checkpoint(); assert(b == 9); return 0; }
[ "jmaxg3@gmail.com" ]
jmaxg3@gmail.com
d850f158620aeef5b5595deb457c08fec50e4d06
d44fe46073bcee3b42d84f43170614dc2249687d
/GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/ContentTools/Common/Filters/FilterTutorial/ConvertToPhantomAction/MyPhantomShape.cpp
6e9cb6527b8b172544715c07f7b1a096ce11305b
[ "MIT" ]
permissive
aditgoyal19/Tropical-Go-Kart-Bananas
1b162a3c994f90d3e5f432bd68251411a369812c
ed3c0489402f8a559c77b56545bd8ebc79c4c563
refs/heads/master
2021-01-11T15:21:24.709156
2017-07-06T21:07:36
2017-07-06T21:07:36
80,340,694
0
0
null
null
null
null
UTF-8
C++
false
false
4,845
cpp
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <ContentTools/Common/Filters/FilterTutorial/hctFilterTutorial.h> #include <ContentTools/Common/Filters/FilterTutorial/ConvertToPhantomAction/MyPhantomShape.h> #include <Physics2012/Dynamics/Action/hkpBinaryAction.h> #include <Physics2012/Dynamics/Entity/hkpRigidBody.h> // // Actions // // Apply a constant force to the rigid body // (Use a binary action so that it maintains a ref to the phantom) class MyWindAction : public hkpBinaryAction { public: MyWindAction( hkpRigidBody* phantom, hkpRigidBody* rb, const hkVector4& force ) : hkpBinaryAction(phantom,rb), m_force(force) {} MyWindAction( hkFinishLoadedObjectFlag flag ) : hkpBinaryAction(flag) {} /*virtual*/ void applyAction( const hkStepInfo& stepInfo ) { hkpRigidBody* rb = (hkpRigidBody*)getEntityB(); rb->applyForce( stepInfo.m_deltaTime, m_force ); } /*virtual*/ MyWindAction* clone( const hkArray<hkpEntity*>& newEntities, const hkArray<hkpPhantom*>& newPhantoms ) const { return HK_NULL; } hkVector4 m_force; }; // Apply a 'point' force to the rigid body class MyAttractAction : public hkpBinaryAction { public: MyAttractAction( hkpRigidBody* phantom, hkpRigidBody* rb, float strength ) : hkpBinaryAction(phantom,rb), m_strength(strength) {} MyAttractAction( hkFinishLoadedObjectFlag flag ) : hkpBinaryAction(flag) {} /*virtual*/ void applyAction( const hkStepInfo& stepInfo ) { hkVector4 force; force.setSub4( getEntityA()->getMotion()->getPosition(), getEntityB()->getMotion()->getPosition() ); float distance = force.length3(); force.mul4( m_strength / ( ( distance * distance ) + HK_REAL_EPSILON ) ); hkpRigidBody* rb = (hkpRigidBody*)getEntityB(); rb->applyForce( stepInfo.m_deltaTime, force ); } /*virtual*/ MyAttractAction* clone( const hkArray<hkpEntity*>& newEntities, const hkArray<hkpPhantom*>& newPhantoms ) const { return HK_NULL; } float m_strength; }; // // hkpPhantom interface implementation // MyPhantomShape::MyPhantomShape() { m_actionType = ACTION_WIND; m_direction.setZero4(); m_strength = 0.0f; } /*virtual*/ void MyPhantomShape::phantomEnterEvent( const hkpCollidable* phantomColl, const hkpCollidable* otherColl, const hkpCollisionInput& env ) { hkpRigidBody* phantom = hkpGetRigidBody( phantomColl ); hkpRigidBody* rb = hkpGetRigidBody( otherColl ); if( !phantom || !rb ) { return; } // Create the appropriate action hkpAction* action = HK_NULL; switch( m_actionType ) { case ACTION_WIND: { hkVector4 force; force.setMul4( m_strength, m_direction ); action = new MyWindAction( phantom, rb, force ); } break; case ACTION_ATTRACT: { action = new MyAttractAction( phantom, rb, m_strength ); } break; case ACTION_DEFLECT: { // use the attract action with a negative strength action = new MyAttractAction( phantom, rb, -m_strength ); } break; } // Add it to the world if( action ) { rb->getWorld()->addAction( action ); action->removeReference(); } } /*virtual*/ void MyPhantomShape::phantomLeaveEvent( const hkpCollidable* phantomColl, const hkpCollidable* otherColl ) { hkpRigidBody* phantom = hkpGetRigidBody( phantomColl ); hkpRigidBody* rb = hkpGetRigidBody( otherColl ); if( !phantom || !rb ) { return; } // Find and remove the appropriate action int numActions = phantom->getNumActions(); for( int i=numActions-1; i>=0; --i ) { hkpAction* action = phantom->getAction(i); if (action) { hkArray<hkpEntity*> entities; action->getEntities( entities ); for( int j=0; j<entities.getSize(); ++j ) { if( entities[j] == rb ) { action->getWorld()->removeAction( action ); } } } } } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "a_goyal3@fanshaweonline.ca" ]
a_goyal3@fanshaweonline.ca
d04992b52749dbba8a5c7c497948ccbe4109f7c7
267c478c3f7bd3c202361c974e8cf987bf7bb72e
/TCStruct3Lib/StandardOutput.h
44d18ef06810deac5d3bc404c66b5511b6c6ea01
[]
no_license
TCSolutions/TCStruct3
ac8ce32c9786961b527a5e38550dddb853e07bea
60f1b7b151d1faa98f777ea23062c236a68fe04a
refs/heads/master
2021-01-23T12:25:44.567432
2013-08-22T08:21:56
2013-08-22T08:21:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
431
h
#ifndef STANDARDOUTPUT_H #define STANDARDOUTPUT_H #include "Global.h" namespace StandardOutputHandler { typedef bool _stdcall StandardOutputCallback(char* szOutput); NOMANGLE bool EXPORTED SetSTANDARDOUTPUTCallback(StandardOutputCallback* soCallback); NOMANGLE bool EXPORTED FreeSTANDARDOUTPUTCallback(void); bool PrintString(char* szOutput); namespace detail { extern StandardOutputCallback* psoCallback; } } #endif
[ "TCSolutions@live.com" ]
TCSolutions@live.com
c470e4fc8c2d4fdfb40c9053a0d8e130dba37adf
4979915833a11a0306b66a25a91fadd009e7d863
/src/ui/scenic/lib/input/tests/touch_source_test.cc
aa68d4995483b48d88b3e2788878b555592d6adc
[ "BSD-2-Clause" ]
permissive
dreamboy9/fuchsia
1f39918fb8fe71d785b43b90e0b3128d440bd33f
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
refs/heads/master
2023-05-08T02:11:06.045588
2021-06-03T01:59:17
2021-06-03T01:59:17
373,352,924
0
0
NOASSERTION
2021-06-03T01:59:18
2021-06-03T01:58:57
null
UTF-8
C++
false
false
28,588
cc
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/scenic/lib/input/touch_source.h" #include <lib/async-testing/test_loop.h> #include <lib/syslog/cpp/macros.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "lib/gtest/test_loop_fixture.h" namespace lib_ui_input_tests { namespace { using fup_EventPhase = fuchsia::ui::pointer::EventPhase; using fuchsia::ui::pointer::TouchResponseType; using scenic_impl::input::ContenderId; using scenic_impl::input::Extents; using scenic_impl::input::GestureResponse; using scenic_impl::input::InternalPointerEvent; using scenic_impl::input::Phase; using scenic_impl::input::StreamId; using scenic_impl::input::TouchSource; using scenic_impl::input::Viewport; constexpr StreamId kStreamId = 1; constexpr uint32_t kDeviceId = 2; constexpr uint32_t kPointerId = 3; namespace { fuchsia::ui::pointer::TouchResponse CreateResponse(TouchResponseType response_type) { fuchsia::ui::pointer::TouchResponse response; response.set_response_type(response_type); return response; } void ExpectEqual(const fuchsia::ui::pointer::ViewParameters& view_parameters, const Viewport& viewport) { EXPECT_THAT(view_parameters.viewport.min, testing::ElementsAre(viewport.extents.min[0], viewport.extents.min[1])); EXPECT_THAT(view_parameters.viewport.max, testing::ElementsAre(viewport.extents.max[0], viewport.extents.max[1])); const auto& mat = viewport.context_from_viewport_transform; EXPECT_THAT(view_parameters.viewport_to_view_transform, testing::ElementsAre(mat[0][0], mat[0][1], mat[0][2], mat[1][0], mat[1][1], mat[1][2], mat[2][0], mat[2][1], mat[2][2])); } } // namespace class TouchSourceTest : public gtest::TestLoopFixture { protected: void SetUp() override { client_ptr_.set_error_handler([this](auto) { channel_closed_ = true; }); touch_source_.emplace( client_ptr_.NewRequest(), /*respond*/ [this](StreamId stream_id, const std::vector<GestureResponse>& responses) { std::copy(responses.begin(), responses.end(), std::back_inserter(received_responses_[stream_id])); }, /*error_handler*/ [this] { internal_error_handler_fired_ = true; }); } bool internal_error_handler_fired_ = false; bool channel_closed_ = false; std::unordered_map<StreamId, std::vector<GestureResponse>> received_responses_; fuchsia::ui::pointer::TouchSourcePtr client_ptr_; std::optional<TouchSource> touch_source_; }; TEST_F(TouchSourceTest, Watch_WithNoPendingMessages_ShouldNeverReturn) { bool callback_triggered = false; client_ptr_->Watch({}, [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(channel_closed_); EXPECT_FALSE(callback_triggered); } TEST_F(TouchSourceTest, ErrorHandler_ShouldFire_OnClientDisconnect) { EXPECT_FALSE(internal_error_handler_fired_); client_ptr_.Unbind(); RunLoopUntilIdle(); EXPECT_TRUE(internal_error_handler_fired_); } TEST_F(TouchSourceTest, NonEmptyResponse_ForInitialWatch_ShouldCloseChannel) { bool callback_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_TRUE(channel_closed_); EXPECT_FALSE(callback_triggered); } TEST_F(TouchSourceTest, ForcedChannelClosing_ShouldFireInternalErrorHandler) { bool callback_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); EXPECT_FALSE(channel_closed_); EXPECT_FALSE(internal_error_handler_fired_); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); EXPECT_TRUE(internal_error_handler_fired_); } TEST_F(TouchSourceTest, EmptyResponse_ForPointerEvent_ShouldCloseChannel) { touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); client_ptr_->Watch({}, [](auto events) { EXPECT_EQ(events.size(), 1u); }); RunLoopUntilIdle(); // Respond with an empty response table. bool callback_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.push_back({}); // Empty response. client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, NonEmptyResponse_ForNonPointerEvent_ShouldCloseChannel) { touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); // This event expects an empty response table. touch_source_->EndContest(kStreamId, /*awarded_win*/ true); client_ptr_->Watch({}, [](auto events) { EXPECT_EQ(events.size(), 2u); }); RunLoopUntilIdle(); bool callback_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); // Expected to be empty. client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, Watch_BeforeEvents_ShouldReturnOnFirstEvent) { uint64_t num_events = 0; client_ptr_->Watch({}, [&num_events](auto events) { num_events += events.size(); }); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(channel_closed_); EXPECT_EQ(num_events, 0u); // Sending fidl message on first event, so expect the second one not to arrive. touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); RunLoopUntilIdle(); EXPECT_TRUE(received_responses_.empty()); EXPECT_FALSE(channel_closed_); EXPECT_EQ(num_events, 1u); // Second event should arrive on next Watch() call. std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&num_events](auto events) { num_events += events.size(); }); RunLoopUntilIdle(); EXPECT_EQ(received_responses_.size(), 1u); EXPECT_FALSE(channel_closed_); EXPECT_EQ(num_events, 2u); } TEST_F(TouchSourceTest, Watch_ShouldAtMostReturn_TOUCH_MAX_EVENT_Events_PerCall) { // Sending fidl message on first event, so expect the second one not to arrive. touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); for (size_t i = 0; i < fuchsia::ui::pointer::TOUCH_MAX_EVENT + 3; ++i) { touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); } client_ptr_->Watch( {}, [](auto events) { ASSERT_EQ(events.size(), fuchsia::ui::pointer::TOUCH_MAX_EVENT); }); RunLoopUntilIdle(); std::vector<fuchsia::ui::pointer::TouchResponse> responses; for (size_t i = 0; i < fuchsia::ui::pointer::TOUCH_MAX_EVENT; ++i) { responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); } // The 4 events remaining in the queue should be delivered with the next Watch() call. client_ptr_->Watch(std::move(responses), [](auto events) { EXPECT_EQ(events.size(), 4u); }); RunLoopUntilIdle(); } TEST_F(TouchSourceTest, Watch_ResponseBeforeEvent_ShouldCloseChannel) { // Initial call to Watch() should be empty since we can't respond to any events yet. bool callback_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, Watch_MoreResponsesThanEvents_ShouldCloseChannel) { touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); client_ptr_->Watch({}, [](auto events) { EXPECT_EQ(events.size(), 1u); }); RunLoopUntilIdle(); EXPECT_FALSE(channel_closed_); // Expecting one response. Send two. bool callback_fired = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&callback_fired](auto) { callback_fired = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_fired); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, Watch_FewerResponsesThanEvents_ShouldCloseChannel) { touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); client_ptr_->Watch({}, [](auto events) { EXPECT_EQ(events.size(), 2u); }); RunLoopUntilIdle(); EXPECT_FALSE(channel_closed_); // Expecting two responses. Send one. bool callback_fired = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [&callback_fired](auto) { callback_fired = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_fired); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, Watch_CallingTwiceWithoutWaiting_ShouldCloseChannel) { client_ptr_->Watch({}, [](auto) { EXPECT_FALSE(true); }); client_ptr_->Watch({}, [](auto) { EXPECT_FALSE(true); }); RunLoopUntilIdle(); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, MissingArgument_ShouldCloseChannel) { uint64_t num_events = 0; client_ptr_->Watch({}, [&num_events](auto events) { num_events += events.size(); }); RunLoopUntilIdle(); EXPECT_EQ(num_events, 0u); EXPECT_FALSE(channel_closed_); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); RunLoopUntilIdle(); EXPECT_EQ(num_events, 1u); EXPECT_FALSE(channel_closed_); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(); // Empty response for pointer event should close channel. client_ptr_->Watch(std::move(responses), [&num_events](auto events) { num_events += events.size(); }); RunLoopUntilIdle(); EXPECT_EQ(num_events, 1u); EXPECT_TRUE(channel_closed_); } TEST_F(TouchSourceTest, UpdateResponse) { { // Complete a stream and respond HOLD to it. client_ptr_->Watch({}, [](auto) {}); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); RunLoopUntilIdle(); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); client_ptr_->Watch(std::move(responses), [](auto) {}); RunLoopUntilIdle(); } { bool callback_triggered = false; client_ptr_->UpdateResponse( fuchsia::ui::pointer::TouchInteractionId{ .device_id = kDeviceId, .pointer_id = kPointerId, .interaction_id = kStreamId, }, CreateResponse(TouchResponseType::YES), [&callback_triggered] { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(callback_triggered); EXPECT_FALSE(channel_closed_); } } TEST_F(TouchSourceTest, UpdateResponse_UnknownStreamId_ShouldCloseChannel) { bool callback_triggered = false; client_ptr_->UpdateResponse( fuchsia::ui::pointer::TouchInteractionId{ .device_id = 1, .pointer_id = 1, .interaction_id = 12153, // Unknown stream id. }, CreateResponse(TouchResponseType::YES), [&callback_triggered] { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); EXPECT_TRUE(received_responses_.empty()); } TEST_F(TouchSourceTest, UpdateResponse_BeforeStreamEnd_ShouldCloseChannel) { { // Start a stream and respond to it. bool callback_triggered = false; client_ptr_->Watch({}, [&callback_triggered](auto) { callback_triggered = true; }); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); RunLoopUntilIdle(); EXPECT_TRUE(callback_triggered); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); client_ptr_->Watch(std::move(responses), [](auto) {}); RunLoopUntilIdle(); } { // Try to reject the stream despite it not having ended. bool callback_triggered = false; client_ptr_->UpdateResponse( fuchsia::ui::pointer::TouchInteractionId{ .device_id = 1, .pointer_id = 1, .interaction_id = kStreamId, }, CreateResponse(TouchResponseType::YES), [&callback_triggered] { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } } TEST_F(TouchSourceTest, UpdateResponse_WhenLastResponseWasntHOLD_ShouldCloseChannel) { { // Start a stream and respond to it. bool callback_triggered = false; client_ptr_->Watch({}, [&callback_triggered](auto) { callback_triggered = true; }); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); RunLoopUntilIdle(); EXPECT_TRUE(callback_triggered); bool callback2_triggered = false; std::vector<fuchsia::ui::pointer::TouchResponse> responses; // Respond with something other than HOLD. responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); client_ptr_->Watch(std::move(responses), [](auto) {}); RunLoopUntilIdle(); } { bool callback_triggered = false; client_ptr_->UpdateResponse( fuchsia::ui::pointer::TouchInteractionId{ .device_id = 1, .pointer_id = 1, .interaction_id = kStreamId, }, CreateResponse(TouchResponseType::YES), [&callback_triggered] { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } } TEST_F(TouchSourceTest, UpdateResponse_WithHOLD_ShouldCloseChannel) { { // Start a stream and respond to it. bool callback_triggered = false; client_ptr_->Watch({}, [&callback_triggered](auto) { callback_triggered = true; }); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); RunLoopUntilIdle(); EXPECT_TRUE(callback_triggered); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); client_ptr_->Watch(std::move(responses), [](auto) {}); RunLoopUntilIdle(); } { // Try to update the stream with a HOLD response. bool callback_triggered = false; client_ptr_->UpdateResponse( fuchsia::ui::pointer::TouchInteractionId{ .device_id = 1, .pointer_id = 1, .interaction_id = kStreamId, }, CreateResponse(TouchResponseType::HOLD), [&callback_triggered] { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_FALSE(callback_triggered); EXPECT_TRUE(channel_closed_); } } TEST_F(TouchSourceTest, ViewportIsDeliveredCorrectly) { Viewport viewport1; viewport1.extents = std::array<std::array<float, 2>, 2>{{{0, 0}, {10, 10}}}; viewport1.context_from_viewport_transform = { // clang-format off 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 // clang-format on }; Viewport viewport2; viewport2.extents = std::array<std::array<float, 2>, 2>{{{-5, 1}, {100, 40}}}; viewport2.context_from_viewport_transform = { // clang-format off 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0, 0, 0, 0, 1 // clang-format on }; touch_source_->UpdateStream(kStreamId, {.phase = Phase::kAdd, .viewport = viewport1}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange, .viewport = viewport1}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove, .viewport = viewport2}, /*is_end_of_stream*/ true); client_ptr_->Watch({}, [&](auto events) { ASSERT_EQ(events.size(), 3u); EXPECT_TRUE(events[0].has_view_parameters()); EXPECT_TRUE(events[0].has_pointer_sample()); EXPECT_FALSE(events[1].has_view_parameters()); EXPECT_TRUE(events[1].has_pointer_sample()); EXPECT_TRUE(events[2].has_view_parameters()); EXPECT_TRUE(events[2].has_pointer_sample()); ExpectEqual(events[0].view_parameters(), viewport1); // ExpectEqual(events[2].view_parameters(), viewport2); }); RunLoopUntilIdle(); } // Sends a full stream and observes that GestureResponses are as expected. TEST_F(TouchSourceTest, NormalStream) { touch_source_->UpdateStream( kStreamId, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); EXPECT_TRUE(received_responses_.empty()); client_ptr_->Watch({}, [&](auto events) { ASSERT_EQ(events.size(), 4u); EXPECT_EQ(events[0].pointer_sample().phase(), fup_EventPhase::ADD); EXPECT_EQ(events[1].pointer_sample().phase(), fup_EventPhase::CHANGE); EXPECT_EQ(events[2].pointer_sample().phase(), fup_EventPhase::CHANGE); EXPECT_EQ(events[3].pointer_sample().phase(), fup_EventPhase::REMOVE); EXPECT_TRUE(events[0].has_timestamp()); EXPECT_TRUE(events[1].has_timestamp()); EXPECT_TRUE(events[2].has_timestamp()); EXPECT_TRUE(events[3].has_timestamp()); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::YES)); client_ptr_->Watch({std::move(responses)}, [](auto events) { // These will be checked after EndContest() below, when the callback runs. EXPECT_EQ(events.size(), 1u); EXPECT_FALSE(events.at(0).has_pointer_sample()); EXPECT_TRUE(events.at(0).has_timestamp()); ASSERT_TRUE(events.at(0).has_interaction_result()); const auto& interaction_result = events.at(0).interaction_result(); EXPECT_EQ(interaction_result.interaction.interaction_id, kStreamId); EXPECT_EQ(interaction_result.interaction.device_id, kDeviceId); EXPECT_EQ(interaction_result.interaction.pointer_id, kPointerId); EXPECT_EQ(interaction_result.status, fuchsia::ui::pointer::TouchInteractionStatus::GRANTED); }); }); RunLoopUntilIdle(); EXPECT_EQ(received_responses_.size(), 1u); EXPECT_THAT(received_responses_[kStreamId], testing::ElementsAre(GestureResponse::kMaybe, GestureResponse::kHold, GestureResponse::kHold, GestureResponse::kYes)); // Check winning conditions. touch_source_->EndContest(kStreamId, /*awarded_win*/ true); RunLoopUntilIdle(); } // Sends a full legacy interaction (including UP and DOWN events) and observes that GestureResponses // are included for the extra events not seen by clients. Each filtered event should duplicate the // response of the previous event. TEST_F(TouchSourceTest, LegacyInteraction) { touch_source_->UpdateStream( kStreamId, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kDown}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kChange}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kUp}, /*is_end_of_stream*/ false); touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); EXPECT_TRUE(received_responses_.empty()); client_ptr_->Watch({}, [&](auto events) { ASSERT_EQ(events.size(), 4u); EXPECT_EQ(events[0].pointer_sample().phase(), fup_EventPhase::ADD); EXPECT_EQ(events[1].pointer_sample().phase(), fup_EventPhase::CHANGE); EXPECT_EQ(events[2].pointer_sample().phase(), fup_EventPhase::CHANGE); EXPECT_EQ(events[3].pointer_sample().phase(), fup_EventPhase::REMOVE); std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::HOLD)); responses.emplace_back(CreateResponse(TouchResponseType::YES)); client_ptr_->Watch({std::move(responses)}, [](auto events) { // These will be checked after EndContest() below. EXPECT_EQ(events.size(), 1u); EXPECT_FALSE(events.at(0).has_pointer_sample()); EXPECT_TRUE(events.at(0).has_timestamp()); ASSERT_TRUE(events.at(0).has_interaction_result()); const auto& interaction_result = events.at(0).interaction_result(); EXPECT_EQ(interaction_result.interaction.interaction_id, kStreamId); EXPECT_EQ(interaction_result.interaction.device_id, kDeviceId); EXPECT_EQ(interaction_result.interaction.pointer_id, kPointerId); EXPECT_EQ(interaction_result.status, fuchsia::ui::pointer::TouchInteractionStatus::GRANTED); }); }); RunLoopUntilIdle(); EXPECT_EQ(received_responses_.size(), 1u); EXPECT_THAT( received_responses_.at(kStreamId), testing::ElementsAre(GestureResponse::kMaybe, GestureResponse::kMaybe, GestureResponse::kHold, GestureResponse::kHold, GestureResponse::kHold, GestureResponse::kYes)); // Check losing conditions. touch_source_->EndContest(kStreamId, /*awarded_win*/ true); RunLoopUntilIdle(); } TEST_F(TouchSourceTest, OnDestruction_ShouldExitOngoingContests) { constexpr StreamId kStreamId2 = 2, kStreamId3 = 3, kStreamId4 = 4, kStreamId5 = 5, kStreamId6 = 6; // Start a few streams. touch_source_->UpdateStream( kStreamId, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream( kStreamId2, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream( kStreamId3, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream( kStreamId4, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream( kStreamId5, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); touch_source_->UpdateStream( kStreamId6, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); // End streams 1-3. touch_source_->UpdateStream(kStreamId, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); touch_source_->UpdateStream(kStreamId2, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); touch_source_->UpdateStream(kStreamId3, {.phase = Phase::kRemove}, /*is_end_of_stream*/ true); // Award some wins and losses. touch_source_->EndContest(kStreamId, /*awarded_win*/ true); touch_source_->EndContest(kStreamId2, /*awarded_win*/ false); touch_source_->EndContest(kStreamId4, /*awarded_win*/ true); touch_source_->EndContest(kStreamId5, /*awarded_win*/ false); // We now have streams in the following states: // 1: Ended, Won // 2: Ended, Lost // 3: Ended, Undecided // 4: Ongoing, Won // 5: Ongoing, Lost // 6: Ongoing, Undecided // // TouchSource should respond only to undecided streams on destruction. EXPECT_TRUE(received_responses_.empty()); // Destroy the event source and observe proper cleanup. touch_source_.reset(); EXPECT_EQ(received_responses_.size(), 2u); EXPECT_THAT(received_responses_.at(kStreamId3), testing::ElementsAre(GestureResponse::kNo)); EXPECT_THAT(received_responses_.at(kStreamId6), testing::ElementsAre(GestureResponse::kNo)); } // Checks that a response to an already ended stream doesn't respond to the gesture arena. TEST_F(TouchSourceTest, WatchAfterContestEnd_ShouldNotRespond) { constexpr StreamId kStreamId2 = 2, kStreamId3 = 3, kStreamId4 = 4, kStreamId5 = 5, kStreamId6 = 6; client_ptr_->Watch({}, [](auto) {}); // Start a stream, then end the contest before receiving responses. touch_source_->UpdateStream( kStreamId, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, /*is_end_of_stream*/ false); RunLoopUntilIdle(); touch_source_->EndContest(kStreamId, /*awarded_win*/ false); RunLoopUntilIdle(); // Now respond to the already ended stream. std::vector<fuchsia::ui::pointer::TouchResponse> responses; responses.emplace_back(CreateResponse(TouchResponseType::MAYBE)); bool callback_triggered = false; client_ptr_->Watch(std::move(responses), [&callback_triggered](auto) { callback_triggered = true; }); RunLoopUntilIdle(); EXPECT_TRUE(callback_triggered); EXPECT_TRUE(received_responses_.empty()); } // Tests that an EndContest() call in |respond| doesn't cause ASAN issues on destruction. TEST_F(TouchSourceTest, ReentryOnDestruction_ShouldNotCauseUseAfterFreeErrors) { bool respond_called = false; touch_source_.emplace( client_ptr_.NewRequest(), /*respond*/ [this, &respond_called](StreamId stream_id, const std::vector<GestureResponse>& responses) { respond_called = true; touch_source_->EndContest(stream_id, /*awarded_win*/ false); }, /*error_handler*/ [] {}); touch_source_->UpdateStream( kStreamId, {.device_id = kDeviceId, .pointer_id = kPointerId, .phase = Phase::kAdd}, false); EXPECT_FALSE(respond_called); touch_source_.reset(); EXPECT_TRUE(respond_called); } } // namespace } // namespace lib_ui_input_tests
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f9a788f550756c6b04fbd578f1a2d12b9a9f9194
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_Veggie_Citronal_parameters.hpp
7852837d9dc8182a9ddb191bfa2411f86ebc2a09
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
818
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_Veggie_Citronal_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemConsumable_Veggie_Citronal.PrimalItemConsumable_Veggie_Citronal_C.ExecuteUbergraph_PrimalItemConsumable_Veggie_Citronal struct UPrimalItemConsumable_Veggie_Citronal_C_ExecuteUbergraph_PrimalItemConsumable_Veggie_Citronal_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
7662f6e6aa74280270feea4e4da085973d378588
298d592e0f76705e1b1523879366a4bab89bb004
/src/util/vec3.h
b2ed7137f8b81477e7870459efaa91982b654b8a
[ "MIT" ]
permissive
delbon93/cpu_raymarcher
c8245ff23e6021442a49344bac60adca03734fac
c756072651482e1b33cd0e3574ba796c278372eb
refs/heads/main
2023-04-11T16:46:49.456445
2021-05-13T12:05:21
2021-05-13T12:05:21
365,757,672
0
0
null
null
null
null
UTF-8
C++
false
false
3,667
h
#ifndef RAYTRACING_IN_A_WEEKEND_VEC3_H #define RAYTRACING_IN_A_WEEKEND_VEC3_H #include <cmath> #include <iostream> using std::sqrt; /** * 3-component vector class */ class vec3 { public: /** * Creates zero-vector */ vec3() : e{0, 0, 0} {} /** * Creates vector with all components set to the same value * @param e0 Value of all components */ vec3(double e0) : e{e0, e0, e0} {} /** * Creates vector with given components * @param e0 First component * @param e1 Second component * @param e2 Third component */ vec3(double e0, double e1, double e2) : e {e0, e1, e2} {} /** * Spatial alias for first component * @return First component */ double x() const { return e[0]; } /** * Spatial alias for second component * @return Second component */ double y() const { return e[1]; } /** * Spatial alias for third component * @return Third component */ double z() const { return e[2]; } /** * Color alias for first component * @return First component */ double r() const { return e[0]; } /** * Color alias for second component * @return Second component */ double g() const { return e[1]; } /** * Color alias for third component * @return Third component */ double b() const { return e[2]; } vec3 operator-() const; double operator[](int i) const; double& operator[](int i); vec3& operator+=(const vec3 &v); vec3& operator*=(double t); vec3& operator/=(double t); /** * @return Magnitude of the vector */ double length() const; /** * @return Squared magnitude of the vector */ double length_squared() const; private: double e[3]; }; using point3 = vec3; using color = vec3; inline std::ostream& operator<<(std::ostream &out, const vec3 &v) { return out << v.x() << " " << v.y() << " " << v.z(); } inline vec3 operator+(const vec3 &u, const vec3 &v) { return vec3(u.x() + v.x(), u.y() + v.y(), u.z() + v.z()); } inline vec3 operator-(const vec3 &u, const vec3 &v) { return vec3(u.x() - v.x(), u.y() - v.y(), u.z() - v.z()); } inline vec3 operator*(const vec3 &u, const vec3 &v) { return vec3(u.x() * v.x(), u.y() * v.y(), u.z() * v.z()); } inline vec3 operator*(double t, const vec3 &v) { return vec3(t*v.x(), t*v.y(), t*v.z()); } inline vec3 operator*(const vec3 &v, double t) { return t * v; } inline vec3 operator/(vec3 v, double t) { return (1/t) * v; } /** * Calculates the dot product of two vectors * @param u Vector * @param v Vector * @return Dot product of u and v */ inline double dot(const vec3 &u, const vec3 &v) { return u.x() * v.x() + u.y() * v.y() + u.z() * v.z(); } /** * Calculates the cross product of two vectors * @param u Vector * @param v Vector * @return Cross product of u and v */ inline vec3 cross(const vec3 &u, const vec3 &v) { return vec3(u.y() * v.z() - u.z() * v.y(), u.z() * v.x() - u.x() * v.z(), u.x() * v.y() - u.y() * v.x()); } /** * Returns a unit vector that points into the direction of v * @param v Vector * @return Unit vector of v */ inline vec3 unit_vector(vec3 v) { return v / v.length(); } /** * Returns a unit vector constructed from given vector components * @param e0 First component * @param e1 Second component * @param e2 Third component * @return Unit vector */ inline vec3 unit_vector(double e0, double e1, double e2) { return unit_vector(vec3(e0, e1, e2)); } #endif //RAYTRACING_IN_A_WEEKEND_VEC3_H
[ "delbon93@gmail.com" ]
delbon93@gmail.com
6c08baff3c0e122526189c7bc0223d24c951a1b3
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/content/browser/frame_host/mixed_content_navigation_throttle.cc
ea6fff18bc4d021136db0d22a2114369e88f7a9e
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
14,342
cc
// Copyright 2017 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 "content/browser/frame_host/mixed_content_navigation_throttle.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/navigation_handle_impl.h" #include "content/browser/frame_host/render_frame_host_delegate.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/common/frame_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_frame_host.h" #include "content/public/common/content_client.h" #include "content/public/common/navigation_policy.h" #include "content/public/common/origin_util.h" #include "content/public/common/web_preferences.h" #include "net/base/url_util.h" #include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom.h" #include "url/gurl.h" #include "url/origin.h" #include "url/url_constants.h" #include "url/url_util.h" namespace content { namespace { // Should return the same value as SchemeRegistry::shouldTreatURLSchemeAsSecure. bool IsSecureScheme(const std::string& scheme) { return base::ContainsValue(url::GetSecureSchemes(), scheme); } // Should return the same value as SecurityOrigin::isLocal and // SchemeRegistry::shouldTreatURLSchemeAsCorsEnabled. bool ShouldTreatURLSchemeAsCorsEnabled(const GURL& url) { return base::ContainsValue(url::GetCorsEnabledSchemes(), url.scheme()); } // Should return the same value as the resource URL checks assigned to // |isAllowed| made inside MixedContentChecker::isMixedContent. bool IsUrlPotentiallySecure(const GURL& url) { // blob: and filesystem: URLs never hit the network, and access is restricted // to same-origin contexts, so they are not blocked. bool is_secure = url.SchemeIs(url::kBlobScheme) || url.SchemeIs(url::kFileSystemScheme) || IsOriginSecure(url) || IsPotentiallyTrustworthyOrigin(url::Origin::Create(url)); // TODO(mkwst): Remove this once the following draft is implemented: // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost-03. See: // https://crbug.com/691930. if (is_secure && url.SchemeIs(url::kHttpScheme) && net::IsLocalHostname(url.HostNoBracketsPiece(), nullptr)) { is_secure = false; } return is_secure; } // This method should return the same results as // SchemeRegistry::shouldTreatURLSchemeAsRestrictingMixedContent. bool DoesOriginSchemeRestrictMixedContent(const url::Origin& origin) { return origin.scheme() == url::kHttpsScheme; } void UpdateRendererOnMixedContentFound(NavigationHandleImpl* navigation_handle, const GURL& mixed_content_url, bool was_allowed, bool for_redirect) { // TODO(carlosk): the root node should never be considered as being/having // mixed content for now. Once/if the browser should also check form submits // for mixed content than this will be allowed to happen and this DCHECK // should be updated. DCHECK(navigation_handle->frame_tree_node()->parent()); RenderFrameHost* rfh = navigation_handle->frame_tree_node()->current_frame_host(); FrameMsg_MixedContentFound_Params params; params.main_resource_url = mixed_content_url; params.mixed_content_url = navigation_handle->GetURL(); params.request_context_type = navigation_handle->request_context_type(); params.was_allowed = was_allowed; params.had_redirect = for_redirect; params.source_location = navigation_handle->source_location(); rfh->Send(new FrameMsg_MixedContentFound(rfh->GetRoutingID(), params)); } } // namespace // static std::unique_ptr<NavigationThrottle> MixedContentNavigationThrottle::CreateThrottleForNavigation( NavigationHandle* navigation_handle) { return std::make_unique<MixedContentNavigationThrottle>(navigation_handle); } MixedContentNavigationThrottle::MixedContentNavigationThrottle( NavigationHandle* navigation_handle) : NavigationThrottle(navigation_handle) { } MixedContentNavigationThrottle::~MixedContentNavigationThrottle() {} NavigationThrottle::ThrottleCheckResult MixedContentNavigationThrottle::WillStartRequest() { bool should_block = ShouldBlockNavigation(false); return should_block ? CANCEL : PROCEED; } NavigationThrottle::ThrottleCheckResult MixedContentNavigationThrottle::WillRedirectRequest() { // Upon redirects the same checks are to be executed as for requests. bool should_block = ShouldBlockNavigation(true); return should_block ? CANCEL : PROCEED; } NavigationThrottle::ThrottleCheckResult MixedContentNavigationThrottle::WillProcessResponse() { // TODO(carlosk): At this point we are about to process the request response. // So if we ever need to, here/now it is a good moment to check for the final // attained security level of the connection. For instance, does it use an // outdated protocol? The implementation should be based off // MixedContentChecker::handleCertificateError. See https://crbug.com/576270. return PROCEED; } const char* MixedContentNavigationThrottle::GetNameForLogging() { return "MixedContentNavigationThrottle"; } // Based off of MixedContentChecker::shouldBlockFetch. bool MixedContentNavigationThrottle::ShouldBlockNavigation(bool for_redirect) { NavigationHandleImpl* handle_impl = static_cast<NavigationHandleImpl*>(navigation_handle()); FrameTreeNode* node = handle_impl->frame_tree_node(); // Find the parent node where mixed content is characterized, if any. FrameTreeNode* mixed_content_node = InWhichFrameIsContentMixed(node, handle_impl->GetURL()); if (!mixed_content_node) { MaybeSendBlinkFeatureUsageReport(); return false; } // From this point on we know this is not a main frame navigation and that // there is mixed content. Now let's decide if it's OK to proceed with it. const WebPreferences& prefs = mixed_content_node->current_frame_host() ->render_view_host() ->GetWebkitPreferences(); ReportBasicMixedContentFeatures(handle_impl->request_context_type(), handle_impl->mixed_content_context_type(), prefs); // If we're in strict mode, we'll automagically fail everything, and // intentionally skip the client/embedder checks in order to prevent degrading // the site's security UI. bool block_all_mixed_content = !!( mixed_content_node->current_replication_state().insecure_request_policy & blink::kBlockAllMixedContent); bool strict_mode = prefs.strict_mixed_content_checking || block_all_mixed_content; blink::WebMixedContentContextType mixed_context_type = handle_impl->mixed_content_context_type(); if (!ShouldTreatURLSchemeAsCorsEnabled(handle_impl->GetURL())) mixed_context_type = blink::WebMixedContentContextType::kOptionallyBlockable; bool allowed = false; RenderFrameHostDelegate* frame_host_delegate = node->current_frame_host()->delegate(); switch (mixed_context_type) { case blink::WebMixedContentContextType::kOptionallyBlockable: allowed = !strict_mode; if (allowed) { frame_host_delegate->PassiveInsecureContentFound(handle_impl->GetURL()); frame_host_delegate->DidDisplayInsecureContent(); } break; case blink::WebMixedContentContextType::kBlockable: { // Note: from the renderer side implementation it seems like we don't need // to care about reporting // blink::UseCounter::BlockableMixedContentInSubframeBlocked because it is // only triggered for sub-resources which are not checked for in the // browser. bool should_ask_delegate = !strict_mode && (!prefs.strictly_block_blockable_mixed_content || prefs.allow_running_insecure_content); allowed = should_ask_delegate && frame_host_delegate->ShouldAllowRunningInsecureContent( handle_impl->GetWebContents(), prefs.allow_running_insecure_content, mixed_content_node->current_origin(), handle_impl->GetURL()); if (allowed) { const GURL& origin_url = mixed_content_node->current_origin().GetURL(); frame_host_delegate->DidRunInsecureContent(origin_url, handle_impl->GetURL()); GetContentClient()->browser()->RecordURLMetric( "ContentSettings.MixedScript.RanMixedScript", origin_url); mixed_content_features_.insert(MIXED_CONTENT_BLOCKABLE_ALLOWED); } break; } case blink::WebMixedContentContextType::kShouldBeBlockable: allowed = !strict_mode; if (allowed) frame_host_delegate->DidDisplayInsecureContent(); break; case blink::WebMixedContentContextType::kNotMixedContent: NOTREACHED(); break; }; UpdateRendererOnMixedContentFound( handle_impl, mixed_content_node->current_url(), allowed, for_redirect); MaybeSendBlinkFeatureUsageReport(); return !allowed; } // This method mirrors MixedContentChecker::inWhichFrameIsContentMixed but is // implemented in a different form that seems more appropriate here. FrameTreeNode* MixedContentNavigationThrottle::InWhichFrameIsContentMixed( FrameTreeNode* node, const GURL& url) { // Main frame navigations cannot be mixed content. // TODO(carlosk): except for form submissions which might be supported in the // future. if (node->IsMainFrame()) return nullptr; // There's no mixed content if any of these are true: // - The navigated URL is potentially secure. // - Neither the root nor parent frames have secure origins. // This next section diverges in how the Blink version is implemented but // should get to the same results. Especially where isMixedContent calls // exist, here they are partially fulfilled here and partially replaced by // DoesOriginSchemeRestrictMixedContent. FrameTreeNode* mixed_content_node = nullptr; FrameTreeNode* root = node->frame_tree()->root(); FrameTreeNode* parent = node->parent(); if (!IsUrlPotentiallySecure(url)) { // TODO(carlosk): we might need to check more than just the immediate parent // and the root. See https://crbug.com/623486. // Checks if the root and then the immediate parent frames' origins are // secure. if (DoesOriginSchemeRestrictMixedContent(root->current_origin())) mixed_content_node = root; else if (DoesOriginSchemeRestrictMixedContent(parent->current_origin())) mixed_content_node = parent; } // Note: The code below should behave the same way as the two calls to // measureStricterVersionOfIsMixedContent from inside // MixedContentChecker::inWhichFrameIs. if (mixed_content_node) { // We're currently only checking for mixed content in `https://*` contexts. // What about other "secure" contexts the SchemeRegistry knows about? We'll // use this method to measure the occurrence of non-webby mixed content to // make sure we're not breaking the world without realizing it. if (mixed_content_node->current_origin().scheme() != url::kHttpsScheme) { mixed_content_features_.insert( MIXED_CONTENT_IN_NON_HTTPS_FRAME_THAT_RESTRICTS_MIXED_CONTENT); } } else if (!IsOriginSecure(url) && (IsSecureScheme(root->current_origin().scheme()) || IsSecureScheme(parent->current_origin().scheme()))) { mixed_content_features_.insert( MIXED_CONTENT_IN_SECURE_FRAME_THAT_DOES_NOT_RESTRICT_MIXED_CONTENT); } return mixed_content_node; } void MixedContentNavigationThrottle::MaybeSendBlinkFeatureUsageReport() { if (!mixed_content_features_.empty()) { NavigationHandleImpl* handle_impl = static_cast<NavigationHandleImpl*>(navigation_handle()); RenderFrameHost* rfh = handle_impl->frame_tree_node()->current_frame_host(); rfh->Send(new FrameMsg_BlinkFeatureUsageReport(rfh->GetRoutingID(), mixed_content_features_)); mixed_content_features_.clear(); } } // Based off of MixedContentChecker::count. void MixedContentNavigationThrottle::ReportBasicMixedContentFeatures( blink::mojom::RequestContextType request_context_type, blink::WebMixedContentContextType mixed_content_context_type, const WebPreferences& prefs) { mixed_content_features_.insert(MIXED_CONTENT_PRESENT); // Report any blockable content. if (mixed_content_context_type == blink::WebMixedContentContextType::kBlockable) { mixed_content_features_.insert(MIXED_CONTENT_BLOCKABLE); return; } // Note: as there's no mixed content checks for sub-resources on the browser // side there should only be a subset of RequestContextType values that could // ever be found here. UseCounterFeature feature; switch (request_context_type) { case blink::mojom::RequestContextType::INTERNAL: feature = MIXED_CONTENT_INTERNAL; break; case blink::mojom::RequestContextType::PREFETCH: feature = MIXED_CONTENT_PREFETCH; break; case blink::mojom::RequestContextType::AUDIO: case blink::mojom::RequestContextType::DOWNLOAD: case blink::mojom::RequestContextType::FAVICON: case blink::mojom::RequestContextType::IMAGE: case blink::mojom::RequestContextType::PLUGIN: case blink::mojom::RequestContextType::VIDEO: default: NOTREACHED() << "RequestContextType has value " << request_context_type << " and has WebMixedContentContextType of " << static_cast<int>(mixed_content_context_type); return; } mixed_content_features_.insert(feature); } // static bool MixedContentNavigationThrottle::IsMixedContentForTesting( const GURL& origin_url, const GURL& url) { const url::Origin origin = url::Origin::Create(origin_url); return !IsUrlPotentiallySecure(url) && DoesOriginSchemeRestrictMixedContent(origin); } } // namespace content
[ "artem@brave.com" ]
artem@brave.com
8d4768251f6bbf5f2f3c5470b3a313431eea775c
a268fbce386bcfaa31cbff2eb229f3bd45f00a98
/lib/renderer.h
9dd2f188bcede29bd61d51a54001750d01c34474
[]
no_license
myhau/pong-arduino
ce097e8668df890bd51672fca50fc5d7238c223b
1e01df97d83818d283db5e59359735e4ba95b6d1
refs/heads/master
2021-01-10T06:54:19.005932
2016-01-17T12:21:30
2016-01-17T12:21:30
45,694,121
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
// // Created by mihau on 11/10/15. // #ifndef PONG_ARDUINO_MOCK_RENDERER_H #define PONG_ARDUINO_MOCK_RENDERER_H #include "color.h" class Renderer { public: virtual void drawRect(int x, int y, int width, int height, Color c, bool filled = false) = 0; virtual void drawCircle(int x, int y, int radius, Color c, bool filled = false) = 0; virtual void clearScreen(Color c) = 0; virtual int screenWidth() = 0; virtual int screenHeight() = 0; }; #endif //PONG_ARDUINO_MOCK_RENDERER_H
[ "mmyhau@gmail.com" ]
mmyhau@gmail.com
923dec6fe33fe305b8c3733d43a93c6acba2ab91
7bc74c12d85d5298f437d043fdc48943ccfdeda7
/001_Project/102_interfaceTMP/adas/gen/dbus/provides/v1/com/harman/adas/ADASDiagTypeDBusDeployment.hpp
5d2357dd4fbd49c6d79dd7fe144a9144e1e976e5
[]
no_license
BobDeng1974/cameraframework-github
364dd6e9c3d09a06384bb4772a24ed38b49cbc30
86efc7356d94f4957998e6e0ae718bd9ed4a4ba0
refs/heads/master
2020-08-29T16:14:02.898866
2017-12-15T14:55:25
2017-12-15T14:55:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
973
hpp
/* * This file was generated by the CommonAPI Generators. * Used org.genivi.commonapi.dbus 3.1.5.201702211714. * Used org.franca.core 0.9.1.201412191134. * * generated by DCIF CodeGen Version: R2_v2.3.0 * generated on: Tue Aug 01 13:37:50 CST 2017 */ #ifndef V1_COM_HARMAN_ADAS_ADAS_DIAG_TYPE_DBUS_DEPLOYMENT_HPP_ #define V1_COM_HARMAN_ADAS_ADAS_DIAG_TYPE_DBUS_DEPLOYMENT_HPP_ #if !defined (COMMONAPI_INTERNAL_COMPILATION) #define COMMONAPI_INTERNAL_COMPILATION #endif #include <CommonAPI/DBus/DBusDeployment.hpp> #undef COMMONAPI_INTERNAL_COMPILATION namespace v1 { namespace com { namespace harman { namespace adas { namespace ADASDiagType_ { // typecollection-specific deployment types typedef CommonAPI::EmptyDeployment enDiagTestStateDeployment_t; // typecollection-specific deployments } // namespace ADASDiagType_ } // namespace adas } // namespace harman } // namespace com } // namespace v1 #endif // V1_COM_HARMAN_ADAS_ADAS_DIAG_TYPE_DBUS_DEPLOYMENT_HPP_
[ "guofeng.lu@harman.com" ]
guofeng.lu@harman.com
bfb56af7b0fb1c58a820704ab911b6c992b72830
38c10c01007624cd2056884f25e0d6ab85442194
/cc/test/surface_aggregator_test_helpers.h
0848515cfdce95bc04d15fe95bb1d134da6d0fef
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
2,586
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_TEST_SURFACE_AGGREGATOR_TEST_HELPERS_H_ #define CC_TEST_SURFACE_AGGREGATOR_TEST_HELPERS_H_ #include "cc/base/scoped_ptr_vector.h" #include "cc/quads/draw_quad.h" #include "cc/quads/render_pass_id.h" #include "cc/surfaces/surface_id.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/geometry/size.h" namespace cc { class RenderPass; class Surface; class TestRenderPass; typedef ScopedPtrVector<RenderPass> RenderPassList; namespace test { struct Quad { static Quad SolidColorQuad(SkColor color) { Quad quad; quad.material = DrawQuad::SOLID_COLOR; quad.color = color; return quad; } static Quad SurfaceQuad(SurfaceId surface_id, float opacity) { Quad quad; quad.material = DrawQuad::SURFACE_CONTENT; quad.opacity = opacity; quad.surface_id = surface_id; return quad; } static Quad RenderPassQuad(RenderPassId id) { Quad quad; quad.material = DrawQuad::RENDER_PASS; quad.render_pass_id = id; return quad; } DrawQuad::Material material; // Set when material==DrawQuad::SURFACE_CONTENT. SurfaceId surface_id; float opacity; // Set when material==DrawQuad::SOLID_COLOR. SkColor color; // Set when material==DrawQuad::RENDER_PASS. RenderPassId render_pass_id; private: Quad() : material(DrawQuad::INVALID), opacity(1.f), color(SK_ColorWHITE) {} }; struct Pass { Pass(Quad* quads, size_t quad_count, RenderPassId id) : quads(quads), quad_count(quad_count), id(id) {} Pass(Quad* quads, size_t quad_count) : quads(quads), quad_count(quad_count), id(1, 1) {} Quad* quads; size_t quad_count; RenderPassId id; }; void AddSurfaceQuad(TestRenderPass* pass, const gfx::Size& surface_size, int surface_id); void AddQuadInPass(TestRenderPass* pass, Quad desc); void AddPasses(RenderPassList* pass_list, const gfx::Rect& output_rect, Pass* passes, size_t pass_count); void TestQuadMatchesExpectations(Quad expected_quad, const DrawQuad* quad); void TestPassMatchesExpectations(Pass expected_pass, const RenderPass* pass); void TestPassesMatchExpectations(Pass* expected_passes, size_t expected_pass_count, const RenderPassList* passes); } // namespace test } // namespace cc #endif // CC_TEST_SURFACE_AGGREGATOR_TEST_HELPERS_H_
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
08a50ff405c744a0fc2f19be4844cce46d844f58
cadd1aed4a0657a5f218008a5e31a4d1029ad575
/source/autogen/PlayerControl.hpp
c1ee065c65e16d70c546791d468719456805bf2e
[ "MIT" ]
permissive
kokjij/among-us-replay-mod
ccdf25da98baa55111f9238381e9c4dbed6f8b61
e47cabeea466fee1f47a06600eefcde9e4a48a8a
refs/heads/master
2023-04-13T06:21:12.799225
2021-04-13T12:42:26
2021-04-13T12:42:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,713
hpp
#pragma once #include <autogen/InnerNet/InnerNetObject.hpp> #include <autogen/System/Collections/Generic/List.hpp> struct PlayerTask; struct CustomNetworkTransform; // IHFJHCCJLKB in 2020.10.8i // GLHCHLEDNBA in 2020.10.22s // APNNOJFGDGP in 2020.11.4s // JENJGDMOEOC in 2020.11.17s // FFGALNAPKCD in 2020.12.9s // PlayerControl in 2021.3.5s // PlayerControl in 2021.4.12s struct PlayerControl : InnerNet::InnerNetObject { std::int32_t LastStartCounter; std::uint8_t PlayerId; float MaxReportDistance; // [marker] bool moveable; bool inVent; struct GameData_PlayerInfo_o *_cachedData; struct UnityEngine_AudioSource_o *FootSteps; struct UnityEngine_AudioClip_o *KillSfx; struct KillAnimation_array *KillAnimations; float killTimer; std::int32_t RemainingEmergencies; struct TextMeshPro_o *nameText; // type changed since 2021.4.12s struct LightSource_o *LightPrefab; struct LightSource_o *myLight; struct TextTranslator_o *textTranslator; // since 2021.3.5 struct UnityEngine_Collider2D_o *Collider; struct PlayerPhysics_o *MyPhysics; CustomNetworkTransform *NetTransform; struct PetBehaviour_o *CurrentPet; struct HatParent_o *HatRenderer; struct UnityEngine_SpriteRenderer_o *myRend; struct UnityEngine_Collider2D_array *hitBuffer; System::Collections::Generic::List<PlayerTask>* myTasks; struct PowerTools_SpriteAnim_array *ScannerAnims; struct UnityEngine_SpriteRenderer_array *ScannersImages; struct IUsable_o *closest; bool isNew; // may be changed in 2021.3.5 bool isDummy; // since 2021.3.5 bool notRealPlayer; // since 2021.3.5 struct System_Collections_Generic_Dictionary_Collider2D__IUsable__o *cache; struct System_Collections_Generic_List_IUsable__o *itemsInRange; struct System_Collections_Generic_List_IUsable__o *newItemsInRange; std::uint8_t scannerCount; bool infectedSet; static Class<PlayerControl>* get_class() { switch (mod_info::get_game_version()) { case game_version::v2020_6_9s: return Class<PlayerControl>::find("PlayerControl"); case game_version::v2020_9_22s: return Class<PlayerControl>::find("PlayerControl"); case game_version::v2020_10_8i: return Class<PlayerControl>::find("IHFJHCCJLKB"); case game_version::v2020_10_22s: return Class<PlayerControl>::find("GLHCHLEDNBA"); case game_version::v2020_11_4s: return Class<PlayerControl>::find("APNNOJFGDGP"); case game_version::v2020_11_17s: return Class<PlayerControl>::find("JENJGDMOEOC"); case game_version::v2020_12_9s: return Class<PlayerControl>::find("FFGALNAPKCD"); case game_version::v2021_3_5s: return Class<PlayerControl>::find("PlayerControl"); case game_version::v2021_4_12s: return Class<PlayerControl>::find("PlayerControl"); } return nullptr; } // [marker] SetTasks in dump.cs void SetTasks(void*); }; CHECK_TYPE(PlayerControl, 0x94); template <> const char* get_method_name<&PlayerControl::SetTasks>() { switch (mod_info::get_game_version()) { case game_version::v2020_6_9s: return "SetTasks"; case game_version::v2020_9_22s: return "SetTasks"; case game_version::v2020_10_8i: return "SetTasks"; case game_version::v2020_10_22s: return "SetTasks"; case game_version::v2020_11_4s: return "SetTasks"; case game_version::v2020_11_17s: return "SetTasks"; case game_version::v2020_12_9s: return "SetTasks"; case game_version::v2021_3_5s: return "SetTasks"; case game_version::v2021_4_12s: return "SetTasks"; } return nullptr; }
[ "akaraevz@mail.ru" ]
akaraevz@mail.ru
5a48feda91568bec4977a5bdbd704f0a107472ee
b7e838eb0204b4a94c2809922d16abbb5630bfca
/MathLib/LinAlg/PETSc/PETScMatrix.cpp
8e706128cb03fc60d6e79f3a2168532c27c4b29e
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
robertladwig/ogs
c80856672e075eb89bc4b014d4d3f5a1d46cf074
78b71852e6e8d79c39bbc93bb3bc934ce04372ed
refs/heads/master
2021-01-18T02:41:13.360596
2014-06-20T12:54:12
2014-06-20T12:54:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,049
cpp
/*! \file PETScMatrix.cpp \brief Definition of member functions of class PETScMatrix, which provides an interface to PETSc matrix routines. \author Wenqing Wang \date Nov 2011 - Sep 2013 \copyright Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org) Distributed under a Modified BSD License. See accompanying file LICENSE.txt or http://www.opengeosys.org/project/license */ #include "PETScMatrix.h" namespace MathLib { PETScMatrix::PETScMatrix (const PetscInt nrows, const PETScMatrixOption &mat_opt) :_nrows(nrows), _ncols(nrows), _n_loc_rows(PETSC_DECIDE), _n_loc_cols(mat_opt.n_local_cols) { if(!mat_opt.is_global_size) { _nrows = PETSC_DECIDE; _ncols = PETSC_DECIDE; _n_loc_rows = nrows; // Make the matrix be square. MPI_Allreduce(&_n_loc_rows, &_nrows, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD); _ncols = _nrows; } create(mat_opt.d_nz, mat_opt.o_nz); } PETScMatrix::PETScMatrix (const PetscInt nrows, const PetscInt ncols, const PETScMatrixOption &mat_opt) :_nrows(nrows), _ncols(ncols), _n_loc_rows(PETSC_DECIDE), _n_loc_cols(mat_opt.n_local_cols) { if(!mat_opt.is_global_size) { _nrows = PETSC_DECIDE; _ncols = PETSC_DECIDE; _n_loc_rows = nrows; _n_loc_cols = ncols; } create(mat_opt.d_nz, mat_opt.o_nz); } void PETScMatrix::setRowsColumnsZero(std::vector<PetscInt> const& row_pos) { // Each rank (compute core) processes only the rows that belong to the rank itself. const PetscScalar one = 1.0; const PetscInt nrows = static_cast<PetscInt> (row_pos.size()); if(nrows>0) MatZeroRows(_A, nrows, &row_pos[0], one, PETSC_NULL, PETSC_NULL); else MatZeroRows(_A, 0, PETSC_NULL, one, PETSC_NULL, PETSC_NULL); } void PETScMatrix::viewer(const std::string &file_name, const PetscViewerFormat vw_format) { PetscViewer viewer; PetscViewerASCIIOpen(PETSC_COMM_WORLD, file_name.c_str(), &viewer); PetscViewerPushFormat(viewer, vw_format); finalizeAssembly(); PetscObjectSetName((PetscObject)_A,"Stiffness_matrix"); MatView(_A,viewer); // This preprocessor is only for debugging, e.g. dump the matrix and exit the program. //#define EXIT_TEST #ifdef EXIT_TEST MatDestroy(&_A); PetscFinalize(); exit(0); #endif } void PETScMatrix::create(const PetscInt d_nz, const PetscInt o_nz) { MatCreate(PETSC_COMM_WORLD, &_A); MatSetSizes(_A, _n_loc_rows, _n_loc_cols, _nrows, _ncols); MatSetFromOptions(_A); MatSeqAIJSetPreallocation(_A, d_nz, PETSC_NULL); MatMPIAIJSetPreallocation(_A, d_nz, PETSC_NULL, o_nz, PETSC_NULL); MatGetOwnershipRange(_A, &_start_rank, &_end_rank); MatGetSize(_A, &_nrows, &_ncols); MatGetLocalSize(_A, &_n_loc_rows, &_n_loc_cols); } bool finalizeMatrixAssembly(PETScMatrix &mat, const MatAssemblyType asm_type) { mat.finalizeAssembly(asm_type); return true; } } //end of namespace
[ "wenqing.wang@ufz.de" ]
wenqing.wang@ufz.de
d6f31df313ecc0726d605f0d443d7f7e114b8d4f
2b73263ff59ecb6a6e4afc587cb92f10fae0bfa4
/isis/src/base/objs/CubeDataThread/CubeDataThread.cpp
445d2ad0b825269dd915c5d963ace930d460efde
[ "Unlicense" ]
permissive
paarongiroux/ISIS3
2bd0ba3db95ee3a1121ff847253a4a859a96ef2a
5b4b9b528707a0b8730872f7d7a79130bbd03c93
refs/heads/dev
2020-04-24T06:26:46.647519
2019-05-17T16:52:20
2019-05-17T16:52:20
171,765,048
0
0
Unlicense
2019-11-06T20:44:14
2019-02-20T23:25:41
C++
UTF-8
C++
false
false
24,742
cpp
#include "IsisDebug.h" #include "CubeDataThread.h" #include <QApplication> #include <QEventLoop> #include <QMap> #include <QMutex> #include <QPair> #include <QReadWriteLock> #include <QString> #include <iomanip> #include <iostream> #include "Brick.h" #include "Cube.h" #include "FileName.h" #include "IException.h" #include "IString.h" #include "UniversalGroundMap.h" namespace Isis { /** * This constructs a CubeDataThread(). This will spawn a new thread and * move the ownership of this instance to itself (so slots are called * in this self-contained thread). * */ CubeDataThread::CubeDataThread() { p_managedCubes = NULL; p_managedData = NULL; p_threadSafeMutex = NULL; p_managedDataSources = NULL; p_managedCubes = new QMap< int, QPair< bool, Cube * > > ; p_managedData = new QList< QPair< QReadWriteLock *, Brick * > > ; p_threadSafeMutex = new QMutex(); p_managedDataSources = new QList< int > ; p_numChangeListeners = 0; p_currentLocksWaiting = 0; p_currentId = 1; // start with ID == 1 p_stopping = false; // Start this thread's event loop and make it so the slots are contained // within this thread (this class automatically runs in its own thread) start(); moveToThread(this); } /** * This class is a self-contained thread, so normally it would be bad to * simply delete it. However, this destructor will synchronize the shutdown * of the thread so you can safely delete an instance of this class without * using the deleteLater() method. * */ CubeDataThread::~CubeDataThread() { // Shutdown the event loop(s) QThread::exit(0); p_stopping = true; while (!isFinished()) { QThread::yieldCurrentThread(); } // Destroy the bricks still in memory if (p_managedData) { for (int i = p_managedData->size() - 1; i >= 0; i--) { delete (*p_managedData)[i].first; delete (*p_managedData)[i].second; p_managedData->removeAt(i); } delete p_managedData; p_managedData = NULL; } // Destroy the cubes still in memory if (p_managedCubes) { for (int i = p_managedCubes->size() - 1; i >= 0; i--) { if ((p_managedCubes->end() - 1)->first) // only delete if we own it! delete (p_managedCubes->end() - 1).value().second; p_managedCubes->erase(p_managedCubes->end() - 1); } } // Destroy the mutex that controls access to the cubes if (p_threadSafeMutex) { delete p_threadSafeMutex; p_threadSafeMutex = NULL; } // Destroy the data sources vector if (p_managedDataSources) { delete p_managedDataSources; p_managedDataSources = NULL; } } /** * This method is designed to be callable from any thread before data is * requested, though no known side effects exist if this is called during * other I/O operations (though I don't recommend it). * * If possible, the cube will be opened with R/W permissions, otherwise it * will be opened with read-only access * * @param fileName The cube to open * @param mustOpenReadWrite If true and cube has read-only access then an * exception will be thrown * * @return int The cube ID necessary for retrieving information about this cube * in the future. */ int CubeDataThread::AddCube(const FileName &fileName, bool mustOpenReadWrite) { Cube *newCube = new Cube(); try { newCube->open(fileName.expanded(), "rw"); } catch (IException &e) { if (!mustOpenReadWrite) { newCube->open(fileName.expanded(), "r"); } else { throw; } } p_threadSafeMutex->lock(); int newId = p_currentId; p_currentId++; QPair< bool, Cube * > newEntry; newEntry.first = true; // we own this! newEntry.second = newCube; p_managedCubes->insert(newId, newEntry); p_threadSafeMutex->unlock(); return newId; } /** * This method is designed to be callable from any thread before data is * requested, though no known side effects exist if this is called during * other I/O operations (though I don't recommend it). * * Ownership is not taken of this cube * * @param cube The cube to encapsulate * * @return int The cube ID necessary for retrieving information about this cube * in the future. */ int CubeDataThread::AddCube(Cube *cube) { p_threadSafeMutex->lock(); int newId = p_currentId; p_currentId++; QPair< bool, Cube * > newEntry; newEntry.first = false; // we don't own this! newEntry.second = cube; p_managedCubes->insert(newId, newEntry); p_threadSafeMutex->unlock(); return newId; } /** * Removes a cube from this lock manager * * * @param cubeId The cube to be deleted's ID * */ void CubeDataThread::RemoveCube(int cubeId) { p_threadSafeMutex->lock(); QMap< int, QPair< bool, Cube * > >::iterator i; i = p_managedCubes->find(cubeId); if (i == p_managedCubes->end()) { p_threadSafeMutex->unlock(); QString msg = "CubeDataThread::RemoveCube failed because cube ID ["; msg += QString::number(cubeId); msg += "] not found"; throw IException(IException::Programmer, msg, _FILEINFO_); } if (p_managedDataSources->contains(cubeId)) { p_threadSafeMutex->unlock(); QString msg = "CubeDataThread::RemoveCube failed cube ID ["; msg += QString::number(cubeId); msg += "] has requested Bricks"; throw IException(IException::Programmer, msg, _FILEINFO_); } // if we have ownership of the cube then me must delete it if (i.value().first) delete i.value().second; i.value().second = NULL; p_managedCubes->remove(i.key()); p_threadSafeMutex->unlock(); } /** * You must call this method after connecting to the BrickChanged signal, * otherwise you are not guaranteed a good Brick pointer. */ void CubeDataThread::AddChangeListener() { p_numChangeListeners++; } /** * You must call this method after disconnecting from the BrickChanged signal, * otherwise bricks cannot be freed from memory. */ void CubeDataThread::RemoveChangeListener() { p_numChangeListeners--; } /** * This helper method reads in cube data and handles the locking of similar * bricks appropriately. * * @param cubeId Cube ID To Read From * @param ss Starting Sample Position * @param sl Starting Line Position * @param es Ending Sample Position * @param el Ending Line Position * @param band Band Number To Read From (multi-band bricks not supported at this * time) * @param caller A pointer to the calling class, used to identify who requested * the data when they receive either the ReadReady or the * ReadWriteReady signal * @param sharedLock True if read-only, false if read-write */ void CubeDataThread::GetCubeData(int cubeId, int ss, int sl, int es, int el, int band, void *caller, bool sharedLock) { Brick *requestedBrick = NULL; p_threadSafeMutex->lock(); requestedBrick = new Brick(*p_managedCubes->value(cubeId).second, es - ss + 1, el - sl + 1, 1); requestedBrick->SetBasePosition(ss, sl, band); p_threadSafeMutex->unlock(); // See if we already have this brick int instance = 0; int exactIndex = -1; bool exactMatch = false; int index = OverlapIndex(requestedBrick, cubeId, instance, exactMatch); // while overlaps are found while (index != -1) { if (sharedLock) { // make sure we can get read locks on exact overlaps // We need to try to get the lock to verify partial overlaps not // write locked and only keep read locks on exact matches. AcquireLock((*p_managedData)[index].first, true); if (!exactMatch) { (*p_managedData)[index].first->unlock(); } } else { AcquireLock((*p_managedData)[index].first, false); // we arent actually writing to this, but now we know we can delete it (*p_managedData)[index].first->unlock(); exactMatch = false; // destroy things that overlap but arent the same when asking to write if (FreeBrick(index)) { instance--; } } if (exactMatch) { exactIndex = index; } instance++; index = OverlapIndex(requestedBrick, cubeId, instance, exactMatch); } if(p_stopping) return; if (exactIndex == -1) { p_threadSafeMutex->lock(); p_managedCubes->value(cubeId).second->read(*requestedBrick); QPair< QReadWriteLock *, Brick * > managedDataEntry; managedDataEntry.first = new QReadWriteLock(); AcquireLock(managedDataEntry.first, sharedLock); managedDataEntry.second = requestedBrick; p_managedData->append(managedDataEntry); p_managedDataSources->append(cubeId); exactIndex = p_managedData->size() - 1; p_threadSafeMutex->unlock(); } if (el - sl + 1 != (*p_managedData)[exactIndex].second->LineDimension()) { //abort(); } if (sharedLock) { emit ReadReady(caller, cubeId, (*p_managedData)[exactIndex].second); } else { emit ReadWriteReady(caller, cubeId, (*p_managedData)[exactIndex].second); } } /** * Given a Cube pointer, return the cube ID associated with it. * * @param cubeToFind Cube to look up the ID for * * @returns the cube ID associated the given Cube pointer */ int CubeDataThread::FindCubeId(const Cube * cubeToFind) const { QMapIterator< int, QPair< bool, Cube * > > i(*p_managedCubes); while (i.hasNext()) { i.next(); if (i.value().second == cubeToFind) return i.key(); } throw IException(IException::Programmer, "Cube does not exist in this CubeDataThread", _FILEINFO_); } /** * This method is exclusively used to acquire locks. This handles the problem * of being unable to receive signals that would free locks while waiting for * a lock to be made. * * @param lockObject Lock object we're trying to acquire a lock on * @param readLock True if we're trying for read lock, false for read/write */ void CubeDataThread::AcquireLock(QReadWriteLock *lockObject, bool readLock) { // This method can be called recursively (sorta). In the "recursive" // cases p_currentLockWaiting is > 0. This guarantees that locks are // aquired in the reverse order as they are requested, which isn't // particularly helpful, but it is consistent :) if (readLock) { while (!lockObject->tryLockForRead()) { // while we can't get the lock, allow other processing to happen for // brief periods of time // // Give time for things to happen in other threads QThread::yieldCurrentThread(); p_currentLocksWaiting++; qApp->sendPostedEvents(this, 0); p_currentLocksWaiting--; if(p_stopping) return; } } else { while (!lockObject->tryLockForWrite()) { // while we can't get the lock, allow other processing to happen for // brief periods of time // // Give time for things to happen in other threads QThread::yieldCurrentThread(); p_currentLocksWaiting++; qApp->sendPostedEvents(this, 0); p_currentLocksWaiting--; if(p_stopping) return; } } } /** * This slot should be connected to and upon receiving a signal it will begin * the necessary cube I/O to get this data. When the data is available, a * ReadReady signal will be emitted with the parameter caller being equal to * the requester pointer in the signal. You should pass "this" for caller, and * you must ignore all ReadReady signals which do not have "requester == this" * -> otherwise your pointer is not guaranteed. * * @param cubeId Cube to read from * @param startSample Starting Sample Position * @param startLine Starting Line Position * @param endSample Ending Sample Position * @param endLine Ending Line Position * @param band Band Number To Read From (multi-band bricks not supported at this * time) * @param caller A pointer to the calling class, used to identify who requested * the data when they receive the ReadReady signal */ void CubeDataThread::ReadCube(int cubeId, int startSample, int startLine, int endSample, int endLine, int band, void *caller) { if(!p_managedCubes->contains(cubeId)) { IString msg = "cube ID ["; msg += IString(cubeId); msg += "] is not a valid cube ID"; throw IException(IException::Programmer, msg, _FILEINFO_); } GetCubeData(cubeId, startSample, startLine, endSample, endLine, band, caller, true); } /** * This slot should be connected to and upon receiving a signal it will begin * the necessary cube I/O to get this data. When the data is available, a * ReadWriteReady signal will be emitted with the parameter caller being equal * to the requester pointer in the signal. You should pass "this" for caller, * and you must ignore all ReadReady signals which do not have "requester == * this" -> otherwise your pointer is not guaranteed and you are corrupting * the process of the real requester. * * @param cubeId Cube to read from * @param startSample Starting Sample Position * @param startLine Starting Line Position * @param endSample Ending Sample Position * @param endLine Ending Line Position * @param band Band Number To Read From (multi-band bricks not supported at * this time) * @param caller A pointer to the calling class, used to identify who * requested the data when they receive the ReadWriteReady * signal */ void CubeDataThread::ReadWriteCube(int cubeId, int startSample, int startLine, int endSample, int endLine, int band, void *caller) { if(!p_managedCubes->contains(cubeId)) { IString msg = "cube ID ["; msg += IString(cubeId); msg += "] is not a valid cube ID"; throw IException(IException::Programmer, msg, _FILEINFO_); } GetCubeData(cubeId, startSample, startLine, endSample, endLine, band, caller, false); } /** * This is a searching method used to identify overlapping data already in * memory. * * @param overlapping Brick to check for overlaps with * @param cubeId Cube ID asssociated with this brick * @param instanceNum Which instance of overlap to return * @param exact This is set to false if the match found is not exactly * the overlapping brick. * * @return int -1 for none found, otherwise the index into p_managedData and * p_managedDataSources that an overlap was found at */ int CubeDataThread::OverlapIndex(const Brick *overlapping, int cubeId, int instanceNum, bool &exact) { exact = false; // Start with extracting the range of the input (search) brick int startSample = overlapping->Sample(0); int endSample = overlapping->Sample(overlapping->size() - 1); int startLine = overlapping->Line(0); int endLine = overlapping->Line(overlapping->size() - 1); int startBand = overlapping->Band(0); int endBand = overlapping->Band(overlapping->size() - 1); // Now let's search for overlaps ASSERT(p_managedData->size() == p_managedDataSources->size()); for (int knownBrick = 0; knownBrick < p_managedData->size(); knownBrick++) { int sourceCube = (*p_managedDataSources)[knownBrick]; // Ignore other cubes; they can't overlap if (sourceCube != cubeId) continue; QPair< QReadWriteLock *, Brick * > &managedBrick = (*p_managedData)[knownBrick]; Brick &brick = *managedBrick.second; // Get the range of this brick we've found in memory to see if any overlap // exists int compareSampStart = brick.Sample(0); int compareSampEnd = brick.Sample(brick.size() - 1); int compareLineStart = brick.Line(0); int compareLineEnd = brick.Line(brick.size() - 1); int compareBandStart = brick.Band(0); int compareBandEnd = brick.Band(brick.size() - 1); bool overlap = false; // sample start is inside our sample range if (compareSampStart >= startSample && compareSampStart <= endSample) { overlap = true; } // sample end is inside our sample range if (compareSampEnd >= startSample && compareSampEnd <= endSample) { overlap = true; } // line start is in our line range if (compareLineStart >= startLine && compareLineStart <= endLine) { overlap = true; } // line end is in our line range if (compareLineEnd >= startLine && compareLineEnd <= endLine) { overlap = true; } // band start is in our line range if (compareBandStart >= startBand && compareBandStart <= endBand) { overlap = true; } // band end is in our line range if (compareBandEnd >= startBand && compareBandEnd <= endBand) { overlap = true; } exact = false; if (compareSampStart == startSample && compareSampEnd == endSample && compareLineStart == startLine && compareLineEnd == endLine && compareBandStart == startBand && compareBandEnd == endBand) { exact = true; } // If we have overlap, and we're at the requested instance of overlap, // return it. if (overlap) { instanceNum--; if (instanceNum < 0) { return knownBrick; } } } // None found at this instance return -1; } /** * When done processing with a brick (reading or writing) this slot needs to * be signalled to free locks and memory. * * @param cubeId Cube associated with the brick * @param brickDone Brick pointer given by ReadReady, ReadWriteReady or * BrickChanged. An equivalent brick is also acceptable * (exact same range, but not same pointer). */ void CubeDataThread::DoneWithData(int cubeId, const Isis::Brick *brickDone) { ASSERT(brickDone != NULL); int instance = 0; bool exactMatch = false; bool writeLock = false; int index = OverlapIndex(brickDone, cubeId, instance, exactMatch); ASSERT(p_managedData->size() == p_managedDataSources->size()); while (index != -1) { // If this isn't the data they're finished with, we don't care about it if (!exactMatch) { instance++; index = OverlapIndex(brickDone, cubeId, instance, exactMatch); continue; } // Test if we had a write lock (tryLockForRead will fail). If we had a // write lock make note of it. if (!(*p_managedData)[index].first->tryLockForRead()) { if (writeLock) { IString msg = "Overlapping data had write locks"; throw IException(IException::Programmer, msg, _FILEINFO_); } writeLock = true; } // A read lock was in place, undo the lock we just made else { if (writeLock) { IString msg = "Overlapping data had write locks"; throw IException(IException::Programmer, msg, _FILEINFO_); } // Unlock the lock we just made (*p_managedData)[index].first->unlock(); } // If we had a write lock we need to write the data to the file and // notify others of the change if we have listeners. if (writeLock) { p_threadSafeMutex->lock(); Brick cpy(*brickDone); p_managedCubes->value(cubeId).second->write(cpy); p_threadSafeMutex->unlock(); // Unlock the existing lock (*p_managedData)[index].first->unlock(); // No listeners? Remove this entry if (p_numChangeListeners == 0) { if (FreeBrick(index)) { // We've freed the one and only match, nobody wants to know about // it, so we're done break; } } // We have listeners, lock the data the appropriate number of times and // then emit the BrickChanged with a pointer else { // notify others of this change for (int i = 0; i < p_numChangeListeners; i++) { AcquireLock((*p_managedData)[index].first, true); } emit BrickChanged((*p_managedDataSources)[index], (*p_managedData)[index].second); } } // if we had a read lock and no longer have any locks, remove data from // list else { // We had the one and only (hopefully!) exact match, let's free it if // we can get a write lock and be done. // Free original read lock (*p_managedData)[index].first->unlock(); if ((*p_managedData)[index].first->tryLockForWrite()) { (*p_managedData)[index].first->unlock(); FreeBrick(index); } break; } instance++; index = OverlapIndex(brickDone, cubeId, instance, exactMatch); } ASSERT(p_managedData->size() == p_managedDataSources->size()); } /** * This is used internally to delete bricks when possible. * * @param brickIndex Brick to request deletion * * @return bool True if deletion actually happened */ bool CubeDataThread::FreeBrick(int brickIndex) { ASSERT(p_managedData->size() == p_managedDataSources->size()); // make sure brick is not still being used! if (!(*p_managedData)[brickIndex].first->tryLockForWrite()) { throw IException(IException::Programmer, "CubeDataThread::FreeBrick called on a locked brick", _FILEINFO_); } else { (*p_managedData)[brickIndex].first->unlock(); } // make sure no one is looking through p_managedData in order to delete it p_threadSafeMutex->lock(); if (p_currentLocksWaiting == 0) { delete (*p_managedData)[brickIndex].first; delete (*p_managedData)[brickIndex].second; p_managedData->removeAt(brickIndex); p_managedDataSources->removeAt(brickIndex); // Try to free any leftover bricks too for (int i = 0; i < p_managedData->size(); i++) { if ((*p_managedData)[i].first->tryLockForWrite()) { delete (*p_managedData)[i].first; delete (*p_managedData)[i].second; p_managedData->removeAt(i); p_managedDataSources->removeAt(i); i--; } } p_threadSafeMutex->unlock(); return true; } p_threadSafeMutex->unlock(); // no actual free was done return false; } /** * This is a helper method for both testing/debugging and general information * that provides the current number of bricks in memory. * * @return int Count of how many bricks reside in memory. */ int CubeDataThread::BricksInMemory() { p_threadSafeMutex->lock(); int numBricksInMemory = p_managedData->size(); p_threadSafeMutex->unlock(); return numBricksInMemory; } /** * This returns a new Universal Ground Map given a Cube ID. Ownership is * given to the caller. * * @param cubeId The Cube ID of the Cube that needs its ground map returned. * * @return UniversalGroundMap * Ground Map associated with the cube. */ UniversalGroundMap *CubeDataThread::GetUniversalGroundMap(int cubeId) const { if (!p_managedCubes->contains(cubeId)) { throw IException(IException::Programmer, "Invalid Cube ID [" + IString(cubeId) + "]", _FILEINFO_); } return new UniversalGroundMap(*(*p_managedCubes)[cubeId].second); } /** * This returns a constant pointer to a Cube at the given Cube ID. * * @param cubeId The Cube ID of the Cube that needs its pointer returned * * @return A thread-safe pointer to the requested Cube. */ const Cube *CubeDataThread::GetCube(int cubeId) const { if (!p_managedCubes->contains(cubeId)) { throw IException(IException::Programmer, "Invalid Cube ID [" + IString(cubeId) + "]", _FILEINFO_); } return (*p_managedCubes)[cubeId].second; } }
[ "slambright@usgs.gov" ]
slambright@usgs.gov
da4d2ce99e39350cd2a2170b85206135db944569
5e557741c8867bca4c4bcf2d5e67409211d059a3
/torch/csrc/jit/tensorexpr/bounds_inference.h
8defed23aaa14c6ab7d0453da3e9cf441aa6e0eb
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
Pandinosaurus/pytorch
a2bb724cfc548f0f2278b5af2fd8b1d2758adb76
bb8978f605e203fbb780f03010fefbece35ac51c
refs/heads/master
2023-05-02T20:07:23.577610
2021-11-05T14:01:30
2021-11-05T14:04:40
119,666,381
2
0
NOASSERTION
2021-11-05T19:55:56
2018-01-31T09:37:34
C++
UTF-8
C++
false
false
2,230
h
#pragma once #include <map> #include <unordered_map> #include <vector> #include <torch/csrc/WindowsTorchApiMacro.h> #include <torch/csrc/jit/tensorexpr/mem_dependency_checker.h> namespace torch { namespace jit { namespace tensorexpr { class Expr; class Buf; class Stmt; enum C10_API_ENUM TensorAccessKind { kLoad, kStore, kMutate }; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) struct TORCH_API TensorAccessBoundsInfo { TensorAccessKind kind; std::vector<ExprPtr> start; std::vector<ExprPtr> stop; }; using BoundsInfo = std::unordered_map<BufPtr, std::vector<TensorAccessBoundsInfo>>; TORCH_API BoundsInfo inferBounds(StmtPtr s, bool distinctAccessKinds = true); // Bounds inference caching the analysis. The MemDependencyChecker must already // have been run. TORCH_API BoundsInfo getInferredBounds( analysis::MemDependencyChecker& analyzer, StmtPtr s, bool distinctAccessKinds = true); TORCH_API BoundsInfo getInferredBounds( analysis::MemDependencyChecker& analyzer, ExprPtr e, bool distinctAccessKinds = true); TORCH_API void printBoundsInfo(const BoundsInfo& v); TORCH_API std::vector<ExprPtr> getBoundExtents( const std::vector<TensorAccessBoundsInfo>& infos); // The kind of dependency found, in increasing order of exclusivity. enum class HazardKind { ReadAfterWrite, WriteAfterRead, WriteAfterWrite, NoDependency, }; TORCH_API HazardKind getPotentialHazards( analysis::MemDependencyChecker& analyzer, StmtPtr A, StmtPtr B); // Returns true if there is a conflicting overlap between accesses in // statements A and B. A conflicting overlap is an overlap in buffer accesses // where at least one of the accesses is a Store. TORCH_API bool hasConflictingOverlap( analysis::MemDependencyChecker& analyzer, StmtPtr A, StmtPtr B); // Same as above, between accesses in stores S1 and S2. TORCH_API bool isOverlapping( analysis::MemDependencyChecker& analyzer, StorePtr S1, StorePtr S2); // Same as above, between accesses in store S and load L. TORCH_API bool isOverlapping( analysis::MemDependencyChecker& analyzer, StorePtr S, LoadPtr L); } // namespace tensorexpr } // namespace jit } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
06f83e921b301f362b68e8bc8725448b9fce8ec4
841a74fa03f511fb8ad0a838d0a175a0e6e10d7b
/Beginner/042/B.cpp
d2ad3374cfc9e9787975e215fc2d3a1bb622ad96
[]
no_license
arusuDev/ATC
e8ed22632dac1dbbfb9fd209162b4955b2f4719f
fe95c568f9dffc5786bc8432cf15e8cba2b037b6
refs/heads/master
2023-08-10T02:55:25.724574
2023-07-23T09:59:39
2023-07-23T09:59:39
202,337,559
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
// C++のテンプレート #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; int main(void){ int N,L; cin >> N >> L; vector<string> S(N); for(int i=0;i<N;i++) cin >> S[i]; sort(S.begin(),S.end()); for(int i=0;i<N;i++){ cout << S[i]; } cout << endl; }
[ "arse.mria@gmail.com" ]
arse.mria@gmail.com
885c858462403e247bef94c2a4c49d4862da19d7
875e79dd215328697da2876e5803a0c481b0c6e1
/SyGameBase/ClientBase/uibase/UILabel.h
6df043ef693a2be04d85963f4e6fdb5bdc9b42fa
[]
no_license
jijinlong/SyGame
304fd85653b147838a77d795e80bc54e89195071
b6bf9d6f7a0d4cd8d5fbe82e84b79683a6c71ae5
refs/heads/master
2021-01-22T05:15:44.142811
2013-10-25T05:40:10
2013-10-25T05:40:10
11,146,791
6
3
null
null
null
null
GB18030
C++
false
false
1,183
h
#pragma once #include "cocos2d.h" #include "UIBase.h" NS_CC_BEGIN class UILabel:public UIBase{ public: static UILabel* create(const char *content,float fontSize); static UILabel* create(); void beLoaded(); bool initWithContent(const char *content,float fontSize); void setPosition(float x,float y); void setSize(float x,float y); /** * 检查是否在区域里 */ virtual bool touchDown(float x,float y) ; /** * 更新位置 */ virtual bool touchMove(float x,float y); /** * 停止拖动 */ virtual bool touchEnd(float x,float y); /** * 设置展示内容 */ void setContent(const char *content); void setEditable(bool tag) { _editable = tag; } std::string getContent(){if (text) return text->getString();return "";} void setColor(const ccColor3B &color); UILabel() { _touchIn = false; _editable = false; text = NULL; uiType = UIBase::UI_LABEL; } /** * 创建父节点下的子节点 */ virtual TiXmlElement * makeNode(TiXmlElement *parent = NULL,const std::string &name="base"); private: CCLabelTTF *text; CCPoint nowTouchPoint; bool _editable; bool _touchIn; std::string content; ccColor3B color; }; NS_CC_END
[ "jjl_2009_hi@163.com" ]
jjl_2009_hi@163.com
b14bb2e54ebfbee382e1c82ae82411d93ec0cc77
230b7714d61bbbc9a75dd9adc487706dffbf301e
/components/omnibox/browser/favicon_cache.h
1a6b51d7ea4dbd4328a53be29d726114dcccc154
[ "BSD-3-Clause" ]
permissive
byte4byte/cloudretro
efe4f8275f267e553ba82068c91ed801d02637a7
4d6e047d4726c1d3d1d119dfb55c8b0f29f6b39a
refs/heads/master
2023-02-22T02:59:29.357795
2021-01-25T02:32:24
2021-01-25T02:32:24
197,294,750
1
2
BSD-3-Clause
2019-09-11T19:35:45
2019-07-17T01:48:48
null
UTF-8
C++
false
false
5,573
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OMNIBOX_BROWSER_FAVICON_CACHE_H_ #define COMPONENTS_OMNIBOX_BROWSER_FAVICON_CACHE_H_ #include <list> #include <map> #include "base/callback_forward.h" #include "base/callback_list.h" #include "base/containers/mru_cache.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/task/cancelable_task_tracker.h" #include "components/favicon_base/favicon_types.h" #include "components/history/core/browser/history_service_observer.h" #include "components/history/core/browser/history_types.h" namespace favicon { class FaviconService; } namespace gfx { class Image; } class GURL; typedef base::OnceCallback<void(const gfx::Image& favicon)> FaviconFetchedCallback; // This caches favicons by both page URL and icon URL. We cache a small number // of them so we can synchronously deliver them to the UI to prevent flicker as // the user types. // // This class also observes the HistoryService, and invalidates cached favicons // and null responses when matching favicons are updated. class FaviconCache : public history::HistoryServiceObserver { public: FaviconCache(favicon::FaviconService* favicon_service, history::HistoryService* history_service); ~FaviconCache() override; // These methods fetch favicons by the |page_url| or |icon_url| respectively. // If the correct favicon is already cached, these methods return the image // synchronously. // // If the correct favicon is not cached, we return an empty gfx::Image and // forward the request to FaviconService. |on_favicon_fetched| is stored in a // pending callback list, and subsequent identical requests are added to the // same pending list without issuing duplicate calls to FaviconService. // // If FaviconService responds with a non-empty image, we fulfill all the // matching |on_favicon_fetched| callbacks in the pending list, and cache the // result so that future matching requests can be fulfilled synchronously. // // If FaviconService responds with an empty image (because the correct favicon // isn't in our database), we simply erase all the pending callbacks, and also // cache the result. // // Therefore, |on_favicon_fetched| may or may not be called asynchrously // later, but will never be called with an empty result. It will also never // be called synchronously. gfx::Image GetFaviconForPageUrl(const GURL& page_url, FaviconFetchedCallback on_favicon_fetched); gfx::Image GetFaviconForIconUrl(const GURL& icon_url, FaviconFetchedCallback on_favicon_fetched); private: FRIEND_TEST_ALL_PREFIXES(FaviconCacheTest, ClearIconsWithHistoryDeletions); FRIEND_TEST_ALL_PREFIXES(FaviconCacheTest, ExpireNullFaviconsByHistory); FRIEND_TEST_ALL_PREFIXES(FaviconCacheTest, ObserveFaviconsChanged); enum class RequestType { BY_PAGE_URL, BY_ICON_URL, }; struct Request { RequestType type; GURL url; // This operator is defined to support using Request as a key of std::map. bool operator<(const Request& rhs) const; }; // Internal method backing GetFaviconForPageUrl and GetFaviconForIconUrl. gfx::Image GetFaviconInternal(const Request& request, FaviconFetchedCallback on_favicon_fetched); // This is the callback passed to the underyling FaviconService. When this // is called, all the pending requests that match |request| will be called. void OnFaviconFetched(const Request& request, const favicon_base::FaviconImageResult& result); // Removes cached favicons and null responses that match |request| from the // cache. Subsequent matching requests pull fresh data from FaviconService. void InvalidateCachedRequests(const Request& request); // history::HistoryServiceObserver: void OnURLVisited(history::HistoryService* history_service, ui::PageTransition transition, const history::URLRow& row, const history::RedirectList& redirects, base::Time visit_time) override; void OnURLsDeleted(history::HistoryService* history_service, const history::DeletionInfo& deletion_info) override; void OnFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url); // Non-owning pointer to a KeyedService. favicon::FaviconService* favicon_service_; ScopedObserver<history::HistoryService, FaviconCache> history_observer_; base::CancelableTaskTracker task_tracker_; std::map<Request, std::list<FaviconFetchedCallback>> pending_requests_; base::MRUCache<Request, gfx::Image> mru_cache_; // Keep responses with empty favicons in a separate list, to prevent a // response with an empty favicon from ever evicting an existing favicon. // The value is always set to true and has no meaning. base::MRUCache<Request, bool> responses_without_favicons_; // Subscription for notifications of changes to favicons. std::unique_ptr<base::CallbackList<void(const std::set<GURL>&, const GURL&)>::Subscription> favicons_changed_subscription_; base::WeakPtrFactory<FaviconCache> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FaviconCache); }; #endif // COMPONENTS_OMNIBOX_BROWSER_FAVICON_CACHE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3577ef6807b44158d8fc8b9304b78bf20ba12152
e6b5d019e565ce55b2febfbe21b82c2a21723385
/TheWaySoFar-Training/2016-01-17/j.cpp
9b038edf15e6fbb8c66a1946d0cde0df247e0036
[]
no_license
Sd-Invol/shoka
a628f7e8544d8eb110014316ab16ef3aed7b7433
1281cb43501d9ef127a2c67aebfba1905229502b
refs/heads/master
2023-06-06T07:23:09.496837
2023-05-13T14:46:23
2023-05-13T14:46:23
13,319,608
37
17
null
null
null
null
UTF-8
C++
false
false
7,490
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> #include <algorithm> #include <set> #include <map> using namespace std; const int N = 2005; int W , H , n , m , K; int cx[N] , cy[N] , hp[N]; int tx[N] , ty[N] , ms[N]; set< pair<int , int> > Mountain; map< pair<int , int> , int> Hash; int dx[] = {1, -1 , -1 , 0 , 0 , 1}; int dy[] = {0, 0 , 1 , 1 , -1 , -1}; vector< pair<int , int> > U , V, P; inline bool in(int x , int y) { return 0 <= x && x < W && 0 <= y && y < H; } inline bool attack(int x , int y , int p) { for (int i = 0 ; i < 6 ; ++ i) { int X = x + dx[i] , Y = y + dy[i]; if (X == cx[p] && Y == cy[p]) return 1; for (int j = 0 ; j < 6 ; ++ j) if (X + dx[j] == cx[p] && Y + dy[j] == cy[p]) return 1; } return 0; } void BFS(int id) { map< pair<int , int> , int> dist; queue< pair<int , int> > Q; Q.push(make_pair(tx[id] , ty[id])); dist[make_pair(tx[id] , ty[id])] = 0; while (!Q.empty()) { int x = Q.front().first; int y = Q.front().second; int w = dist[make_pair(x , y)]; //printf("%d %d : %d\n" , x , y , w); Q.pop(); for (int i = 0 ; i < n ; ++ i) { if (attack(x , y , i)) { if (!Hash.count(make_pair(x , y))) { Hash[make_pair(x , y)] = K ++; P.push_back(make_pair(x, y)); } int j = Hash[make_pair(x , y)]; U.push_back(make_pair(id , j)); V.push_back(make_pair(j , i)); } } if (w + 1 == ms[id]) continue; for (int i = 0 ; i < 6 ; ++ i) { int X = x + dx[i] , Y = y + dy[i]; //printf("-%d %d\n" , X , Y); pair<int , int> D(X , Y); if (!in(X , Y) || Mountain.count(D)) continue; //printf("--%d %d\n" , X , Y); if (dist.count(D)) continue; //printf("---%d %d\n" , X , Y); dist[D] = w + 1; Q.push(D); } } } int s , t , pre[N] , mcnt; struct arc { int x , f, next; }e[N * N * 4]; void addarc(int x , int y, int z) { e[mcnt] = (arc) {y , z , pre[x]} , pre[x] = mcnt ++; e[mcnt] = (arc) {x , 0 , pre[y]} , pre[y] = mcnt ++; } int d[N] , cur[N]; bool bfs() { queue<int> Q; memset(d , -1 , sizeof(d)); d[t] = 1 , Q.push(t); while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i = pre[x] ; ~i ; i = e[i].next) { int y = e[i].x; if (e[i ^ 1].f && !~d[y]) { d[y] = d[x] + 1; Q.push(y); if (y == s) return 1; } } } return 0; } int DFS(int x , int flow = 1 << 30) { if (x == t || !flow) return flow; int sum = 0 , u; for (int &i = cur[x] ; ~i ; i = e[i].next) { int y = e[i].x; if (d[y] + 1 == d[x] && (u = DFS(y , min(flow , e[i].f)))) { e[i].f -= u , e[i ^ 1].f += u; flow -= u , sum += u; if (!flow) break; } } if (!sum) d[x] = -1; return sum; } int dinic() { int res = 0; while (bfs()) { memcpy(cur , pre , sizeof(pre)); res += DFS(s); } return res; } int car_bo[1000]; map<pair<int, int>, int> pos_bo; int main() { scanf("%d%d" , &W , &H); scanf("%d" , &n); for (int i = 0 ; i < n ; ++ i) { scanf("%d%d%d" , cx + i , cy + i , hp + i); Mountain.insert(make_pair(cx[i] , cy[i])); } scanf("%d" , &m); for (int i = 0 ; i < m ; ++ i) { scanf("%d%d%d" , tx + i , ty + i , ms + i); pos_bo[make_pair(tx[i], ty[i])] = i; } scanf("%d" , &K); for (int i = 0 ; i < K ; ++ i) { int x , y; scanf("%d%d" , &x , &y); Mountain.insert(make_pair(x , y)); } K = 0; for (int i = 0 ; i < m ; ++ i) { BFS(i); } sort(U.begin() , U.end()); U.erase(unique(U.begin() , U.end()) , U.end()); sort(V.begin() , V.end()); V.erase(unique(V.begin() , V.end()) , V.end()); s = n + m + K + K , t = s + 1; for (int res = n ; res >= 0 ; -- res) { for (int mask = 0 ; mask < 1 << n ; ++ mask) { if (__builtin_popcount(mask) != res) continue; int sum = 0; memset(pre , -1 , sizeof(pre)); mcnt = 0; for (int i = 0 ; i < m ; ++ i) { addarc(s , i , 1); } for (int i = 0 ; i < (int)U.size() ; ++ i) { addarc(U[i].first , m + U[i].second , 1); } for (int i = 0 ; i < K ; ++ i) { addarc(m + i , m + K + i , 1); } for (int i = 0 ; i < (int)V.size() ; ++ i) { addarc(m + K + V[i].first , m + K + K + V[i].second , 1); } for (int i = 0 ; i < n ; ++ i) { if (mask >> i & 1) { addarc(m + K + K + i , t , hp[i]); sum += hp[i]; } } if (dinic() != sum) continue; printf("%d\n" , res); vector<pair<int, int> > pr; for (int i = 0; i < m; ++i) for (int k = pre[i]; k != -1; k = e[k].next) { int y = e[k].x; if (e[k ^ 1].f != 1) continue; if (y < m || y >= m + K) continue; pr.push_back(make_pair(i, y - m)); //printf("!%d %d %d\n", i, P[y - m].first, P[y-m].second); } while (1) { for (int i = 0; i < pr.size(); ++i) car_bo[pr[i].first] = 1; int flag = 0; for (int i = 0; i < pr.size(); ++i) { int x = P[pr[i].second].first; int y = P[pr[i].second].second; if (pos_bo.count(make_pair(x, y)) == 0) continue; int id = pos_bo[make_pair(x, y)]; if (car_bo[id]) continue; flag = 1; car_bo[id] = 1; car_bo[pr[i].first] = 0; pr[i].first = id; break; } if (flag == 0) break; } for (int i = 0; i < pr.size(); ++i) { int id = pr[i].first; tx[id] = i; } for (int i = 0; i < m; ++i) if (!car_bo[i]) { printf("%d %d 0\n", tx[i], ty[i]); } else { int id = tx[i]; id = pr[id].second; printf("%d %d ", P[id].first, P[id].second); int flag = -1; for (int k = pre[id + m + K]; k != -1; k = e[k].next) { int y = e[k].x; if (e[k ^ 1].f == 1) { if (y >= m + K + K && y < m + K + K + n) { flag = y - m - K - K; break; } } } printf("%d\n", flag + 1); } return 0; } } return 0; }
[ "Sd.Invol@gmail.com" ]
Sd.Invol@gmail.com
d14f2ce7c014a71d579ad9aca8d83c83a5eb7405
5bc47dcf9ab0843b9d06bc25012bcb2f78874216
/697B.cpp
8067e5f800d65ace3142699b9df41c22ab615e7f
[]
no_license
MijaTola/Codeforce
428f466248a4e9d42ac457aa971f681320dc5018
9e85803464ed192c6c643bd0f920f345503ac967
refs/heads/master
2021-01-10T16:27:12.479907
2020-10-14T15:00:14
2020-10-14T15:00:14
45,284,776
0
0
null
null
null
null
UTF-8
C++
false
false
1,628
cpp
#include <iostream> #include <algorithm> #include <queue> #include <stack> #include <vector> #include <climits> #include <map> #include <set> #include <cassert> #include <cstdio> #include <cstring> #include <cmath> #include <deque> #include <string> #include <sstream> using namespace std; typedef long long ll; int main(){ string x; cin >> x; int pos = 0; string A = ""; int coma = -1; while(x[pos] != 'e'){ if(x[pos] == '.'){ coma = pos;pos++; continue;} A += x[pos]; pos++; } if(coma == -1) coma = pos-1; pos++; int number = 0; //cout << A << endl; while(pos < (int)x.size()){ number += int(x[pos]-'0'); if(pos+1 < (int)x.size()) number *= 10; pos++; } coma += number; if((int)A.size() <= coma){ bool flag = true; for (int i = 0; i < (int)A.size(); ++i){ if(A[i] == '0' and flag) continue; flag = false; cout << A[i]; } for (int i = (int)A.size(); i < coma; ++i) cout << 0; return 0; } pos = 0; bool flag = true; if(A[0] == '0'){ cout << A[0];} while(pos < coma){ if(A[pos] == '0' and flag){ pos++; continue; } flag = false; cout << A[pos]; pos++; } string ans2 = ""; pos = (int)A.size()-1; flag = true; while(pos >= coma){ if(A[pos] == '0' and flag){ pos--; continue; } flag = false; ans2 = A[pos]+ans2; pos--; } if(ans2.size() != 0) cout << "." << ans2 << endl; return 0; }
[ "mija.tola.ap@gmail.com" ]
mija.tola.ap@gmail.com
5327ce8d6aa681c72be12eae56cf85c0750d21f7
aba9b00edec394f1389a7ecf88a290112303414d
/semestr_3/obiektowe/11/cwym.h
b5e030bedbb916082d41f9b2bea671b1b715a585
[]
no_license
torgiren/szkola
2aca12807f0030f8e2ae2dfcb808bf7cae5e2e27
5ed18bed273ab25b8e52a488e28af239b8beb89c
refs/heads/master
2020-12-25T18:18:36.317496
2014-04-27T23:43:21
2014-04-27T23:43:21
3,892,030
1
1
null
null
null
null
UTF-8
C++
false
false
273
h
#ifndef __CWYM__ #define __CWYM__ #include <iostream> using namespace std; class CWym { public: friend class CTabWym; friend ostream& operator<<(ostream& out, CWym& co); CWym(int l=0,int m=1); CWym operator+(CWym& wym); private: int itsL; int itsM; }; #endif
[ "i9fabryk@fatcat.ftj.agh.edu.pl" ]
i9fabryk@fatcat.ftj.agh.edu.pl
6ec0224c06a661360c7a8233e50cd008908e75c5
3fc5033efb6a5fbb7b6900d6908956de0f1cc4ab
/xls/codegen/function_to_proc.cc
442c1bea066a4e1b47bcd44a6b3245fd2bafa5ed
[ "Apache-2.0" ]
permissive
Tryweirder/xls
bbee800563cae923c563d7456531d095c95d2050
befa3ddfb52f8504e50569b6424fc384aa20f9e7
refs/heads/main
2023-04-20T00:15:08.222701
2021-04-30T23:06:39
2021-04-30T23:07:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,982
cc
// Copyright 2021 The XLS Authors // // 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 "xls/codegen/function_to_proc.h" #include <vector> #include "absl/container/flat_hash_map.h" #include "xls/codegen/vast.h" #include "xls/ir/channel.h" #include "xls/ir/function_builder.h" #include "xls/ir/node.h" #include "xls/ir/node_iterator.h" #include "xls/ir/value_helpers.h" namespace xls { namespace verilog { // Adds the function parameters as input ports on the proc (receives on a port // channel). For each function parameter adds a key/value to node map where the // key is the parameter and the value is the received data from the // port. Zero-width values are not emitted as ports as Verilog does not support // zero-width ports. In these cases, a zero-valued literal is added to the map // rather than a receive operation. Returns a vector containing the tokens from // the receive operations. static absl::StatusOr<std::vector<Node*>> AddInputPorts( Function* f, Proc* proc, absl::flat_hash_map<Node*, Node*>* node_map) { std::vector<Node*> tokens; // Skip zero-width inputs/output. Verilog does not support zero-width ports. for (Param* param : f->params()) { if (param->GetType()->GetFlatBitCount() == 0) { // Create a (zero-valued) literal of the given type to standin for the // port. // TODO(meheff): 2021/04/21 Consider adding these ports unconditionally // then removing them as a separate pass. This simplifies this process // and is a better separation of concerns. XLS_ASSIGN_OR_RETURN(Node * dummy_input, proc->MakeNode<xls::Literal>( param->loc(), ZeroOfType(param->GetType()))); (*node_map)[param] = dummy_input; continue; } XLS_ASSIGN_OR_RETURN( PortChannel * ch, f->package()->CreatePortChannel( param->GetName(), ChannelOps::kReceiveOnly, param->GetType())); XLS_ASSIGN_OR_RETURN( Node * rcv, proc->MakeNode<Receive>(param->loc(), proc->TokenParam(), ch->id())); XLS_ASSIGN_OR_RETURN(Node * rcv_token, proc->MakeNode<TupleIndex>( param->loc(), rcv, /*index=*/0)); XLS_ASSIGN_OR_RETURN(Node * rcv_data, proc->MakeNode<TupleIndex>( param->loc(), rcv, /*index=*/1)); tokens.push_back(rcv_token); (*node_map)[param] = rcv_data; } return tokens.empty() ? std::vector<Node*>({proc->TokenParam()}) : tokens; } // Add an output port which sends the given return value. The send operation // uses the given token. Returns the token from the send operation. static absl::StatusOr<Node*> AddOutputPort(Node* return_value, Node* token) { if (return_value->GetType()->GetFlatBitCount() == 0) { return token; } // TODO(meheff): 2021-03-01 Allow port names other than "out". XLS_ASSIGN_OR_RETURN( PortChannel * out_ch, return_value->package()->CreatePortChannel("out", ChannelOps::kSendOnly, return_value->GetType())); XLS_ASSIGN_OR_RETURN( Node * send, return_value->function_base()->MakeNode<Send>( return_value->loc(), token, return_value, out_ch->id())); return send; } // Creates and returns a stateless proc (state is an empty tuple). static Proc* CreateStatelessProc(Package* p, absl::string_view proc_name) { return p->AddProc( absl::make_unique<Proc>(proc_name, Value::Tuple({}), "tkn", "state", p)); } absl::StatusOr<Proc*> FunctionToProc(Function* f, absl::string_view proc_name) { Proc* proc = CreateStatelessProc(f->package(), proc_name); // A map from the nodes in 'f' to their corresponding node in the proc. absl::flat_hash_map<Node*, Node*> node_map; XLS_ASSIGN_OR_RETURN(std::vector<Node*> input_tokens, AddInputPorts(f, proc, &node_map)); // Clone in the nodes from the function into the proc. for (Node* node : TopoSort(f)) { if (node->Is<Param>()) { // Parameters become receive nodes in the proc and are added above. continue; } std::vector<Node*> new_operands; for (Node* operand : node->operands()) { new_operands.push_back(node_map.at(operand)); } XLS_ASSIGN_OR_RETURN(Node * proc_node, node->CloneInNewFunction(new_operands, proc)); node_map[node] = proc_node; } XLS_ASSIGN_OR_RETURN( Node * merged_input_token, proc->MakeNode<AfterAll>(/*loc=*/absl::nullopt, input_tokens)); XLS_ASSIGN_OR_RETURN( Node * output_token, AddOutputPort(node_map.at(f->return_value()), merged_input_token)); XLS_RETURN_IF_ERROR(proc->SetNextToken(output_token)); XLS_RETURN_IF_ERROR(proc->SetNextState(proc->StateParam())); return proc; } // Returns pipeline-stage prefixed signal name for the given node. For // example: p3_foo. static std::string PipelineSignalName(Node* node, int64_t stage) { return absl::StrFormat("p%d_%s", stage, SanitizeIdentifier(node->GetName())); } absl::StatusOr<Proc*> FunctionToPipelinedProc(const PipelineSchedule& schedule, Function* f, absl::string_view proc_name) { Proc* proc = CreateStatelessProc(f->package(), proc_name); // A map from the nodes in 'f' to their corresponding node in the proc. absl::flat_hash_map<Node*, Node*> node_map; XLS_ASSIGN_OR_RETURN(std::vector<Node*> input_tokens, AddInputPorts(f, proc, &node_map)); XLS_ASSIGN_OR_RETURN( Node * previous_token, proc->MakeNode<AfterAll>(/*loc=*/absl::nullopt, input_tokens)); std::vector<Node*> output_tokens; for (int64_t stage = 0; stage < schedule.length(); ++stage) { for (Node* function_node : schedule.nodes_in_cycle(stage)) { if (function_node->Is<Param>()) { // Parameters become receive nodes in the proc and are added above. continue; } std::vector<Node*> new_operands; for (Node* operand : function_node->operands()) { new_operands.push_back(node_map.at(operand)); } XLS_ASSIGN_OR_RETURN( Node * node, function_node->CloneInNewFunction(new_operands, proc)); node_map[function_node] = node; auto is_live_out_of_stage = [&](Node* n) { if (stage == schedule.length() - 1) { return false; } if (n == f->return_value()) { return true; } for (Node* user : n->users()) { if (schedule.cycle(user) > stage) { return true; } } return false; }; if (is_live_out_of_stage(function_node)) { // A register is represented as a Send node (register "D" port) followed // by a Receive node (register "Q" port). These are connected via a // token. A receive operation produces a tuple of (token, data) so this // construct also includes a tuple-index to extract the data. XLS_ASSIGN_OR_RETURN( RegisterChannel * reg_ch, f->package()->CreateRegisterChannel(PipelineSignalName(node, stage), node->GetType())); XLS_ASSIGN_OR_RETURN( Send * send, proc->MakeNode<Send>(node->loc(), previous_token, node, reg_ch->id())); XLS_ASSIGN_OR_RETURN( Receive * receive, proc->MakeNode<Receive>(node->loc(), /*token=*/send, reg_ch->id())); // Receives produce a tuple of (token, data). XLS_ASSIGN_OR_RETURN( Node * receive_token, proc->MakeNode<TupleIndex>(node->loc(), receive, /*index=*/0)); XLS_ASSIGN_OR_RETURN( Node * receive_data, proc->MakeNode<TupleIndex>(node->loc(), receive, /*index=*/1)); output_tokens.push_back(receive_token); node_map[node] = receive_data; } } if (!output_tokens.empty()) { XLS_ASSIGN_OR_RETURN( previous_token, proc->MakeNode<AfterAll>(/*loc=*/absl::nullopt, output_tokens)); } } XLS_ASSIGN_OR_RETURN( Node * output_token, AddOutputPort(node_map.at(f->return_value()), previous_token)); XLS_RETURN_IF_ERROR(proc->SetNextToken(output_token)); XLS_RETURN_IF_ERROR(proc->SetNextState(proc->StateParam())); return proc; } } // namespace verilog } // namespace xls
[ "copybara-worker@google.com" ]
copybara-worker@google.com
d8dfbcf1cf395b5f677c5c421805049c426c5f7a
ed997b3a8723cc9e77787c1d868f9300b0097473
/libs/math/tools/ellint_pi3_data.cpp
d77d81901246d07d22eff4285429901932b8ba17
[ "BSL-1.0" ]
permissive
juslee/boost-svn
7ddb99e2046e5153e7cb5680575588a9aa8c79b2
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
refs/heads/master
2023-04-13T11:00:16.289416
2012-11-16T11:14:39
2012-11-16T11:14:39
6,734,455
0
0
BSL-1.0
2023-04-03T23:13:08
2012-11-17T11:21:17
C++
UTF-8
C++
false
false
2,172
cpp
// Copyright John Maddock 2006. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/math/bindings/rr.hpp> //#include <boost/math/tools/dual_precision.hpp> #include <boost/math/tools/test_data.hpp> #include <boost/test/included/test_exec_monitor.hpp> #include <boost/math/special_functions/ellint_3.hpp> #include <fstream> #include <boost/math/tools/test_data.hpp> #include <boost/tr1/random.hpp> float extern_val; // confuse the compilers optimiser, and force a truncation to float precision: float truncate_to_float(float const * pf) { extern_val = *pf; return *pf; } boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> generate_data(boost::math::ntl::RR n, boost::math::ntl::RR phi) { static std::tr1::mt19937 r; std::tr1::uniform_real<float> ui(0, 1); float k = ui(r); boost::math::ntl::RR kr(truncate_to_float(&k)); boost::math::ntl::RR result = boost::math::ellint_3(kr, n, phi); return boost::math::make_tuple(kr, result); } int test_main(int argc, char*argv []) { using namespace boost::math::tools; boost::math::ntl::RR::SetOutputPrecision(50); boost::math::ntl::RR::SetPrecision(1000); parameter_info<boost::math::ntl::RR> arg1, arg2; test_data<boost::math::ntl::RR> data; bool cont; std::string line; if(argc < 1) return 1; do{ if(0 == get_user_parameter_info(arg1, "n")) return 1; if(0 == get_user_parameter_info(arg2, "phi")) return 1; data.insert(&generate_data, arg1, arg2); std::cout << "Any more data [y/n]?"; std::getline(std::cin, line); boost::algorithm::trim(line); cont = (line == "y"); }while(cont); std::cout << "Enter name of test data file [default=ellint_pi3_data.ipp]"; std::getline(std::cin, line); boost::algorithm::trim(line); if(line == "") line = "ellint_pi3_data.ipp"; std::ofstream ofs(line.c_str()); line.erase(line.find('.')); ofs << std::scientific; write_code(ofs, data, line.c_str()); return 0; }
[ "johnmaddock@b8fc166d-592f-0410-95f2-cb63ce0dd405" ]
johnmaddock@b8fc166d-592f-0410-95f2-cb63ce0dd405
e8bf271494c6ee91197c330e5b96164f82c33d7b
f3d3796a62d5f2c222bd88054ea1ec0c6ebea454
/src/ini/SimpleIni.h
6a29adad2acbb617eea3a982bba9fe2d4d56ed25
[ "BSD-3-Clause" ]
permissive
open-license-manager/lcc-license-generator
57ae2c42c13e8f8376d396867ef777cbedf7d6c6
816fc5787786541a9074b2a5c3f665d54fac28b0
refs/heads/develop
2022-08-27T11:11:11.602507
2021-05-27T00:38:34
2021-05-27T00:38:34
217,804,988
39
37
BSD-3-Clause
2022-08-22T14:35:11
2019-10-27T04:30:51
C++
UTF-8
C++
false
false
105,536
h
/** @mainpage <table> <tr><th>Library <td>SimpleIni <tr><th>File <td>SimpleIni.h <tr><th>Author <td>Brodie Thiesfield [code at jellycan dot com] <tr><th>Source <td>https://github.com/brofield/simpleini <tr><th>Version <td>4.17 </table> Jump to the @link CSimpleIniTempl CSimpleIni @endlink interface documentation. @section intro INTRODUCTION This component allows an INI-style configuration file to be used on both Windows and Linux/Unix. It is fast, simple and source code using this component will compile unchanged on either OS. @section features FEATURES - MIT Licence allows free use in all software (including GPL and commercial) - multi-platform (Windows 95/98/ME/NT/2K/XP/2003, Windows CE, Linux, Unix) - loading and saving of INI-style configuration files - configuration files can have any newline format on all platforms - liberal acceptance of file format - key/values with no section - removal of whitespace around sections, keys and values - support for multi-line values (values with embedded newline characters) - optional support for multiple keys with the same name - optional case-insensitive sections and keys (for ASCII characters only) - saves files with sections and keys in the same order as they were loaded - preserves comments on the file, section and keys where possible. - supports both char or wchar_t programming interfaces - supports both MBCS (system locale) and UTF-8 file encodings - system locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file - support for non-ASCII characters in section, keys, values and comments - support for non-standard character types or file encodings via user-written converter classes - support for adding/modifying values programmatically - compiles cleanly in the following compilers: - Windows/VC6 (warning level 3) - Windows/VC.NET 2003 (warning level 4) - Windows/VC 2005 (warning level 4) - Linux/gcc (-Wall) @section usage USAGE SUMMARY -# Define the appropriate symbol for the converter you wish to use and include the SimpleIni.h header file. If no specific converter is defined then the default converter is used. The default conversion mode uses SI_CONVERT_WIN32 on Windows and SI_CONVERT_GENERIC on all other platforms. If you are using ICU then SI_CONVERT_ICU is supported on all platforms. -# Declare an instance the appropriate class. Note that the following definitions are just shortcuts for commonly used types. Other types (PRUnichar, unsigned short, unsigned char) are also possible. <table> <tr><th>Interface <th>Case-sensitive <th>Load UTF-8 <th>Load MBCS <th>Typedef <tr><th>SI_CONVERT_GENERIC <tr><td>char <td>No <td>Yes <td>Yes #1 <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW <tr><th>SI_CONVERT_WIN32 <tr><td>char <td>No <td>No #2 <td>Yes <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW <tr><th>SI_CONVERT_ICU <tr><td>char <td>No <td>Yes <td>Yes <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>UChar <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>UChar <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW </table> #1 On Windows you are better to use CSimpleIniA with SI_CONVERT_WIN32.<br> #2 Only affects Windows. On Windows this uses MBCS functions and so may fold case incorrectly leading to uncertain results. -# Call LoadData() or LoadFile() to load and parse the INI configuration file -# Access and modify the data of the file using the following functions <table> <tr><td>GetAllSections <td>Return all section names <tr><td>GetAllKeys <td>Return all key names within a section <tr><td>GetAllValues <td>Return all values within a section & key <tr><td>GetSection <td>Return all key names and values in a section <tr><td>GetSectionSize <td>Return the number of keys in a section <tr><td>GetValue <td>Return a value for a section & key <tr><td>SetValue <td>Add or update a value for a section & key <tr><td>Delete <td>Remove a section, or a key from a section </table> -# Call Save() or SaveFile() to save the INI configuration data @section iostreams IO STREAMS SimpleIni supports reading from and writing to STL IO streams. Enable this by defining SI_SUPPORT_IOSTREAMS before including the SimpleIni.h header file. Ensure that if the streams are backed by a file (e.g. ifstream or ofstream) then the flag ios_base::binary has been used when the file was opened. @section multiline MULTI-LINE VALUES Values that span multiple lines are created using the following format. <pre> key = <<<ENDTAG .... multiline value .... ENDTAG </pre> Note the following: - The text used for ENDTAG can be anything and is used to find where the multi-line text ends. - The newline after ENDTAG in the start tag, and the newline before ENDTAG in the end tag is not included in the data value. - The ending tag must be on it's own line with no whitespace before or after it. - The multi-line value is modified at load so that each line in the value is delimited by a single '\\n' character on all platforms. At save time it will be converted into the newline format used by the current platform. @section comments COMMENTS Comments are preserved in the file within the following restrictions: - Every file may have a single "file comment". It must start with the first character in the file, and will end with the first non-comment line in the file. - Every section may have a single "section comment". It will start with the first comment line following the file comment, or the last data entry. It ends at the beginning of the section. - Every key may have a single "key comment". This comment will start with the first comment line following the section start, or the file comment if there is no section name. - Comments are set at the time that the file, section or key is first created. The only way to modify a comment on a section or a key is to delete that entry and recreate it with the new comment. There is no way to change the file comment. @section save SAVE ORDER The sections and keys are written out in the same order as they were read in from the file. Sections and keys added to the data after the file has been loaded will be added to the end of the file when it is written. There is no way to specify the location of a section or key other than in first-created, first-saved order. @section notes NOTES - To load UTF-8 data on Windows 95, you need to use Microsoft Layer for Unicode, or SI_CONVERT_GENERIC, or SI_CONVERT_ICU. - When using SI_CONVERT_GENERIC, ConvertUTF.c must be compiled and linked. - When using SI_CONVERT_ICU, ICU header files must be on the include path and icuuc.lib must be linked in. - To load a UTF-8 file on Windows AND expose it with SI_CHAR == char, you should use SI_CONVERT_GENERIC. - The collation (sorting) order used for sections and keys returned from iterators is NOT DEFINED. If collation order of the text is important then it should be done yourself by either supplying a replacement SI_STRLESS class, or by sorting the strings external to this library. - Usage of the <mbstring.h> header on Windows can be disabled by defining SI_NO_MBCS. This is defined automatically on Windows CE platforms. @section contrib CONTRIBUTIONS - 2010/05/03: Tobias Gehrig: added GetDoubleValue() @section licence MIT LICENCE The licence text below is the boilerplate "MIT Licence" used from: http://www.opensource.org/licenses/mit-license.php Copyright (c) 2006-2012, Brodie Thiesfield Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INCLUDED_SimpleIni_h #define INCLUDED_SimpleIni_h #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif // Disable these warnings in MSVC: // 4127 "conditional expression is constant" as the conversion classes trigger // it with the statement if (sizeof(SI_CHAR) == sizeof(char)). This test will // be optimized away in a release build. // 4503 'insert' : decorated name length exceeded, name was truncated // 4702 "unreachable code" as the MS STL header causes it in release mode. // Again, the code causing the warning will be cleaned up by the compiler. // 4786 "identifier truncated to 256 characters" as this is thrown hundreds // of times VC6 as soon as STL is used. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127 4503 4702 4786) #endif #include <cstring> #include <string> #include <map> #include <list> #include <algorithm> #include <stdio.h> #ifdef SI_SUPPORT_IOSTREAMS #include <iostream> #endif // SI_SUPPORT_IOSTREAMS #ifdef _DEBUG #ifndef assert #include <cassert> #endif #define SI_ASSERT(x) assert(x) #else #define SI_ASSERT(x) #endif enum SI_Error { SI_OK = 0, //!< No error SI_UPDATED = 1, //!< An existing value was updated SI_INSERTED = 2, //!< A new value was inserted // note: test for any error with (retval < 0) SI_FAIL = -1, //!< Generic failure SI_NOMEM = -2, //!< Out of memory error SI_FILE = -3 //!< File error (see errno for detail error) }; #define SI_UTF8_SIGNATURE "\xEF\xBB\xBF" #ifdef _WIN32 #define SI_NEWLINE_A "\r\n" #define SI_NEWLINE_W L"\r\n" #else // !_WIN32 #define SI_NEWLINE_A "\n" #define SI_NEWLINE_W L"\n" #endif // _WIN32 #if defined(SI_CONVERT_ICU) #include <unicode/ustring.h> #endif #if defined(_WIN32) #define SI_HAS_WIDE_FILE #define SI_WCHAR_T wchar_t #elif defined(SI_CONVERT_ICU) #define SI_HAS_WIDE_FILE #define SI_WCHAR_T UChar #endif // --------------------------------------------------------------------------- // MAIN TEMPLATE CLASS // --------------------------------------------------------------------------- /** Simple INI file reader. This can be instantiated with the choice of unicode or native characterset, and case sensitive or insensitive comparisons of section and key names. The supported combinations are pre-defined with the following typedefs: <table> <tr><th>Interface <th>Case-sensitive <th>Typedef <tr><td>char <td>No <td>CSimpleIniA <tr><td>char <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>CSimpleIniCaseW </table> Note that using other types for the SI_CHAR is supported. For instance, unsigned char, unsigned short, etc. Note that where the alternative type is a different size to char/wchar_t you may need to supply new helper classes for SI_STRLESS and SI_CONVERTER. */ template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> class CSimpleIniTempl { public: typedef SI_CHAR SI_CHAR_T; /** key entry */ struct Entry { const SI_CHAR *pItem; const SI_CHAR *pComment; int nOrder; Entry(const SI_CHAR *a_pszItem = NULL, int a_nOrder = 0) : pItem(a_pszItem), pComment(NULL), nOrder(a_nOrder) {} Entry(const SI_CHAR *a_pszItem, const SI_CHAR *a_pszComment, int a_nOrder) : pItem(a_pszItem), pComment(a_pszComment), nOrder(a_nOrder) {} Entry(const Entry &rhs) { operator=(rhs); } Entry &operator=(const Entry &rhs) { pItem = rhs.pItem; pComment = rhs.pComment; nOrder = rhs.nOrder; return *this; } #if defined(_MSC_VER) && _MSC_VER <= 1200 /** STL of VC6 doesn't allow me to specify my own comparator for list::sort() */ bool operator<(const Entry &rhs) const { return LoadOrder()(*this, rhs); } bool operator>(const Entry &rhs) const { return LoadOrder()(rhs, *this); } #endif /** Strict less ordering by name of key only */ struct KeyOrder : std::binary_function<Entry, Entry, bool> { bool operator()(const Entry &lhs, const Entry &rhs) const { const static SI_STRLESS isLess = SI_STRLESS(); return isLess(lhs.pItem, rhs.pItem); } }; /** Strict less ordering by order, and then name of key */ struct LoadOrder : std::binary_function<Entry, Entry, bool> { bool operator()(const Entry &lhs, const Entry &rhs) const { if (lhs.nOrder != rhs.nOrder) { return lhs.nOrder < rhs.nOrder; } return KeyOrder()(lhs.pItem, rhs.pItem); } }; }; /** map keys to values */ typedef std::multimap<Entry, const SI_CHAR *, typename Entry::KeyOrder> TKeyVal; /** map sections to key/value map */ typedef std::map<Entry, TKeyVal, typename Entry::KeyOrder> TSection; /** set of dependent string pointers. Note that these pointers are dependent on memory owned by CSimpleIni. */ typedef std::list<Entry> TNamesDepend; /** interface definition for the OutputWriter object to pass to Save() in order to output the INI file data. */ class OutputWriter { public: OutputWriter() {} virtual ~OutputWriter() {} virtual void Write(const char *a_pBuf) = 0; private: OutputWriter(const OutputWriter &); // disable OutputWriter &operator=(const OutputWriter &); // disable }; /** OutputWriter class to write the INI data to a file */ class FileWriter : public OutputWriter { FILE *m_file; public: FileWriter(FILE *a_file) : m_file(a_file) {} void Write(const char *a_pBuf) { fputs(a_pBuf, m_file); } private: FileWriter(const FileWriter &); // disable FileWriter &operator=(const FileWriter &); // disable }; /** OutputWriter class to write the INI data to a string */ class StringWriter : public OutputWriter { std::string &m_string; public: StringWriter(std::string &a_string) : m_string(a_string) {} void Write(const char *a_pBuf) { m_string.append(a_pBuf); } private: StringWriter(const StringWriter &); // disable StringWriter &operator=(const StringWriter &); // disable }; #ifdef SI_SUPPORT_IOSTREAMS /** OutputWriter class to write the INI data to an ostream */ class StreamWriter : public OutputWriter { std::ostream &m_ostream; public: StreamWriter(std::ostream &a_ostream) : m_ostream(a_ostream) {} void Write(const char *a_pBuf) { m_ostream << a_pBuf; } private: StreamWriter(const StreamWriter &); // disable StreamWriter &operator=(const StreamWriter &); // disable }; #endif // SI_SUPPORT_IOSTREAMS /** Characterset conversion utility class to convert strings to the same format as is used for the storage. */ class Converter : private SI_CONVERTER { public: using SI_CONVERTER::SizeToStore; Converter(bool a_bStoreIsUtf8) : SI_CONVERTER(a_bStoreIsUtf8) { m_scratch.resize(1024); } Converter(const Converter &rhs) { operator=(rhs); } Converter &operator=(const Converter &rhs) { m_scratch = rhs.m_scratch; return *this; } bool ConvertToStore(const SI_CHAR *a_pszString) { size_t uLen = SizeToStore(a_pszString); if (uLen == (size_t)(-1)) { return false; } while (uLen > m_scratch.size()) { m_scratch.resize(m_scratch.size() * 2); } return SI_CONVERTER::ConvertToStore(a_pszString, const_cast<char *>(m_scratch.data()), m_scratch.size()); } const char *Data() { return m_scratch.data(); } private: std::string m_scratch; }; public: /*-----------------------------------------------------------------------*/ /** Default constructor. @param a_bIsUtf8 See the method SetUnicode() for details. @param a_bMultiKey See the method SetMultiKey() for details. @param a_bMultiLine See the method SetMultiLine() for details. */ CSimpleIniTempl(bool a_bIsUtf8 = false, bool a_bMultiKey = false, bool a_bMultiLine = false); /** Destructor */ ~CSimpleIniTempl(); /** Deallocate all memory stored by this object */ void Reset(); /** Has any data been loaded */ bool IsEmpty() const { return m_data.empty(); } /*-----------------------------------------------------------------------*/ /** @{ @name Settings */ /** Set the storage format of the INI data. This affects both the loading and saving of the INI data using all of the Load/Save API functions. This value cannot be changed after any INI data has been loaded. If the file is not set to Unicode (UTF-8), then the data encoding is assumed to be the OS native encoding. This encoding is the system locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP. If the storage format is set to Unicode then the file will be loaded as UTF-8 encoded data regardless of the native file encoding. If SI_CHAR == char then all of the char* parameters take and return UTF-8 encoded data regardless of the system locale. \param a_bIsUtf8 Assume UTF-8 encoding for the source? */ void SetUnicode(bool a_bIsUtf8 = true) { if (!m_pData) m_bStoreIsUtf8 = a_bIsUtf8; } /** Get the storage format of the INI data. */ bool IsUnicode() const { return m_bStoreIsUtf8; } /** Should multiple identical keys be permitted in the file. If set to false then the last value encountered will be used as the value of the key. If set to true, then all values will be available to be queried. For example, with the following input: <pre> [section] test=value1 test=value2 </pre> Then with SetMultiKey(true), both of the values "value1" and "value2" will be returned for the key test. If SetMultiKey(false) is used, then the value for "test" will only be "value2". This value may be changed at any time. \param a_bAllowMultiKey Allow multi-keys in the source? */ void SetMultiKey(bool a_bAllowMultiKey = true) { m_bAllowMultiKey = a_bAllowMultiKey; } /** Get the storage format of the INI data. */ bool IsMultiKey() const { return m_bAllowMultiKey; } /** Should data values be permitted to span multiple lines in the file. If set to false then the multi-line construct <<<TAG as a value will be returned as is instead of loading the data. This value may be changed at any time. \param a_bAllowMultiLine Allow multi-line values in the source? */ void SetMultiLine(bool a_bAllowMultiLine = true) { m_bAllowMultiLine = a_bAllowMultiLine; } /** Query the status of multi-line data */ bool IsMultiLine() const { return m_bAllowMultiLine; } /** Should spaces be added around the equals sign when writing key/value pairs out. When true, the result will be "key = value". When false, the result will be "key=value". This value may be changed at any time. \param a_bSpaces Add spaces around the equals sign? */ void SetSpaces(bool a_bSpaces = true) { m_bSpaces = a_bSpaces; } /** Query the status of spaces output */ bool UsingSpaces() const { return m_bSpaces; } /*-----------------------------------------------------------------------*/ /** @} @{ @name Loading INI Data */ /** Load an INI file from disk into memory @param a_pszFile Path of the file to be loaded. This will be passed to fopen() and so must be a valid path for the current platform. @return SI_Error See error definitions */ SI_Error LoadFile(const char *a_pszFile); #ifdef SI_HAS_WIDE_FILE /** Load an INI file from disk into memory @param a_pwszFile Path of the file to be loaded in UTF-16. @return SI_Error See error definitions */ SI_Error LoadFile(const SI_WCHAR_T *a_pwszFile); #endif // SI_HAS_WIDE_FILE /** Load the file from a file pointer. @param a_fpFile Valid file pointer to read the file data from. The file will be read until end of file. @return SI_Error See error definitions */ SI_Error LoadFile(FILE *a_fpFile); #ifdef SI_SUPPORT_IOSTREAMS /** Load INI file data from an istream. @param a_istream Stream to read from @return SI_Error See error definitions */ SI_Error LoadData(std::istream &a_istream); #endif // SI_SUPPORT_IOSTREAMS /** Load INI file data direct from a std::string @param a_strData Data to be loaded @return SI_Error See error definitions */ SI_Error LoadData(const std::string &a_strData) { return LoadData(a_strData.c_str(), a_strData.size()); } /** Load INI file data direct from memory @param a_pData Data to be loaded @param a_uDataLen Length of the data in bytes @return SI_Error See error definitions */ SI_Error LoadData(const char *a_pData, size_t a_uDataLen); /*-----------------------------------------------------------------------*/ /** @} @{ @name Saving INI Data */ /** Save an INI file from memory to disk @param a_pszFile Path of the file to be saved. This will be passed to fopen() and so must be a valid path for the current platform. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this parameter is ignored. @return SI_Error See error definitions */ SI_Error SaveFile(const char *a_pszFile, bool a_bAddSignature = true) const; #ifdef SI_HAS_WIDE_FILE /** Save an INI file from memory to disk @param a_pwszFile Path of the file to be saved in UTF-16. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this parameter is ignored. @return SI_Error See error definitions */ SI_Error SaveFile(const SI_WCHAR_T *a_pwszFile, bool a_bAddSignature = true) const; #endif // _WIN32 /** Save the INI data to a file. See Save() for details. @param a_pFile Handle to a file. File should be opened for binary output. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the file. @return SI_Error See error definitions */ SI_Error SaveFile(FILE *a_pFile, bool a_bAddSignature = false) const; /** Save the INI data. The data will be written to the output device in a format appropriate to the current data, selected by: <table> <tr><th>SI_CHAR <th>FORMAT <tr><td>char <td>same format as when loaded (MBCS or UTF-8) <tr><td>wchar_t <td>UTF-8 <tr><td>other <td>UTF-8 </table> Note that comments from the original data is preserved as per the documentation on comments. The order of the sections and values from the original file will be preserved. Any data prepended or appended to the output device must use the the same format (MBCS or UTF-8). You may use the GetConverter() method to convert text to the correct format regardless of the output format being used by SimpleIni. To add a BOM to UTF-8 data, write it out manually at the very beginning like is done in SaveFile when a_bUseBOM is true. @param a_oOutput Output writer to write the data to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the OutputWriter. @return SI_Error See error definitions */ SI_Error Save(OutputWriter &a_oOutput, bool a_bAddSignature = false) const; #ifdef SI_SUPPORT_IOSTREAMS /** Save the INI data to an ostream. See Save() for details. @param a_ostream String to have the INI data appended to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the stream. @return SI_Error See error definitions */ SI_Error Save(std::ostream &a_ostream, bool a_bAddSignature = false) const { StreamWriter writer(a_ostream); return Save(writer, a_bAddSignature); } #endif // SI_SUPPORT_IOSTREAMS /** Append the INI data to a string. See Save() for details. @param a_sBuffer String to have the INI data appended to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the string. @return SI_Error See error definitions */ SI_Error Save(std::string &a_sBuffer, bool a_bAddSignature = false) const { StringWriter writer(a_sBuffer); return Save(writer, a_bAddSignature); } /*-----------------------------------------------------------------------*/ /** @} @{ @name Accessing INI Data */ /** Retrieve all section names. The list is returned as an STL vector of names and can be iterated or searched as necessary. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these pointers are in use! @param a_names Vector that will receive all of the section names. See note above! */ void GetAllSections(TNamesDepend &a_names) const; /** Retrieve all unique key names in a section. The sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. Only unique key names are returned. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use! @param a_pSection Section to request data for @param a_names List that will receive all of the key names. See note above! @return true Section was found. @return false Matching section was not found. */ bool GetAllKeys(const SI_CHAR *a_pSection, TNamesDepend &a_names) const; /** Retrieve all values for a specific key. This method can be used when multiple keys are both enabled and disabled. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. NOTE! The returned values are pointers to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer! @param a_pSection Section to search @param a_pKey Key to search for @param a_values List to return if the key is not found @return true Key was found. @return false Matching section/key was not found. */ bool GetAllValues(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, TNamesDepend &a_values) const; /** Query the number of keys in a specific section. Note that if multiple keys are enabled, then this value may be different to the number of keys returned by GetAllKeys. @param a_pSection Section to request data for @return -1 Section does not exist in the file @return >=0 Number of keys in the section */ int GetSectionSize(const SI_CHAR *a_pSection) const; /** Retrieve all key and value pairs for a section. The data is returned as a pointer to an STL map and can be iterated or searched as desired. Note that multiple entries for the same key may exist when multiple keys have been enabled. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use! @param a_pSection Name of the section to return @return boolean Was a section matching the supplied name found. */ const TKeyVal *GetSection(const SI_CHAR *a_pSection) const; /** Retrieve the value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. NOTE! The returned value is a pointer to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer! @param a_pSection Section to search @param a_pKey Key to search for @param a_pDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_pDefault Key was not found in the section @return other Value of the key */ const SI_CHAR *GetValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pDefault = NULL, bool *a_pHasMultiple = NULL) const; /** Retrieve a numeric value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. @param a_pSection Section to search @param a_pKey Key to search for @param a_nDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ long GetLongValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nDefault = 0, bool *a_pHasMultiple = NULL) const; /** Retrieve a numeric value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. @param a_pSection Section to search @param a_pKey Key to search for @param a_nDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ double GetDoubleValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nDefault = 0, bool *a_pHasMultiple = NULL) const; /** Retrieve a boolean value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. Strings starting with "t", "y", "on" or "1" are returned as logically true. Strings starting with "f", "n", "of" or "0" are returned as logically false. For all other values the default is returned. Character comparisons are case-insensitive. @param a_pSection Section to search @param a_pKey Key to search for @param a_bDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ bool GetBoolValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bDefault = false, bool *a_pHasMultiple = NULL) const; /** Add or update a section or value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. Set to NULL to create an empty section. @param a_pValue Value to set. Set to NULL to create an empty section. @param a_pComment Comment to be associated with the section or the key. If a_pKey is NULL then it will be associated with the section, otherwise the key. Note that a comment may be set ONLY when the section or key is first created (i.e. when this function returns the value SI_INSERTED). If you wish to create a section with a comment then you need to create the section separately to the key. The comment string must be in full comment form already (have a comment character starting every line). @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetValue and SetValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pValue, const SI_CHAR *a_pComment = NULL, bool a_bForceReplace = false) { return AddEntry(a_pSection, a_pKey, a_pValue, a_pComment, a_bForceReplace, true); } /** Add or update a numeric value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_nValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bUseHex By default the value will be written to the file in decimal format. Set this to true to write it as hexadecimal. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetLongValue and SetLongValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetLongValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nValue, const SI_CHAR *a_pComment = NULL, bool a_bUseHex = false, bool a_bForceReplace = false); /** Add or update a double value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_nValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetDoubleValue and SetDoubleValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetDoubleValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nValue, const SI_CHAR *a_pComment = NULL, bool a_bForceReplace = false); /** Add or update a boolean value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_bValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetBoolValue and SetBoolValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetBoolValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bValue, const SI_CHAR *a_pComment = NULL, bool a_bForceReplace = false); /** Delete an entire section, or a key from a section. Note that the data returned by GetSection is invalid and must not be used after anything has been deleted from that section using this method. Note when multiple keys is enabled, this will delete all keys with that name; there is no way to selectively delete individual key/values in this situation. @param a_pSection Section to delete key from, or if a_pKey is NULL, the section to remove. @param a_pKey Key to remove from the section. Set to NULL to remove the entire section. @param a_bRemoveEmpty If the section is empty after this key has been deleted, should the empty section be removed? @return true Key or section was deleted. @return false Key or section was not found. */ bool Delete(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bRemoveEmpty = false); /*-----------------------------------------------------------------------*/ /** @} @{ @name Converter */ /** Return a conversion object to convert text to the same encoding as is used by the Save(), SaveFile() and SaveString() functions. Use this to prepare the strings that you wish to append or prepend to the output INI data. */ Converter GetConverter() const { return Converter(m_bStoreIsUtf8); } /*-----------------------------------------------------------------------*/ /** @} */ private: // copying is not permitted CSimpleIniTempl(const CSimpleIniTempl &); // disabled CSimpleIniTempl &operator=(const CSimpleIniTempl &); // disabled /** Parse the data looking for a file comment and store it if found. */ SI_Error FindFileComment(SI_CHAR *&a_pData, bool a_bCopyStrings); /** Parse the data looking for the next valid entry. The memory pointed to by a_pData is modified by inserting NULL characters. The pointer is updated to the current location in the block of text. */ bool FindEntry(SI_CHAR *&a_pData, const SI_CHAR *&a_pSection, const SI_CHAR *&a_pKey, const SI_CHAR *&a_pVal, const SI_CHAR *&a_pComment) const; /** Add the section/key/value to our data. @param a_pSection Section name. Sections will be created if they don't already exist. @param a_pKey Key name. May be NULL to create an empty section. Existing entries will be updated. New entries will be created. @param a_pValue Value for the key. @param a_pComment Comment to be associated with the section or the key. If a_pKey is NULL then it will be associated with the section, otherwise the key. This must be a string in full comment form already (have a comment character starting every line). @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/AddEntry and AddEntry with a_bForceReplace = true, is that the load order and comment will be preserved this way. @param a_bCopyStrings Should copies of the strings be made or not. If false then the pointers will be used as is. */ SI_Error AddEntry(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pValue, const SI_CHAR *a_pComment, bool a_bForceReplace, bool a_bCopyStrings); /** Is the supplied character a whitespace character? */ inline bool IsSpace(SI_CHAR ch) const { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'); } /** Does the supplied character start a comment line? */ inline bool IsComment(SI_CHAR ch) const { return (ch == ';' || ch == '#'); } /** Skip over a newline character (or characters) for either DOS or UNIX */ inline void SkipNewLine(SI_CHAR *&a_pData) const { a_pData += (*a_pData == '\r' && *(a_pData + 1) == '\n') ? 2 : 1; } /** Make a copy of the supplied string, replacing the original pointer */ SI_Error CopyString(const SI_CHAR *&a_pString); /** Delete a string from the copied strings buffer if necessary */ void DeleteString(const SI_CHAR *a_pString); /** Internal use of our string comparison function */ bool IsLess(const SI_CHAR *a_pLeft, const SI_CHAR *a_pRight) const { const static SI_STRLESS isLess = SI_STRLESS(); return isLess(a_pLeft, a_pRight); } bool IsMultiLineTag(const SI_CHAR *a_pData) const; bool IsMultiLineData(const SI_CHAR *a_pData) const; bool LoadMultiLineText(SI_CHAR *&a_pData, const SI_CHAR *&a_pVal, const SI_CHAR *a_pTagName, bool a_bAllowBlankLinesInComment = false) const; bool IsNewLineChar(SI_CHAR a_c) const; bool OutputMultiLineText(OutputWriter &a_oOutput, Converter &a_oConverter, const SI_CHAR *a_pText) const; private: /** Copy of the INI file data in our character format. This will be modified when parsed to have NULL characters added after all interesting string entries. All of the string pointers to sections, keys and values point into this block of memory. */ SI_CHAR *m_pData; /** Length of the data that we have stored. Used when deleting strings to determine if the string is stored here or in the allocated string buffer. */ size_t m_uDataLen; /** File comment for this data, if one exists. */ const SI_CHAR *m_pFileComment; /** Parsed INI data. Section -> (Key -> Value). */ TSection m_data; /** This vector stores allocated memory for copies of strings that have been supplied after the file load. It will be empty unless SetValue() has been called. */ TNamesDepend m_strings; /** Is the format of our datafile UTF-8 or MBCS? */ bool m_bStoreIsUtf8; /** Are multiple values permitted for the same key? */ bool m_bAllowMultiKey; /** Are data values permitted to span multiple lines? */ bool m_bAllowMultiLine; /** Should spaces be written out surrounding the equals sign? */ bool m_bSpaces; /** Next order value, used to ensure sections and keys are output in the same order that they are loaded/added. */ int m_nOrder; }; // --------------------------------------------------------------------------- // IMPLEMENTATION // --------------------------------------------------------------------------- template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::CSimpleIniTempl(bool a_bIsUtf8, bool a_bAllowMultiKey, bool a_bAllowMultiLine) : m_pData(0), m_uDataLen(0), m_pFileComment(NULL), m_bStoreIsUtf8(a_bIsUtf8), m_bAllowMultiKey(a_bAllowMultiKey), m_bAllowMultiLine(a_bAllowMultiLine), m_bSpaces(true), m_nOrder(0) {} template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::~CSimpleIniTempl() { Reset(); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::Reset() { // remove all data delete[] m_pData; m_pData = NULL; m_uDataLen = 0; m_pFileComment = NULL; if (!m_data.empty()) { m_data.erase(m_data.begin(), m_data.end()); } // remove all strings if (!m_strings.empty()) { typename TNamesDepend::iterator i = m_strings.begin(); for (; i != m_strings.end(); ++i) { delete[] const_cast<SI_CHAR *>(i->pItem); } m_strings.erase(m_strings.begin(), m_strings.end()); } } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(const char *a_pszFile) { FILE *fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE fopen_s(&fp, a_pszFile, "rb"); #else // !__STDC_WANT_SECURE_LIB__ fp = fopen(a_pszFile, "rb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) { return SI_FILE; } SI_Error rc = LoadFile(fp); fclose(fp); return rc; } #ifdef SI_HAS_WIDE_FILE template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(const SI_WCHAR_T *a_pwszFile) { #ifdef _WIN32 FILE *fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE _wfopen_s(&fp, a_pwszFile, L"rb"); #else // !__STDC_WANT_SECURE_LIB__ fp = _wfopen(a_pwszFile, L"rb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = LoadFile(fp); fclose(fp); return rc; #else // !_WIN32 (therefore SI_CONVERT_ICU) char szFile[256]; u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); return LoadFile(szFile); #endif // _WIN32 } #endif // SI_HAS_WIDE_FILE template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(FILE *a_fpFile) { // load the raw file data int retval = fseek(a_fpFile, 0, SEEK_END); if (retval != 0) { return SI_FILE; } long lSize = ftell(a_fpFile); if (lSize < 0) { return SI_FILE; } if (lSize == 0) { return SI_OK; } // allocate and ensure NULL terminated char *pData = new char[lSize + 1]; if (!pData) { return SI_NOMEM; } pData[lSize] = 0; // load data into buffer fseek(a_fpFile, 0, SEEK_SET); size_t uRead = fread(pData, sizeof(char), lSize, a_fpFile); if (uRead != (size_t)lSize) { delete[] pData; return SI_FILE; } // convert the raw data to unicode SI_Error rc = LoadData(pData, uRead); delete[] pData; return rc; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadData(const char *a_pData, size_t a_uDataLen) { SI_CONVERTER converter(m_bStoreIsUtf8); if (a_uDataLen == 0) { return SI_OK; } // consume the UTF-8 BOM if it exists if (m_bStoreIsUtf8 && a_uDataLen >= 3) { if (memcmp(a_pData, SI_UTF8_SIGNATURE, 3) == 0) { a_pData += 3; a_uDataLen -= 3; } } // determine the length of the converted data size_t uLen = converter.SizeFromStore(a_pData, a_uDataLen); if (uLen == (size_t)(-1)) { return SI_FAIL; } // allocate memory for the data, ensure that there is a NULL // terminator wherever the converted data ends SI_CHAR *pData = new SI_CHAR[uLen + 1]; if (!pData) { return SI_NOMEM; } memset(pData, 0, sizeof(SI_CHAR) * (uLen + 1)); // convert the data if (!converter.ConvertFromStore(a_pData, a_uDataLen, pData, uLen)) { delete[] pData; return SI_FAIL; } // parse it const static SI_CHAR empty = 0; SI_CHAR *pWork = pData; const SI_CHAR *pSection = &empty; const SI_CHAR *pItem = NULL; const SI_CHAR *pVal = NULL; const SI_CHAR *pComment = NULL; // We copy the strings if we are loading data into this class when we // already have stored some. bool bCopyStrings = (m_pData != NULL); // find a file comment if it exists, this is a comment that starts at the // beginning of the file and continues until the first blank line. SI_Error rc = FindFileComment(pWork, bCopyStrings); if (rc < 0) return rc; // add every entry in the file to the data table while (FindEntry(pWork, pSection, pItem, pVal, pComment)) { rc = AddEntry(pSection, pItem, pVal, pComment, false, bCopyStrings); if (rc < 0) return rc; } // store these strings if we didn't copy them if (bCopyStrings) { delete[] pData; } else { m_pData = pData; m_uDataLen = uLen + 1; } return SI_OK; } #ifdef SI_SUPPORT_IOSTREAMS template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadData(std::istream &a_istream) { std::string strData; char szBuf[512]; do { a_istream.get(szBuf, sizeof(szBuf), '\0'); strData.append(szBuf); } while (a_istream.good()); return LoadData(strData); } #endif // SI_SUPPORT_IOSTREAMS template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::FindFileComment(SI_CHAR *&a_pData, bool a_bCopyStrings) { // there can only be a single file comment if (m_pFileComment) { return SI_OK; } // Load the file comment as multi-line text, this will modify all of // the newline characters to be single \n chars if (!LoadMultiLineText(a_pData, m_pFileComment, NULL, false)) { return SI_OK; } // copy the string if necessary if (a_bCopyStrings) { SI_Error rc = CopyString(m_pFileComment); if (rc < 0) return rc; } return SI_OK; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::FindEntry(SI_CHAR *&a_pData, const SI_CHAR *&a_pSection, const SI_CHAR *&a_pKey, const SI_CHAR *&a_pVal, const SI_CHAR *&a_pComment) const { a_pComment = NULL; SI_CHAR *pTrail = NULL; while (*a_pData) { // skip spaces and empty lines while (*a_pData && IsSpace(*a_pData)) { ++a_pData; } if (!*a_pData) { break; } // skip processing of comment lines but keep a pointer to // the start of the comment. if (IsComment(*a_pData)) { LoadMultiLineText(a_pData, a_pComment, NULL, true); continue; } // process section names if (*a_pData == '[') { // skip leading spaces ++a_pData; while (*a_pData && IsSpace(*a_pData)) { ++a_pData; } // find the end of the section name (it may contain spaces) // and convert it to lowercase as necessary a_pSection = a_pData; while (*a_pData && *a_pData != ']' && !IsNewLineChar(*a_pData)) { ++a_pData; } // if it's an invalid line, just skip it if (*a_pData != ']') { continue; } // remove trailing spaces from the section pTrail = a_pData - 1; while (pTrail >= a_pSection && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // skip to the end of the line ++a_pData; // safe as checked that it == ']' above while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } a_pKey = NULL; a_pVal = NULL; return true; } // find the end of the key name (it may contain spaces) // and convert it to lowercase as necessary a_pKey = a_pData; while (*a_pData && *a_pData != '=' && !IsNewLineChar(*a_pData)) { ++a_pData; } // if it's an invalid line, just skip it if (*a_pData != '=') { continue; } // empty keys are invalid if (a_pKey == a_pData) { while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } continue; } // remove trailing spaces from the key pTrail = a_pData - 1; while (pTrail >= a_pKey && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // skip leading whitespace on the value ++a_pData; // safe as checked that it == '=' above while (*a_pData && !IsNewLineChar(*a_pData) && IsSpace(*a_pData)) { ++a_pData; } // find the end of the value which is the end of this line a_pVal = a_pData; while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } // remove trailing spaces from the value pTrail = a_pData - 1; if (*a_pData) { // prepare for the next round SkipNewLine(a_pData); } while (pTrail >= a_pVal && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // check for multi-line entries if (m_bAllowMultiLine && IsMultiLineTag(a_pVal)) { // skip the "<<<" to get the tag that will end the multiline const SI_CHAR *pTagName = a_pVal + 3; return LoadMultiLineText(a_pData, a_pVal, pTagName); } // return the standard entry return true; } return false; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::IsMultiLineTag(const SI_CHAR *a_pVal) const { // check for the "<<<" prefix for a multi-line entry if (*a_pVal++ != '<') return false; if (*a_pVal++ != '<') return false; if (*a_pVal++ != '<') return false; return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::IsMultiLineData(const SI_CHAR *a_pData) const { // data is multi-line if it has any of the following features: // * whitespace prefix // * embedded newlines // * whitespace suffix // empty string if (!*a_pData) { return false; } // check for prefix if (IsSpace(*a_pData)) { return true; } // embedded newlines while (*a_pData) { if (IsNewLineChar(*a_pData)) { return true; } ++a_pData; } // check for suffix if (IsSpace(*--a_pData)) { return true; } return false; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::IsNewLineChar(SI_CHAR a_c) const { return (a_c == '\n' || a_c == '\r'); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadMultiLineText(SI_CHAR *&a_pData, const SI_CHAR *&a_pVal, const SI_CHAR *a_pTagName, bool a_bAllowBlankLinesInComment) const { // we modify this data to strip all newlines down to a single '\n' // character. This means that on Windows we need to strip out some // characters which will make the data shorter. // i.e. LINE1-LINE1\r\nLINE2-LINE2\0 will become // LINE1-LINE1\nLINE2-LINE2\0 // The pDataLine entry is the pointer to the location in memory that // the current line needs to start to run following the existing one. // This may be the same as pCurrLine in which case no move is needed. SI_CHAR *pDataLine = a_pData; SI_CHAR *pCurrLine; // value starts at the current line a_pVal = a_pData; // find the end tag. This tag must start in column 1 and be // followed by a newline. No whitespace removal is done while // searching for this tag. SI_CHAR cEndOfLineChar = *a_pData; for (;;) { // if we are loading comments then we need a comment character as // the first character on every line if (!a_pTagName && !IsComment(*a_pData)) { // if we aren't allowing blank lines then we're done if (!a_bAllowBlankLinesInComment) { break; } // if we are allowing blank lines then we only include them // in this comment if another comment follows, so read ahead // to find out. SI_CHAR *pCurr = a_pData; int nNewLines = 0; while (IsSpace(*pCurr)) { if (IsNewLineChar(*pCurr)) { ++nNewLines; SkipNewLine(pCurr); } else { ++pCurr; } } // we have a comment, add the blank lines to the output // and continue processing from here if (IsComment(*pCurr)) { for (; nNewLines > 0; --nNewLines) *pDataLine++ = '\n'; a_pData = pCurr; continue; } // the comment ends here break; } // find the end of this line pCurrLine = a_pData; while (*a_pData && !IsNewLineChar(*a_pData)) ++a_pData; // move this line down to the location that it should be if necessary if (pDataLine < pCurrLine) { size_t nLen = (size_t)(a_pData - pCurrLine); memmove(pDataLine, pCurrLine, nLen * sizeof(SI_CHAR)); pDataLine[nLen] = '\0'; } // end the line with a NULL cEndOfLineChar = *a_pData; *a_pData = 0; // if are looking for a tag then do the check now. This is done before // checking for end of the data, so that if we have the tag at the end // of the data then the tag is removed correctly. if (a_pTagName && (!IsLess(pDataLine, a_pTagName) && !IsLess(a_pTagName, pDataLine))) { break; } // if we are at the end of the data then we just automatically end // this entry and return the current data. if (!cEndOfLineChar) { return true; } // otherwise we need to process this newline to ensure that it consists // of just a single \n character. pDataLine += (a_pData - pCurrLine); *a_pData = cEndOfLineChar; SkipNewLine(a_pData); *pDataLine++ = '\n'; } // if we didn't find a comment at all then return false if (a_pVal == a_pData) { a_pVal = NULL; return false; } // the data (which ends at the end of the last line) needs to be // null-terminated BEFORE before the newline character(s). If the // user wants a new line in the multi-line data then they need to // add an empty line before the tag. *--pDataLine = '\0'; // if looking for a tag and if we aren't at the end of the data, // then move a_pData to the start of the next line. if (a_pTagName && cEndOfLineChar) { SI_ASSERT(IsNewLineChar(cEndOfLineChar)); *a_pData = cEndOfLineChar; SkipNewLine(a_pData); } return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::CopyString(const SI_CHAR *&a_pString) { size_t uLen = 0; if (sizeof(SI_CHAR) == sizeof(char)) { uLen = strlen((const char *)a_pString); } else if (sizeof(SI_CHAR) == sizeof(wchar_t)) { uLen = wcslen((const wchar_t *)a_pString); } else { for (; a_pString[uLen]; ++uLen) /*loop*/ ; } ++uLen; // NULL character SI_CHAR *pCopy = new SI_CHAR[uLen]; if (!pCopy) { return SI_NOMEM; } memcpy(pCopy, a_pString, sizeof(SI_CHAR) * uLen); m_strings.push_back(pCopy); a_pString = pCopy; return SI_OK; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::AddEntry(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pValue, const SI_CHAR *a_pComment, bool a_bForceReplace, bool a_bCopyStrings) { SI_Error rc; bool bInserted = false; SI_ASSERT(!a_pComment || IsComment(*a_pComment)); // if we are copying strings then make a copy of the comment now // because we will need it when we add the entry. if (a_bCopyStrings && a_pComment) { rc = CopyString(a_pComment); if (rc < 0) return rc; } // create the section entry if necessary typename TSection::iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { // if the section doesn't exist then we need a copy as the // string needs to last beyond the end of this function if (a_bCopyStrings) { rc = CopyString(a_pSection); if (rc < 0) return rc; } // only set the comment if this is a section only entry Entry oSection(a_pSection, ++m_nOrder); if (a_pComment && (!a_pKey || !a_pValue)) { oSection.pComment = a_pComment; } typename TSection::value_type oEntry(oSection, TKeyVal()); typedef typename TSection::iterator SectionIterator; std::pair<SectionIterator, bool> i = m_data.insert(oEntry); iSection = i.first; bInserted = true; } if (!a_pKey || !a_pValue) { // section only entries are specified with pItem and pVal as NULL return bInserted ? SI_INSERTED : SI_UPDATED; } // check for existence of the key TKeyVal &keyval = iSection->second; typename TKeyVal::iterator iKey = keyval.find(a_pKey); // remove all existing entries but save the load order and // comment of the first entry int nLoadOrder = ++m_nOrder; if (iKey != keyval.end() && m_bAllowMultiKey && a_bForceReplace) { const SI_CHAR *pComment = NULL; while (iKey != keyval.end() && !IsLess(a_pKey, iKey->first.pItem)) { if (iKey->first.nOrder < nLoadOrder) { nLoadOrder = iKey->first.nOrder; pComment = iKey->first.pComment; } ++iKey; } if (pComment) { DeleteString(a_pComment); a_pComment = pComment; (void)CopyString(a_pComment); } Delete(a_pSection, a_pKey); iKey = keyval.end(); } // make string copies if necessary bool bForceCreateNewKey = m_bAllowMultiKey && !a_bForceReplace; if (a_bCopyStrings) { if (bForceCreateNewKey || iKey == keyval.end()) { // if the key doesn't exist then we need a copy as the // string needs to last beyond the end of this function // because we will be inserting the key next rc = CopyString(a_pKey); if (rc < 0) return rc; } // we always need a copy of the value rc = CopyString(a_pValue); if (rc < 0) return rc; } // create the key entry if (iKey == keyval.end() || bForceCreateNewKey) { Entry oKey(a_pKey, nLoadOrder); if (a_pComment) { oKey.pComment = a_pComment; } typename TKeyVal::value_type oEntry(oKey, static_cast<const SI_CHAR *>(NULL)); iKey = keyval.insert(oEntry); bInserted = true; } iKey->second = a_pValue; return bInserted ? SI_INSERTED : SI_UPDATED; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> const SI_CHAR *CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pDefault, bool *a_pHasMultiple) const { if (a_pHasMultiple) { *a_pHasMultiple = false; } if (!a_pSection || !a_pKey) { return a_pDefault; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return a_pDefault; } typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return a_pDefault; } // check for multiple entries with the same key if (m_bAllowMultiKey && a_pHasMultiple) { typename TKeyVal::const_iterator iTemp = iKeyVal; if (++iTemp != iSection->second.end()) { if (!IsLess(a_pKey, iTemp->first.pItem)) { *a_pHasMultiple = true; } } } return iKeyVal->second; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> long CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetLongValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nDefault, bool *a_pHasMultiple) const { // return the default if we don't have a value const SI_CHAR *pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_nDefault; // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII char szValue[64] = {0}; SI_CONVERTER c(m_bStoreIsUtf8); if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { return a_nDefault; } // handle the value as hex if prefaced with "0x" long nValue = a_nDefault; char *pszSuffix = szValue; if (szValue[0] == '0' && (szValue[1] == 'x' || szValue[1] == 'X')) { if (!szValue[2]) return a_nDefault; nValue = strtol(&szValue[2], &pszSuffix, 16); } else { nValue = strtol(szValue, &pszSuffix, 10); } // any invalid strings will return the default value if (*pszSuffix) { return a_nDefault; } return nValue; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SetLongValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nValue, const SI_CHAR *a_pComment, bool a_bUseHex, bool a_bForceReplace) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string char szInput[64]; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE sprintf_s(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); #else // !__STDC_WANT_SECURE_LIB__ sprintf(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); #endif // __STDC_WANT_SECURE_LIB__ // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(szInput, strlen(szInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> double CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetDoubleValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nDefault, bool *a_pHasMultiple) const { // return the default if we don't have a value const SI_CHAR *pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_nDefault; // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII char szValue[64] = {0}; SI_CONVERTER c(m_bStoreIsUtf8); if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { return a_nDefault; } char *pszSuffix = NULL; double nValue = strtod(szValue, &pszSuffix); // any invalid strings will return the default value if (!pszSuffix || *pszSuffix) { return a_nDefault; } return nValue; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SetDoubleValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nValue, const SI_CHAR *a_pComment, bool a_bForceReplace) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string char szInput[64]; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE sprintf_s(szInput, "%f", a_nValue); #else // !__STDC_WANT_SECURE_LIB__ sprintf(szInput, "%f", a_nValue); #endif // __STDC_WANT_SECURE_LIB__ // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(szInput, strlen(szInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetBoolValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bDefault, bool *a_pHasMultiple) const { // return the default if we don't have a value const SI_CHAR *pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_bDefault; // we only look at the minimum number of characters switch (pszValue[0]) { case 't': case 'T': // true case 'y': case 'Y': // yes case '1': // 1 (one) return true; case 'f': case 'F': // false case 'n': case 'N': // no case '0': // 0 (zero) return false; case 'o': case 'O': if (pszValue[1] == 'n' || pszValue[1] == 'N') return true; // on if (pszValue[1] == 'f' || pszValue[1] == 'F') return false; // off break; } // no recognized value, return the default return a_bDefault; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SetBoolValue(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bValue, const SI_CHAR *a_pComment, bool a_bForceReplace) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string const char *pszInput = a_bValue ? "true" : "false"; // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(pszInput, strlen(pszInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetAllValues(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, TNamesDepend &a_values) const { a_values.clear(); if (!a_pSection || !a_pKey) { return false; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return false; } // insert all values for this key a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); if (m_bAllowMultiKey) { ++iKeyVal; while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)) { a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); ++iKeyVal; } } return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> int CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetSectionSize(const SI_CHAR *a_pSection) const { if (!a_pSection) { return -1; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return -1; } const TKeyVal &section = iSection->second; // if multi-key isn't permitted then the section size is // the number of keys that we have. if (!m_bAllowMultiKey || section.empty()) { return (int)section.size(); } // otherwise we need to count them int nCount = 0; const SI_CHAR *pLastKey = NULL; typename TKeyVal::const_iterator iKeyVal = section.begin(); for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n) { if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { ++nCount; pLastKey = iKeyVal->first.pItem; } } return nCount; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> const typename CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::TKeyVal * CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetSection(const SI_CHAR *a_pSection) const { if (a_pSection) { typename TSection::const_iterator i = m_data.find(a_pSection); if (i != m_data.end()) { return &(i->second); } } return 0; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetAllSections(TNamesDepend &a_names) const { a_names.clear(); typename TSection::const_iterator i = m_data.begin(); for (int n = 0; i != m_data.end(); ++i, ++n) { a_names.push_back(i->first); } } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::GetAllKeys(const SI_CHAR *a_pSection, TNamesDepend &a_names) const { a_names.clear(); if (!a_pSection) { return false; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } const TKeyVal &section = iSection->second; const SI_CHAR *pLastKey = NULL; typename TKeyVal::const_iterator iKeyVal = section.begin(); for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n) { if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { a_names.push_back(iKeyVal->first); pLastKey = iKeyVal->first.pItem; } } return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SaveFile(const char *a_pszFile, bool a_bAddSignature) const { FILE *fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE fopen_s(&fp, a_pszFile, "wb"); #else // !__STDC_WANT_SECURE_LIB__ fp = fopen(a_pszFile, "wb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = SaveFile(fp, a_bAddSignature); fclose(fp); return rc; } #ifdef SI_HAS_WIDE_FILE template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SaveFile(const SI_WCHAR_T *a_pwszFile, bool a_bAddSignature) const { #ifdef _WIN32 FILE *fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE _wfopen_s(&fp, a_pwszFile, L"wb"); #else // !__STDC_WANT_SECURE_LIB__ fp = _wfopen(a_pwszFile, L"wb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = SaveFile(fp, a_bAddSignature); fclose(fp); return rc; #else // !_WIN32 (therefore SI_CONVERT_ICU) char szFile[256]; u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); return SaveFile(szFile, a_bAddSignature); #endif // _WIN32 } #endif // SI_HAS_WIDE_FILE template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::SaveFile(FILE *a_pFile, bool a_bAddSignature) const { FileWriter writer(a_pFile); return Save(writer, a_bAddSignature); } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::Save(OutputWriter &a_oOutput, bool a_bAddSignature) const { Converter convert(m_bStoreIsUtf8); // add the UTF-8 signature if it is desired if (m_bStoreIsUtf8 && a_bAddSignature) { a_oOutput.Write(SI_UTF8_SIGNATURE); } // get all of the sections sorted in load order TNamesDepend oSections; GetAllSections(oSections); #if defined(_MSC_VER) && _MSC_VER <= 1200 oSections.sort(); #elif defined(__BORLANDC__) oSections.sort(Entry::LoadOrder()); #else oSections.sort(typename Entry::LoadOrder()); #endif // write the file comment if we have one bool bNeedNewLine = false; if (m_pFileComment) { if (!OutputMultiLineText(a_oOutput, convert, m_pFileComment)) { return SI_FAIL; } bNeedNewLine = true; } // iterate through our sections and output the data typename TNamesDepend::const_iterator iSection = oSections.begin(); for (; iSection != oSections.end(); ++iSection) { // write out the comment if there is one if (iSection->pComment) { if (bNeedNewLine) { a_oOutput.Write(SI_NEWLINE_A); a_oOutput.Write(SI_NEWLINE_A); } if (!OutputMultiLineText(a_oOutput, convert, iSection->pComment)) { return SI_FAIL; } bNeedNewLine = false; } if (bNeedNewLine) { a_oOutput.Write(SI_NEWLINE_A); a_oOutput.Write(SI_NEWLINE_A); bNeedNewLine = false; } // write the section (unless there is no section name) if (*iSection->pItem) { if (!convert.ConvertToStore(iSection->pItem)) { return SI_FAIL; } a_oOutput.Write("["); a_oOutput.Write(convert.Data()); a_oOutput.Write("]"); a_oOutput.Write(SI_NEWLINE_A); } // get all of the keys sorted in load order TNamesDepend oKeys; GetAllKeys(iSection->pItem, oKeys); #if defined(_MSC_VER) && _MSC_VER <= 1200 oKeys.sort(); #elif defined(__BORLANDC__) oKeys.sort(Entry::LoadOrder()); #else oKeys.sort(typename Entry::LoadOrder()); #endif // write all keys and values typename TNamesDepend::const_iterator iKey = oKeys.begin(); for (; iKey != oKeys.end(); ++iKey) { // get all values for this key TNamesDepend oValues; GetAllValues(iSection->pItem, iKey->pItem, oValues); typename TNamesDepend::const_iterator iValue = oValues.begin(); for (; iValue != oValues.end(); ++iValue) { // write out the comment if there is one if (iValue->pComment) { a_oOutput.Write(SI_NEWLINE_A); if (!OutputMultiLineText(a_oOutput, convert, iValue->pComment)) { return SI_FAIL; } } // write the key if (!convert.ConvertToStore(iKey->pItem)) { return SI_FAIL; } a_oOutput.Write(convert.Data()); // write the value if (!convert.ConvertToStore(iValue->pItem)) { return SI_FAIL; } a_oOutput.Write(m_bSpaces ? " = " : "="); if (m_bAllowMultiLine && IsMultiLineData(iValue->pItem)) { // multi-line data needs to be processed specially to ensure // that we use the correct newline format for the current system a_oOutput.Write("<<<END_OF_TEXT" SI_NEWLINE_A); if (!OutputMultiLineText(a_oOutput, convert, iValue->pItem)) { return SI_FAIL; } a_oOutput.Write("END_OF_TEXT"); } else { a_oOutput.Write(convert.Data()); } a_oOutput.Write(SI_NEWLINE_A); } } bNeedNewLine = true; } // Append new empty line a_oOutput.Write(SI_NEWLINE_A); return SI_OK; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::OutputMultiLineText(OutputWriter &a_oOutput, Converter &a_oConverter, const SI_CHAR *a_pText) const { const SI_CHAR *pEndOfLine; SI_CHAR cEndOfLineChar = *a_pText; while (cEndOfLineChar) { // find the end of this line pEndOfLine = a_pText; for (; *pEndOfLine && *pEndOfLine != '\n'; ++pEndOfLine) /*loop*/ ; cEndOfLineChar = *pEndOfLine; // temporarily null terminate, convert and output the line *const_cast<SI_CHAR *>(pEndOfLine) = 0; if (!a_oConverter.ConvertToStore(a_pText)) { return false; } *const_cast<SI_CHAR *>(pEndOfLine) = cEndOfLineChar; a_pText += (pEndOfLine - a_pText) + 1; a_oOutput.Write(a_oConverter.Data()); a_oOutput.Write(SI_NEWLINE_A); } return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::Delete(const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bRemoveEmpty) { if (!a_pSection) { return false; } typename TSection::iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } // remove a single key if we have a keyname if (a_pKey) { typename TKeyVal::iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return false; } // remove any copied strings and then the key typename TKeyVal::iterator iDelete; do { iDelete = iKeyVal++; DeleteString(iDelete->first.pItem); DeleteString(iDelete->second); iSection->second.erase(iDelete); } while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)); // done now if the section is not empty or we are not pruning away // the empty sections. Otherwise let it fall through into the section // deletion code if (!a_bRemoveEmpty || !iSection->second.empty()) { return true; } } else { // delete all copied strings from this section. The actual // entries will be removed when the section is removed. typename TKeyVal::iterator iKeyVal = iSection->second.begin(); for (; iKeyVal != iSection->second.end(); ++iKeyVal) { DeleteString(iKeyVal->first.pItem); DeleteString(iKeyVal->second); } } // delete the section itself DeleteString(iSection->first.pItem); m_data.erase(iSection); return true; } template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::DeleteString(const SI_CHAR *a_pString) { // strings may exist either inside the data block, or they will be // individually allocated and stored in m_strings. We only physically // delete those stored in m_strings. if (a_pString < m_pData || a_pString >= m_pData + m_uDataLen) { typename TNamesDepend::iterator i = m_strings.begin(); for (; i != m_strings.end(); ++i) { if (a_pString == i->pItem) { delete[] const_cast<SI_CHAR *>(i->pItem); m_strings.erase(i); break; } } } } // --------------------------------------------------------------------------- // CONVERSION FUNCTIONS // --------------------------------------------------------------------------- // Defines the conversion classes for different libraries. Before including // SimpleIni.h, set the converter that you wish you use by defining one of the // following symbols. // // SI_CONVERT_GENERIC Use the Unicode reference conversion library in // the accompanying files ConvertUTF.h/c // SI_CONVERT_ICU Use the IBM ICU conversion library. Requires // ICU headers on include path and icuuc.lib // SI_CONVERT_WIN32 Use the Win32 API functions for conversion. #if !defined(SI_CONVERT_GENERIC) && !defined(SI_CONVERT_WIN32) && !defined(SI_CONVERT_ICU) #ifdef _WIN32 #define SI_CONVERT_WIN32 #else #define SI_CONVERT_GENERIC #endif #endif /** * Generic case-sensitive less than comparison. This class returns numerically * ordered ASCII case-sensitive text for all possible sizes and types of * SI_CHAR. */ template <class SI_CHAR> struct SI_GenericCase { bool operator()(const SI_CHAR *pLeft, const SI_CHAR *pRight) const { long cmp; for (; *pLeft && *pRight; ++pLeft, ++pRight) { cmp = (long)*pLeft - (long)*pRight; if (cmp != 0) { return cmp < 0; } } return *pRight != 0; } }; /** * Generic ASCII case-insensitive less than comparison. This class returns * numerically ordered ASCII case-insensitive text for all possible sizes * and types of SI_CHAR. It is not safe for MBCS text comparison where * ASCII A-Z characters are used in the encoding of multi-byte characters. */ template <class SI_CHAR> struct SI_GenericNoCase { inline SI_CHAR locase(SI_CHAR ch) const { return (ch < 'A' || ch > 'Z') ? ch : (ch - 'A' + 'a'); } bool operator()(const SI_CHAR *pLeft, const SI_CHAR *pRight) const { long cmp; for (; *pLeft && *pRight; ++pLeft, ++pRight) { cmp = (long)locase(*pLeft) - (long)locase(*pRight); if (cmp != 0) { return cmp < 0; } } return *pRight != 0; } }; /** * Null conversion class for MBCS/UTF-8 to char (or equivalent). */ template <class SI_CHAR> class SI_ConvertA { bool m_bStoreIsUtf8; protected: SI_ConvertA() {} public: SI_ConvertA(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) {} /* copy and assignment */ SI_ConvertA(const SI_ConvertA &rhs) { operator=(rhs); } SI_ConvertA &operator=(const SI_ConvertA &rhs) { m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore(const char *a_pInputData, size_t a_uInputDataLen) { (void)a_pInputData; SI_ASSERT(a_uInputDataLen != (size_t)-1); // ASCII/MBCS/UTF-8 needs no conversion return a_uInputDataLen; } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore(const char *a_pInputData, size_t a_uInputDataLen, SI_CHAR *a_pOutputData, size_t a_uOutputDataSize) { // ASCII/MBCS/UTF-8 needs no conversion if (a_uInputDataLen > a_uOutputDataSize) { return false; } memcpy(a_pOutputData, a_pInputData, a_uInputDataLen); return true; } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore(const SI_CHAR *a_pInputData) { // ASCII/MBCS/UTF-8 needs no conversion return strlen((const char *)a_pInputData) + 1; } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_uOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore(const SI_CHAR *a_pInputData, char *a_pOutputData, size_t a_uOutputDataSize) { // calc input string length (SI_CHAR type and size independent) size_t uInputLen = strlen((const char *)a_pInputData) + 1; if (uInputLen > a_uOutputDataSize) { return false; } // ascii/UTF-8 needs no conversion memcpy(a_pOutputData, a_pInputData, uInputLen); return true; } }; // --------------------------------------------------------------------------- // SI_CONVERT_GENERIC // --------------------------------------------------------------------------- #ifdef SI_CONVERT_GENERIC #define SI_Case SI_GenericCase #define SI_NoCase SI_GenericNoCase #include <wchar.h> #include "ConvertUTF.h" /** * Converts UTF-8 to a wchar_t (or equivalent) using the Unicode reference * library functions. This can be used on all platforms. */ template <class SI_CHAR> class SI_ConvertW { bool m_bStoreIsUtf8; protected: SI_ConvertW() {} public: SI_ConvertW(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) {} /* copy and assignment */ SI_ConvertW(const SI_ConvertW &rhs) { operator=(rhs); } SI_ConvertW &operator=(const SI_ConvertW &rhs) { m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore(const char *a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t)-1); if (m_bStoreIsUtf8) { // worst case scenario for UTF-8 to wchar_t is 1 char -> 1 wchar_t // so we just return the same number of characters required as for // the source text. return a_uInputDataLen; } #if defined(SI_NO_MBSTOWCS_NULL) || (!defined(_MSC_VER) && !defined(_linux)) // fall back processing for platforms that don't support a NULL dest to mbstowcs // worst case scenario is 1:1, this will be a sufficient buffer size (void)a_pInputData; return a_uInputDataLen; #else // get the actual required buffer size return mbstowcs(NULL, a_pInputData, a_uInputDataLen); #endif } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore(const char *a_pInputData, size_t a_uInputDataLen, SI_CHAR *a_pOutputData, size_t a_uOutputDataSize) { if (m_bStoreIsUtf8) { // This uses the Unicode reference implementation to do the // conversion from UTF-8 to wchar_t. The required files are // ConvertUTF.h and ConvertUTF.c which should be included in // the distribution but are publically available from unicode.org // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ ConversionResult retval; const UTF8 *pUtf8 = (const UTF8 *)a_pInputData; if (sizeof(wchar_t) == sizeof(UTF32)) { UTF32 *pUtf32 = (UTF32 *)a_pOutputData; retval = ConvertUTF8toUTF32(&pUtf8, pUtf8 + a_uInputDataLen, &pUtf32, pUtf32 + a_uOutputDataSize, lenientConversion); } else if (sizeof(wchar_t) == sizeof(UTF16)) { UTF16 *pUtf16 = (UTF16 *)a_pOutputData; retval = ConvertUTF8toUTF16(&pUtf8, pUtf8 + a_uInputDataLen, &pUtf16, pUtf16 + a_uOutputDataSize, lenientConversion); } return retval == conversionOK; } // convert to wchar_t size_t retval = mbstowcs(a_pOutputData, a_pInputData, a_uOutputDataSize); return retval != (size_t)(-1); } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore(const SI_CHAR *a_pInputData) { if (m_bStoreIsUtf8) { // worst case scenario for wchar_t to UTF-8 is 1 wchar_t -> 6 char size_t uLen = 0; while (a_pInputData[uLen]) { ++uLen; } return (6 * uLen) + 1; } else { size_t uLen = wcstombs(NULL, a_pInputData, 0); if (uLen == (size_t)(-1)) { return uLen; } return uLen + 1; // include NULL terminator } } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_uOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore(const SI_CHAR *a_pInputData, char *a_pOutputData, size_t a_uOutputDataSize) { if (m_bStoreIsUtf8) { // calc input string length (SI_CHAR type and size independent) size_t uInputLen = 0; while (a_pInputData[uInputLen]) { ++uInputLen; } ++uInputLen; // include the NULL char // This uses the Unicode reference implementation to do the // conversion from wchar_t to UTF-8. The required files are // ConvertUTF.h and ConvertUTF.c which should be included in // the distribution but are publically available from unicode.org // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ ConversionResult retval; UTF8 *pUtf8 = (UTF8 *)a_pOutputData; if (sizeof(wchar_t) == sizeof(UTF32)) { const UTF32 *pUtf32 = (const UTF32 *)a_pInputData; retval = ConvertUTF32toUTF8(&pUtf32, pUtf32 + uInputLen, &pUtf8, pUtf8 + a_uOutputDataSize, lenientConversion); } else if (sizeof(wchar_t) == sizeof(UTF16)) { const UTF16 *pUtf16 = (const UTF16 *)a_pInputData; retval = ConvertUTF16toUTF8(&pUtf16, pUtf16 + uInputLen, &pUtf8, pUtf8 + a_uOutputDataSize, lenientConversion); } return retval == conversionOK; } else { size_t retval = wcstombs(a_pOutputData, a_pInputData, a_uOutputDataSize); return retval != (size_t)-1; } } }; #endif // SI_CONVERT_GENERIC // --------------------------------------------------------------------------- // SI_CONVERT_ICU // --------------------------------------------------------------------------- #ifdef SI_CONVERT_ICU #define SI_Case SI_GenericCase #define SI_NoCase SI_GenericNoCase #include <unicode/ucnv.h> /** * Converts MBCS/UTF-8 to UChar using ICU. This can be used on all platforms. */ template <class SI_CHAR> class SI_ConvertW { const char *m_pEncoding; UConverter *m_pConverter; protected: SI_ConvertW() : m_pEncoding(NULL), m_pConverter(NULL) {} public: SI_ConvertW(bool a_bStoreIsUtf8) : m_pConverter(NULL) { m_pEncoding = a_bStoreIsUtf8 ? "UTF-8" : NULL; } /* copy and assignment */ SI_ConvertW(const SI_ConvertW &rhs) { operator=(rhs); } SI_ConvertW &operator=(const SI_ConvertW &rhs) { m_pEncoding = rhs.m_pEncoding; m_pConverter = NULL; return *this; } ~SI_ConvertW() { if (m_pConverter) ucnv_close(m_pConverter); } /** Calculate the number of UChar required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to UChar. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of UChar required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore(const char *a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t)-1); UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return (size_t)-1; } } nError = U_ZERO_ERROR; int32_t nLen = ucnv_toUChars(m_pConverter, NULL, 0, a_pInputData, (int32_t)a_uInputDataLen, &nError); if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { return (size_t)-1; } return (size_t)nLen; } /** Convert the input string from the storage format to UChar. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to UChar. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in UChar. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore(const char *a_pInputData, size_t a_uInputDataLen, UChar *a_pOutputData, size_t a_uOutputDataSize) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return false; } } nError = U_ZERO_ERROR; ucnv_toUChars(m_pConverter, a_pOutputData, (int32_t)a_uOutputDataSize, a_pInputData, (int32_t)a_uInputDataLen, &nError); if (U_FAILURE(nError)) { return false; } return true; } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore(const UChar *a_pInputData) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return (size_t)-1; } } nError = U_ZERO_ERROR; int32_t nLen = ucnv_fromUChars(m_pConverter, NULL, 0, a_pInputData, -1, &nError); if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { return (size_t)-1; } return (size_t)nLen + 1; } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_pOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore(const UChar *a_pInputData, char *a_pOutputData, size_t a_uOutputDataSize) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return false; } } nError = U_ZERO_ERROR; ucnv_fromUChars(m_pConverter, a_pOutputData, (int32_t)a_uOutputDataSize, a_pInputData, -1, &nError); if (U_FAILURE(nError)) { return false; } return true; } }; #endif // SI_CONVERT_ICU // --------------------------------------------------------------------------- // SI_CONVERT_WIN32 // --------------------------------------------------------------------------- #ifdef SI_CONVERT_WIN32 #define SI_Case SI_GenericCase // Windows CE doesn't have errno or MBCS libraries #ifdef _WIN32_WCE #ifndef SI_NO_MBCS #define SI_NO_MBCS #endif #endif #include <windows.h> #ifdef SI_NO_MBCS #define SI_NoCase SI_GenericNoCase #else // !SI_NO_MBCS /** * Case-insensitive comparison class using Win32 MBCS functions. This class * returns a case-insensitive semi-collation order for MBCS text. It may not * be safe for UTF-8 text returned in char format as we don't know what * characters will be folded by the function! Therefore, if you are using * SI_CHAR == char and SetUnicode(true), then you need to use the generic * SI_NoCase class instead. */ #include <mbstring.h> template <class SI_CHAR> struct SI_NoCase { bool operator()(const SI_CHAR *pLeft, const SI_CHAR *pRight) const { if (sizeof(SI_CHAR) == sizeof(char)) { return _mbsicmp((const unsigned char *)pLeft, (const unsigned char *)pRight) < 0; } if (sizeof(SI_CHAR) == sizeof(wchar_t)) { return _wcsicmp((const wchar_t *)pLeft, (const wchar_t *)pRight) < 0; } return SI_GenericNoCase<SI_CHAR>()(pLeft, pRight); } }; #endif // SI_NO_MBCS /** * Converts MBCS and UTF-8 to a wchar_t (or equivalent) on Windows. This uses * only the Win32 functions and doesn't require the external Unicode UTF-8 * conversion library. It will not work on Windows 95 without using Microsoft * Layer for Unicode in your application. */ template <class SI_CHAR> class SI_ConvertW { UINT m_uCodePage; protected: SI_ConvertW() {} public: SI_ConvertW(bool a_bStoreIsUtf8) { m_uCodePage = a_bStoreIsUtf8 ? CP_UTF8 : CP_ACP; } /* copy and assignment */ SI_ConvertW(const SI_ConvertW &rhs) { operator=(rhs); } SI_ConvertW &operator=(const SI_ConvertW &rhs) { m_uCodePage = rhs.m_uCodePage; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore(const char *a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t)-1); int retval = MultiByteToWideChar(m_uCodePage, 0, a_pInputData, (int)a_uInputDataLen, 0, 0); return (size_t)(retval > 0 ? retval : -1); } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore(const char *a_pInputData, size_t a_uInputDataLen, SI_CHAR *a_pOutputData, size_t a_uOutputDataSize) { int nSize = MultiByteToWideChar(m_uCodePage, 0, a_pInputData, (int)a_uInputDataLen, (wchar_t *)a_pOutputData, (int)a_uOutputDataSize); return (nSize > 0); } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore(const SI_CHAR *a_pInputData) { int retval = WideCharToMultiByte(m_uCodePage, 0, (const wchar_t *)a_pInputData, -1, 0, 0, 0, 0); return (size_t)(retval > 0 ? retval : -1); } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_pOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore(const SI_CHAR *a_pInputData, char *a_pOutputData, size_t a_uOutputDataSize) { int retval = WideCharToMultiByte(m_uCodePage, 0, (const wchar_t *)a_pInputData, -1, a_pOutputData, (int)a_uOutputDataSize, 0, 0); return retval > 0; } }; #endif // SI_CONVERT_WIN32 // --------------------------------------------------------------------------- // TYPE DEFINITIONS // --------------------------------------------------------------------------- typedef CSimpleIniTempl<char, SI_NoCase<char>, SI_ConvertA<char>> CSimpleIniA; typedef CSimpleIniTempl<char, SI_Case<char>, SI_ConvertA<char>> CSimpleIniCaseA; #if defined(SI_CONVERT_ICU) typedef CSimpleIniTempl<UChar, SI_NoCase<UChar>, SI_ConvertW<UChar>> CSimpleIniW; typedef CSimpleIniTempl<UChar, SI_Case<UChar>, SI_ConvertW<UChar>> CSimpleIniCaseW; #else typedef CSimpleIniTempl<wchar_t, SI_NoCase<wchar_t>, SI_ConvertW<wchar_t>> CSimpleIniW; typedef CSimpleIniTempl<wchar_t, SI_Case<wchar_t>, SI_ConvertW<wchar_t>> CSimpleIniCaseW; #endif #ifdef _UNICODE #define CSimpleIni CSimpleIniW #define CSimpleIniCase CSimpleIniCaseW #define SI_NEWLINE SI_NEWLINE_W #else // !_UNICODE #define CSimpleIni CSimpleIniA #define CSimpleIniCase CSimpleIniCaseA #define SI_NEWLINE SI_NEWLINE_A #endif // _UNICODE #ifdef _MSC_VER #pragma warning(pop) #endif #endif // INCLUDED_SimpleIni_h
[ "gcontini@users.noreply.github.com" ]
gcontini@users.noreply.github.com
ab314fa96282c2fa9a4d8ed84bd170288868019f
47924885db91ffb9b6860c6a8886c84d5ed7aaa2
/1014.最佳观光组合.cpp
7f35e5c695b5835959fe7f2bdf89e81dfe35d867
[]
no_license
wanghuohuo0716/myleetcode
576711f88996358910cce5c2c5231d636bbf0242
743e2f44c3696339d8f959de47bca8416ccda63d
refs/heads/master
2020-09-13T07:41:29.291862
2020-03-14T03:50:33
2020-03-14T03:50:33
222,698,286
1
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
/* * @lc app=leetcode.cn id=1014 lang=cpp * * [1014] 最佳观光组合 */ #include <vector> using namespace std; // 此题的本质是求A[i] + A[j] + i - j的最大值,这个值可以解耦计算,分别计算A[i] + i与A[j] - j的最大值,然后求和即可 // 即维护两个变量记录这两个最大值,一遍遍历完后就知道了结果 // @lc code=start class Solution{ public: int maxScoreSightseeingPair(vector<int> &A){ int res = 0; int pre_max = A[0] + 0; // 初始值 for (int j = 1; j < A.size(); j++){ res = max(res, pre_max + A[j] - j); // 判断能否刷新res pre_max = max(pre_max, A[j] + j); // 判断能否刷新pre_max, 得到更大的A[i] + i } return res; } }; // @lc code=end
[ "wanghuohuo0716@outlook.com" ]
wanghuohuo0716@outlook.com
61e7bbd79fbfec7109bcec5a182f777dacee0202
0f5e7c855849f14588168134921632e06a373589
/Pods/gRPC-Core/src/core/lib/compression/stream_compression_gzip.cc
682f712843a5b6a0284c824546765b0795d78919
[ "MIT", "Apache-2.0" ]
permissive
vanshg/MacAssistant
477a743289a6ff34c8127d14c66ccfef4ca92a2c
a0c3b4fd6d01815159ca286b0bc135b0b55a5104
refs/heads/master
2023-03-07T18:11:18.372398
2023-03-05T23:23:34
2023-03-05T23:23:34
89,634,004
1,763
186
MIT
2020-09-22T18:54:18
2017-04-27T19:40:13
Swift
UTF-8
C++
false
false
7,989
cc
/* * * Copyright 2017 gRPC authors. * * 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 <grpc/support/port_platform.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/compression/stream_compression_gzip.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/slice/slice_internal.h" #define OUTPUT_BLOCK_SIZE (1024) typedef struct grpc_stream_compression_context_gzip { grpc_stream_compression_context base; z_stream zs; int (*flate)(z_stream* zs, int flush); } grpc_stream_compression_context_gzip; static bool gzip_flate(grpc_stream_compression_context_gzip* ctx, grpc_slice_buffer* in, grpc_slice_buffer* out, size_t* output_size, size_t max_output_size, int flush, bool* end_of_context) { GPR_ASSERT(flush == 0 || flush == Z_SYNC_FLUSH || flush == Z_FINISH); /* Full flush is not allowed when inflating. */ GPR_ASSERT(!(ctx->flate == inflate && (flush == Z_FINISH))); grpc_core::ExecCtx exec_ctx; int r; bool eoc = false; size_t original_max_output_size = max_output_size; while (max_output_size > 0 && (in->length > 0 || flush) && !eoc) { size_t slice_size = max_output_size < OUTPUT_BLOCK_SIZE ? max_output_size : OUTPUT_BLOCK_SIZE; grpc_slice slice_out = GRPC_SLICE_MALLOC(slice_size); ctx->zs.avail_out = static_cast<uInt>(slice_size); ctx->zs.next_out = GRPC_SLICE_START_PTR(slice_out); while (ctx->zs.avail_out > 0 && in->length > 0 && !eoc) { grpc_slice slice = grpc_slice_buffer_take_first(in); ctx->zs.avail_in = static_cast<uInt> GRPC_SLICE_LENGTH(slice); ctx->zs.next_in = GRPC_SLICE_START_PTR(slice); r = ctx->flate(&ctx->zs, Z_NO_FLUSH); if (r < 0 && r != Z_BUF_ERROR) { gpr_log(GPR_ERROR, "zlib error (%d)", r); grpc_slice_unref_internal(slice_out); return false; } else if (r == Z_STREAM_END && ctx->flate == inflate) { eoc = true; } if (ctx->zs.avail_in > 0) { grpc_slice_buffer_undo_take_first( in, grpc_slice_sub(slice, GRPC_SLICE_LENGTH(slice) - ctx->zs.avail_in, GRPC_SLICE_LENGTH(slice))); } grpc_slice_unref_internal(slice); } if (flush != 0 && ctx->zs.avail_out > 0 && !eoc) { GPR_ASSERT(in->length == 0); r = ctx->flate(&ctx->zs, flush); if (flush == Z_SYNC_FLUSH) { switch (r) { case Z_OK: /* Maybe flush is not complete; just made some partial progress. */ if (ctx->zs.avail_out > 0) { flush = 0; } break; case Z_BUF_ERROR: case Z_STREAM_END: flush = 0; break; default: gpr_log(GPR_ERROR, "zlib error (%d)", r); grpc_slice_unref_internal(slice_out); return false; } } else if (flush == Z_FINISH) { switch (r) { case Z_OK: case Z_BUF_ERROR: /* Wait for the next loop to assign additional output space. */ GPR_ASSERT(ctx->zs.avail_out == 0); break; case Z_STREAM_END: flush = 0; break; default: gpr_log(GPR_ERROR, "zlib error (%d)", r); grpc_slice_unref_internal(slice_out); return false; } } } if (ctx->zs.avail_out == 0) { grpc_slice_buffer_add(out, slice_out); } else if (ctx->zs.avail_out < slice_size) { size_t len = GRPC_SLICE_LENGTH(slice_out); GRPC_SLICE_SET_LENGTH(slice_out, len - ctx->zs.avail_out); grpc_slice_buffer_add(out, slice_out); } else { grpc_slice_unref_internal(slice_out); } max_output_size -= (slice_size - ctx->zs.avail_out); } if (end_of_context) { *end_of_context = eoc; } if (output_size) { *output_size = original_max_output_size - max_output_size; } return true; } static bool grpc_stream_compress_gzip(grpc_stream_compression_context* ctx, grpc_slice_buffer* in, grpc_slice_buffer* out, size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush) { if (ctx == nullptr) { return false; } grpc_stream_compression_context_gzip* gzip_ctx = reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx); GPR_ASSERT(gzip_ctx->flate == deflate); int gzip_flush; switch (flush) { case GRPC_STREAM_COMPRESSION_FLUSH_NONE: gzip_flush = 0; break; case GRPC_STREAM_COMPRESSION_FLUSH_SYNC: gzip_flush = Z_SYNC_FLUSH; break; case GRPC_STREAM_COMPRESSION_FLUSH_FINISH: gzip_flush = Z_FINISH; break; default: gzip_flush = 0; } return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, gzip_flush, nullptr); } static bool grpc_stream_decompress_gzip(grpc_stream_compression_context* ctx, grpc_slice_buffer* in, grpc_slice_buffer* out, size_t* output_size, size_t max_output_size, bool* end_of_context) { if (ctx == nullptr) { return false; } grpc_stream_compression_context_gzip* gzip_ctx = reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx); GPR_ASSERT(gzip_ctx->flate == inflate); return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, Z_SYNC_FLUSH, end_of_context); } static grpc_stream_compression_context* grpc_stream_compression_context_create_gzip( grpc_stream_compression_method method) { GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_GZIP_COMPRESS || method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS); grpc_stream_compression_context_gzip* gzip_ctx = static_cast<grpc_stream_compression_context_gzip*>( gpr_zalloc(sizeof(grpc_stream_compression_context_gzip))); int r; if (gzip_ctx == nullptr) { return nullptr; } if (method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS) { r = inflateInit2(&gzip_ctx->zs, 0x1F); gzip_ctx->flate = inflate; } else { r = deflateInit2(&gzip_ctx->zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 0x1F, 8, Z_DEFAULT_STRATEGY); gzip_ctx->flate = deflate; } if (r != Z_OK) { gpr_free(gzip_ctx); return nullptr; } gzip_ctx->base.vtable = &grpc_stream_compression_gzip_vtable; return reinterpret_cast<grpc_stream_compression_context*>(gzip_ctx); } static void grpc_stream_compression_context_destroy_gzip( grpc_stream_compression_context* ctx) { if (ctx == nullptr) { return; } grpc_stream_compression_context_gzip* gzip_ctx = reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx); if (gzip_ctx->flate == inflate) { inflateEnd(&gzip_ctx->zs); } else { deflateEnd(&gzip_ctx->zs); } gpr_free(ctx); } const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable = { grpc_stream_compress_gzip, grpc_stream_decompress_gzip, grpc_stream_compression_context_create_gzip, grpc_stream_compression_context_destroy_gzip};
[ "vansh.gandhi@gmail.com" ]
vansh.gandhi@gmail.com
0b0c51affa591f691c50eae4b2e8b392c0252891
deeff44aa20aa4202c5bbaa21ac04873f8e5318a
/ExplicitSolver.h
e62aa574b7a2c8c051c1f73432a7443a904f92ee
[]
no_license
dsbabkov/FiniteDifferenceMethod
82958181a83ccb9ed1371a244cec52e29af0aac4
1d0164e495df8d23f2140d9910c5ec9dc8437f6e
refs/heads/master
2021-01-20T22:05:15.289037
2016-08-18T14:14:12
2016-08-18T14:14:12
65,534,545
1
0
null
null
null
null
UTF-8
C++
false
false
426
h
#pragma once #include "AbstractSolver.h" #include <QObject> class ExplicitSolver: public AbstractSolver { Q_OBJECT Q_DISABLE_COPY(ExplicitSolver) public: ExplicitSolver(); virtual ~ExplicitSolver() override; virtual void solve() override; private: void computeLayer(); double computedValue(arma::uword j) const; double dUdX(arma::uword j) const; double d2UdX2(arma::uword j) const; };
[ "dsbabkov@gmail.com" ]
dsbabkov@gmail.com
45f252640e7963d1578e26462f4f08acbef7294c
ff231fed44ad0c0b3b9f1eec3a13400f89ea1fcb
/include/galaxy.h
1ab10453d36b0d32ebbf2ae1a2a2878f3e9ffb29
[ "MIT" ]
permissive
dpearson1983/SHELLBI
bad5ecd1ad7dfcec0308d97fe13ddd5a48d2acfe
360509baf5cd03765751f3fbff15d4f0b060cb7a
refs/heads/master
2020-03-26T19:03:48.055295
2018-08-18T19:23:37
2018-08-18T19:23:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
798
h
#ifndef _GALAXY_H_ #define _GALAXY_H_ #include <vector> #include <gsl/gsl_integration.h> #include "cosmology.h" #include "tpods.h" class galaxy{ double ra, dec, red, w, nbar; vec3<double> cart; bool cart_set; public: galaxy(double RA, double DEC, double RED, double NZ, double W); void bin(std::vector<double> &delta, vec3<int> N, vec3<double> L, vec3<double> r_min, cosmology &cosmo, vec3<double> &pk_nbw, vec3<double> &bk_nbw, gsl_integration_workspace *ws); void set_cartesian(cosmology &cosmo, vec3<double> r_min, gsl_integration_workspace *ws); vec3<double> get_unshifted_cart(cosmology &cosmo, gsl_integration_workspace *ws); vec3<double> get_cart(); }; #endif
[ "dpearson@localhost.localdomain" ]
dpearson@localhost.localdomain
7c3948b1d49314a0e634dd9c5df05754ca634c43
13b43eedd2f00f5195c2def8951760d5338be24f
/main.cpp
14f7589819c18ece51083fe6f74cc63a7b2f4609
[]
no_license
y894577/Nanhai_Guide
1a880cb65b7e76a3db805cffa0c70121958cdba5
cdb4e14a13045ad5d221c03fdb981adc5d3f377c
refs/heads/master
2020-09-24T14:37:13.618267
2019-12-04T08:20:12
2019-12-04T08:20:12
225,782,202
2
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include "mainwindow.h" #include "main_welcome.h" #include "test.h" #include "mgraph.h" #include <QApplication> #include <QPushButton> #include <QDebug> #include <QSpinBox> #include <QSlider> #include <QLayout> #include <QMainWindow> #include <QQuickWidget> #include <QUrl> #include <QtQuickControls2> #include <QDesktopWidget> #include <QtQml> Q_INVOKABLE int main(int argc, char *argv[]); int main(int argc, char *argv[]) { QApplication a(argc, argv); //定义类型 qmlRegisterType<MainWindow>("MainWindow",1,0,"Main"); //主窗口 MainWindow *view = new MainWindow(); view->enter(); return a.exec(); }
[ "44811269+y894577@users.noreply.github.com" ]
44811269+y894577@users.noreply.github.com
81fea5492a9982c4138e96dc25b53c89502ceb50
d0be9a869d4631c58d09ad538b0908554d204e1c
/utf8/lib/client/FairyCore/src/EffectSystem/FairyEffectManager.h
0119e31836bf5de91d4e3965cb20f74383a00cec
[]
no_license
World3D/pap
19ec5610393e429995f9e9b9eb8628fa597be80b
de797075062ba53037c1f68cd80ee6ab3ed55cbe
refs/heads/master
2021-05-27T08:53:38.964500
2014-07-24T08:10:40
2014-07-24T08:10:40
null
0
0
null
null
null
null
GB18030
C++
false
false
12,432
h
/******************************************************************** filename: FairyEffectManager.h created: 2005/10/5 author: Weiliang Xie (feiyurainy@163.com) purpose: effect manager manage all effects, skills and path files. *********************************************************************/ #ifndef __EffectManager_H__ #define __EffectManager_H__ // ogre header #include <OgreSingleton.h> #include <OgreScriptLoader.h> #include <OgreStringVector.h> #include <OgreDataStream.h> #include "OgreIteratorWrappers.h" // fairy header #include "Core/FairyPrerequisites.h" #include "FairyBulletCallbacks.h" //#include "FairyScriptResGet.h" #include <OgreStringVector.h> // stl header #include <map> // 前向声明 namespace Ogre { class SceneNode; } namespace Fairy { class Effect; class EffectElementFactory; class EffectElement; class System; class EffectBasic; class Skill; class AnimationEffectInfo; class AnimationBulletFlow; class AnimationRibbon; class AnimationSound; class AnimationSceneLightInfo; class AnimationCameraShake; class MainSceneLight; } namespace Fairy { /// 特效级别,默认为HIGH enum EffectLevel { EL_LOW, EL_MID, EL_HIGH, }; class EffectManager : public Ogre::Singleton<EffectManager>, Ogre::ScriptLoader { public: typedef std::map<String, Effect *> EffectTemplateMap; //typedef std::map<String, Effect *> EffectMap; typedef std::list<Effect *> ActiveEffectList; typedef std::list<Effect *> FreeEffectList; typedef std::map<String, FreeEffectList *> FreeEffectMap; typedef std::map<String, EffectElementFactory *> ElementFactoryMap; typedef std::map<String,Ogre::String> EffectTemplateScriptFileMap; typedef std::map<String,Ogre::String> SkillTemplateScriptFileMap; typedef std::map<String,Ogre::String> ParticleTemplateScriptFileMap; typedef std::map<String, Skill *> SkillMap; public: EffectManager( System *system ); ~EffectManager(); /// @copydoc ScriptLoader::getScriptPatterns const Ogre::StringVector& getScriptPatterns(void) const; /// @copydoc ScriptLoader::parseScript void parseScript(Ogre::DataStreamPtr& stream, const Ogre::String& groupName); /// @copydoc ScriptLoader::getLoadingOrder Ogre::Real getLoadingOrder(void) const; static EffectManager& getSingleton(void); static EffectManager* getSingletonPtr(void); /// debug void dump(const Ogre::String &fileName); /// 根据特效模板来创建一个新的特效 Effect *createEffect( const Ogre::String &templateName ); Skill *getSkill( const Ogre::String &skillName ); /// 根据特效元素的类型来创建一个特效元素 EffectElement * createElement(const Ogre::String &type); /// 真正地删除一个特效 ActiveEffectList::iterator destroyEffect( Effect *effect ); /** 暂时地删除一个特效 并不是真正地删除特效,而是把它从活动的特效链表中删除,放入 空闲的特效的链表,以备后用 @param removeParentNode 是否要把该effect的节点从他的父节点上卸下来, 如果创建effect的节点调用的是createSceneNode,这个参数为false, 如果创建effect的节点调用的是createSceneNode( Ogre::SceneNode *parentNode ),这个参数为true @param removeNow 是否马上就删除这个effect,如果为false,那么这个effect会在它完全播放完才 被删除 @remarks 如果removeNow为false,不会马上删除effect,这时要保证effect的SceneNode不会先于effect删除, 所以如果需要removeNow为false,创建effect的scnenode最好使用createSceneNode(),这样,scenenode保存 在effect内部,可以保证scenenode的删除时机 */ void removeEffect( Effect *effect, bool removeParentNode = true, bool removeNow = true ); /** 创建一个控制器,用于每帧更新effect */ void createController(void); /// 由控制器调用,每帧更新活动的特效 void updateActiveEffects(Ogre::Real time); size_t getNumEffectTemplates(void); typedef Ogre::MapIterator<EffectTemplateMap> EffectTemplateIterator; EffectTemplateIterator getEffectTemplateIterator(void); typedef Ogre::MapIterator<ElementFactoryMap> ElementFactoryIterator; ElementFactoryIterator getElementFactoryIterator(void); typedef Ogre::MapIterator<SkillMap> SkillIterator; SkillIterator getSkillIterator(void); const Ogre::String & getFileNameByTemplateName( const Ogre::String &templateName ); const Ogre::String & getFileNameBySkillTemplateName( const Ogre::String &templateName ); const Ogre::String & getFileNameByParticleTemplateName( const Ogre::String &templateName ); void getTemplatesFromScriptFile( const Ogre::String &fileName, Ogre::StringVector &templates ); void getSkillTemplatesFromScriptFile( const Ogre::String &fileName, Ogre::StringVector &templates ); void getParticleTemplatesFromScriptFile( const Ogre::String &fileName, Ogre::StringVector &templates ); void getLoadedScripts( Ogre::StringVector &files ) { files = mLoadedScripts; } void getLoadedSkillScripts( Ogre::StringVector &files ) { files = mLoadedSkillScripts; } /// 根据模板名称来获取模板 Effect * getTemplate(const Ogre::String& name); Skill * createSkillTemplate(const Ogre::String &name); /** 创建一个新的effect模板 @param name 特效名称 */ Effect * createEffectTemplate(const Ogre::String &name); void addToEffectTemplateScriptFileMap( const Ogre::String &templateName, const Ogre::String &fileName ); void addToSkillTemplateScriptFileMap( const Ogre::String &templateName, const Ogre::String &fileName ); void addToParticleTemplateScriptFileMap( const Ogre::String &templateName, const Ogre::String &fileName ); void removeParticleTemplateScriptFileMap( const Ogre::String &templateName); Skill * createSkill(const Ogre::String &skillName); void removeSkill(Skill *skill); /** 设置每条空闲的effect链中最多可保存的空闲effect个数 @remarks effect在removeEffect时会被回收,放入一个map中,map的key是effect的模板名称, value是一条空闲的effect链,这个方法设置的就是这条链的最大个数,也就是说,在 空闲effect池中,同个模板最多可以保存mMaxNumFreeEffectPerList个空闲的effect */ void setMaxNumFreeEffectPerList(unsigned short num) { mMaxNumFreeEffectPerList = num; } unsigned short getMaxNumFreeEffectPerList(void) { return mMaxNumFreeEffectPerList; } MainSceneLight* getMainSceneLight(void) { return mMainSceneLight; } /// 清空特效池中的特效 void clearAllFreeEffects(void); /// 设置特效级别 void setEffectLevel(EffectLevel level); EffectLevel getEffectLevel(void) { return mEffectLevel; } void _destroyEffectTemplates(void); void _destroySkillTemplates(void); //void setDestroySkillCallback( DestroySkillCallback *cback ); protected: /** 注册新的特效元素工厂 每增加一种新类型的特效元素,都得在这个函数中添加相应的代码 */ void registerElementFactory(void); void addElementFactory( EffectElementFactory *factory ); void skipToNextCloseBrace(Ogre::DataStreamPtr& chunk); void skipToNextOpenBrace(Ogre::DataStreamPtr& chunk); /// 解析脚本中的新的特效元素 void parseNewElement(const Ogre::String &type, Ogre::DataStreamPtr &stream, Effect *effectParent); /// 解析特效元素的属性 void parseElementAttrib(const Ogre::String& line, EffectElement *element); /// 解析.effect文件 void parseEffectFile( Ogre::DataStreamPtr &stream ); void parseEffectAttrib(const Ogre::String& line, Effect *effect); /* void parseEffectFile(Ogre::DataStreamPtr &stream , const String& groupName); void parseEffectTemlpateSegment( const String& templateName,Ogre::DataStreamPtr &stream , const String& groupName); void parseEffectAttrib(const String& line, Effect *effect); */ /// 解析.skill文件 void parseSkillFile( Ogre::DataStreamPtr &stream ); void parseSkillAttrib(const Ogre::String& line, Skill *skill); void parseAnimEffectInfo(Ogre::DataStreamPtr &stream, Skill *skill); void parseAnimEffectInfoAttrib(const Ogre::String& line, AnimationEffectInfo *effectInfo); void parseAnimBulletFlow(Ogre::DataStreamPtr &stream,Skill* skill); void parseAnimBulletFlowAttrib(const String& line,AnimationBulletFlow* animationBulletFlow); void parseAnimRibbon(Ogre::DataStreamPtr &stream, Skill *skill); void parseAnimRibbonAttrib(const Ogre::String& line, AnimationRibbon *ribbon); void parseAnimSound(Ogre::DataStreamPtr &stream, Skill *skill); void parseAnimSoundAttrib(const Ogre::String& line, AnimationSound *sound); void parseAnimSceneLightInfo(Ogre::DataStreamPtr &stream, Skill *skill); void parseAnimSceneLightInfoAttrib(const Ogre::String& line, AnimationSceneLightInfo *sceneLightInfo); void parseAnimCameraShake(Ogre::DataStreamPtr &stream, Skill *skill); void parseAnimCameraShakeAttrib(const Ogre::String& line, AnimationCameraShake *cameraShake); /** 从空闲的特效链表中获取一个所指定模板的特效 一般来说,在游戏运行时如果要删除一个特效(比如说一个挂接 特效的动作完成了),都不会直接删除特效的,而是把它经过一些处理后 (重新初始化)放入到一个空闲的链表中,下次如果要求创建同种类型的特效, 就先从空闲链表中找,如果没有,再重新创建一个全新的 */ Effect * getFromFreeMap( const Ogre::String &templateName ); /// 把一个特效加入到空闲链表中 void addToFreeEffectMap( Effect *effect ); void addToLoadedScripts( const Ogre::String &fileName ) { mLoadedScripts.push_back(fileName); } void addToLoadedSkillScripts( const Ogre::String &fileName ) { mLoadedSkillScripts.push_back(fileName); } /// 输出错误信息 void _logErrorInfo(const Ogre::String& errorInfo, const Ogre::String& lineContent, const Ogre::String& functionName); //解析粒子文件 /** Internal script parsing method. */ void parseNewParticleEmitter(const Ogre::String& type, Ogre::DataStreamPtr& chunk, Ogre::ParticleSystem* sys); /** Internal script parsing method. */ void parseNewParticleAffector(const Ogre::String& type, Ogre::DataStreamPtr& chunk, Ogre::ParticleSystem* sys); /** Internal script parsing method. */ void parseParticleAttrib(const Ogre::String& line, Ogre::ParticleSystem* sys); /** Internal script parsing method. */ void parseParticleEmitterAttrib(const Ogre::String& line, Ogre::ParticleEmitter* sys); /** Internal script parsing method. */ void parseParticleAffectorAttrib(const Ogre::String& line, Ogre::ParticleAffector* sys); private: ElementFactoryMap mElementFactoryMap; EffectTemplateMap mEffectTemplateMap; FreeEffectMap mFreeEffectMap; SkillMap mSkillMap; EffectTemplateScriptFileMap mEffectTemplateScriptFileMap; SkillTemplateScriptFileMap mSkillTemplateScriptFileMap; ParticleTemplateScriptFileMap mParticleTemplateScriptFileMap; Ogre::StringVector mLoadedScripts; Ogre::StringVector mLoadedSkillScripts; ActiveEffectList mActiveEffectList; Ogre::StringVector mScriptPatterns; System *mSystem; Ogre::Controller<Ogre::Real> *mController; unsigned short mMaxNumFreeEffectPerList; /// 每次进行getLine的时候就递增行号,作为错误的输出信息 int mWrongLineNum; /// 当前解析的文件名称 Ogre::String mParsingFileName; /// 当前场景上的灯光变化信息 MainSceneLight* mMainSceneLight; /// 特效级别 EffectLevel mEffectLevel; public: DestroySkillCallback* getDestroySkillCallback() const; void setDestroySkillCallback(DestroySkillCallback* val); CameraShakeCallback* getEffectCameraShakeCallback() const { return m_CameraShakeCallback;} void setEffectCameraShakeCallback(CameraShakeCallback* val) {m_CameraShakeCallback = val;} protected: DestroySkillCallback* m_destroySkillCallback; CameraShakeCallback* m_CameraShakeCallback; Ogre::String mGroupName; }; } #endif
[ "viticm@126.com" ]
viticm@126.com
c9c551cfc6faaaf7d89757e426b5b0a9daf4ffa8
c0fa09fd6e1b5600cbfff63533669e3473c8b586
/kernel_selector/core/actual_kernels/reorder/reorder_weights_kernel.cpp
fd230187c1f0be74833cade93799846d7a03113d
[ "BSL-1.0", "Apache-2.0" ]
permissive
Guokr1991/clDNN
b2dae1371c9797bb563748f1c3a993d1bc3ba1a1
1b4b0c29faa07ae9a91b6f12b8b60e0ff49102fe
refs/heads/master
2021-05-08T05:04:28.421525
2017-10-26T11:18:05
2017-10-26T11:18:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
cpp
/* // Copyright (c) 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "kernel_selector_common.h" #include "reorder_weights_kernel.h" #include "kernel_selector_utils.h" namespace KernelSelector { ParamsKey ReorderWeightsKernel::GetSupportedKey() const { ParamsKey k; k.EnableInputWeightsType(WeightsType::F16); k.EnableInputWeightsType(WeightsType::F32); k.EnableOutputWeightsType(WeightsType::F16); k.EnableOutputWeightsType(WeightsType::F32); k.EnableDifferentTypes(); k.EnableTensorOffset(); k.EnableTensorPitches(); return k; } KernelsData ReorderWeightsKernel::GetKernelsData(const Params& params, const OptionalParams& options) const { assert(params.GetType() == KernelType::REORDER); KernelData kd = KernelData::Default<ReorderWeightsParams>(params); ReorderWeightsParams& newParams = *static_cast<ReorderWeightsParams*>(kd.params.get()); auto entry_point = GetEntryPoint(kernelName, newParams.layerID, options); auto cldnn_jit = GetJitConstants(newParams); std::string jit = CreateJit(kernelName, cldnn_jit, entry_point); const auto& out = newParams.reorderParams.output; auto& kernel = kd.kernels[0]; kernel.workGroups.global = { out.OFM().v, out.IFM().v, out.X().v*out.Y().v }; kernel.workGroups.local = GetOptimalLocalWorkGroupSizes(kernel.workGroups.global); kernel.kernelString = GetKernelString(kernelName, jit, entry_point, ROUND_ROBIN); kernel.arguments = GetArgsDesc(1, false, false); kd.estimatedTime = DONT_USE_IF_HAVE_SOMETHING_ELSE; return{ kd }; } }
[ "tomasz.poniecki@intel.com" ]
tomasz.poniecki@intel.com
f33b34fcf9283741451bb8bf488d903569a6a914
620ba07e9ff02e68ce3c90c1bcc9247fff1a5751
/include/tracker_manager/tracker.h
dddc7bda9a14ced663b0125dc06152541b246e9f
[]
no_license
DHNicoles/Meepo
1b4a33ea151383b943b7bf0a941ff5eff056c463
981f22dfc684054c6c907d73842a5836693e800e
refs/heads/master
2020-03-25T19:54:11.969018
2018-08-09T05:43:50
2018-08-09T05:43:50
144,106,065
0
0
null
null
null
null
UTF-8
C++
false
false
1,355
h
/* * File: BasicTracker.h * Author: Joao F. Henriques, Joao Faro, Christian Bailer * Contact address: henriques@isr.uc.pt, joaopfaro@gmail.com, Christian.Bailer@dfki.de * Instute of Systems and Robotics- University of COimbra / Department Augmented Vision DFKI * * This source code is provided for for research purposes only. For a commercial license or a different use case please contact us. * You are not allowed to publish the unmodified sourcecode on your own e.g. on your webpage. Please refer to the official download page instead. * If you want to publish a modified/extended version e.g. because you wrote a publication with a modified version of the sourcecode you need our * permission (Please contact us for the permission). * * We reserve the right to change the license of this sourcecode anytime to BSD, GPL or LGPL. * By using the sourcecode you agree to possible restrictions and requirements of these three license models so that the license can be changed * anytime without you knowledge. */ #pragma once #include <opencv2/opencv.hpp> #include <string> class Tracker { public: Tracker() {} virtual ~Tracker() { } virtual void init(const cv::Rect &roi, cv::Mat image) = 0; virtual cv::Rect update( cv::Mat image)=0; protected: cv::Rect_<float> _roi; };
[ "18800152810@163.com" ]
18800152810@163.com
1ed2e87833ac33ba98449dd2ea88c00b0406d347
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/multimedia/WMP/Wizards/services/templates/1033/Type1/sample.cpp
08b40dd35c09882534850a1d9e91c5c97d0b02d7
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
5,388
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // #include "stdafx.h" #include "[!output root].h" CONTENT_PARTNER_GLOBALS g; OBJECT_ENTRY_AUTO(__uuidof(C[!output Safe_root]), C[!output Safe_root]) C[!output Safe_root]::C[!output Safe_root]() { ZeroMemory( g.credentialsFile, MAX_PATH*sizeof(g.credentialsFile[1]) ); g.totalDownloadFailures = 0; g.userLoggedIn = 0; g.haveCachedCredentials = 0; m_downloadThreadHandle = 0; m_downloadThreadId = 0; m_msgDownloadBatch = 0; m_buyThreadHandle = 0; m_buyThreadId = 0; m_msgBuy = 0; m_refreshLicenseThreadHandle = 0; m_refreshLicenseThreadId = 0; m_msgRefreshLicense = 0; m_loginThreadHandle = 0; m_loginThreadId = 0; m_msgLogin = 0; m_msgLogout = 0; m_msgAuthenticate = 0; m_msgVerifyPermission = 0; m_sendMessageThreadHandle = 0; m_sendMessageThreadId = 0; m_msgSendMessage = 0; m_updateDeviceThreadHandle = 0; m_updateDeviceThreadId = 0; m_msgUpdateDevice = 0; m_listThreadHandle = 0; m_listThreadId = 0; m_msgGetListContents = 0; m_msgExitMessageLoop = 0; } HRESULT C[!output Safe_root]::FinalConstruct() { HRESULT hr = S_OK; ATLTRACE2("%x: FinalConstruct\n", GetCurrentThreadId()); m_msgDownloadBatch = RegisterWindowMessage( L"DownloadBatch" ); if(0 == m_msgDownloadBatch) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgBuy = RegisterWindowMessage( L"Buy" ); if(0 == m_msgBuy) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgRefreshLicense = RegisterWindowMessage( L"RefreshLicense" ); if(0 == m_msgRefreshLicense) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgLogin = RegisterWindowMessage( L"Login" ); if(0 == m_msgLogin) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgAuthenticate = RegisterWindowMessage( L"Authenticate" ); if(0 == m_msgAuthenticate) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgLogout = RegisterWindowMessage( L"Logout" ); if(0 == m_msgLogout) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgVerifyPermission = RegisterWindowMessage( L"VerifyPermission" ); if(0 == m_msgVerifyPermission) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgSendMessage = RegisterWindowMessage( L"SendMessage" ); if(0 == m_msgSendMessage) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgGetListContents = RegisterWindowMessage( L"GetListContents" ); if(0 == m_msgGetListContents) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } m_msgExitMessageLoop = RegisterWindowMessage( L"ExitMessageLoop" ); if(0 == m_msgExitMessageLoop) { hr = HRESULT_FROM_WIN32(GetLastError()); ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr); goto cleanup; } hr = this->CreateCredentialsFilePath(); if(FAILED(hr)) { ATLTRACE2("FinalConstruct: CreateCredentialsFilePath failed. %x\n", hr); goto cleanup; } // Determine whether we have cached credentials. HANDLE hInfoFile = INVALID_HANDLE_VALUE; hInfoFile = CreateFile( g.credentialsFile, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE != hInfoFile) { // The file exists. // We have cached credentials. g.haveCachedCredentials = 1; } CloseHandle(hInfoFile); cleanup: return hr; } C[!output Safe_root]::~C[!output Safe_root]() { ATLTRACE2("%x: [!output Safe_root] destructor: Total download failures: %d\n", GetCurrentThreadId(), g.totalDownloadFailures); } class C[!output Safe_root]Module : public CAtlDllModuleT< C[!output Safe_root]Module > {}; C[!output Safe_root]Module _AtlModule; BOOL WINAPI DllMain(HINSTANCE /*hInstance*/, DWORD dwReason, LPVOID lpReserved) { return _AtlModule.DllMain(dwReason, lpReserved); } STDAPI DllCanUnloadNow(void) { return _AtlModule.DllCanUnloadNow(); } STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _AtlModule.DllGetClassObject(rclsid, riid, ppv); } STDAPI DllRegisterServer(void) { // There is no type library, so pass // FALSE to _AtlModule.DllRegistreServer HRESULT hr = _AtlModule.DllRegisterServer(FALSE); return hr; } STDAPI DllUnregisterServer(void) { // There is no type library, so pass // FALSE to _AtlModule.DllUnRegistreServer HRESULT hr = _AtlModule.DllUnregisterServer(FALSE); return hr; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com