blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31917fb64763a23b74c96af58fe8e1dfd43e13d1 | 72cce5b8440d64c103c9dcc4f501606696828218 | /src/sbo_category.h | 8028a176cfefaaabe8f91b27fdc3dbbb08cb60ab | [] | no_license | atelszewski/sbosubmit | 2eb7bef4f540324c8a30c8ffb068102cfb4b0ea2 | 7d318172fd2dd1200fcc6505b085b232ab3b2256 | refs/heads/master | 2021-07-08T23:26:31.446988 | 2021-04-17T07:28:54 | 2021-04-17T07:28:54 | 241,956,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | h | #ifndef SBO_CATEGORY_H_INCLUDED
#define SBO_CATEGORY_H_INCLUDED
#include <string>
using namespace std;
bool sbo_check_cat(string const &pcat);
#endif
| [
"[email protected]"
] | |
6d21622843c20e96758b96d04922e4c7e25c5bde | 8a899be7c1f978d8ecb1975461493df57b85b854 | /Sourcecode/ESP8266_CSGO-Ambilight/Parsing.ino | b1dfb34300522ba4c9c8f0d0fdfa802f7d0e7166 | [] | no_license | TheAmadeus25/CounterStrike-GlobalOffensive-Ambilight-System | 0fd94a45c05504e3f5784245c091b79d9d975b4f | 4b324c89422ffc8f73d8ca02aee214f77bcdedf4 | refs/heads/master | 2020-08-06T21:11:14.226902 | 2019-10-13T13:07:53 | 2019-10-13T13:07:53 | 213,156,161 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,227 | ino | void Parsing() {
//char Buffer[payload.length() + 1];
//payload.toCharArray(Buffer, (payload.length() + 1) );
Player.health = atoi( strtok(incomingPacket, ";") );
Player.armor = atoi( strtok(NULL, ";") );
Player.helmet = strtok(NULL, ";");
Round.win_team = strtok(NULL, ";");
Player.flashed = atoi( strtok(NULL, ";") );
Player.smoked = atoi( strtok(NULL, ";") );
Player.activity = strtok(NULL, ";");
Refresh.last_refresh = millis();
return;
}
bool CheckDifferent() {
if ( Player_Last.health != Player.health ||
Player_Last.armor != Player.armor ||
Player_Last.helmet != Player.helmet ||
Round_Last.win_team != Round.win_team ||
Player_Last.flashed != Player.flashed ||
Player_Last.smoked != Player.smoked ||
Player_Last.activity != Player.activity) {
if (Round.win_team) ClearLED(); // Refresh the hole LED strip for next round
return true; // Something has changed
} else {
return false; // Nothing has changed
}
}
| [
"[email protected]"
] | |
df1a9e55fd109fa7dc521228d7ce994932947dc5 | 0e5aef62ab3a611e230e2b9b6d744848124458c0 | /app.cpp | fa20a8a3c27ddb1a49430f81ae1f7dafdbeb7f6c | [] | no_license | koalamrfan/koala | fb2069bf4c081e23f51288458733846c34c41eb3 | 28a1a71ce1eaa738c0967c852c44c2810353b042 | refs/heads/master | 2021-01-22T03:13:06.039562 | 2013-10-05T14:39:53 | 2013-10-05T14:39:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | cpp | #include "app.h"
#include "texture_pool.h"
namespace ui
{
std::shared_ptr<Window> App::window_;
void App::Init(HWND hwnd, int argc, TCHAR** argv) {
window_ = std::make_shared<Window>(hwnd);
main(argc, argv);
}
Widget* App::MainWindowHitest(int x, int y) {
if(window_) {
return window_->HitTest(x, y);
} else {
return nullptr;
}
}
void App::Update( const SkRect& clip_rect ) {
if(window_) {
RECT rect;
rect.left = SkScalarFloorToInt(clip_rect.fLeft);
rect.top = SkScalarFloorToInt(clip_rect.fTop);
rect.right = SkScalarFloorToInt(clip_rect.fRight);
rect.bottom = SkScalarFloorToInt(clip_rect.fBottom);
InvalidateRect(window_->GetHwnd(), &rect, FALSE);
}
}
void App::DoLayout() {
if(window_) {
window_->Dolayout();
}
}
Window* App::MainWindow() {
if(window_) {
return window_.get();
} else {
return nullptr;
}
}
} // namespace ui | [
"[email protected]"
] | |
8727bbc484aebeea368a91b96cc9d8a16f8907ee | 90184bb72202ba4663fb96c6410db804c5dbe574 | /681. Next Closest Time.cpp | f960b6dd1cef8eb589b0061d9ae7b0cd3d2a194e | [] | no_license | habib302/leetcode-1 | 08da70eea3ab5c59af530c97c8619f1b79de4dde | 32f6ccecd9213edb51824c3214246194ccbc4ccb | refs/heads/master | 2023-08-04T13:28:11.732528 | 2021-09-21T07:45:10 | 2021-09-21T07:45:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,288 | cpp | class Solution {
public:
string nextClosestTime(string time) {
string ans = time;
int hr = (time[0] - '0') * 10 + ( time[1] - '0');
int min = (time[3] - '0') * 10 + ( time[4] - '0');
int startingMins = (hr * 60 ) + min;
int digitPresent[10] = {0};
digitPresent[time[0]-'0'] = 1;
digitPresent[time[1]-'0'] = 1;
digitPresent[time[3]-'0'] = 1;
digitPresent[time[4]-'0'] = 1;
int wholeMins = 60 * 24;
int curMins = startingMins;
curMins = ( curMins + 1 ) % wholeMins;
int diffInMins = -1;
// cout << "curMins " << curMins << endl;
bool notFound = true;
while(notFound) {
// cout << " curMins " << curMins << endl;
int hr = (curMins) / 60;
int min = (curMins ) % 60;
notFound = false;
if( hr < 10 ) {
if(digitPresent[hr] == 0 ) notFound = true;
if(digitPresent[0] == 0 ) notFound = true;
} else {
if(digitPresent[hr/10] == 0 ) notFound = true;
if(digitPresent[hr%10] == 0 ) notFound = true;
}
if( min < 10 ) {
if(digitPresent[min] == 0 ) notFound = true;
if(digitPresent[0] == 0 ) notFound = true;
} else {
if(digitPresent[min/10] == 0 ) notFound = true;
if(digitPresent[min%10] == 0 ) notFound = true;
}
if(notFound == false) {
if(hr < 10 ) {
ans[0] = '0';
ans[1] = hr + '0';
} else {
ans[0] = (hr / 10 ) + '0';
ans[1] = (hr % 10 ) + '0';
}
if(min < 10 ) {
ans[3] = '0';
ans[4] = min + '0';
} else {
ans[3] = (min / 10 ) + '0';
ans[4] = (min % 10 ) + '0';
}
break;
}
curMins = ( curMins + 1 ) % wholeMins;
}
return ans;
}
};
| [
"[email protected]"
] | |
03ef3367f5dbe6658533999255b1a9123cda80bc | 6ffa05486404b09ac789d71a37b2bdcd1d2768a6 | /src/copperfx/panels/NodeFlowViewPanel/NodeItem.h | ea78a74ebafae9f44bceb9acbcadee5cef112781 | [
"Unlicense"
] | permissive | all-in-one-of/CopperFX | 4dada97d54b9f92ad960a7af27d22b12ce3c6464 | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | refs/heads/master | 2020-07-08T18:49:47.834624 | 2019-08-24T01:38:44 | 2019-08-24T01:38:44 | 203,748,279 | 0 | 0 | Unlicense | 2019-08-22T08:23:37 | 2019-08-22T08:23:36 | null | UTF-8 | C++ | false | false | 1,684 | h | #ifndef NODE_ITEM_H
#define NODE_ITEM_H
#include <QSizeF>
#include <QPainter>
#include <QVector>
#include <QtCore/QUuid>
#include <QtWidgets/QGraphicsItem>
#include <QtWidgets/QGraphicsObject>
#include <QGraphicsSimpleTextItem>
#include <flags/flags.hpp>
#include "copper/Operator/OpNode.h"
#include "copper/Operator/OpDataSocket.h"
#include "NodeSocketItem.h"
namespace copper { namespace ui {
class NodeFlowScene;
class NodeSocketItem;
class NodeItem : public QGraphicsItem {
public:
enum class Flags {
SOCKETS_VERTICAL = 0x01, /// Socket for output data
SOCKETS_HORIZONTAL = 0x02, /// Socket for ouput data
};
//Q_OBJECT
public:
NodeItem(NodeFlowScene *scene, OpNode *op_node, NodeItem::Flags flags);
~NodeItem();
QSizeF size() const;
const OpNode *opNode() const;
const QVector<NodeSocketItem*>& inputSocketItems() const;
const QVector<NodeSocketItem*>& outputSocketItems() const;
private:
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) override;
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
void mousePressEvent(QGraphicsSceneMouseEvent * event) override;
private:
void addSocket(const OpDataSocket *opdata_socket);
private:
NodeFlowScene *_scene;
bool _locked;
NodeItem::Flags _flags;
OpNode *_op_node;
QGraphicsSimpleTextItem _node_name_item;
QSizeF _size = QSizeF(60,20);
QVector<NodeSocketItem*> _input_socket_items;
QVector<NodeSocketItem*> _output_socket_items;
};
}}
ALLOW_FLAGS_FOR_ENUM(copper::ui::NodeItem::Flags)
#endif // NODE_ITEM_H | [
"[email protected]"
] | |
2e34e116883ead65671c17d628d13a6e6f403d7e | d928143913c7b298b7bc637c2dcfa2ae617229e7 | /src/Utils/Core/Rect.cpp | 79e85c430326491c7162e71cf5059ab09071387f | [] | no_license | hackerlank/Mengine | d7e649c29ab6cfd861bd85c75e514939ba7a09d6 | 108491a9ef86946fc4abed0662b0beafbde4fda4 | refs/heads/master | 2021-01-12T06:19:27.136456 | 2016-12-13T00:55:25 | 2016-12-13T00:55:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | # include "Rect.h"
namespace Menge
{
/////////////////////////////////////////////////////////////////////////////////
Rect::Rect()
: top(0)
, bottom(0)
, left(0)
, right(0)
{
}
/////////////////////////////////////////////////////////////////////////////////
Rect::Rect( uint32_t _left, uint32_t _top, uint32_t _right, uint32_t _bottom )
: top(_top)
, bottom(_bottom)
, left(_left)
, right(_right)
{
}
/////////////////////////////////////////////////////////////////////////////////
} | [
"yuriy_levchenko@202150c4-1a32-4ab8-af31-e3358ecdd631"
] | yuriy_levchenko@202150c4-1a32-4ab8-af31-e3358ecdd631 |
692dfe1210b3064d09982af9a286de18664c3f26 | 974d04d2ea27b1bba1c01015a98112d2afb78fe5 | /paddle/fluid/distributed/ps/service/ps_service/service.h | eb190073fbd834a92793f6a6f99016d0fa916d46 | [
"Apache-2.0"
] | permissive | PaddlePaddle/Paddle | b3d2583119082c8e4b74331dacc4d39ed4d7cff0 | 22a11a60e0e3d10a3cf610077a3d9942a6f964cb | refs/heads/develop | 2023-08-17T21:27:30.568889 | 2023-08-17T12:38:22 | 2023-08-17T12:38:22 | 65,711,522 | 20,414 | 5,891 | Apache-2.0 | 2023-09-14T19:20:51 | 2016-08-15T06:59:08 | C++ | UTF-8 | C++ | false | false | 2,563 | h | /* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "paddle/fluid/distributed/ps/service/ps_client.h"
#include "paddle/fluid/distributed/ps/service/sendrecv.pb.h"
#include "paddle/fluid/distributed/ps/service/server.h"
#include "paddle/fluid/distributed/the_one_ps.pb.h"
namespace paddle {
namespace distributed {
class PSClient;
class PSServer;
class PsRequestMessage;
class PsResponseMessage;
class PsService;
using paddle::distributed::PsRequestMessage;
using paddle::distributed::PsResponseMessage;
using paddle::distributed::PsService;
class PSCore {
public:
PSCore() {}
virtual ~PSCore() {}
virtual int InitServer(
const std::string& dist_desc,
const std::vector<std::string>* host_sign_list,
int node_num,
int index,
int trainers,
const std::vector<framework::ProgramDesc>& server_sub_program = {});
virtual int InitWorker(
const std::string& dist_desc,
const std::map<uint64_t, std::vector<paddle::distributed::Region>>&
regions,
const std::vector<std::string>* host_sign_list,
int node_num,
int index);
virtual uint64_t RunServer(const std::string& ip, uint32_t port);
virtual int StopServer();
virtual int FinalizeWorker();
virtual std::vector<uint64_t> GetClientInfo();
virtual int CreateClient2ClientConnection(int pserver_timeout_ms,
int pserver_connect_timeout_ms,
int max_retry);
std::shared_ptr<paddle::distributed::PSServer>
_server_ptr; // pointer to server
std::shared_ptr<paddle::distributed::PSClient>
_worker_ptr; // pointer to worker
virtual paddle::distributed::PSParameter* GetParam();
private:
void InitGFlag(const std::string& gflags);
paddle::distributed::PSParameter _ps_param;
paddle::distributed::PaddlePSEnvironment _ps_env;
};
} // namespace distributed
} // namespace paddle
| [
"[email protected]"
] | |
130a8d53136b77d7bda73ebc283c3a79b1e22efc | 23b26776ea152c261c9f4fdb7caecfea37fa034b | /src/Corrade/Utility/Test/GlobalStateAcrossLibrariesTest.cpp | 173df8095a29528164bdf5f80846f133cee0420b | [
"MIT",
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | fauder/corrade | bce2314461dc86a3d6468003ece7e2baf44c4e8c | c48c0d1caa51c90fdec81a9ec5162b1b6cf98cae | refs/heads/master | 2022-07-12T19:29:54.092140 | 2020-05-12T09:33:37 | 2020-05-12T09:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,188 | cpp | /*
This file is part of Corrade.
Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019 Vladimír Vondruš <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include "Corrade/TestSuite/Tester.h"
#include "Corrade/Utility/Resource.h"
#include "GlobalStateAcrossLibrariesLibrary.h"
namespace Corrade { namespace Utility { namespace Test { namespace {
struct GlobalStateAcrossLibrariesTest: TestSuite::Tester {
explicit GlobalStateAcrossLibrariesTest();
void debug();
void resource();
};
GlobalStateAcrossLibrariesTest::GlobalStateAcrossLibrariesTest() {
addTests({&GlobalStateAcrossLibrariesTest::debug,
&GlobalStateAcrossLibrariesTest::resource});
}
void GlobalStateAcrossLibrariesTest::debug() {
#if defined(CORRADE_BUILD_STATIC_UNIQUE_GLOBALS) && !defined(CORRADE_BUILD_STATIC)
CORRADE_VERIFY(!"CORRADE_BUILD_STATIC_UNIQUE_GLOBALS enabled but CORRADE_BUILD_STATIC not");
#endif
std::ostringstream out;
std::ostream* current = Debug::output();
CORRADE_COMPARE(debugOutputFromALibrary(), current);
{
Debug redirectOutput{&out};
#ifndef CORRADE_BUILD_STATIC_UNIQUE_GLOBALS
CORRADE_EXPECT_FAIL("CORRADE_BUILD_STATIC_UNIQUE_GLOBALS not enabled.");
#endif
CORRADE_COMPARE(debugOutputFromALibrary(), &out);
}
CORRADE_COMPARE(debugOutputFromALibrary(), current);
}
void GlobalStateAcrossLibrariesTest::resource() {
#if defined(CORRADE_BUILD_STATIC_UNIQUE_GLOBALS) && !defined(CORRADE_BUILD_STATIC)
CORRADE_VERIFY(!"CORRADE_BUILD_STATIC_UNIQUE_GLOBALS enabled but CORRADE_BUILD_STATIC not");
#endif
/* The resource is complied into the the library, but the executable should
see it too */
CORRADE_VERIFY(libraryHasATestResourceGroup());
#ifndef CORRADE_BUILD_STATIC_UNIQUE_GLOBALS
CORRADE_EXPECT_FAIL("CORRADE_BUILD_STATIC_UNIQUE_GLOBALS not enabled.");
#endif
CORRADE_VERIFY(Utility::Resource::hasGroup("test"));
}
}}}}
CORRADE_TEST_MAIN(Corrade::Utility::Test::GlobalStateAcrossLibrariesTest)
| [
"[email protected]"
] | |
ce87e5d7b23b3e236c56b923cfa90ed1749d2387 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/079/913/CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad.cpp | 6f49504e556e48fb8e9bef4fcec545bb0ae77a35 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,041 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-84_bad.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: environment Read input from an environment variable
* GoodSource: Copy a fixed string into data
* Sinks: vprintf
* GoodSink: vprintf with a format string
* BadSink : vprintf without a format string
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITBAD
#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_environment_vprintf_84.h"
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
namespace CWE134_Uncontrolled_Format_String__char_environment_vprintf_84
{
CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad::CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad(char * dataCopy)
{
data = dataCopy;
{
/* Append input from an environment variable to data */
size_t dataLen = strlen(data);
char * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
strncat(data+dataLen, environment, 100-dataLen-1);
}
}
}
static void badVaSink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
vprintf(data, args);
va_end(args);
}
}
CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad::~CWE134_Uncontrolled_Format_String__char_environment_vprintf_84_bad()
{
badVaSink(data, data);
}
}
#endif /* OMITBAD */
| [
"[email protected]"
] | |
9d1cd3a1c82b0f106249896d75913054d49da0dc | 4f8a4ce45d4ba89aaa674254a2ac126e12e79f73 | /Project2/ScoreInfo.h | 6284ae28cee5ac92506f13bd8726808bff4d78b6 | [] | no_license | aohara19/Ohara-CSC17A | 659d8291e439d133311afb81fc122e1fca10cab2 | 7942fb628b943c240b09f7c8ed406209825bfe83 | refs/heads/master | 2020-04-22T18:20:15.821636 | 2019-05-27T13:35:57 | 2019-05-27T13:35:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | h |
#ifndef SCORE_INFO_H
#define SCORE_INFO_H
#include <iostream>
#include "Property.h"
using namespace std;
class ScoreInfo;
ostream &operator << (ostream &, const ScoreInfo &);
//ScoreInfo class to store information to be put on the scoreboard
class ScoreInfo{
private:
int money;
int numProps,numSpecial;
int totalValueOfProps;
int totalValue;
Property highestProp;
public:
ScoreInfo()
{ScoreInfo(0,0,0,0,0);}
ScoreInfo(int m,int n,int s,int t,int v)
{money = m; numProps = n; numSpecial = s; totalValueOfProps = t; totalValue = v;}
~ScoreInfo()
{cout<<"GAME OVER\n";}
int getMoney()
{return money;}
int getNumProps()
{return numProps;}
int getTotalValueOfProps()
{return totalValueOfProps;}
int getTotalValue()
{return totalValue;}
void setProp(Property prop)
{highestProp = prop;}
Property returnProp()
{return highestProp;}
friend ostream &operator <<(ostream &, const ScoreInfo&);
};
#endif /* SCORE_INFO_H */ | [
"[email protected]"
] | |
5f037d70e0f36b758e1b96c6481da2dc27720ab0 | 75f68be3954d272ffb676ff24372fe9b848f3cf4 | /Tatanova_Alexandra/vector/vectorChapter18.cpp | 3041d4751d569c40ad5d0d5508c3aaeed764ccf8 | [] | no_license | droidroot1995/DAFE_CPP_013 | 9f0f2cd1e08e12dc554a066cdb7d3e1e1fff2fba | ee16c83e24d692b05191ea3915102bbcdbfacf79 | refs/heads/main | 2023-02-01T13:31:06.317281 | 2020-12-16T15:17:12 | 2020-12-16T15:17:12 | 300,523,531 | 0 | 12 | null | 2023-04-26T18:19:54 | 2020-10-02T06:35:38 | C++ | UTF-8 | C++ | false | false | 1,810 | cpp | #include "vectorChapter18.h"
vector::vector() : sz{0}, elem {nullptr}, space{0} { }
vector::vector(int s)
: sz{s}, elem{new double[s]}, space{s}
{
for (int i = 0; i<sz; ++i)
elem[i] = 0;
}
void vector::reserve(int newalloc)
{
if ( newalloc <= space )
return;
double* p = new double[newalloc];
for ( int i = 0; i < sz; ++i )
p[i] = elem[i];
delete[] elem;
elem = p;
space = newalloc;
}
void vector:: resize( int newsize )
{
reserve( newsize );
for (int i = sz; i < newsize; ++i)
elem[i] = 0;
sz = newsize;
}
void vector::push_back(double d)
{
if (space == 0)
reserve(8);
else
if (sz == space)
reserve(2*space);
elem[sz] = d;
++sz;
}
vector& vector :: operator= (const vector& a) // Делаем данный вектор копией а
{
if (this == &a)
return *this;
if (a.sz <= space)
{
for (int i = 0; i < a.sz; ++i)
elem[i] = a.elem[i]; // Копирование эелентов
sz = a.sz;
return *this;
}
double* p = new double [a.sz]; // Выделение памяти
for (int i = 0; i < a.sz; ++i)
p[i] = a.elem[i]; // Копирование эелентов
delete[] elem; // Освобождение памяти
space = sz = a.sz;
elem = p; // Переназначение указателя
return *this; // Возрат ссылки на себя
}
vector :: vector(vector&& a)
:sz{a.sz}, elem{a.elem} // Копируем elem и sz из а
{
a.sz = 0; // Делаем вектор а пустым
a.elem = nullptr;
}
vector& vector:: operator= (vector&& a)
{
delete[] elem;
elem = a.elem;
sz = a.sz;
a.elem = nullptr;
a.sz = 0;
return *this;
}
| [
"[email protected]"
] | |
bc69b1d3f58cc12e071494476ff8fa54407df1aa | ee50df330a0fd0d5088836eb19b7dff7e7736da8 | /src/cryptonote_config.h | b9f28290468948374892a98754722bdc16693742 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | deep-recoal/recoal-2 | f37c8e09e34f31518519286932e6fc1bc9659c55 | 36d0e56513ac6fde647d3b26ebbb4427341a7357 | refs/heads/master | 2020-03-18T15:57:37.838896 | 2018-05-24T20:10:57 | 2018-05-24T20:10:57 | 134,939,549 | 0 | 0 | null | 2018-05-26T07:30:18 | 2018-05-26T07:30:18 | null | UTF-8 | C++ | false | false | 11,119 | h | // Copyright (c) 2018, ReCoal Project
// Copyright (c) 2014-2018, The Monero 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#pragma once
#include <string>
#include <boost/uuid/uuid.hpp>
#define CRYPTONOTE_DNS_TIMEOUT_MS 20000
#define CRYPTONOTE_MAX_BLOCK_NUMBER 500000000
#define CRYPTONOTE_MAX_BLOCK_SIZE 500000000 // block header blob limit, never used!
#define CRYPTONOTE_GETBLOCKTEMPLATE_MAX_BLOCK_SIZE 196608 //size of block (bytes) that is the maximum that miners will produce
#define CRYPTONOTE_MAX_TX_SIZE 1000000000
#define CRYPTONOTE_PUBLIC_ADDRESS_TEXTBLOB_VER 0
#define CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW 60
#define CURRENT_TRANSACTION_VERSION 2
#define CURRENT_BLOCK_MAJOR_VERSION 1
#define CURRENT_BLOCK_MINOR_VERSION 0
#define CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT 60*60*2
#define CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE 10
#define BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW 60
// MONEY_SUPPLY - total number coins to be generated
#define MONEY_SUPPLY ((uint64_t)(-1))
#define EMISSION_SPEED_FACTOR_PER_MINUTE (20)
#define FINAL_SUBSIDY_PER_MINUTE ((uint64_t)300000000000) // 3 * pow(10, 11)
#define CRYPTONOTE_REWARD_BLOCKS_WINDOW 100
#define CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2 60000 //size of block (bytes) after which reward for block calculated using block size
#define CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1 20000 //size of block (bytes) after which reward for block calculated using block size - before first fork
#define CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5 300000 //size of block (bytes) after which reward for block calculated using block size - second change, from v5
#define CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE 600
#define CRYPTONOTE_DISPLAY_DECIMAL_POINT 12
// COIN - number of smallest units in one coin
#define COIN ((uint64_t)1000000000000) // pow(10, 12)
#define FEE_PER_KB_OLD ((uint64_t)10000000000) // pow(10, 10)
#define FEE_PER_KB ((uint64_t)2000000000) // 2 * pow(10, 9)
#define DYNAMIC_FEE_PER_KB_BASE_FEE ((uint64_t)2000000000) // 2 * pow(10,9)
#define DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD ((uint64_t)10000000000000) // 10 * pow(10,12)
#define DYNAMIC_FEE_PER_KB_BASE_FEE_V5 ((uint64_t)2000000000 * (uint64_t)CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2 / CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5)
#define ORPHANED_BLOCKS_MAX_COUNT 100
#define DIFFICULTY_TARGET_V2 120 // seconds
#define DIFFICULTY_TARGET_V1 60 // seconds - before first fork
#define DIFFICULTY_WINDOW 720 // blocks
#define DIFFICULTY_LAG 15 // !!!
#define DIFFICULTY_CUT 60 // timestamps to cut after sorting
#define DIFFICULTY_BLOCKS_COUNT DIFFICULTY_WINDOW + DIFFICULTY_LAG
#define CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1 DIFFICULTY_TARGET_V1 * CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS
#define CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 DIFFICULTY_TARGET_V2 * CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS
#define CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS 1
#define DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN DIFFICULTY_TARGET_V1 //just alias; used by tests
#define BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT 10000 //by default, blocks ids count in synchronizing
#define BLOCKS_SYNCHRONIZING_DEFAULT_COUNT_PRE_V4 100 //by default, blocks count in blocks downloading
#define BLOCKS_SYNCHRONIZING_DEFAULT_COUNT 20 //by default, blocks count in blocks downloading
#define CRYPTONOTE_MEMPOOL_TX_LIVETIME (86400*3) //seconds, three days
#define CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME 604800 //seconds, one week
#define COMMAND_RPC_GET_BLOCKS_FAST_MAX_COUNT 1000
#define P2P_LOCAL_WHITE_PEERLIST_LIMIT 1000
#define P2P_LOCAL_GRAY_PEERLIST_LIMIT 5000
#define P2P_DEFAULT_CONNECTIONS_COUNT 8
#define P2P_DEFAULT_HANDSHAKE_INTERVAL 60 //secondes
#define P2P_DEFAULT_PACKET_MAX_SIZE 50000000 //50000000 bytes maximum packet size
#define P2P_DEFAULT_PEERS_IN_HANDSHAKE 250
#define P2P_DEFAULT_CONNECTION_TIMEOUT 5000 //5 seconds
#define P2P_DEFAULT_PING_CONNECTION_TIMEOUT 2000 //2 seconds
#define P2P_DEFAULT_INVOKE_TIMEOUT 60*2*1000 //2 minutes
#define P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT 5000 //5 seconds
#define P2P_DEFAULT_WHITELIST_CONNECTIONS_PERCENT 70
#define P2P_DEFAULT_ANCHOR_CONNECTIONS_COUNT 2
#define P2P_FAILED_ADDR_FORGET_SECONDS (60*60) //1 hour
#define P2P_IP_BLOCKTIME (60*60*24) //24 hour
#define P2P_IP_FAILS_BEFORE_BLOCK 10
#define P2P_IDLE_CONNECTION_KILL_INTERVAL (5*60) //5 minutes
#define P2P_SUPPORT_FLAG_FLUFFY_BLOCKS 0x01
#define P2P_SUPPORT_FLAGS P2P_SUPPORT_FLAG_FLUFFY_BLOCKS
#define ALLOW_DEBUG_COMMANDS
#define CRYPTONOTE_NAME "recoal"
#define CRYPTONOTE_POOLDATA_FILENAME "poolstate.bin"
#define CRYPTONOTE_BLOCKCHAINDATA_FILENAME "data.mdb"
#define CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME "lock.mdb"
#define P2P_NET_DATA_FILENAME "p2pstate.bin"
#define MINER_CONFIG_FILE_NAME "miner_conf.json"
#define THREAD_STACK_SIZE 5 * 1024 * 1024
#define HF_VERSION_DYNAMIC_FEE 4
#define HF_VERSION_MIN_MIXIN_4 6
#define HF_VERSION_MIN_MIXIN_6 7
#define HF_VERSION_ENFORCE_RCT 6
#define PER_KB_FEE_QUANTIZATION_DECIMALS 8
#define HASH_OF_HASHES_STEP 256
#define DEFAULT_TXPOOL_MAX_SIZE 648000000ull // 3 days at 300000, in bytes
// New constants are intended to go here
namespace config
{
uint64_t const DEFAULT_FEE_ATOMIC_XMR_PER_KB = 500; // Just a placeholder! Change me!
uint8_t const FEE_CALCULATION_MAX_RETRIES = 10;
uint64_t const DEFAULT_DUST_THRESHOLD = ((uint64_t)2000000000); // 2 * pow(10, 9)
uint64_t const BASE_REWARD_CLAMP_THRESHOLD = ((uint64_t)100000000); // pow(10, 8)
std::string const P2P_REMOTE_DEBUG_TRUSTED_PUB_KEY = "0000000000000000000000000000000000000000000000000000000000000000";
uint64_t const CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX = 0xd6; //co
uint64_t const CRYPTONOTE_PUBLIC_INTEGRATED_ADDRESS_BASE58_PREFIX = 0x3dd5; //ci
uint64_t const CRYPTONOTE_PUBLIC_SUBADDRESS_BASE58_PREFIX = 0x7b54; //cc
uint16_t const P2P_DEFAULT_PORT = 12121;
uint16_t const RPC_DEFAULT_PORT = 12122;
uint16_t const ZMQ_RPC_DEFAULT_PORT = 12123;
boost::uuids::uuid const NETWORK_ID = { {
0xdf, 0xb3, 0xed, 0x71, 0x82, 0x9e, 0xb0, 0xe9, 0x34, 0x0e, 0x42, 0xbd, 0xee, 0x86, 0x90, 0xfb
} }; // Bender's nightmare
std::string const GENESIS_TX = "013c01ff0001ffffffffffff03026a7e01fb9d6cac5f7db1d6c11b8c86a5387f9e611967d11c1afb11e592a3c39221015dc9e284b11c63bd4e8373cccf738e0250f8d9049a1cb6e69cd2cc00a1a3542c";
uint32_t const GENESIS_NONCE = 10000;
namespace testnet
{
uint64_t const CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX = 0x4e56; // ct
uint64_t const CRYPTONOTE_PUBLIC_INTEGRATED_ADDRESS_BASE58_PREFIX = 0x4ad6; // cti
uint64_t const CRYPTONOTE_PUBLIC_SUBADDRESS_BASE58_PREFIX = 0x48956; // ctc
uint16_t const P2P_DEFAULT_PORT = 22121;
uint16_t const RPC_DEFAULT_PORT = 22122;
uint16_t const ZMQ_RPC_DEFAULT_PORT = 22123;
boost::uuids::uuid const NETWORK_ID = { {
0xa6, 0x12, 0x3f, 0x7a, 0x52, 0x60, 0x4c, 0x75, 0x0c, 0xcd, 0x8e, 0xc3, 0x48, 0x03, 0xa1, 0x64
} }; // Bender's daydream
std::string const GENESIS_TX = "013c01ff0001ffffffffffff03029b2e4c0281c0b02e7c53291a94d1d0cbff8883f8024f5142ee494ffbbd08807121017767aafcde9be00dcfd098715ebcf7f410daebc582fda69d24a28e9d0bc890d1";
uint32_t const GENESIS_NONCE = 10001;
}
namespace stagenet
{
uint64_t const CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX = 0x7753; //cS
uint64_t const CRYPTONOTE_PUBLIC_INTEGRATED_ADDRESS_BASE58_PREFIX = 0x73d3; //cSi
uint64_t const CRYPTONOTE_PUBLIC_SUBADDRESS_BASE58_PREFIX = 0x75d3; //cSs
uint16_t const P2P_DEFAULT_PORT = 32121;
uint16_t const RPC_DEFAULT_PORT = 32122;
uint16_t const ZMQ_RPC_DEFAULT_PORT = 32123;
boost::uuids::uuid const NETWORK_ID = { {
0x12 ,0x31, 0xF1, 0x71 , 0x61, 0x04 , 0x41, 0x6a, 0x17, 0x31, 0x00, 0x8f, 0x16, 0xA1, 0xA1, 0x12
} }; // Bender's daydream
std::string const GENESIS_TX = "013c01ff0001ffffffffffff0302df5d56da0c7d643ddd1ce61901c7bdc5fb1738bfe39fbe69c28a3a7032729c0f2101168d0c4ca86fb55a4cf6a36d31431be1c53a3bd7411bb24e8832410289fa6f3b";
uint32_t const GENESIS_NONCE = 10002;
}
}
namespace cryptonote
{
enum network_type : uint8_t
{
MAINNET = 0,
TESTNET,
STAGENET,
FAKECHAIN,
UNDEFINED = 255
};
}
| [
"[email protected]"
] | |
8df1eecb92c6906f40936906d9e8b94d1c6b48d4 | e105aa526b1e17bad15345700d1844690f42db69 | /kirakira_bleimage/mode_bright.cpp | 722d9cb1816fa0cb6f7ed70ef0b793b0f5bcc2a1 | [] | no_license | carcon999/kirakira_bleimage | b23abda3cac697fd5f3c5d221895bfa08b9f8fb5 | 5a7d5c8f499cce5fffc143f26b93e1d627317481 | refs/heads/master | 2020-05-25T05:47:48.228773 | 2019-07-02T14:32:45 | 2019-07-02T14:32:45 | 187,656,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp |
#include "arduino.h"
#include "mode_ble.h"
#include "drv_ledbar.h"
#include "drv_beep.h"
#include "drv_display.h"
#include "drv_key.h"
#include "mode_bright.h"
using namespace kirabit;
#define LEVEL_MIN 0
#define LEVEL_MAX 4
#define BRIGHT_MODE_TIMEOUT (2000)
// global instance
kirabit::ModeBright MODE_BRIGHT;
ModeBright::ModeBright()
{
img_bright = LEVEL_MAX;
}
void ModeBright::start(void)
{
ModeBase::start();
#ifdef DEBUG_SERIAL_ON
Serial.println("* start Bright mode");
#endif
// 明るさ指定モードへ
DSP5x5.begin();
DSP5x5.level(img_bright);
m_tout = millis() + BRIGHT_MODE_TIMEOUT;
}
void ModeBright::stop(void)
{
DSP5x5.end();
}
void ModeBright::main(void)
{
if(KEY.is_pushed(kirabit::BTN::A))
{
BEEP.tone(4000, 20);
img_bright++;
if(img_bright > LEVEL_MAX){
img_bright = LEVEL_MIN;
}
DSP5x5.level(img_bright);
m_tout = millis() + BRIGHT_MODE_TIMEOUT;
}
else if(millis() > m_tout)
{
LEDBAR.setBright(img_bright);
m_change = true;
}
}
| [
"[email protected]"
] | |
b5f86b17323e5d43937e8c292b32bedc0977e207 | a37bfc73b0421abe419c29b285fec41c17070320 | /src/yb/common/clock.cc | b3234c2ab6523c92fe93c8b3bd840e21d10dbe3f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL"
] | permissive | ymahajan/yugabyte-db | 939c0e11cef985cbb152c48b28d73c28c9f78750 | c3bfef94eb2ed59836771ab419f3d5403fa888f5 | refs/heads/master | 2023-06-27T02:56:00.446944 | 2021-02-18T20:26:27 | 2021-07-29T22:23:22 | 376,983,542 | 1 | 1 | NOASSERTION | 2021-06-14T23:44:38 | 2021-06-14T23:44:37 | null | UTF-8 | C++ | false | false | 1,454 | cc | // Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/common/clock.h"
#include <thread>
using namespace std::literals;
DEFINE_uint64(wait_hybrid_time_sleep_interval_us, 10000,
"Sleep interval in microseconds that will be used while waiting for specific "
"hybrid time.");
namespace yb {
Result<HybridTime> WaitUntil(ClockBase* clock, HybridTime hybrid_time, CoarseTimePoint deadline) {
auto ht_now = clock->Now();
while (ht_now < hybrid_time) {
if (CoarseMonoClock::now() > deadline) {
return STATUS_FORMAT(TimedOut, "Timed out waiting for $0, now $1", deadline, ht_now);
}
auto delta_micros = hybrid_time.GetPhysicalValueMicros() - ht_now.GetPhysicalValueMicros();
std::this_thread::sleep_for(
std::max(FLAGS_wait_hybrid_time_sleep_interval_us, delta_micros) * 1us);
ht_now = clock->Now();
}
return ht_now;
}
} // namespace yb
| [
"[email protected]"
] | |
18843a74d7def41ab9034b3014bfb2c2f8af1e56 | 82ac8fa864d4386c9b69489aacabc2c5a98e4aff | /OikakeCppPractice3/OikakeCppPractice/src/main.cpp | 63400a18111465d9eb33736ddc54eb7c8362e230 | [] | no_license | ITSUKI0910/team10_2018 | ac4260b966d2b07f66f51a8e91db374955c1857a | f3a8e67f055c6633eae6a01d6b5cc02a54f5a2bf | refs/heads/master | 2021-10-10T10:36:56.104012 | 2019-01-09T14:49:15 | 2019-01-09T14:49:15 | 160,620,741 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 271 | cpp | #include<DxLib.h>
#include"Application/GameFrame/GameFrame.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
return GameFrame().Run();
}
/*
1,30
履歴書
作品
羽田
3かい
二回受けることが出来る
*/ | [
"[email protected]"
] | |
0f5c3ff0d8e39269c53a459c57dcce0ebaad1c38 | 94708218e6209d344d0a33dd131c9482a9156bb1 | /ugr_ig-master/P4/Material.cc | 8983c979250bc0d33db91666865a8e917807300a | [] | no_license | lorenmanu/variado | d1f3493a20b0dc96427966b70d8f610a3893591b | f5c36e66ade9f0edd96a8c12a0a809bacb4b6618 | refs/heads/master | 2021-01-10T08:14:17.978568 | 2015-10-25T15:45:03 | 2015-10-25T15:45:03 | 36,402,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cc | /*
* Jesús Ángel González Novez
* Práctica 4 IG
*
*/
#include "Material.h"
Material::Material() {
isIlluminated = false;
texturePtr = NULL;
amb[3] = dis[3] = spe[3] = 1.0;
}
Material::Material(const char * materialFile) {
texturePtr = new Textura(materialFile);
amb[3] = dis[3] = spe[3] = 1.0;
}
Material::~Material() {
if (texturePtr != NULL)
delete texturePtr;
}
void Material::activate() {
glEnable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_NORMALIZE);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, amb);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, dis);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, spe);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, brillo);
if (texturePtr != NULL)
texturePtr->activate();
else
glDisable(GL_TEXTURE_2D);
}
void Material::setAmbient(GLfloat amb[3]) {
for (int i = 0; i < 4; i++)
this->amb[i] = amb[i];
}
void Material::setDiffuse(GLfloat dis[3]) {
for (int i = 0; i < 4; i++)
this->dis[i] = dis[i];
}
void Material::setSpecular(GLfloat spe[3]) {
for (int i = 0; i < 4; i++)
this->spe[i] = spe[i];
}
void Material::setBrightness(GLfloat brillo) {
this->brillo = brillo;
}
GLfloat * Material::getAmbient() const {
return (GLfloat *)this->amb;
}
GLfloat * Material::getDiffuse() const {
return (GLfloat *)this->dis;
}
GLfloat * Material::getSpecular() const {
return (GLfloat *)this->spe;
}
GLfloat Material::getBrillo() const {
return this->brillo;
}
| [
"[email protected]"
] | |
c6f190e12746639375c6352ad1b50c30a5a43431 | 82807ca4a9e755782778f02695461f6a083fdfdf | /offer_14/main.cpp | 2874a753168be263a8e095e957d470673ce4d12d | [] | no_license | hanny-liu/offer | b267e3ae32151d8d4d24f4eb30ab3f5b5a6742c7 | 62eac9d37ad10cb16925324fa8337ba098f225be | refs/heads/master | 2020-07-24T06:51:03.676844 | 2019-09-11T14:45:05 | 2019-09-11T14:45:05 | 207,835,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,948 | cpp | /*
剪绳子
给一根长度为n的绳子,请把绳子剪成m段(m\n都是整数,n>1且m>1),每段绳子的长度记为k[0],k[1],...k[m].
请问k[0]*k[1]*...*k[m]可能的最大乘积是多少?
例,当绳子长度是8时,我们把它剪成长度分别为2,3,3的三段,此时得到的最大乘积是18.
方法一:动态规划
从下到上,分别求出每个长度最大的乘积,f(n)=max(f(i)*f(n-i))
*/
/**
* 动态规划法:
* 动态规划求解问题的四个特征:
①求一个问题的最优解;
②整体的问题的最优解是依赖于各个子问题的最优解;
③小问题之间还有相互重叠的更小的子问题;
④从上往下分析问题,从下往上求解问题;
* 动态规划:
有一段长度为n的绳子,我们现在要剪第一刀,我可以选择下第一刀的地方有1~n-1这些地方;比如长度为10的绳子,我第一刀可以在1~9这些地方下刀,共9种方式。
第一刀下去后,绳子分成两部分,假设在i处下刀,绳子两部分就分别为:[0~i]与[i~n],长度分为表示为i与n-i;那么找出第一刀最合适的位置,其实就是找i在哪下刀,可以使得[0~i]与[i~n]的乘积最大,函数表示为:f(n)=max(f(i)×f(n−i))f(n)=max(f(i)×f(n−i))。
那么如何判断i处切最大呢?这个时候,我们就要知道,[0~i]这个长度的绳子,任意方式切,最大的乘积是多少;假如说,当我们要切一个长度为10的绳子:切成1和9与4和6,两种方式,哪个乘积更大?
回答:不光要考虑第一刀后两个绳子的大小,还要考虑到9、4、6这三种情况,因为第一刀切出的绳子长度是否可以再切第二刀,使它有更大的乘积,比如将9再切成 3×3×33×3×3,6切成 4×24×2,哪个更大?
这种情况下,我们可以发现,无论再怎么切,一定是越切越短,那么我们是否可以将小于给定长度的绳子的每一个长度的最大乘积都求出来?
即:长度为10的绳子,我们就计算出:长度1~9这9种长度的绳子,每种长度的最大乘积是多少。
要求长度9的绳子的最大乘积,我们要知道1~8各个长度的最大乘积,要知道长度8的最大乘积,就要知道1~7长度的各个最大乘积,以此类推。
*
* 动态规划版本
* f(n)定义为将长度为n的绳子分成若干段后的各段长度的最大乘积(最优解),在剪第一刀时有n-1种剪法,可选择在0 < i < n处下刀
* 在i处下刀,分成长度为i的左半绳子和长度为n-i的右半绳子,对于这两根绳子,定义最优解为f(i)和f(n-i),于是f(n) = max(f(i) * f(n-i)),即求出各种相乘可能中的最大值就是f(n)的最优解
* 就这样从上到下的分下去,但是问题的解决从下到上。即先求出f(2)、f(3)的最优解,然后根据这两个值求出f(4)、f(5)...直到f(n)
* f(2) = 1,因为只能分成两半
* f(3) = 2,因为分成两段2*1 大于分成三段的1*1*1
* ...
*/
#include <iostream>
#include <math.h>
using namespace std;
///动态规划
int maxProduct(int length)
{
if (length < 2) return 0;
if (length == 2) return 1;
if (length == 3) return 2;
int* products = new int[length + 1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (int i = 4; i <= length; ++i) {
max = 0;
for (int j = 1; j <= i / 2; ++j) {
int product = products[j] * products[i - j];
if (max < product)
max = product;
products[i] = max;
}
}
max = products[length];
delete[] products;
return max;
}
///贪心算法
/**
贪心算法在对问题求解时,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解;
选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关;
题目贪婪策略:当n>=5时,尽可能多地剪长度为3的绳子;当剩下的绳子长度为4时,把绳子剪成两段长度为2的绳子。
* @return
*/
int maxProduct1(int length)
{
if (length < 2) return 0;
if (length == 2) return 1;
if (length == 3) return 2;
int timesOf3 = length / 3;
if (length - timesOf3 * 3 == 1)
timesOf3--;
int timesOf2 = (length - timesOf3 * 3) / 2;
int result = pow(3, timesOf3) * pow(2, timesOf2);
return result;
}
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
} | [
"[email protected]"
] | |
453c6785c4e9092aaef70cdeacb8254b83d10e58 | d5b3641f180dd4edba75c1bcc48d45a05fae7770 | /Graph Basics/LargestAreaHistogram.cpp | c5aafd3224897231e6261b1231e85141aaccd1ec | [] | no_license | clicknshade/Cp-Practice | 0a1be56d3bdacc754d8088caa9d3570db7b549b9 | 627a26a326473aed26e9d8e9337044de372d883b | refs/heads/master | 2020-07-28T06:19:00.986831 | 2019-08-16T13:05:48 | 2019-08-16T13:05:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
int maxAreaHist(int a[],int n){
stack<int> s;
int maxArea,curArea;
int i=0,tp;
while(i<n) {
//current bar greater than previous bar
if (s.empty() || a[s.top()] <= a[i] ){
s.push(i++);
}
//if present bar is lower than higher
else {
tp = s.top();
s.pop();
if(s.empty()) {
//popped bar height * index
curArea = a[tp] * i;
}
else {
//popped bar height * (index- rightBound - 1);
curArea = a[tp] * (i - s.top() - 1);
}
if (curArea > maxArea) {
maxArea = curArea;
}
}
}
//pop all remaining bars
while(!s.empty()) {
tp = s.top();
s.pop();
if(s.empty()) {
curArea = a[tp] * i;
}
else {
curArea = a[tp] * (i - s.top() - 1);
}
if (curArea > maxArea) {
maxArea = curArea;
}
}
// cout<<maxArea<<endl;
return maxArea;
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<maxAreaHist(a,n)<<endl;
return 0;
} | [
"[email protected]"
] | |
80900e023afa015c3e72c228d957e8a309bb738c | bbdf7d39828129907c11b6a3b0745e9f3ff6117a | /problem0070.cpp | 5ff990c0cbfe459061d5c14012320d5f15e14603 | [] | no_license | DavieV/Euler | 9b25b27275f3adba82e1ae2653a5d27d37e49945 | d5eb59cb739cf003e02e0db5e63b6a3bcdfefa68 | refs/heads/master | 2021-01-18T16:11:21.723996 | 2015-02-12T17:42:49 | 2015-02-12T17:42:49 | 27,414,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,472 | cpp | #include <iostream>
#include "eutility.hpp"
#define MAX 10000000
int next_prime(int p, bool s[]);
void del_mult(int p, bool s[]);
int main() {
int *euler_sieve = new int[MAX]; // sieve for euler's totient function
bool *prime_sieve = new bool[MAX]; // sieve of prime numbers
for (int i = 0; i < MAX; ++i) {
prime_sieve[i] = true;
euler_sieve[i] = i;
}
prime_sieve[0] = false;
prime_sieve[1] = false;
int prime = 2;
// Complete the sieve of prime numbers
for (int i = 0; i * i < MAX; ++i) {
del_mult(prime, prime_sieve);
prime = next_prime(prime, prime_sieve);
}
// Complete the sieve of euler totient functions
for (int i = 1; i < MAX; ++i) {
if (prime_sieve[i]) {
for (int j = i; j < MAX; j += i)
euler_sieve[j] -= euler_sieve[j] / i;
}
}
double min = 1000000, tmp;
int n;
for (int i = 2; i < MAX; ++i) {
if (is_permutation(i, euler_sieve[i])) {
tmp = (double)(i) / (double)(euler_sieve[i]);
if (tmp < min) {
min = tmp;
n = i;
}
}
}
std::cout << n << " " << euler_sieve[n] << std::endl;
delete[] euler_sieve;
delete[] prime_sieve;
return 0;
}
int next_prime(int p, bool s[]) {
while (!s[++p]);
return p;
}
void del_mult(int p, bool s[]) {
for (int i = p * p; i < MAX; i +=p)
s[i] = false;
}
| [
"[email protected]"
] | |
fc81d4b765eef1836838ade971eb4c4fc9ac05a6 | ea6a9bcf02fe7d72df645302909b1de63cdf7fe0 | /src/script/standard.h | 7b2fb3bae62ebde1135e60ddda463fa241e7b395 | [
"MIT"
] | permissive | durgeshkmr/minicoin | 69a834786413122eb2b85731b20f0fda931c7a72 | 4f082abe13cd34a759bf8ffb344a49244615960e | refs/heads/master | 2020-05-04T22:59:23.367524 | 2019-04-06T16:13:28 | 2019-04-06T16:13:28 | 179,529,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,020 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MINICOIN_SCRIPT_STANDARD_H
#define MINICOIN_SCRIPT_STANDARD_H
#include <script/interpreter.h>
#include <uint256.h>
#include <boost/variant.hpp>
#include <stdint.h>
static const bool DEFAULT_ACCEPT_DATACARRIER = true;
class CKeyID;
class CScript;
/** A reference to a CScript: the Hash160 of its serialization (see script.h) */
class CScriptID : public uint160
{
public:
CScriptID() : uint160() {}
explicit CScriptID(const CScript& in);
CScriptID(const uint160& in) : uint160(in) {}
};
/**
* Default setting for nMaxDatacarrierBytes. 80 bytes of data, +1 for OP_RETURN,
* +2 for the pushdata opcodes.
*/
static const unsigned int MAX_OP_RETURN_RELAY = 83;
/**
* A data carrying output is an unspendable output containing data. The script
* type is designated as TX_NULL_DATA.
*/
extern bool fAcceptDatacarrier;
/** Maximum size of TX_NULL_DATA scripts that this node considers standard. */
extern unsigned nMaxDatacarrierBytes;
/**
* Mandatory script verification flags that all new blocks must comply with for
* them to be valid. (but old blocks may not comply with) Currently just P2SH,
* but in the future other flags may be added, such as a soft-fork to enforce
* strict DER encoding.
*
* Failing one of these tests may trigger a DoS ban - see CheckInputs() for
* details.
*/
static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
enum txnouttype
{
TX_NONSTANDARD,
// 'standard' transaction types:
TX_PUBKEY,
TX_PUBKEYHASH,
TX_SCRIPTHASH,
TX_MULTISIG,
TX_NULL_DATA, //!< unspendable OP_RETURN script that carries data
TX_WITNESS_V0_SCRIPTHASH,
TX_WITNESS_V0_KEYHASH,
TX_WITNESS_UNKNOWN, //!< Only for Witness versions not already defined above
};
class CNoDestination {
public:
friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
};
struct WitnessV0ScriptHash : public uint256
{
WitnessV0ScriptHash() : uint256() {}
explicit WitnessV0ScriptHash(const uint256& hash) : uint256(hash) {}
explicit WitnessV0ScriptHash(const CScript& script);
using uint256::uint256;
};
struct WitnessV0KeyHash : public uint160
{
WitnessV0KeyHash() : uint160() {}
explicit WitnessV0KeyHash(const uint160& hash) : uint160(hash) {}
using uint160::uint160;
};
//! CTxDestination subtype to encode any future Witness version
struct WitnessUnknown
{
unsigned int version;
unsigned int length;
unsigned char program[40];
friend bool operator==(const WitnessUnknown& w1, const WitnessUnknown& w2) {
if (w1.version != w2.version) return false;
if (w1.length != w2.length) return false;
return std::equal(w1.program, w1.program + w1.length, w2.program);
}
friend bool operator<(const WitnessUnknown& w1, const WitnessUnknown& w2) {
if (w1.version < w2.version) return true;
if (w1.version > w2.version) return false;
if (w1.length < w2.length) return true;
if (w1.length > w2.length) return false;
return std::lexicographical_compare(w1.program, w1.program + w1.length, w2.program, w2.program + w2.length);
}
};
/**
* A txout script template with a specific destination. It is either:
* * CNoDestination: no destination set
* * CKeyID: TX_PUBKEYHASH destination (P2PKH)
* * CScriptID: TX_SCRIPTHASH destination (P2SH)
* * WitnessV0ScriptHash: TX_WITNESS_V0_SCRIPTHASH destination (P2WSH)
* * WitnessV0KeyHash: TX_WITNESS_V0_KEYHASH destination (P2WPKH)
* * WitnessUnknown: TX_WITNESS_UNKNOWN destination (P2W???)
* A CTxDestination is the internal data type encoded in a minicoin address
*/
typedef boost::variant<CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown> CTxDestination;
/** Check whether a CTxDestination is a CNoDestination. */
bool IsValidDestination(const CTxDestination& dest);
/** Get the name of a txnouttype as a C string, or nullptr if unknown. */
const char* GetTxnOutputType(txnouttype t);
/**
* Parse a scriptPubKey and identify script type for standard scripts. If
* successful, returns script type and parsed pubkeys or hashes, depending on
* the type. For example, for a P2SH script, vSolutionsRet will contain the
* script hash, for P2PKH it will contain the key hash, etc.
*
* @param[in] scriptPubKey Script to parse
* @param[out] typeRet The script type
* @param[out] vSolutionsRet Vector of parsed pubkeys and hashes
* @return True if script matches standard template
*/
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
/**
* Parse a standard scriptPubKey for the destination address. Assigns result to
* the addressRet parameter and returns true if successful. For multisig
* scripts, instead use ExtractDestinations. Currently only works for P2PK,
* P2PKH, P2SH, P2WPKH, and P2WSH scripts.
*/
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
/**
* Parse a standard scriptPubKey with one or more destination addresses. For
* multisig scripts, this populates the addressRet vector with the pubkey IDs
* and nRequiredRet with the n required to spend. For other destinations,
* addressRet is populated with a single value and nRequiredRet is set to 1.
* Returns true if successful. Currently does not extract address from
* pay-to-witness scripts.
*
* Note: this function confuses destinations (a subset of CScripts that are
* encodable as an address) with key identifiers (of keys involved in a
* CScript), and its use should be phased out.
*/
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
/**
* Generate a Minicoin scriptPubKey for the given CTxDestination. Returns a P2PKH
* script for a CKeyID destination, a P2SH script for a CScriptID, and an empty
* script for CNoDestination.
*/
CScript GetScriptForDestination(const CTxDestination& dest);
/** Generate a P2PK script for the given pubkey. */
CScript GetScriptForRawPubKey(const CPubKey& pubkey);
/** Generate a multisig script. */
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys);
/**
* Generate a pay-to-witness script for the given redeem script. If the redeem
* script is P2PK or P2PKH, this returns a P2WPKH script, otherwise it returns a
* P2WSH script.
*
* TODO: replace calls to GetScriptForWitness with GetScriptForDestination using
* the various witness-specific CTxDestination subtypes.
*/
CScript GetScriptForWitness(const CScript& redeemscript);
#endif // MINICOIN_SCRIPT_STANDARD_H
| [
"[email protected]"
] | |
73722e40bae9fd1897234e6f698c2ba6d3e197d6 | 4512f06cae743a0c9863802df6efa100a970c758 | /Tortoise-Core/libs/AtlasUtils.h | c3aea6b4e88c40e1c372eb09e33a5fd195d213a8 | [] | no_license | jjenki11/tortoise-dti | d38da5f214d90860352f52c4a34679b3f4707a2c | a938c063c41022c040266d921350bdd70e9dd3f3 | refs/heads/master | 2020-04-16T13:40:49.352875 | 2015-10-06T19:10:32 | 2015-10-06T19:10:32 | 40,923,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,424 | h | #include <list>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <string>
#include <stdio.h>
#include <string>
#include <cstring>
#include <setjmp.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "AtlasGraphUtils.h"
using
namespace
std;
/*
Subject structure
*/
struct
subject {
int index; // order in list (?)
string name; // name without *.nii extension
string path; // path to nii file
};
/*
Group structure
*/
struct
group {
list<subject> subjects; // list of JSON objects for graph
list<string> transforms; // transforms in queue for procedure
string label; // <group_name>
string path; // <name>_list.txt
string template_path; // average_diffeo_6.nii
bool final_target; // is this the final target? a.k.a. is an atlas without subject data
};
/*
Atlas structure
*/
struct
atlas {
// list<std::pair<group, group> > groupRelations; // TBD
list<group> groups; // list of group nodes
list<std::pair<string, string> > relations; // list of relations requiring relations(i).first -> relations(i).second
list<std::pair<string, string> > transforms; // transforms in queue for procedure
string label; // possibly could have more than one atlas object
};
/************ BELOW ARE (BLOCKING) FUNCTIONS WHICH CALL EXTERNAL FUNCTIONALITY ************/
/*
CombineTransformations
*/
int
runExternal_CombineTransformations(char *ppid, char *arg1, char *arg2 )
{
std::cout << "Combining Transformations ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/raid1b/STBBapps/DTIREG/bin/CombineTransformations",
"/raid1b/STBBapps/DTIREG/bin/CombineTransformations",
arg1,
arg2,
(char *)0
);
perror("execl error");
_exit(0);
}
};
/*
CombineTransformations helper
*/
int
runExternal_CombineTransformations_helper(char *ppid, char *arg1, char *arg2, char *arg3 )
{
std::cout << "Combining Transformations with helper ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/combine_xform_helper.sh",
"/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/combine_xform_helper.sh",
arg1,
arg2,
arg3,
(char *)0
);
perror("execl error");
_exit(0);
}
};
/*
ApplyTransformationToTensor -> <original>, <combined_displacement>, <output_file>, <reorientation_type>, <provide final atlas for correct dimensions>
*/
int
runExternal_ApplyTransformationToTensor(char *ppid, char *orig_tens, char *comb_disp, char *out_file, char *ref_size )
{
std::cout << "Applying Transformation to Tensor ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/raid1b/STBBapps/DTIREG/bin/ApplyTransformationToTensor",
"/raid1b/STBBapps/DTIREG/bin/ApplyTransformationToTensor",
orig_tens,
comb_disp,
out_file,
"FS",
ref_size,
(char *)0
);
perror("execl error");
_exit(0);
}
};
/*
Batch_Import_DTIREG
*/
int
runExternal_Batch_Import_DTIREG(char *ppid, char *file_path )
{
std::cout << "Running DTIREG create template ..." << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/idl_help_script.sh",
"/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/idl_help_script.sh",
file_path,
(char *)0
);
perror("execl error");
_exit(0);
}
};
/*
DTIREG_Create_Template
*/
int
runExternal_DTIREG_Create_Template(char *ppid, char *txt_file, char *step_num, char *path_to_exe)
{
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { // I am the parent - wait for the child to finish //
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { // I am the child rawr //
string tf(txt_file);
if(tf.empty())
{
std::cout << "NO FILE PROVIDED, SKIPPING." << std::endl;
_exit(0);
}
else
{
std::cout << "Running DTIREG create template ..." << std::endl;
execl("/raid1b/STBBapps/DTIREG/bin/dtireg_create_template_jeff",
"/raid1b/STBBapps/DTIREG/bin/dtireg_create_template_jeff",
txt_file,
step_num,
path_to_exe,
(char *)0
);
perror("execl error");
_exit(0);
}
}
return 1;
}
/*
DTIREG
*/
int
runExternal_DTIREG(char *ppid, char *fixed_tensor, char *moving_tensor)
{
std::cout << "Running DTIREG ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/raid1e/raid1_restore/codes/my_codes/DTIReg/DTIReg/DTIREG",
"/raid1e/raid1_restore/codes/my_codes/DTIReg/DTIReg/DTIREG",
"--fixed_tensor",
fixed_tensor, //TARGET (DESIRED SPACE)
"--moving_tensor",
moving_tensor, //MOVING (ORIGINAL SPACE)
"--metric",
"DTITK",
"--metric",
"Trace",
"-t",
"SyN\[0.75,3,0.5\]",
"-c",
"100x100x100",
"-f",
"4x2x1",
"-s",
"0.5x0.25x0",
"--final_reorientation",
"FS",
(char *)0
);
perror("execl error with dtireg... :(");
_exit(0);
}
};
/*
DTIREG
*/
int
runExternal_get_xform_files(char *ppid, char *group_folder, char *group_name)
{
std::cout << "Running Get XFORM files ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/get_xform_files.sh",
"/stbb_home/jenkinsjc/Desktop/Trepo/Tortoise-Core/libs/get_xform_files.sh",
group_folder,
group_name,
(char *)0
);
perror("execl error with get_xform_helper... :(");
_exit(0);
}
};
int
runExternal_reg_and_combine(char *ppid, char *path, char *grp1, char *grp2)
{
std::cout << "Running reg and combine ... " << std::endl;
int status;
pid_t child = fork();
if (child == -1) return 1; //Failed
if (child > 0) { /* I am the parent - wait for the child to finish */
pid_t pid = waitpid(child, &status, 0);
if (pid != -1 && WIFEXITED(status)) {
int low8bits = WEXITSTATUS(status);
printf("Process %d returned %d\n" , pid, low8bits);
}
else {
printf("NOT SURE WHAT THIS COND IS!\n");
}
} else { /* I am the child rawr */
execl("/raid1b/STBBapps/DTIREG/bin/reg_and_combine.sh",
"/raid1b/STBBapps/DTIREG/bin/reg_and_combine.sh",
path,
grp1,
grp2,
(char *)0
);
perror("execl error with get_xform_helper... :(");
_exit(0);
}
}
/*
Generic element printer
*/
template <class T>
inline void
PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos=coll.begin(); pos!=coll.end(); ++pos)
{
std::cout << *pos << ' ';
}
std::cout << std::endl;
};
/*
Prints all info for each member of a group
*/
void
print_group_members( group g )
{
for (std::list<subject>::const_iterator iterator = g.subjects.begin(), end = g.subjects.end(); iterator != end; ++iterator)
{
subject s = *iterator;
std::cout << "subject #" << s.index << '\n';
std::cout << " path: " << s.path << '\n';
std::cout << " name: " << s.name << '\n';
std::cout << "\n";
}
std::cout << std::endl;
};
/*
Creates list of subjects contained in group file
*/
list<subject>
create_subjects_from_group_file( const char * fname )
{
list<subject> subs;
FILE *fr; /* declare the file pointer */
char line[255];
fr = fopen (fname, "rt");
list<string> lines;
while(fgets(line, 255, fr) != NULL)
{
//lines.push_back(line);
subject tmp;
tmp.path = line;
tmp.name = fname;
subs.push_back(tmp);
}
fclose(fr);
return subs;
// return lines;
};
/*
Prints a list of strings
*/
void
print_string_list( list<string> s )
{
for (std::list<string>::const_iterator iterator = s.begin(), end = s.end(); iterator != end; ++iterator)
{
string theString = *iterator;
std::cout << theString << "\n";
}
};
/*
Prints paired group labels
*/
void
print_group_pair_labels( std::pair<group,group> thePair )
{
std::cout << thePair.first.label << "->" << thePair.second.label << "\n";
};
/*
Prints a string pair
*/
void
print_string_pair( std::pair<string,string> thePair)
{
std::cout << thePair.first << "->" << thePair.second << "\n";
};
/*
Prints relation pairs from a given atlas
*/
void
print_atlas_pairs( atlas at )
{
for (std::list<std::pair<string, string> >::const_iterator iterator = at.relations.begin(), end = at.relations.end(); iterator != end; ++iterator)
{
std::pair<string, string> aPair = *iterator;
print_string_pair(aPair);
}
};
/*
This will return a list of all var->file mappings in string form
first arg is of the form:
"patients=/path/to/file/containing/patient/nii/files.txt,"...=..."
*/
list<string>
get_file_mappings( string x )
{
list<string> rels;
std::string delimiter = ",";
size_t pos = 0;
std::string token;
while ((pos = x.find(delimiter)) != std::string::npos)
{
token = x.substr(0, pos);
rels.push_back(token);
x.erase(0, pos + delimiter.length());
}
rels.push_back(x);
return rels;
};
/*
This will return a list of all relations in string form
i.e. - list<"a->b", "b->c", ...>
*/
list<string>
get_relation_mappings( string x )
{
list<string> maps;
std::string delimiter = ",";
size_t pos = 0;
std::string token;
while ((pos = x.find(delimiter)) != std::string::npos)
{
token = x.substr(0, pos);
maps.push_back(token);
x.erase(0, pos + delimiter.length());
}
maps.push_back(x);
return maps;
};
/*
This will make variable -> path pairs for all groups passed in input
*/
list<std::pair<string, string> >
make_var_path_pairs(list<string> theList)
{
char tab2[1024];
list<std::pair<string,string> > pairList;
std::pair<string,string> tmpPair;
std::string first;
std::string last;
for (std::list<string>::const_iterator iterator = theList.begin(), end = theList.end(); iterator != end; ++iterator)
{
int counter = 0;
string theString = *iterator;
strncpy(tab2, theString.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
char * pch;
pch = strtok (tab2,"=");
first = pch;
while (pch != NULL)
{
++counter;
if(counter > 1)
{
last = pch;
}
pch = strtok (NULL, "=");
}
tmpPair = std::make_pair(first, last);
//print_string_pair(tmpPair);
pairList.push_back(tmpPair);
}
return pairList;
};
/*
This will make relations from input and returns an atlas
*/
atlas
make_atlas_relations(list<string> theList)
{
atlas at;
char tab2[1024];
list<std::pair<string,string> > pairList;
std::pair<string,string> tmpPair;
std::string first;
std::string last;
for (std::list<string>::const_iterator iterator = theList.begin(), end = theList.end(); iterator != end; ++iterator)
{
int counter = 0;
string theString = *iterator;
strncpy(tab2, theString.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
char * pch;
pch = strtok (tab2,"->");
first = pch;
while (pch != NULL)
{
++counter;
if(counter > 1)
{
last = pch;
}
pch = strtok (NULL, "->");
}
tmpPair = std::make_pair(first, last);
pairList.push_back(tmpPair);
}
at.relations = pairList;
at.label = "Main Atlas";
return at;
};
/*
This will return a group within an atlas having a specified label
*/
group
get_group_with_label(atlas at, string lbl)
{
list<group> gList = at.groups;
group found;
for (std::list<group>::const_iterator iterator = gList.begin(), end = gList.end(); iterator != end; ++iterator)
{
group tmp = *iterator;
if((tmp.label).compare(lbl) == 0)
{
found = tmp;
return found;
}
}
return found;
};
/*
This will create a list of groups, a label and the path to list file containing subject file paths per group
*/
list<group>
create_groups(list<std::pair<string, string> > maps, int makeTemplate)
{
list<group> gList;
for (list<std::pair<string, string> >::const_iterator iterator = maps.begin(), end = maps.end(); iterator != end; ++iterator)
{
std::pair<string, string> tPair = *iterator;
group tmp;
tmp.label = tPair.first;
const char * file_path = (tPair.second).c_str();
std::cout << file_path <<"\n";
tmp.subjects = create_subjects_from_group_file(file_path);
tmp.path = tPair.second;
if((makeTemplate == 1) && (strcmp(tmp.label.c_str(), "c") == 0))
{
std::cout << "Making new template for file: "<<file_path<<std::endl;
runExternal_DTIREG_Create_Template("1234",
(char *)file_path,
"0",
"/raid1b/STBBapps/DTIREG/bin/"
);
}
else
{
std::cout << "Looks like you already have templates, moving on ... " << std::endl;
}
gList.push_back(tmp);
}
return gList;
};
list<group>
get_groups(atlas at)
{
return at.groups;
};
/*
This will take a group and print out the paths of subjects
*/
void
print_subject_paths(group grp)
{
list<subject> sList = grp.subjects;
for (std::list<subject>::const_iterator iterator = sList.begin(), end = sList.end(); iterator != end; ++iterator)
{
subject tmp = *iterator;
std::cout << "\t" << tmp.path;
}
};
/*
This will take an atlas and print out the group labels as well as the subject paths within each group
*/
void
print_group_labels(atlas at)
{
list<group> gList = at.groups;
for (std::list<group>::const_iterator iterator = gList.begin(), end = gList.end(); iterator != end; ++iterator)
{
group tmp = *iterator;
std::cout << tmp.label << "\n";
//print_subject_paths(tmp);
}
};
/*
This will take an atlas and print out the group relations
*/
void
print_group_relations(atlas at)
{
list<std::pair<string, string> > rels = at.relations;
for (std::list<std::pair<string, string> >::const_iterator iterator = rels.begin(), end = rels.end(); iterator != end; ++iterator)
{
std::pair<string, string> tmp = *iterator;
print_string_pair(tmp);
}
};
list<std::pair<string, string> >
generate_intermediate_graphs(atlas at)
{
list<std::pair<string, string> > rels = at.relations;
list<std::pair<string, string> > new_rels;
for (std::list<std::pair<string, string> >::const_iterator iterator = rels.begin(), end = rels.end(); iterator != end; ++iterator)
{
std::pair<string, string> tmp = *iterator;
string lhs = tmp.first;
string rhs = tmp.second;
string mid = lhs+"_"+rhs;
std::pair<string, string> p1 = make_pair(lhs,mid);
std::pair<string, string> p2 = make_pair(mid,rhs);
new_rels.push_back(p1);
new_rels.push_back(p2);
}
return new_rels;
};
string
get_final_target(atlas at)
{
list<std::pair<string, string> > rels = at.relations;
string lhs;
string rhs;
string final_target;
for (std::list<std::pair<string, string> >::const_iterator iterator = rels.begin(), end = rels.end(); iterator != end; ++iterator)
{
std::pair<string, string> tmp = *iterator;
if(lhs.empty() && rhs.empty())
{
lhs = tmp.first;
final_target = rhs = tmp.second;
}
else
{
lhs = tmp.first;
rhs = tmp.second;
if(strcmp(final_target.c_str(), lhs.c_str()) == 0)
{
std::cout << "replacing final target "<<final_target<<" with "<<rhs<<"."<<std::endl;
final_target = rhs;
}
}
}
std::cout << "final target value is: "<<final_target<<"."<<std::endl;
return final_target;
};
void
set_final_group_label(atlas at)
{
group g = get_group_with_label(at, get_final_target(at));
g.final_target = 1;
};
//list<std::pair<string, string> >
void
create_transforms(atlas at)
{
print_group_relations(at);
group control = get_group_with_label(at, "c");
group patient = get_group_with_label(at, "p");
//std::cout << "GROUP CONTROL PATH = " << control.path << "\n\n\n";
//std::cout << "GROUP PATIENT PATH = " << patient.path << "\n\n\n";
runExternal_get_xform_files("1234",
(char *)patient.path.c_str(),
(char *)patient.label.c_str());
runExternal_get_xform_files("1234",
(char *)control.path.c_str(),
(char *)control.label.c_str());
// return NULL;
};
void
reg_and_combine(string ppid, string path, string a, string b)
{
runExternal_reg_and_combine("1234",
(char *)path.c_str(),
(char *)a.c_str(),
(char *)b.c_str());
}
| [
"[email protected]"
] | |
195372d7c031ab6786421ffdc4f477d9e1648862 | 047b62f1ea767c717626e70bda9bf56c01678ed9 | /ColorImageClass.cpp | 0e0c52293a7b405507fcaee814a24f84044a836e | [] | no_license | aheldrich14/PPM-Image-Modifier | a8b5d0805a1bef35b9f2de647d488450b461faed | 6211caf3035d92b6d72127d24e380438216d19a8 | refs/heads/main | 2023-01-19T20:13:45.160710 | 2020-11-10T20:31:16 | 2020-11-10T20:31:16 | 311,775,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,132 | cpp | #include "ColorImageClass.h"
ColorImageClass::ColorImageClass()
{
pixelArr = 0;
}
ColorImageClass::~ColorImageClass()
{
if (pixelArr) //only delete pointers if they exist
{
for (int i = 0; i < imgRec.getHght(); i++)
{
delete [] pixelArr[i];
}
delete [] pixelArr;
}
}
bool ColorImageClass::readImageFile(string &errMsg)
{
ifstream inFile;
bool success = false;
bool isOpen = false;
string imgFileMsg = "Enter string for PPM image file name to load: ";
string eofVals = "";
isOpen = openInputFile(inFile, imgFileMsg, errMsg);
if (isOpen)
{
//file must contain valid header, height/width, max RBG, and pixels
if (processMagicNum(inFile, errMsg) &&
processHghtWdth(inFile, errMsg) &&
checkRbgVal(inFile, errMsg) &&
processPixels(inFile, errMsg))
{
inFile >> eofVals; //extract anything leftover
//make sure no extra values/junk at end of file
if (inFile.eof() && eofVals == "")
{
success = true;
}
else
{
errMsg = "Too many pixel values for width and height.";
}
}
inFile.close(); //always close file
}
return success;
}
bool ColorImageClass::openInputFile(ifstream &inFile,
string imgFileMsg,
string &errMsg)
{
string imgFileName;
bool success = false;
cout << imgFileMsg;
cin >> imgFileName;
inFile.open(imgFileName.c_str());
if (inFile.fail())
{
errMsg = "Unable to open input file!";
}
else
{
success = true;
}
return success;
}
bool ColorImageClass::processMagicNum(ifstream &inFile, string &errMsg)
{
bool success = false;
string magicNum;
if (inFile >> magicNum)
{
success = (magicNum == MAGIC_NUM);
if (!success)
{
errMsg = "File header does not contain P3";
}
}
else
{
errMsg = "Unable to read file header.";
}
return success;
}
bool ColorImageClass::processHghtWdth(ifstream &inFile, string &errMsg)
{
bool success = false;
const int MIN_WDTH_HGHT = 1;
int inWidth = 0;
int inHeight = 0;
if (inFile >> inWidth >> inHeight)
{
if (inWidth >= MIN_WDTH_HGHT && inHeight >= MIN_WDTH_HGHT)
{
success = true;
imgRec.setHghtWdth(inHeight, inWidth);
}
else
{
//technically this is valid, but let's error out b/c we can't
//do anything with a blank image
errMsg = "Image is blank.";
}
}
else
{
errMsg = "Unable to read integers for width and height.";
}
return success;
}
bool ColorImageClass::checkRbgVal(ifstream &inFile, string &errMsg)
{
bool success = false;
int rbg;
if (inFile >> rbg)
{
success = (rbg == MAX_RBG);
if (!success)
{
errMsg = "Max pixel value does not equal 255";
}
}
else
{
errMsg = "Unable to read integer for max pixel value.";
}
return success;
}
bool ColorImageClass::processPixels(ifstream &inFile, string &errMsg)
{
ColorClass pixel;
bool success = false;
bool pixelSuccess = true;
initPixelArr(); //allocate pixel array
for (int i = 0; i < imgRec.getHght() && pixelSuccess; i++)
{
for (int j = 0; j < imgRec.getWdth() && pixelSuccess; j++)
{
pixelSuccess = pixel.readImageFile(inFile, errMsg);
if (pixelSuccess)
{
pixelArr[i][j] = pixel;
}
}
}
if (pixelSuccess) //if all pixels look good, return true
{
success = true;
}
return success;
}
void ColorImageClass::initPixelArr()
{
pixelArr = new ColorClass*[imgRec.getHght()];
for (int i = 0; i < imgRec.getHght(); i++)
{
pixelArr[i] = new ColorClass[imgRec.getWdth()];
}
}
bool ColorImageClass::writeImageFile(string &errMsg)
{
ofstream outFile;
bool success = false;
bool isOpen = false;
string imgFileMsg = "Enter string for PPM image file name to output: ";
isOpen = openOutputFile(outFile, imgFileMsg, errMsg);
if (isOpen)
{
success = true;
writePixels(outFile);
outFile.close(); //always close file
}
return success;
}
bool ColorImageClass::openOutputFile(ofstream &outFile,
string imgFileMsg,
string &errMsg)
{
string imgFileName;
bool success = false;
cout << imgFileMsg;
cin >> imgFileName;
outFile.open(imgFileName.c_str());
if (outFile.fail())
{
errMsg = "Unable to open output file!";
}
else
{
success = true;
}
return success;
}
void ColorImageClass::writePixels(ofstream &outFile)
{
ColorClass pixel;
bool leadingSpace = false;
int fistCol = 0;
writeMagicNum(outFile);
writeHghtWdth(outFile);
writeMaxRbg(outFile);
for (int i = 0; i < imgRec.getHght(); i++)
{
outFile << "\n";
for (int j = 0; j < imgRec.getWdth(); j++)
{
pixel = pixelArr[i][j];
//no leading space for first value in row
leadingSpace = (j != fistCol);
pixel.writeImageFile(outFile, leadingSpace);
}
}
}
void ColorImageClass::writeMagicNum(ofstream &outFile)
{
outFile << MAGIC_NUM;
}
void ColorImageClass::writeHghtWdth(ofstream &outFile)
{
outFile << "\n" << imgRec.getWdth() << " " << imgRec.getHght();
}
void ColorImageClass::writeMaxRbg(ofstream &outFile)
{
outFile << "\n" << MAX_RBG;
}
bool ColorImageClass::setColorAtLocation(
RowColumnClass &inRowCol,
ColorClass &inColor
)
{
int inRow = inRowCol.getRow();
int inCol = inRowCol.getCol();
ColorClass pixel;
bool isLocValid = getColorAtLocation(inRowCol, pixel);
if (isLocValid) //only update if location is valid
{
pixel.setTo(inColor);
pixelArr[inRow][inCol] = pixel;
}
//if the location is valid the pixel will always be updated
return isLocValid;
}
bool ColorImageClass::getColorAtLocation(
RowColumnClass &inRowCol,
ColorClass &outColor
)
{
bool isValidLoc = false;
int inRow = inRowCol.getRow();
int inCol = inRowCol.getCol();
const int MIN_ROW_COL = 0;
//check if passed in rowCol is within size of image
//rowCol class not guaranteed to be positive, so need to check
//first and last pixel
if ( inRow < imgRec.getHght() && inCol < imgRec.getWdth() &&
inRow >= MIN_ROW_COL && inCol >= MIN_ROW_COL
)
{
isValidLoc = true;
outColor = pixelArr[inRow][inCol];
}
return isValidLoc;
}
bool ColorImageClass::annotateRectangle(string &errMsg)
{
RectangleClass annotateRec;
bool success = false;
RowColumnClass currentRowCol;
bool foundInvalidLoc = false;
annotateRec.createRectangle(); //create rectangle from user inputs
int startRowIdx = annotateRec.getUpperLeftRow();
int startColIdx = annotateRec.getUpperLeftCol();
ColorClass pixel = annotateRec.getColor();
//safety check since this is public: must have valid image loaded
if (checkArrValid(errMsg))
{
for (int i = startRowIdx; i < annotateRec.getEndRow(); i++)
{
for (int j = startColIdx; j < annotateRec.getEndCol(); j++)
{
currentRowCol.setRowCol(i, j);
//set pixel if we're filling in entire rectangle or
//we're on the border
if (annotateRec.getFill() || annotateRec.checkBorder(i, j))
{
if (setColorAtLocation(currentRowCol, pixel))
{
success = true; //if we update one pixel, we succeed
}
else
{
foundInvalidLoc = true;
}
}
}
}
if (success && foundInvalidLoc)
{
cout << "Warning: Only partial rectangle added to image" << endl;
}
else if (!success)
{
errMsg = "Rectangle did not fit within image";
}
}
return success;
}
bool ColorImageClass::addPattern(string &errMsg)
{
PatternClass pattern;
RectangleClass patternRec;
ColorClass patternColor;
int startRowIdx = 0;
int startColIdx = 0;
RowColumnClass currentRowCol;
bool foundInvalidLoc = false;
bool foundPattern = false;
bool success = false;
//must have valid image loaded and successfully read in pattern file
if (checkArrValid(errMsg) && pattern.readPatternFile(errMsg))
{
//get pattern rectangle
patternRec = pattern.getRec();
patternColor = patternRec.getColor();
startRowIdx = patternRec.getUpperLeftRow();
startColIdx = patternRec.getUpperLeftCol();
for (int i = startRowIdx; i < patternRec.getEndRow(); i++)
{
for (int j = startColIdx; j < patternRec.getEndCol(); j++)
{
currentRowCol.setRowCol(i, j);
//only update pixel if pattern value = 1
if(pattern.getPatternVal(i, j))
{
foundPattern = true;
if (setColorAtLocation(currentRowCol, patternColor))
{
success = true; //if we update one pixel, we succeed
}
else
{
foundInvalidLoc = true;
}
}
}
}
if (success && foundInvalidLoc)
{
cout << "Warning: Only partial pattern added to image" << endl;
}
else if (!foundPattern)
{
//pattern could be all zeroes, so technically this is valid
//but lets warn the user
success = true;
cout << "Warning: Pattern is blank. Image not updated" << endl;
}
else
{
errMsg = "Pattern outside bounds of image";
}
}
return success;
}
bool ColorImageClass::checkArrValid(string &errMsg)
{
bool isValid = false;
if (!pixelArr) //don't operate on null pointer
{
errMsg = "No valid image file currently loaded";
}
else
{
isValid = true;
}
return isValid;
}
bool ColorImageClass::insertImage(string &errMsg)
{
ColorImageClass insrtImg;
bool success = false;
int startRowIdx = 0;
int startColIdx = 0;
ColorClass pixel;
RowColumnClass currentRowCol;
RowColumnClass insrtImgRowCol;
bool foundInvalidLoc = false;
bool foundNonTransparent = false;
string upLeDesc = "upper left corner";
string colorDesc = "transparency";
const int MIN_ROW_COL = 0;
//must have valid image loaded and successfully read in image file
if (checkArrValid(errMsg) && insrtImg.readImageFile(errMsg))
{
//set position/color of insertion image
insrtImg.imgRec.setUpperLeft(upLeDesc, MIN_ROW_COL , MIN_ROW_COL);
insrtImg.imgRec.setColor(colorDesc);
startRowIdx = insrtImg.imgRec.getUpperLeftRow();
startColIdx = insrtImg.imgRec.getUpperLeftCol();
for (int i = startRowIdx; i < insrtImg.imgRec.getEndRow(); i++)
{
for (int j = startColIdx; j < insrtImg.imgRec.getEndCol(); j++)
{
currentRowCol.setRowCol(i, j);
//set pixel only if not transparentColor
if (insrtImg.checkTransparency(i, j, pixel))
{
foundNonTransparent = true;
if (setColorAtLocation(currentRowCol, pixel))
{
success = true; //if we update one pixel, we succeed
}
else
{
foundInvalidLoc = true;
}
}
}
}
if (success && foundInvalidLoc)
{
cout << "Warning: Only partial image inserted" << endl;
}
else if (!foundNonTransparent)
{
//we never found a pixel that did not match transparency color
success = true;
cout << "Warning: Insertion image is completely transparent. ";
cout << "Image not updated" << endl;
}
else
{
errMsg = "Insertion outside bounds of image.";
}
}
return success;
}
bool ColorImageClass::checkTransparency(int rowIdx,
int colIdx,
ColorClass &pixel)
{
bool updatePixel = false;
ColorClass transparencyColor;
RowColumnClass rowCol;
//indexes currently relative to upper left position
imgRec.translateIdx(rowIdx, colIdx);
rowCol.setRowCol(rowIdx, colIdx);
if (getColorAtLocation(rowCol, pixel))
{
transparencyColor = imgRec.getColor();
//we want to update pixel if it is not the same as the transparency
//color and is in a valid location
updatePixel = !pixel.compareColors(transparencyColor);
}
return updatePixel;
}
void ColorImageClass::outputErrors(bool &hasError, string errMsg)
{
if(hasError)
{
cout << "Error: " << errMsg << endl;
//reset
hasError = false;
errMsg = "";
}
} | [
"[email protected]"
] | |
cccdbccfbc9589383261201107bc3ecef5eaf239 | 5899280b047464b63d956690e1fabaf2fe1a7ee3 | /src/loopback.cpp | c5844a92da368795fe6416e383cb3c02e309db34 | [
"BSD-2-Clause"
] | permissive | kylemcdonald/libtins | d4f6c60e21057eafdd7ede609401b6659f18aa2b | 416edc34f7f4464bcd510d9f7c9fa44ff7d9b612 | refs/heads/master | 2020-12-11T05:56:03.189974 | 2014-07-27T04:24:16 | 2014-07-27T04:24:16 | 19,407,574 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,410 | cpp | /*
* Copyright (c) 2014, Matias Fontanini
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WIN32
#include <sys/socket.h>
#ifdef BSD
#include <net/if_dl.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#endif
#else
#include <ws2tcpip.h>
#endif
#include <stdexcept>
#ifdef TINS_DEBUG
#include <cassert>
#endif
#include <cstring>
#include "loopback.h"
#include "packet_sender.h"
#include "ip.h"
#include "llc.h"
#include "rawpdu.h"
#include "exceptions.h"
#if !defined(PF_LLC)
// compilation fix, nasty but at least works on BSD
#define PF_LLC 26
#endif
namespace Tins {
Loopback::Loopback()
: _family()
{
}
Loopback::Loopback(const uint8_t *buffer, uint32_t total_sz)
{
if(total_sz < sizeof(_family))
throw malformed_packet();
_family = *reinterpret_cast<const uint32_t*>(buffer);
buffer += sizeof(uint32_t);
total_sz -= sizeof(uint32_t);
#ifndef WIN32
if(total_sz) {
switch(_family) {
case PF_INET:
inner_pdu(new Tins::IP(buffer, total_sz));
break;
case PF_LLC:
inner_pdu(new Tins::LLC(buffer, total_sz));
break;
default:
inner_pdu(new Tins::RawPDU(buffer, total_sz));
break;
};
}
#endif // WIN32
}
void Loopback::family(uint32_t family_id) {
_family = family_id;
}
uint32_t Loopback::header_size() const {
return sizeof(_family);
}
void Loopback::write_serialization(uint8_t *buffer, uint32_t total_sz, const PDU *)
{
#ifdef TINS_DEBUG
assert(total_sz >= sizeof(_family));
#endif
#ifndef WIN32
if(tins_cast<const Tins::IP*>(inner_pdu()))
_family = PF_INET;
else if(tins_cast<const Tins::LLC*>(inner_pdu()))
_family = PF_LLC;
*reinterpret_cast<uint32_t*>(buffer) = _family;
#endif // WIN32
}
#ifdef BSD
void Loopback::send(PacketSender &sender, const NetworkInterface &iface) {
if(!iface)
throw invalid_interface();
sender.send_l2(*this, 0, 0, iface);
}
#endif // WIN32
}
| [
"[email protected]"
] | |
0cb666650ec2aa358a004bdfafc5dd01bb3e8fd7 | 8c55c025b546d112786d3bc437f5d64c99d6efc2 | /02 Primitive Types/2_12.cpp | 1fdaf16ceaeca0b7c5038da732e9add0ef92930f | [] | no_license | tshrjn/EPI | ac0c7d6b44bf8b35df6206c00bee1d2350316b42 | f9aa4da2d2648deabae020de9e5c3dd3b0e9e761 | refs/heads/master | 2021-01-21T06:24:13.276833 | 2017-02-26T16:17:27 | 2017-02-26T16:17:27 | 83,221,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,258 | cpp | // 2_11 - Given n , return the primes from 1 to n
/* Things learnt:
1. primes.emplace_back(2);
*/
#include "/Users/tshrjn/stdc++.h"
using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::max;
using std::min;
/*#define dim pair<int, int> // h x w
#define pos pair<int, int> // (x,y)
#define rect pair<pos, dim>
#define F first
#define S second
*/
class Rect
{
public:
int x,y, h, w;
void print()
{
std::cout << "Rect: (x,y,h,w): " << this->x << ' ' << this->y << ' ' << this->h << ' '
<< this->w << endl;
}
};
bool is_intersect(Rect R, Rect S)
{
return R.x <= S.x + S.w && R.x + R.w >= S.x &&
R.y <= S.y + S.h && R.y + R.h <= S.y;
}
Rect rect_interection(Rect r, Rect s)
{
if(is_intersect(r,s))
{
return { max(r.x, s.x), max(r.y, s.y),
min(r.x +r.w, s.x +s.w) - max(r.x, s.x),
min(r.y +r.h, s.y +s.h) - max(r.y, s.y)
};
}
else
{
return {0, 0, -1, -1};
}
}
void SmallTest() {
Rect R1 = {0, 0, 2, 2}, R2 = {1, 1, 3, 3};
auto result = rect_interection(R1, R2);
assert(result.x == 1 && result.y == 1 && result.w == 1 &&
result.h == 1);
R1 = {0, 0, 1, 1}, R2 = {1, 1, 3, 3};
result = rect_interection(R1, R2);
assert(result.x == 1 && result.y == 1 && result.w == 0 &&
result.h == 0);
R1 = {0, 0, 1, 1}, R2 = {2, 2, 3, 3};
result = rect_interection(R1, R2);
assert(result.x == 0 && result.y == 0 && result.w == -1 &&
result.h == -1);
}
int main(int argc, char const *argv[])
{
Rect R1, R2;
if (argc == 9) {
R1.x = atoi(argv[1]), R1.y = atoi(argv[2]), R1.w = atoi(argv[3]),
R1.h = atoi(argv[4]);
R2.x = atoi(argv[5]), R2.y = atoi(argv[6]), R2.w = atoi(argv[7]),
R2.h = atoi(argv[8]);
} else {
return 0;
// default_random_engine gen((random_device())());
// uniform_int_distribution<int> dis(1, 100);
// R1.x = dis(gen), R1.y = dis(gen), R1.w = dis(gen),
// R1.h = dis(gen);
// R2.x = dis(gen), R2.y = dis(gen), R2.w = dis(gen),
// R2.h = dis(gen);
}
// Intersect rectangle.
bool res = is_intersect(R1, R2);
cout << std::boolalpha << is_intersect(R1, R2) << endl;
Rect ans = rect_interection(R1, R2);
ans.print();
assert(res == false || (ans.h >= 0 && ans.w >= 0));
return 0;
} | [
"[email protected]"
] | |
6ba816901e93798f1c3f153eaf98659398b2697c | 4ea5083a2dc96943b12c61dbac9a44359d4a5760 | /OpenVPN Tunnel Provider/Vendors/openvpn/openvpn/common/rc.hpp | d2a055e3a7509f0c9481e9e3a8ecf3ca6b72134e | [] | no_license | shahzaibiqbal/openvpn-adapter | afff351a1d2fbcfe966042c060c13364986c954e | d316cd7ebd0d29d636c755d4e10721e2891b6431 | refs/heads/master | 2020-09-08T17:36:24.694975 | 2017-02-05T10:38:35 | 2017-02-05T10:38:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,552 | hpp | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2016 OpenVPN Technologies, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// A basic reference-counting garbage collection scheme. Simply inherit
// from RC to create an object that can be tracked with an RCPtr.
//
// We use tend to use RCPtr rather than the other smart pointer
// classes (std or boost) for performance.
//
// When using the RC template class, it is necessary to specify whether
// the reference count should be thread safe or unsafe, i.e.:
//
// class Foo : public RC<thread_safe_refcount> {}
// or
// class Bar : public RC<thread_unsafe_refcount> {}
//
// Thread-safe reference counting can be significantly more expensive
// because an atomic object must be used for the reference count.
// Therefore, thread-safe reference counting should only be used for
// objects that have visibility across multiple threads.
//
// For clarity, any object that inherits from RC should also declare a Ptr
// typedef that defines the smart pointer type that should be used to track
// the object, e.g.:
//
// class Foo : public RC<thread_unsafe_refcount> {
// public:
// typedef RCPtr<Foo> Ptr;
// };
//
// This allows a smart-pointer to Foo to be referred to
// as Foo::Ptr
#ifndef OPENVPN_COMMON_RC_H
#define OPENVPN_COMMON_RC_H
#include <atomic>
#include <utility>
#include <openvpn/common/olong.hpp>
#ifdef OPENVPN_RC_DEBUG
#include <iostream>
#include <openvpn/common/demangle.hpp>
#endif
namespace openvpn {
// The smart pointer class
template <typename T>
class RCPtr
{
public:
typedef T element_type;
RCPtr() noexcept
: px(nullptr)
{
}
RCPtr(T* p, const bool add_ref=true) noexcept
: px(p)
{
if (px && add_ref)
intrusive_ptr_add_ref(px);
}
RCPtr(const RCPtr& rhs) noexcept
: px(rhs.px)
{
if (px)
intrusive_ptr_add_ref(px);
}
RCPtr(RCPtr&& rhs) noexcept
: px(rhs.px)
{
rhs.px = nullptr;
}
template <typename U>
RCPtr(const RCPtr<U>& rhs) noexcept
: px(rhs.get())
{
if (px)
intrusive_ptr_add_ref(px);
}
~RCPtr()
{
if (px)
intrusive_ptr_release(px);
}
RCPtr& operator=(const RCPtr& rhs) noexcept
{
RCPtr(rhs).swap(*this);
return *this;
}
RCPtr& operator=(RCPtr&& rhs) noexcept
{
RCPtr(std::move(rhs)).swap(*this);
return *this;
}
void reset() noexcept
{
RCPtr().swap(*this);
}
void reset(T* rhs) noexcept
{
RCPtr(rhs).swap(*this);
}
void swap(RCPtr& rhs) noexcept
{
std::swap(px, rhs.px);
}
T* get() const noexcept
{
return px;
}
T& operator*() const noexcept
{
return *px;
}
T* operator->() const noexcept
{
return px;
}
explicit operator bool() const noexcept
{
return px != nullptr;
}
template <typename U>
RCPtr<U> dynamic_pointer_cast() const noexcept
{
return RCPtr<U>(dynamic_cast<U*>(px));
}
private:
T* px;
};
template <typename T>
class RCWeakPtr
{
typedef RCPtr<T> Strong;
public:
typedef T element_type;
RCWeakPtr() noexcept {}
RCWeakPtr(const Strong& p) noexcept
{
if (p)
controller = p->refcount_.controller;
}
RCWeakPtr(T* p) noexcept
{
if (p)
controller = p->refcount_.controller;
}
void reset(const Strong& p) noexcept
{
if (p)
controller = p->refcount_.controller;
else
controller.reset();
}
void reset(T* p) noexcept
{
if (p)
controller = p->refcount_.controller;
else
controller.reset();
}
void reset() noexcept
{
controller.reset();
}
void swap(RCWeakPtr& other) noexcept
{
controller.swap(other.controller);
}
olong use_count() const noexcept
{
if (controller)
return controller->use_count();
else
return 0;
}
bool expired() const noexcept
{
return use_count() == 0;
}
Strong lock() const noexcept
{
if (controller)
return controller->template lock<Strong>();
else
return Strong();
}
private:
typename T::Controller::Ptr controller;
};
class thread_unsafe_refcount
{
public:
thread_unsafe_refcount() noexcept
: rc(olong(0))
{
}
void operator++() noexcept
{
++rc;
}
olong operator--() noexcept
{
return --rc;
}
bool inc_if_nonzero() noexcept
{
if (rc)
{
++rc;
return true;
}
else
return false;
}
olong use_count() const noexcept
{
return rc;
}
#ifdef OPENVPN_RC_NOTIFY
void notify_release() noexcept
{
}
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class ListHead
{
public:
ListHead() noexcept : ptr(nullptr) {}
T* load() noexcept
{
return ptr;
}
void insert(T* item) noexcept
{
item->next = ptr;
ptr = item;
}
private:
ListHead(const ListHead&) = delete;
ListHead& operator=(const ListHead&) = delete;
T* ptr;
};
#endif
private:
thread_unsafe_refcount(const thread_unsafe_refcount&) = delete;
thread_unsafe_refcount& operator=(const thread_unsafe_refcount&) = delete;
olong rc;
};
class thread_safe_refcount
{
public:
thread_safe_refcount() noexcept
: rc(olong(0))
{
}
void operator++() noexcept
{
rc.fetch_add(1, std::memory_order_relaxed);
}
olong operator--() noexcept
{
// http://www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html
const olong ret = rc.fetch_sub(1, std::memory_order_release) - 1;
if (ret == 0)
std::atomic_thread_fence(std::memory_order_acquire);
return ret;
}
// If refcount is 0, do nothing and return false.
// If refcount != 0, increment it and return true.
bool inc_if_nonzero() noexcept
{
olong previous = rc.load(std::memory_order_relaxed);
while (true)
{
if (!previous)
break;
if (rc.compare_exchange_weak(previous, previous + 1, std::memory_order_relaxed))
break;
}
return previous > 0;
}
olong use_count() const noexcept
{
return rc.load(std::memory_order_relaxed);
}
#ifdef OPENVPN_RC_NOTIFY
void notify_release() noexcept
{
}
#endif
#ifdef OPENVPN_RC_NOTIFY
template <typename T>
class ListHead
{
public:
ListHead() noexcept : ptr(nullptr) {}
T* load() noexcept
{
return ptr.load(std::memory_order_relaxed);
}
void insert(T* item) noexcept
{
T* previous = ptr.load(std::memory_order_relaxed);
while (true)
{
item->next = previous;
if (ptr.compare_exchange_weak(previous, item, std::memory_order_relaxed))
break;
}
}
private:
ListHead(const ListHead&) = delete;
ListHead& operator=(const ListHead&) = delete;
std::atomic<T*> ptr;
};
#endif
private:
thread_safe_refcount(const thread_safe_refcount&) = delete;
thread_safe_refcount& operator=(const thread_safe_refcount&) = delete;
std::atomic<olong> rc;
};
// Reference count base class for objects tracked by RCPtr.
// Disallows copying and assignment.
template <typename RCImpl> // RCImpl = thread_safe_refcount or thread_unsafe_refcount
class RC
{
public:
typedef RCPtr<RC> Ptr;
RC() noexcept {}
virtual ~RC() {}
olong use_count() const noexcept
{
return refcount_.use_count();
}
private:
RC(const RC&) = delete;
RC& operator=(const RC&) = delete;
template <typename R> friend void intrusive_ptr_add_ref(R* p) noexcept;
template <typename R> friend void intrusive_ptr_release(R* p) noexcept;
RCImpl refcount_;
};
// Like RC, but allows object to be copied and assigned.
template <typename RCImpl> // RCImpl = thread_safe_refcount or thread_unsafe_refcount
class RCCopyable
{
public:
RCCopyable() noexcept {}
RCCopyable(const RCCopyable&) noexcept {}
RCCopyable& operator=(const RCCopyable&) noexcept { return *this; }
virtual ~RCCopyable() {}
olong use_count() const noexcept
{
return refcount_.use_count();
}
private:
template <typename R> friend void intrusive_ptr_add_ref(R* p) noexcept;
template <typename R> friend void intrusive_ptr_release(R* p) noexcept;
RCImpl refcount_;
};
// Like RC, but also allows weak pointers and release notification callables
template <typename RCImpl> // RCImpl = thread_safe_refcount or thread_unsafe_refcount
class RCWeak
{
template<typename T>
friend class RCWeakPtr;
#ifdef OPENVPN_RC_NOTIFY
// Base class of release notification callables
class NotifyBase
{
public:
NotifyBase() noexcept {}
virtual void call() noexcept = 0;
virtual ~NotifyBase() {}
NotifyBase* next;
private:
NotifyBase(const NotifyBase&) = delete;
NotifyBase& operator=(const NotifyBase&) = delete;
};
// A release notification callable
template <typename CALLABLE>
class NotifyItem : public NotifyBase
{
public:
NotifyItem(const CALLABLE& c) noexcept
: callable(c)
{
}
NotifyItem(CALLABLE&& c) noexcept
: callable(std::move(c))
{
}
private:
virtual void call() noexcept override
{
callable();
}
CALLABLE callable;
};
// Head of a linked-list of release notification callables
class NotifyListHead
{
public:
NotifyListHead() noexcept {}
template <typename CALLABLE>
void add(const CALLABLE& c) noexcept
{
NotifyBase* item = new NotifyItem<CALLABLE>(c);
head.insert(item);
}
template <typename CALLABLE>
void add(CALLABLE&& c) noexcept
{
NotifyBase* item = new NotifyItem<CALLABLE>(std::move(c));
head.insert(item);
}
void release() noexcept
{
// In thread-safe mode, list traversal is guaranteed to be
// contention-free because we are not called until refcount
// reaches zero and after a std::memory_order_acquire fence.
NotifyBase* nb = head.load();
while (nb)
{
NotifyBase* next = nb->next;
nb->call();
delete nb;
nb = next;
}
}
private:
NotifyListHead(const NotifyListHead&) = delete;
NotifyListHead& operator=(const NotifyListHead&) = delete;
typename RCImpl::template ListHead<NotifyBase> head;
};
#endif
// For weak-referenceable objects, we must detach the
// refcount from the object and place it in Controller.
struct Controller : public RC<RCImpl>
{
typedef RCPtr<Controller> Ptr;
Controller(RCWeak* parent_arg) noexcept
: parent(parent_arg)
{
}
olong use_count() const noexcept
{
return rc.use_count();
}
template <typename PTR>
PTR lock() noexcept
{
if (rc.inc_if_nonzero())
return PTR(static_cast<typename PTR::element_type*>(parent), false);
else
return PTR();
}
RCWeak *const parent; // dangles (harmlessly) after rc decrements to 0
RCImpl rc; // refcount
};
struct ControllerRef
{
ControllerRef(RCWeak* parent) noexcept
: controller(new Controller(parent))
{
}
void operator++() noexcept
{
++controller->rc;
}
olong operator--() noexcept
{
return --controller->rc;
}
#ifdef OPENVPN_RC_NOTIFY
void notify_release() noexcept
{
notify.release();
}
#endif
typename Controller::Ptr controller; // object containing actual refcount
#ifdef OPENVPN_RC_NOTIFY
NotifyListHead notify; // linked list of callables to be notified on object release
#endif
};
public:
typedef RCPtr<RCWeak> Ptr;
typedef RCWeakPtr<RCWeak> WPtr;
RCWeak() noexcept
: refcount_(this)
{
}
virtual ~RCWeak()
{
}
#ifdef OPENVPN_RC_NOTIFY
// Add observers to be called just prior to object deletion,
// but after refcount has been decremented to 0. At this
// point, all weak pointers have expired, and no strong
// pointers are outstanding. Callables can access the
// object by raw pointer but must NOT attempt to create a
// strong pointer referencing the object.
template <typename CALLABLE>
void rc_release_notify(const CALLABLE& c) noexcept
{
refcount_.notify.add(c);
}
template <typename CALLABLE>
void rc_release_notify(CALLABLE&& c) noexcept
{
refcount_.notify.add(std::move(c));
}
#endif
private:
RCWeak(const RCWeak&) = delete;
RCWeak& operator=(const RCWeak&) = delete;
template <typename R> friend void intrusive_ptr_add_ref(R* p) noexcept;
template <typename R> friend void intrusive_ptr_release(R* p) noexcept;
ControllerRef refcount_;
};
template <typename R>
inline void intrusive_ptr_add_ref(R *p) noexcept
{
#ifdef OPENVPN_RC_DEBUG
std::cout << "ADD REF " << cxx_demangle(typeid(p).name()) << std::endl;
#endif
++p->refcount_;
}
template <typename R>
inline void intrusive_ptr_release(R *p) noexcept
{
if (--p->refcount_ == 0)
{
#ifdef OPENVPN_RC_DEBUG
std::cout << "DEL OBJ " << cxx_demangle(typeid(p).name()) << std::endl;
#endif
#ifdef OPENVPN_RC_NOTIFY
p->refcount_.notify_release();
#endif
delete p;
}
else
{
#ifdef OPENVPN_RC_DEBUG
std::cout << "REL REF " << cxx_demangle(typeid(p).name()) << std::endl;
#endif
}
}
} // namespace openvpn
#endif // OPENVPN_COMMON_RC_H
| [
"[email protected]"
] | |
501b00872c6e49aa707eeec17c52d283fe623222 | ed15e8e1e24cdfe459d2a92e7e9302fe0746f35d | /cc1.cpp | 6ca94171e4beeacee8f899638c0d7b6f5e193eaf | [] | no_license | thenooz/test | 748eb187d95db114bed0507c617822ba2df21357 | 868dbc2bacf25608694bf0764f4343ff14f90ea6 | refs/heads/master | 2021-01-10T02:28:42.050265 | 2016-03-29T18:12:42 | 2016-03-29T18:12:42 | 49,647,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | cpp | #include<iostream>
using namespace std;
void numstones(int,int,int);
int main()
{
int nums;
cin>>nums;
int arr[nums][3];
for(int i=0;i<nums;i++)
{
//arr[i]=new int[3];
cin>>arr[i][0]>>arr[i][1]>>arr[i][2];
}
for(int i=0;i<nums;i++)
{
numstones(arr[i][0],arr[i][1],arr[i][2]);
}
return 0;
}
void numstones(int n1, int n2, int m)
{
//int n1,n2,m;//given
int min,i;
//cin>>n1>>n2>>m;
min=n1<n2?n1:n2;
//min=min<m?min:m;
if(m<=min){i=min/m;i--;i=m-i;
for(;i<=m;i++)
{
n1=n1-i;
n2=n2-i;
}
}
else
{
n1=n1-min;
n2=n2-min;
}
cout<<n1+n2<<endl;
}
| [
"[email protected]"
] | |
85cf7613f577589aeece3e3eab080586e6db6e93 | ef4177737c934fcc401c7f315df4e5844e299e1d | /Ch2 LinearList/拼写检查.cpp | e8dd62c0a1ddccef28abf092f0f18cef908800d5 | [] | no_license | wr786/Key-to-DSA | e495a20f24946d0caf869a4e8012ed563239b235 | 7351d81e673eb757c0ee4b4556dbce60168db781 | refs/heads/master | 2023-02-12T14:40:10.538240 | 2021-01-01T08:35:02 | 2021-01-01T08:35:02 | 297,310,726 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,658 | cpp | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
vector<string> dict;
unordered_map<string, bool> inDict;
bool is_similar(string word, string lookup, int chances) {
int l1 = word.length(), l2 = lookup.length();
if(chances < abs(l1 - l2)) return false; // prune
int i1 = 0, i2 = 0;
while(i1 < l1 && i2 < l2) {
if(word[i1] != lookup[i2]) {
if(chances <= 0) return false;
// rm
if(is_similar(word.substr(i1+1), lookup.substr(i2), chances-1)) return true;
// mv
if(is_similar(word.substr(i1+1), lookup.substr(i2+1), chances-1)) return true;
// add
if(is_similar(word.substr(i1), lookup.substr(i2+1), chances-1)) return true;
return false;
}
i1 ++;
i2 ++;
}
return (i1 == l1 && i2 == l2) || (chances && ((i1 == l1 && l2 - i2 <= chances) || (i2 == l2 && l1 - i1 <= chances)));
}
int main() {
string tmp;
while (cin >> tmp) {
if(tmp == "#") {
break;
} else {
dict.push_back(tmp);
inDict[tmp] = true;
}
}
while (cin >> tmp) {
if(tmp == "#") {
break;
} else {
if(inDict[tmp]) {
cout << tmp << " is correct\n";
} else {
cout << tmp << ":";
for(auto& word: dict) {
if(is_similar(word, tmp, 1)) {
cout << " " << word;
}
}
cout << '\n';
}
}
}
} | [
"[email protected]"
] | |
0a451286014ecbe889a3fb2aaaa5cb554461dcb9 | bb8c4b31a519d9c3eafa1e9c923176c938c562ad | /Motor2D/j1Map.cpp | 0ae4a4f43cd8251fc2f8a6eaf7c9ae4529de45e1 | [
"MIT"
] | permissive | oscarroyo4/UnknownMiner | 700dcd5dd757dab826387aca43bd583ead4d134d | 4283bd553ef2fcbe6ef208ecc4513439eac15edc | refs/heads/master | 2023-02-15T10:56:15.507345 | 2021-01-13T16:43:38 | 2021-01-09T21:50:19 | 210,903,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,693 | cpp | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Collision.h"
#include "j1Textures.h"
#include "j1Map.h"
j1Map::j1Map() : j1Module(), map_loaded(false)
{
name.create("map");
}
// Destructor
j1Map::~j1Map()
{}
// Called before render is available
bool j1Map::Awake(pugi::xml_node& config)
{
LOG("Loading Map Parser");
bool ret = true;
folder.create(config.child("folder").child_value());
return ret;
}
iPoint j1Map::MapToWorld(int x, int y) const
{
iPoint ret;
if (data.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x * data.tile_width;
ret.y = y * data.tile_height;
}
else if (data.type == MAPTYPE_ISOMETRIC)
{
ret.x = (x - y) * (data.tile_width * 0.5f);
ret.y = (x + y) * (data.tile_height * 0.5f);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
iPoint j1Map::WorldToMap(int x, int y) const
{
iPoint ret(0, 0);
if (data.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x / data.tile_width;
ret.y = y / data.tile_height;
}
else if (data.type == MAPTYPE_ISOMETRIC)
{
float half_width = data.tile_width * 0.5f;
float half_height = data.tile_height * 0.5f;
ret.x = int((x / half_width + y / half_height) / 2) - 1;
ret.y = int((y / half_height - (x / half_width)) / 2);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
void j1Map::Draw()
{
if(map_loaded == false)
return;
// TODO 5: Prepare the loop to iterate all the tiles in a layer
p2List_item<Layer*>* item_layer = data.layers.start;
while (item_layer != NULL)
{
Layer* l = item_layer->data;
item_layer = item_layer->next;
for (int i = 0; i <l->width ; i++)
{
for (int j = 0; j < l->height; j++)
{
if (l->gid[l->Get(i, j)] != 0)
{
l->Get(i, j);
SDL_Texture* texture = data.tilesets.start->data->texture;
iPoint position = PosConverter(i, j);
SDL_Rect sect = data.tilesets.start->data->TileToRect(l->gid[l->Get(i, j)]);
App->render->Blit(texture, position.x, position.y, §);
}
}
}
}
// TODO 9: Complete the draw function
}
// Called before quitting
bool j1Map::CleanUp()
{
LOG("Unloading map");
// Remove all tilesets
p2List_item<TileSet*>* item;
item = data.tilesets.start;
while(item != NULL)
{
RELEASE(item->data);
item = item->next;
}
data.tilesets.clear();
// TODO 2: clean up all layer data
// Remove all layers
data.layers.clear();
// Clean up the pugui tree
map_file.reset();
return true;
}
// Load new map
bool j1Map::Load(const char* file_name)
{
bool ret = true;
p2SString tmp("%s%s", folder.GetString(), file_name);
pugi::xml_parse_result result = map_file.load_file(tmp.GetString());
if(result == NULL)
{
LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description());
ret = false;
}
// Load general info ----------------------------------------------
if(ret == true)
{
ret = LoadMap();
}
// Load all tilesets info ----------------------------------------------
pugi::xml_node tileset;
for(tileset = map_file.child("map").child("tileset"); tileset && ret; tileset = tileset.next_sibling("tileset"))
{
TileSet* set = new TileSet();
if(ret == true)
{
ret = LoadTilesetDetails(tileset, set);
}
if(ret == true)
{
ret = LoadTilesetImage(tileset, set);
}
data.tilesets.add(set);
}
// TODO 4: Iterate all layers and load each of them
// Load layer info ----------------------------------------------
pugi::xml_node layernode;
for (layernode = map_file.child("map").child("layer"); layernode && ret; layernode = layernode.next_sibling("layer"))
{
Layer* set1 = new Layer();
if (ret == true)
{
ret = LoadLayer(layernode, set1);
}
data.layers.add(set1);
}
if(ret == true)
{
LOG("Successfully parsed map XML file: %s", file_name);
LOG("width: %d height: %d", data.width, data.height);
LOG("tile_width: %d tile_height: %d", data.tile_width, data.tile_height);
p2List_item<TileSet*>* item = data.tilesets.start;
while(item != NULL)
{
TileSet* s = item->data;
LOG("Tileset ----");
LOG("name: %s firstgid: %d", s->name.GetString(), s->firstgid);
LOG("tile width: %d tile height: %d", s->tile_width, s->tile_height);
LOG("spacing: %d margin: %d", s->spacing, s->margin);
item = item->next;
}
// TODO 4: Add info here about your loaded layers
// Adapt this code with your own variables
p2List_item<Layer*>* item_layer = data.layers.start;
while(item_layer != NULL)
{
Layer* l = item_layer->data;
LOG("Layer ----");
LOG("name: %s", l->name.GetString());
LOG("tile width: %d tile height: %d", l->width, l->height);
item_layer = item_layer->next;
if (l->name == "Collision") {
for (int i = 0; i < l->width; i++)
{
for (int j = 0; j < l->height; j++)
{
if (l->gid[l->Get(i, j)] != 0)
{
l->Get(i, j);
iPoint position = PosConverter(i, j);
SDL_Rect sect = data.tilesets.start->data->TileToRect(l->gid[l->Get(i, j)]);
groundCol.add(App->collision->AddCollider({ position.x,position.y,sect.w,sect.h }, COLLIDER_GROUND));
}
}
}
}
}
}
map_loaded = ret;
return ret;
}
// Load map general properties
bool j1Map::LoadMap()
{
bool ret = true;
pugi::xml_node map = map_file.child("map");
if(map == NULL)
{
LOG("Error parsing map xml file: Cannot find 'map' tag.");
ret = false;
}
else
{
data.width = map.attribute("width").as_int();
data.height = map.attribute("height").as_int();
data.tile_width = map.attribute("tilewidth").as_int();
data.tile_height = map.attribute("tileheight").as_int();
p2SString bg_color(map.attribute("backgroundcolor").as_string());
data.background_color.r = 0;
data.background_color.g = 0;
data.background_color.b = 0;
data.background_color.a = 0;
if(bg_color.Length() > 0)
{
p2SString red, green, blue;
bg_color.SubString(1, 2, red);
bg_color.SubString(3, 4, green);
bg_color.SubString(5, 6, blue);
int v = 0;
sscanf_s(red.GetString(), "%x", &v);
if(v >= 0 && v <= 255) data.background_color.r = v;
sscanf_s(green.GetString(), "%x", &v);
if(v >= 0 && v <= 255) data.background_color.g = v;
sscanf_s(blue.GetString(), "%x", &v);
if(v >= 0 && v <= 255) data.background_color.b = v;
}
p2SString orientation(map.attribute("orientation").as_string());
if(orientation == "orthogonal")
{
data.type = MAPTYPE_ORTHOGONAL;
}
else if(orientation == "isometric")
{
data.type = MAPTYPE_ISOMETRIC;
}
else if(orientation == "staggered")
{
data.type = MAPTYPE_STAGGERED;
}
else
{
data.type = MAPTYPE_UNKNOWN;
}
}
return ret;
}
bool j1Map::LoadTilesetDetails(pugi::xml_node& tileset_node, TileSet* set)
{
bool ret = true;
set->name.create(tileset_node.attribute("name").as_string());
set->firstgid = tileset_node.attribute("firstgid").as_int();
set->tile_width = tileset_node.attribute("tilewidth").as_int();
set->tile_height = tileset_node.attribute("tileheight").as_int();
set->margin = tileset_node.attribute("margin").as_int();
set->spacing = tileset_node.attribute("spacing").as_int();
pugi::xml_node offset = tileset_node.child("tileoffset");
if(offset != NULL)
{
set->offset_x = offset.attribute("x").as_int();
set->offset_y = offset.attribute("y").as_int();
}
else
{
set->offset_x = 0;
set->offset_y = 0;
}
return ret;
}
bool j1Map::LoadTilesetImage(pugi::xml_node& tileset_node, TileSet* set)
{
bool ret = true;
pugi::xml_node image = tileset_node.child("image");
if(image == NULL)
{
LOG("Error parsing tileset xml file: Cannot find 'image' tag.");
ret = false;
}
else
{
set->texture = App->tex->Load(PATH(folder.GetString(), image.attribute("source").as_string()));
if (set->texture == NULL) {
LOG("Error loading texture: Cannot load texture.");
ret = false;
}
int w, h;
SDL_QueryTexture(set->texture, NULL, NULL, &w, &h);
set->tex_width = image.attribute("width").as_int();
if(set->tex_width <= 0)
{
set->tex_width = w;
}
set->tex_height = image.attribute("height").as_int();
if(set->tex_height <= 0)
{
set->tex_height = h;
}
set->num_tiles_width = set->tex_width / set->tile_width;
set->num_tiles_height = set->tex_height / set->tile_height;
}
return ret;
}
//TODO 3: Create the definition for a function that loads a single layer
bool j1Map::LoadLayer(pugi::xml_node& layer, Layer* set)
{
bool ret = true;
set->name.create(layer.attribute("name").as_string());
set->width = layer.attribute("width").as_int();
set->height = layer.attribute("height").as_int();
set->gid = new uint[set->width * set->height];
set->nav = layer.attribute("nav").as_int();
memset(set->gid,0, set->width * set->height);
pugi::xml_node tilesgid;
int i = 0;
for (tilesgid = layer.child("data").child("tile"); tilesgid && ret; tilesgid = tilesgid.next_sibling("tile"))
{
set->gid[i] = tilesgid.attribute("gid").as_uint();
i++;
}
return ret;
}
SDL_Rect TileSet::TileToRect(uint tileid)
{
uint id= tileid - firstgid;
SDL_Rect rect;
rect.w = tile_width;
rect.h = tile_height;
rect.x = margin + ((rect.w + spacing) * (id % num_tiles_width));
rect.y = margin + ((rect.h + spacing) * (id / num_tiles_width));
return rect;
}
iPoint j1Map :: PosConverter(int x, int y){
iPoint ret;
ret.x = x * data.tile_width;
ret.y = y * data.tile_height;
return ret;
}
bool j1Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer) const
{
bool ret = false;
p2List_item<Layer*>* item;
item = data.layers.start;
for (item = data.layers.start; item != NULL; item = item->next)
{
Layer* layer = item->data;
if (layer->nav == 0)
continue;
uchar * map = new uchar[layer->width * layer->height];
memset(map, 1, layer->width * layer->height);
for (int y = 0; y < data.height; ++y)
{
for (int x = 0; x < data.width; ++x)
{
int i = (y * layer->width) + x;
int tile_id = layer->Get(x, y);
TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL;
if (tileset != NULL)
{
map[i] = (layer->gid[tile_id] == 6) > 0 ? 0 : 1;
/*TileType* ts = tileset->GetTileType(tile_id);
if(ts != NULL)
{
map[i] = ts->properties.Get("walkable", 1);
}*/
}
}
}
*buffer = map;
width = data.width;
height = data.height;
ret = true;
break;
}
return ret;
}
TileSet* j1Map::GetTilesetFromTileId(int id) const
{
p2List_item<TileSet*>* item = data.tilesets.start;
TileSet* set = item->data;
while (item)
{
if (id < item->data->firstgid)
{
set = item->prev->data;
break;
}
set = item->data;
item = item->next;
}
return set;
} | [
"[email protected]"
] | |
c14c40635f9e3890dce5ea66c5b8da9da501f2d6 | 5be08a041fa9c019337f2187813a4f54108e6e2d | /Actions/AddCircleAction.h | 0592ade22e3dd085e65124efaed2723d52f7f828 | [] | no_license | AymanAzzam/Paint-for-Kids | ae8c647b7ffb64ad87dd2a78be3a3bf15ebfc5c9 | 66ac8c7f24f881175fb505ed468e7055b313b5e5 | refs/heads/master | 2020-08-10T02:38:52.562643 | 2019-10-10T17:53:02 | 2019-10-10T17:53:02 | 214,212,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | #pragma once
#include "Action.h"
class AddCircleAction : public Action
{
private:
Point P1, P2; //Circlele center and a point on it
GfxInfo CircleGfxInfo;
public:
AddCircleAction(ApplicationManager *pApp);
//Reads Circlele parameters
virtual void ReadActionParameters();
//Add Circlele to the ApplicationManager
virtual void Execute();
};
| [
"[email protected]"
] | |
0ac29ec116dda59868a4a5f645e60f798c4e2fc2 | 25ce41a0ba24160058bd76d22118d481f9f27fa8 | /kjvm_fold/kjvm/Stack.cpp | c89c12599e576670da6ae64314d8cdcb42dd4f92 | [] | no_license | kosta2222/kjvm_proj | 84446324eb9a680bd642248ff5cb098ab5ff296b | 4c2e7bd47d8d7b8cabe90d151ec8d07e32396aa0 | refs/heads/master | 2020-04-23T06:30:18.180216 | 2019-02-16T07:24:26 | 2019-02-16T07:24:26 | 170,975,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | #include "StdAfx.h"
#include "Stack.h"
Stack::Stack(void)
{
}
Stack::~Stack(void)
{
}
| [
"[email protected]"
] | |
12b789f7786843c000392494c7c455b99390daaa | 75b72ab86c2df0eca7e78634c49d5a757b2286c9 | /optimize.h | 2a655f60252b62898a4084412c78e1e5d7722c59 | [] | no_license | ftang921/pars-optimization | 0ff906370615d93fb8cc2db40f594a4477d03e98 | d04747b106b45e73acfb2a15a7ef01fd8f9fed2b | refs/heads/master | 2021-05-31T01:05:26.446406 | 2016-02-08T21:40:32 | 2016-02-08T21:40:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,709 | h | //
// optimize.h
// pars_optimize
//
// Created by Feng Tang on 6/9/15.
// Copyright (c) 2015 Fordham University. All rights reserved.
//
#ifndef optimize_h
#define optimize_h
#include <vector>
using namespace std;
class OptiEntry {
public:
vector<int> time;
vector<double> prob;
vector<double> nonCumProb;
vector<double> delp;
vector<double> del2p;
OptiEntry() {
prob.clear();
time.clear();
delp.clear();
del2p.clear();
}
~OptiEntry() {}
};
class OptionEntry {
public:
vector<int> time;
vector<double> bestProb;
vector<double> worstProb;
vector<double> avgProb;
vector<double> sumProb;
vector<OptiEntry> bestHistory;
vector<OptiEntry> worstHistory;
OptionEntry() {
time.clear();
bestProb.clear();
worstProb.clear();
avgProb.clear();
bestHistory.clear();
worstHistory.clear();
}
~OptionEntry(){}
};
class OptionEntryAux {
public:
vector<double> prob;
vector<int> time;
vector<OptiEntry> history;
OptionEntryAux() {
prob.clear();
time.clear();
history.clear();
}
~OptionEntryAux(){}
};
class Optimize{
int minT;
int maxT;
vector<OptiEntry> optiTable;
OptionEntry options;
OptionEntryAux optionsAux;
public:
int minTime;
int maxTime;
Optimize(){
optiTable.clear();
}
~Optimize() {}
void readData(string filePath);
void cleanOptionsAux();
bool isTableReady();
void printTable(vector<OptiEntry> table);
void printTable();
void parseTable(vector<int> &singlePos, vector<OptiEntry> &singleTable, vector<OptiEntry> &multiTable);
void parseTable(vector<OptiEntry> table, vector<int> &singlePos, vector<OptiEntry> &singleTable, vector<OptiEntry> &multiTable);
void makeOptions(int tMin, int tMax);
void makeOptionsAux(int level, vector<OptiEntry> table, double cProb, int cTime, int tMax,
vector<double> hProb, vector<int> hTime);
int findBest(vector<double> prob);
int findWorst(vector<double> prob);
double findAvg(vector<double> prob);
double findSum(vector<double> prob);
void completeHistory(vector<int> singlePos, OptiEntry &history);
void outputResult(string filePath, string mode);
bool evalSolution(vector<int> sol, int &sTime, double &sProb);
int findBestDel(vector<int> sol);
int findWorstDel(vector<int> sol);
bool findBest2(int maxT, double &optiProb, int &optiTime);
bool findWorst2(int maxT, double &optiProb, int &optiTime);
void makeLocalOptions(int tMin, int tMax);
};
#endif
| [
"[email protected]"
] | |
639214ef6cfa0fde3cee3922cb902b3ceb8f33ff | e0afb11f8f519057e40a14a3047b7baaf5cb4894 | /element.cpp | 64ecb186e28e61cb8c22a0a463a94536d060cde8 | [] | no_license | futurnaingenieur/UTBM-RPG | e6d8e2b5d5e5a96c5e432f5fba4ce4d55316ee57 | 2ee9f2f2e481c25461b68dce5ca7a3567324565a | refs/heads/master | 2020-05-18T07:09:25.600040 | 2015-04-01T11:19:09 | 2015-04-01T11:19:09 | 24,602,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | #include <SFML/Graphics.hpp>
#include <string>
#include "element.hpp"
using namespace sf;
Element::Element(int input_x,int input_y)
{
dimensions.x=input_x;
dimensions.y=input_y;
rectangle.setSize(dimensions);
}
void Element::setTexture(Texture input_texture)
{
rectangle.setTexture(&input_texture);
}
void Element::setPosition(Vector2f input_position)
{
rectangle.setPosition(input_position);
}
| [
"[email protected]"
] | |
dd990cbe5efe85660c1f5dae29dca9ca521167a5 | 3c228807174968ae3320e8093ad1357bc7b2e4c3 | /CF-489C.cpp | c8d134b50f0584014f34fe1f0070e1dab9622cfa | [] | no_license | rajputji/Problem-Solutions-CPP | 151069d606baf7a11541109e6ca891edacf8568b | 8cfd220584f8ce11a080431a69fb9daf2c0177cf | refs/heads/master | 2023-03-24T05:54:13.283503 | 2021-03-26T12:56:23 | 2021-03-26T12:56:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,961 | cpp | /*
This code is written by Shammi Anand
contact : [email protected], shammianand.me
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define f first
#define s second
#define vi vector<int>
#define pii pair<int, int>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define F(i,n) for(int i=0;i<n;i++)
#define all(a) a.begin(), a.end()
#define INF 1e9+7
#define nl "\n"
#define w(x) int x; cin>>x; while(x--)
void shammi() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main() {
shammi();
int n, s; cin >> n >> s;
string mn(n, '0'), mx(n, '0');
if (s == 0) {
if (n != 1) cout << -1 << " " << -1 << nl;
else cout << 0 << " " << 0 << nl;
} else if (s <= 9) {
int target = s;
mx[0] = char('0' + s);
mn[0] = '1';
target -= 1;
for (int i = n - 1; i >= 0 && target > 0; i--) {
if (target >= (9 - (mn[i] - '0'))) {
target -= (9 - (mn[i] - '0'));
mn[i] = '9';
} else {
int curr = mn[i] - '0';
target += curr;
mn[i] = char('0' + target);
break;
}
}
cout << mn << " " << mx << nl;
} else {
if (9 * n < s) {
cout << -1 << " " << -1 << nl;
} else {
int target = s;
mn[0] = '1';
target -= 1;
for (int i = n - 1; i >= 0 && target > 0; i--) {
if (target >= (9 - (mn[i] - '0'))) {
target -= (9 - (mn[i] - '0'));
mn[i] = '9';
} else {
int curr = mn[i] - '0';
target += curr;
mn[i] = char('0' + target);
break;
}
}
target = s;
for (int i = 0; i < n && target > 0; i++) {
if (target >= 9) {
target -= 9;
mx[i] = '9';
} else {
mx[i] = char('0' + target);
break;
}
}
cout << mn << " " << mx << nl;
}
}
return 0;
} | [
"[email protected]"
] | |
267196d5d53e4bcec6caed1c2b62d06b33886179 | fc0de36ac327936ba88559978d85d9c6d373f457 | /etc/17680.cpp | fea05d23ac5c1d08f058ea4b3abb91aa33500e5c | [] | no_license | KimSeongHeon/Algorithm | 0c749998eabaf49c67c9ac23a9d349fe1ca5bc23 | 24f3996228ed16f3673571c4f64f2017ba453373 | refs/heads/master | 2021-10-18T05:57:31.824937 | 2019-02-14T07:31:16 | 2019-02-14T07:31:16 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,357 | cpp | #include <string>
#include <vector>
#include<algorithm>
using namespace std;
using std::transform;
vector<string> cache;
int use[31];
int solution(int cacheSize, vector<string> cities) {
int answer = 0;
int cSize = 0, found = 0, mincnt;
string target;
if(cacheSize == 0)
answer = cities.size()*5;
else{
for(int i=0; i<cities.size(); i++){
transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower);
target = cities[i];
mincnt = found = 0;
for(int j=0; j<cache.size(); j++){
if(cache[j] == target){
found = 1;
use[j] = i+1;
break;
}
if(use[j] < use[mincnt])
mincnt=j;
}
if(found == 1){ //찾았을 경우
answer++;
}
else{ //cache에 없는 경우
if(cache.size() < cacheSize){
cache.push_back(target);
use[cache.size()-1] = i+1;
}
else{
cache[mincnt] = target;
use[mincnt] = i+1; //사용했을 때
}
answer += 5;
}
}
}
return answer;
} | [
"[email protected]"
] | |
3ed00bbd651d00bf6aedf442a937685836997675 | 9a32178d3c2fdf377d84f65b55989264e67f40e9 | /2002/ALL VC SAMPLES/Attributes/General/Labrador/labdriv/labdriv.cpp | 3be12bc93b8ae95eda34476f670de1fc0e238a42 | [] | no_license | philipwolfe/Samples | 5e5cc1376575ac6361b62a3554c98626f153b694 | 7eb703287a6d07596a141c4557f271efe6c1666f | refs/heads/master | 2021-12-25T12:52:52.616313 | 2021-12-19T04:26:29 | 2021-12-19T04:26:29 | 250,445,305 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,539 | cpp | // labdriv.cpp : driver for the Labrador sample
//
// This is a part of the Active Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
#include "prelabdr.h"
#include "..\\labobj.h"
///////////////////////////////////////////////////////////////
// helper to do print traces
void _cdecl Trace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512];
nBuf = _vstprintf(szBuffer, lpszFormat, args);
_ASSERT(nBuf < sizeof(szBuffer));
_tprintf(szBuffer);
OutputDebugString(szBuffer);
va_end(args);
}
// helper function to do the work
void _cdecl CallLabrador()
{
WCHAR szTmp[32];
Trace(_T("\nSTARTING\n=============================\n"));
Trace(_T("Calling CoCreateInstance()...\n"));
IUnknown* pUnk = NULL;
HRESULT hRes = S_OK;
hRes = CoCreateInstance(__uuidof(CLabrador), NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**)&pUnk);
if (FAILED(hRes))
{
Trace(_T("Failed to create Labrador\n"));
return;
}
Trace(_T("Object created\n"));
IMammal* pMammal = NULL;
hRes = pUnk->QueryInterface(__uuidof(IMammal), (LPVOID*)&pMammal);
pUnk->Release();
if (FAILED(hRes))
{
Trace(_T("QueryInterface() for IMammal failed\n"));
return;
}
Trace(_T("Calling through IMammal methods...\n"));
pMammal->GetSpeciesName(szTmp);
Trace(_T("Species name is <%ls>\n"), szTmp);
BOOL bIsAlive;
pMammal->IsAlive(&bIsAlive);
if (bIsAlive)
Trace(_T("And it's alive!\n"));
else
Trace(_T("And it's dead!\n"));
IDog* pDog = NULL;
hRes = pMammal->QueryInterface(__uuidof(IDog), (void**)&pDog);
pMammal->Release();
if (FAILED(hRes))
{
Trace(_T("QueryInterface() for IDog failed\n"));
return;
}
Trace(_T("Calling through IDog methods...\n"));
BOOL bIsBarking;
pDog->GetPetName(szTmp);
Trace(_T("Dog's name is <%ls>\n"), szTmp);
pDog->IsBarking(&bIsBarking);
if (bIsBarking)
printf("BARK! BARK! BARK! BARK!\n");
pDog->SetPetName(L"KIVA");
pDog->GetPetName(szTmp);
printf("Dog's New name is <%ls>\n", szTmp);
Trace(_T("Releasing Object\n"));
pDog->Release();
Trace(_T("\nDONE!!!\n=============================\n"));
}
void main()
{
if (FAILED(CoInitialize(NULL)))
return;
CallLabrador();
#ifdef _DEBUG
_CrtDumpMemoryLeaks();
#endif
CoUninitialize();
}
| [
"[email protected]"
] | |
0396ad88585ef28dffb0ec7b6433af659839ff4c | 607fb1e7f847cb779e41fc4249c9d41fb5ab4825 | /Contain.ino | b27ec9b63a2bc80ffb4420ca5ea0756249aff346 | [] | no_license | fchegez24/Strings-Manupulation | 1b3c2e48de331ece09862120a10a13c056fdf8ce | d9ce1ff0ad005db9be169763e490e3a926a6adee | refs/heads/master | 2021-01-21T21:00:10.685316 | 2017-06-19T11:28:51 | 2017-06-19T11:28:51 | 94,769,185 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | ino | ///////////////////////////////////////////////////////////////////////
//This example is meant for checking if a string consist a piece of////
//strin.By fredrick chege nyamu.For Improvements question email ////
//at [email protected]/////
//improve the library to be better returns true if it has ////
//////////////////////////////////////////////////////////////////////
#include <ExString.h>
ExString exstring(0,0,0,0,0," ");
String xxx="abcdefghijkl";
String xx="ghi";
boolean con=false;
void setup()
{
Serial.begin(9600);
}
void loop()
{
con=exstring.Contains(xxx,xx);
if (con==true)
{
Serial.println("found ");
}
}
| [
"[email protected]"
] | |
7d03621d2aae01ea51ef5cb720d47d1061e698c0 | 60799c0854702d8b7589814f1304f534c3dd6c23 | /isabelle_barbosa/src/ListaEncadeada.h | 08984372aa5795986f1dbca8cc92b68327039433 | [] | no_license | isabellevieirab/tp1_ed | 06166f622f29cbc6bdbd9c1810d1d6885dfc1adb | bb1c57097f2b48e5c6b77d9307f04900d0254d03 | refs/heads/master | 2022-02-18T03:02:04.112510 | 2019-10-05T01:24:09 | 2019-10-05T01:24:09 | 212,720,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | #ifndef __TP1_ED_1__
#define __TP1_ED_1__
struct celula{
int v;
int opr;
celula* prox;
};
class ListaEncadeada{
public:
celula* cabeca;
celula* ponta;
int tamanho;
ListaEncadeada();
ListaEncadeada(int v);
virtual ~ListaEncadeada();
void imprime();
bool vazia();
void insere(int v, int operacao);
void apaga(int v);
int verificaLista(int valor);
celula acessa(int posicao);
};
#endif
| [
"[email protected]"
] | |
28f0ae024e35489fb2fbd629cf3f1b2a599ac449 | 6ec47f8b798b0875c3d30b3aa419715c380be4ee | /Finalized Code/iomanip.cpp | 2a7993e6a007ff540b4ba838b18c70b24836e95e | [] | no_license | Captain-Price-TF-141/CS135 | 740a3bbcac7a0a5e72df31e4e91718510b500e17 | 7ef5337778b65554243220fdf80b09ca6a8a7f3b | refs/heads/main | 2023-03-05T00:37:31.345843 | 2021-02-21T06:48:03 | 2021-02-21T06:48:03 | 340,825,673 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43 | cpp | //Captain-Price-TF-141
#include <iomanip>
| [
"[email protected]"
] | |
043ed589f8967239bf1c0a5748e3d160af063f44 | fce0d1bf8e69505c67be0f929194e1d8a7475ebf | /Analyzer/BDT/Trial/v05_eventWeght/BDTTraining.cxx | 2dfaba0ad44c2af722e87c7d328cdfeebc8f1de7 | [] | no_license | KyeongPil-Lee/DYScouting | e86ccfbb8fad60554f4e5a152ced9db9d013a162 | 9150e3aa82ef5dc11de83728f65ebc62304c472b | refs/heads/master | 2021-12-19T08:53:46.435674 | 2021-12-06T18:29:09 | 2021-12-06T18:29:09 | 214,085,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,283 | cxx | // -- reference: https://github.com/root-project/root/blob/master/tutorials/tmva/TMVAClassification.C
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TObjString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TMVA/Factory.h"
#include "TMVA/DataLoader.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"
int TMVAClassification( TString myMethodList = "" )
{
//---------------------------------------------------------------
// This loads the library
TMVA::Tools::Instance();
// Default MVA methods to be trained + tested
// only run BDT
std::map<std::string,int> Use;
// Cut optimisation
Use["Cuts"] = 0;
Use["CutsD"] = 0;
Use["CutsPCA"] = 0;
Use["CutsGA"] = 0;
Use["CutsSA"] = 0;
//
// 1-dimensional likelihood ("naive Bayes estimator")
Use["Likelihood"] = 0;
Use["LikelihoodD"] = 0; // the "D" extension indicates decorrelated input variables (see option strings)
Use["LikelihoodPCA"] = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
Use["LikelihoodKDE"] = 0;
Use["LikelihoodMIX"] = 0;
//
// Mutidimensional likelihood and Nearest-Neighbour methods
Use["PDERS"] = 0;
Use["PDERSD"] = 0;
Use["PDERSPCA"] = 0;
Use["PDEFoam"] = 0;
Use["PDEFoamBoost"] = 0; // uses generalised MVA method boosting
Use["KNN"] = 0; // k-nearest neighbour method
//
// Linear Discriminant Analysis
Use["LD"] = 0; // Linear Discriminant identical to Fisher
Use["Fisher"] = 0;
Use["FisherG"] = 0;
Use["BoostedFisher"] = 0; // uses generalised MVA method boosting
Use["HMatrix"] = 0;
//
// Function Discriminant analysis
Use["FDA_GA"] = 0; // minimisation of user-defined function using Genetics Algorithm
Use["FDA_SA"] = 0;
Use["FDA_MC"] = 0;
Use["FDA_MT"] = 0;
Use["FDA_GAMT"] = 0;
Use["FDA_MCMT"] = 0;
//
// Neural Networks (all are feed-forward Multilayer Perceptrons)
Use["MLP"] = 0; // Recommended ANN
Use["MLPBFGS"] = 0; // Recommended ANN with optional training method
Use["MLPBNN"] = 0; // Recommended ANN with BFGS training method and bayesian regulator
Use["CFMlpANN"] = 0; // Depreciated ANN from ALEPH
Use["TMlpANN"] = 0; // ROOT's own ANN
#ifdef R__HAS_TMVAGPU
Use["DNN_GPU"] = 1; // CUDA-accelerated DNN training.
#else
Use["DNN_GPU"] = 0;
#endif
#ifdef R__HAS_TMVACPU
Use["DNN_CPU"] = 1; // Multi-core accelerated DNN.
#else
Use["DNN_CPU"] = 0;
#endif
//
// Support Vector Machine
Use["SVM"] = 0;
//
// Boosted Decision Trees
Use["BDT"] = 0; // uses Adaptive Boost
Use["BDTG"] = 1; // uses Gradient Boost
Use["BDTB"] = 0; // uses Bagging
Use["BDTD"] = 0; // decorrelation + Adaptive Boost
Use["BDTF"] = 0; // allow usage of fisher discriminant for node splitting
//
// Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
Use["RuleFit"] = 0;
// ---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVAClassification" << std::endl;
// Select methods (don't look at this code - not of interest)
if (myMethodList != "") {
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
for (UInt_t i=0; i<mlist.size(); i++) {
std::string regMethod(mlist[i]);
if (Use.find(regMethod) == Use.end()) {
std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
std::cout << std::endl;
return 1;
}
Use[regMethod] = 1;
}
}
// --------------------------------------------------------------------------------------------------
// Here the preparation phase begins
// Read training and test data
TFile *f_input_signal = TFile::Open("TreeMaker/ROOTFile_BDTInputTreeProducer_DYJetsToLL_Madgraph_All.root");
TFile *f_input_bkg = TFile::Open("TreeMaker/ROOTFile_BDTInputTreeProducer_QCDMuEnriched_All.root");
TTree *signalTree = (TTree*)f_input_signal->Get("BDTInput");
TTree *background = (TTree*)f_input_bkg->Get("BDTInput");
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory is
// the only TMVA object you have to interact with
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
TMVA::DataLoader *dataloader = new TMVA::DataLoader("dataset");
// If you wish to modify default settings
// (please check "src/Config.h" to see all available global options)
//
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
// [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
dataloader->AddVariable( "diMuNormVtxChi2", "Normalized dimuon vertex chi2", "", 'F' );
dataloader->AddVariable( "diMuDEta", "eta difference between two muons", "", 'F' );
dataloader->AddVariable( "diMuDPhi", "phi difference between two muons", "", 'F' );
dataloader->AddVariable( "caloMET_pt", "Calo MET", "GeV", 'F' );
dataloader->AddVariable( "nMuonHit_lead", "# muon hits (leading muon)", "", 'I' );
dataloader->AddVariable( "nMatchedStation_lead", "# matched station (leading muon)", "", 'I' );
dataloader->AddVariable( "nPixelHit_lead", "# pixel hits (leading muon)", "", 'I' );
dataloader->AddVariable( "nTrackerLayer_lead", "# tracker layers (leading muon)", "", 'I' );
dataloader->AddVariable( "normChi2_lead", "Normalized chi2 (leading muon)", "", 'F' );
dataloader->AddVariable( "relTrkIso_lead", "Relative tracker isolation (leading muon)", "", 'F' );
dataloader->AddVariable( "nMuonHit_sub", "# muon hits (sub-leading muon)", "", 'I' );
dataloader->AddVariable( "nMatchedStation_sub", "# matched station (sub-leading muon)", "", 'I' );
dataloader->AddVariable( "nPixelHit_sub", "# pixel hits (sub-leading muon)", "", 'I' );
dataloader->AddVariable( "nTrackerLayer_sub", "# tracker layers (sub-leading muon)", "", 'I' );
dataloader->AddVariable( "normChi2_sub", "Normalized chi2 (sub-leading muon)", "", 'F' );
dataloader->AddVariable( "relTrkIso_sub", "Relative tracker isolation (sub-leading muon)", "", 'F' );
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
dataloader->AddSpectator( "diMuM", "Dimuon mass", "GeV", 'F' );
dataloader->AddSpectator( "diMuRap", "Dimuon rapidity", "", 'F' );
dataloader->AddSpectator( "diMuPt", "Dimuon pT", "GeV", 'F' );
// global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// You can add an arbitrary number of signal or background trees
dataloader->AddSignalTree ( signalTree, signalWeight );
dataloader->AddBackgroundTree( background, backgroundWeight );
// Set individual event weights (the variables must exist in the original TTree)
// - for signal : `dataloader->SetSignalWeightExpression ("weight1*weight2");`
// - for background: `dataloader->SetBackgroundWeightExpression("weight1*weight2");`
dataloader->SetSignalWeightExpression( "weight" );
dataloader->SetBackgroundWeightExpression( "weight" );
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
// dataloader->PrepareTrainingAndTestTree( mycuts, "nTrain_Signal=50000:nTrain_Background=50000:nTest_Signal=50000:nTest_Background=50000:SplitMode=Random:!V" );
dataloader->PrepareTrainingAndTestTree( mycuts, "SplitMode=Random:!V" ); // -- do not specify # events: use all # events & split half and half for training and testing
// ### Book MVA methods
//
// Please lookup the various method configuration options in the corresponding cxx files, eg:
// src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
// it is possible to preset ranges in the option string in which the cut optimisation should be done:
// "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
// Cut optimisation
if (Use["Cuts"])
factory->BookMethod( dataloader, TMVA::Types::kCuts, "Cuts",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
if (Use["CutsD"])
factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsD",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );
if (Use["CutsPCA"])
factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsPCA",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );
if (Use["CutsGA"])
factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsGA",
"H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" );
if (Use["CutsSA"])
factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsSA",
"!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
// Likelihood ("naive Bayes estimator")
if (Use["Likelihood"])
factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "Likelihood",
"H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
// Decorrelated likelihood
if (Use["LikelihoodD"])
factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodD",
"!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" );
// PCA-transformed likelihood
if (Use["LikelihoodPCA"])
factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodPCA",
"!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" );
// Use a kernel density estimator to approximate the PDFs
if (Use["LikelihoodKDE"])
factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodKDE",
"!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" );
// Use a variable-dependent mix of splines and kernel density estimator
if (Use["LikelihoodMIX"])
factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodMIX",
"!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" );
// Test the multi-dimensional probability density estimator
// here are the options strings for the MinMax and RMS methods, respectively:
//
// "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
// "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
if (Use["PDERS"])
factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERS",
"!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );
if (Use["PDERSD"])
factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSD",
"!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );
if (Use["PDERSPCA"])
factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSPCA",
"!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );
// Multi-dimensional likelihood estimator using self-adapting phase-space binning
if (Use["PDEFoam"])
factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoam",
"!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );
if (Use["PDEFoamBoost"])
factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoamBoost",
"!H:!V:Boost_Num=30:Boost_Transform=linear:SigBgSeparate=F:MaxDepth=4:UseYesNoCell=T:DTLogic=MisClassificationError:FillFoamWithOrigWeights=F:TailCut=0:nActiveCells=500:nBin=20:Nmin=400:Kernel=None:Compress=T" );
// K-Nearest Neighbour classifier (KNN)
if (Use["KNN"])
factory->BookMethod( dataloader, TMVA::Types::kKNN, "KNN",
"H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
// H-Matrix (chi2-squared) method
if (Use["HMatrix"])
factory->BookMethod( dataloader, TMVA::Types::kHMatrix, "HMatrix", "!H:!V:VarTransform=None" );
// Linear discriminant (same as Fisher discriminant)
if (Use["LD"])
factory->BookMethod( dataloader, TMVA::Types::kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
// Fisher discriminant (same as LD)
if (Use["Fisher"])
factory->BookMethod( dataloader, TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
// Fisher with Gauss-transformed input variables
if (Use["FisherG"])
factory->BookMethod( dataloader, TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );
// Composite classifier: ensemble (tree) of boosted Fisher classifiers
if (Use["BoostedFisher"])
factory->BookMethod( dataloader, TMVA::Types::kFisher, "BoostedFisher",
"H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2:!Boost_DetailedMonitoring" );
// Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
if (Use["FDA_MC"])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MC",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );
if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GA",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=100:Cycles=2:Steps=5:Trim=True:SaveBestGen=1" );
if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_SA",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
if (Use["FDA_MT"])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MT",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );
if (Use["FDA_GAMT"])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GAMT",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );
if (Use["FDA_MCMT"])
factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MCMT",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );
// TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
if (Use["MLP"])
factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" );
if (Use["MLPBFGS"])
factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" );
if (Use["MLPBNN"])
factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLPBNN", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=60:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:UseRegulator" ); // BFGS training with bayesian regulators
// Multi-architecture DNN implementation.
if (Use["DNN_CPU"] or Use["DNN_GPU"]) {
// General layout.
TString layoutString ("Layout=TANH|128,TANH|128,TANH|128,LINEAR");
// Training strategies.
TString training0("LearningRate=1e-2,Momentum=0.9,Repetitions=1,"
"ConvergenceSteps=30,BatchSize=256,TestRepetitions=10,"
"WeightDecay=1e-4,Regularization=None,"
"DropConfig=0.0+0.5+0.5+0.5, Multithreading=True");
TString training1("LearningRate=1e-2,Momentum=0.9,Repetitions=1,"
"ConvergenceSteps=20,BatchSize=256,TestRepetitions=10,"
"WeightDecay=1e-4,Regularization=L2,"
"DropConfig=0.0+0.0+0.0+0.0, Multithreading=True");
TString training2("LearningRate=1e-3,Momentum=0.0,Repetitions=1,"
"ConvergenceSteps=20,BatchSize=256,TestRepetitions=10,"
"WeightDecay=1e-4,Regularization=L2,"
"DropConfig=0.0+0.0+0.0+0.0, Multithreading=True");
TString trainingStrategyString ("TrainingStrategy=");
trainingStrategyString += training0 + "|" + training1 + "|" + training2;
// General Options.
TString dnnOptions ("!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=N:"
"WeightInitialization=XAVIERUNIFORM");
dnnOptions.Append (":"); dnnOptions.Append (layoutString);
dnnOptions.Append (":"); dnnOptions.Append (trainingStrategyString);
// // Cuda implementation.
// if (Use["DNN_GPU"]) {
// TString gpuOptions = dnnOptions + ":Architecture=GPU";
// factory->BookMethod(dataloader, TMVA::Types::kDL, "DNN_GPU", gpuOptions);
// }
// // Multi-core CPU implementation.
// if (Use["DNN_CPU"]) {
// TString cpuOptions = dnnOptions + ":Architecture=CPU";
// factory->BookMethod(dataloader, TMVA::Types::kDL, "DNN_CPU", cpuOptions);
// }
}
// CF(Clermont-Ferrand)ANN
if (Use["CFMlpANN"])
factory->BookMethod( dataloader, TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N" ); // n_cycles:#nodes:#nodes:...
// Tmlp(Root)ANN
if (Use["TMlpANN"])
factory->BookMethod( dataloader, TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3" ); // n_cycles:#nodes:#nodes:...
// Support Vector Machine
if (Use["SVM"])
factory->BookMethod( dataloader, TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
// Boosted Decision Trees
if (Use["BDTG"]) // Gradient Boost
factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTG",
"!H:!V:NTrees=1000:MinNodeSize=2.5%:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.5:nCuts=20:MaxDepth=2" );
if (Use["BDT"]) // Adaptive Boost
factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDT",
"!H:!V:NTrees=850:MinNodeSize=2.5%:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20" );
if (Use["BDTB"]) // Bagging
factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTB",
"!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20" );
if (Use["BDTD"]) // Decorrelation + Adaptive Boost
factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTD",
"!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate" );
if (Use["BDTF"]) // Allow Using Fisher discriminant in node splitting for (strong) linearly correlated variables
factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTF",
"!H:!V:NTrees=50:MinNodeSize=2.5%:UseFisherCuts:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20" );
// RuleFit -- TMVA implementation of Friedman's method
if (Use["RuleFit"])
factory->BookMethod( dataloader, TMVA::Types::kRuleFit, "RuleFit",
"H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" );
// For an example of the category classifier usage, see: TMVAClassificationCategory
//
// --------------------------------------------------------------------------------------------------
// Now you can optimize the setting (configuration) of the MVAs using the set of training events
// STILL EXPERIMENTAL and only implemented for BDT's !
//
// factory->OptimizeAllMethods("SigEffAtBkg0.01","Scan");
// factory->OptimizeAllMethods("ROCIntegral","FitGA");
//
// --------------------------------------------------------------------------------------------------
// Now you can tell the factory to train, test, and evaluate the MVAs
//
// Train MVAs using the set of training events
factory->TrainAllMethods();
// Evaluate all MVAs using the set of test events
factory->TestAllMethods();
// Evaluate and compare performance of all configured MVAs
factory->EvaluateAllMethods();
// --------------------------------------------------------------
// Save the output
outputFile->Close();
std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
std::cout << "==> TMVAClassification is done!" << std::endl;
delete factory;
delete dataloader;
// Launch the GUI for the root macros
if (!gROOT->IsBatch()) TMVA::TMVAGui( outfileName );
return 0;
}
void BDTTraining()
{
TMVAClassification();
}
// int main( int argc, char** argv )
// {
// // Select methods (don't look at this code - not of interest)
// TString methodList;
// for (int i=1; i<argc; i++) {
// TString regMethod(argv[i]);
// if(regMethod=="-b" || regMethod=="--batch") continue;
// if (!methodList.IsNull()) methodList += TString(",");
// methodList += regMethod;
// }
// return TMVAClassification(methodList);
// } | [
"[email protected]"
] | |
db01d49b3eb1d966656869a33aeffb15c21ffbf0 | 007816a6304b8b75c6506cfb1c80a05e78a5faff | /CAMPON.cpp | c8fc267d160178eba98dbf1f8194b5177148af12 | [] | no_license | hst005/Competitive-Programming-Basics-and-examples | 00382a5b2ffe25538a438f301521b1ea7e57ac1d | 5e95cfce4e716df9f802743ac369ae9db7f3776f | refs/heads/master | 2020-06-30T09:43:55.480088 | 2019-08-06T07:03:56 | 2019-08-06T07:03:56 | 200,794,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | #include <iostream>
#define ll long long
using namespace std;
int main()
{
ll t;
cin>>t;
while(t--){
ll ar[32];
for(int i=0;i<32;i++){
ar[i]=0;
}
ll d;
cin>>d;
for(int i=0;i<d;i++){
int day,pr;
cin>>day>>pr;
for(int j=day;j<32;j++){
ar[j]+=pr;
}
}
ll q;
cin>>q;
while(q--){
int dy,qu;
cin>>dy>>qu;
if(ar[dy]>=qu){
cout<<"Go Camp"<<endl;
}
else{
cout<<"Go Sleep"<<endl;
}
}
}
return 0;
}
| [
"[email protected]"
] | |
c1f515896c112856d4553e4f73c50425323a2c1d | 0a83b3293fbf3016395cacf12a8511dd7fb02673 | /src/server/scripts/Kalimdor/ashenvale.cpp | dab574c378d2797c698462f07a3ad999cca4b29e | [] | no_license | demooo/PandaFire | 55a9b992d3f30e0671d32cf3e2f8b34b4d24bf44 | f70f41114b166b0f299ed5543e33e2de51c132dc | refs/heads/master | 2020-04-08T05:28:18.097603 | 2015-01-09T07:40:22 | 2015-01-09T07:40:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,360 | cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Ashenvale
SD%Complete: 70
SDComment: Quest support: 6544, 6482
SDCategory: Ashenvale Forest
EndScriptData */
/* ContentData
npc_torek
npc_ruul_snowhoof
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedEscortAI.h"
/*####
# npc_torek
####*/
enum TorekSays
{
SAY_READY = 0,
SAY_MOVE = 1,
SAY_PREPARE = 2,
SAY_WIN = 3,
SAY_END = 4,
};
enum TorekSpells
{
SPELL_REND = 11977,
SPELL_THUNDERCLAP = 8078,
};
enum TorekMisc
{
QUEST_TOREK_ASSULT = 6544,
ENTRY_SPLINTERTREE_RAIDER = 12859,
ENTRY_DURIEL = 12860,
ENTRY_SILVERWING_SENTINEL = 12896,
ENTRY_SILVERWING_WARRIOR = 12897,
};
class npc_torek : public CreatureScript
{
public:
npc_torek() : CreatureScript("npc_torek")
{
}
struct npc_torekAI : public npc_escortAI
{
npc_torekAI(Creature* creature) : npc_escortAI(creature) {}
uint32 Rend_Timer;
uint32 Thunderclap_Timer;
bool Completed;
void WaypointReached(uint32 waypointId)
{
if (Player* player = GetPlayerForEscort())
{
switch (waypointId)
{
case 1:
Talk(SAY_MOVE, player->GetGUID());
break;
case 8:
Talk(SAY_PREPARE, player->GetGUID());
break;
case 19:
//TODO: verify location and creatures amount.
me->SummonCreature(ENTRY_DURIEL, 1776.73f, -2049.06f, 109.83f, 1.54f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000);
me->SummonCreature(ENTRY_SILVERWING_SENTINEL, 1774.64f, -2049.41f, 109.83f, 1.40f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000);
me->SummonCreature(ENTRY_SILVERWING_WARRIOR, 1778.73f, -2049.50f, 109.83f, 1.67f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000);
break;
case 20:
DoScriptText(SAY_WIN, me, player);
Completed = true;
player->GroupEventHappens(QUEST_TOREK_ASSULT, me);
break;
case 21:
Talk(SAY_END, player->GetGUID());
break;
}
}
}
void Reset()
{
Rend_Timer = 5000;
Thunderclap_Timer = 8000;
Completed = false;
}
void EnterCombat(Unit* /*who*/)
{
}
void JustSummoned(Creature* summoned)
{
summoned->AI()->AttackStart(me);
}
void UpdateAI(const uint32 diff)
{
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (Rend_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_REND);
Rend_Timer = 20000;
}
else
Rend_Timer -= diff;
if (Thunderclap_Timer <= diff)
{
DoCast(me, SPELL_THUNDERCLAP);
Thunderclap_Timer = 30000;
}
else
Thunderclap_Timer -= diff;
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_torekAI(creature);
}
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest)
{
if (quest->GetQuestId() == QUEST_TOREK_ASSULT)
{
//TODO: find companions, make them follow Torek, at any time (possibly done by core/database in future?)
creature->AI()->Talk(SAY_READY, player->GetGUID());
creature->setFaction(113);
if (npc_escortAI* pEscortAI = CAST_AI(npc_torekAI, creature->AI()))
pEscortAI->Start(true, true, player->GetGUID());
}
return true;
}
};
/*####
# npc_ruul_snowhoof
####*/
enum RuulSnowhoof
{
NPC_THISTLEFUR_URSA = 3921,
NPC_THISTLEFUR_TOTEMIC = 3922,
NPC_THISTLEFUR_PATHFINDER = 3926,
QUEST_FREEDOM_TO_RUUL = 6482,
GO_CAGE = 178147
};
Position const RuulSnowhoofSummonsCoord[6] =
{
{3449.218018f, -587.825073f, 174.978867f, 4.714445f},
{3446.384521f, -587.830872f, 175.186279f, 4.714445f},
{3444.218994f, -587.835327f, 175.380600f, 4.714445f},
{3508.344482f, -492.024261f, 186.929031f, 4.145029f},
{3506.265625f, -490.531006f, 186.740128f, 4.239277f},
{3503.682373f, -489.393799f, 186.629684f, 4.349232f}
};
class npc_ruul_snowhoof : public CreatureScript
{
public:
npc_ruul_snowhoof() : CreatureScript("npc_ruul_snowhoof") { }
struct npc_ruul_snowhoofAI : public npc_escortAI
{
npc_ruul_snowhoofAI(Creature* creature) : npc_escortAI(creature) { }
void WaypointReached(uint32 waypointId)
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 0:
me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20))
Cage->SetGoState(GO_STATE_ACTIVE);
break;
case 13:
me->SummonCreature(NPC_THISTLEFUR_TOTEMIC, RuulSnowhoofSummonsCoord[0], TEMPSUMMON_DEAD_DESPAWN, 60000);
me->SummonCreature(NPC_THISTLEFUR_URSA, RuulSnowhoofSummonsCoord[1], TEMPSUMMON_DEAD_DESPAWN, 60000);
me->SummonCreature(NPC_THISTLEFUR_PATHFINDER, RuulSnowhoofSummonsCoord[2], TEMPSUMMON_DEAD_DESPAWN, 60000);
break;
case 19:
me->SummonCreature(NPC_THISTLEFUR_TOTEMIC, RuulSnowhoofSummonsCoord[3], TEMPSUMMON_DEAD_DESPAWN, 60000);
me->SummonCreature(NPC_THISTLEFUR_URSA, RuulSnowhoofSummonsCoord[4], TEMPSUMMON_DEAD_DESPAWN, 60000);
me->SummonCreature(NPC_THISTLEFUR_PATHFINDER, RuulSnowhoofSummonsCoord[5], TEMPSUMMON_DEAD_DESPAWN, 60000);
break;
case 21:
player->GroupEventHappens(QUEST_FREEDOM_TO_RUUL, me);
break;
}
}
void EnterCombat(Unit* /*who*/) {}
void Reset()
{
if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20))
Cage->SetGoState(GO_STATE_READY);
}
void JustSummoned(Creature* summoned)
{
summoned->AI()->AttackStart(me);
}
void UpdateAI(const uint32 diff)
{
npc_escortAI::UpdateAI(diff);
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_ruul_snowhoofAI(creature);
}
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest)
{
if (quest->GetQuestId() == QUEST_FREEDOM_TO_RUUL)
{
creature->setFaction(113);
if (npc_escortAI* pEscortAI = CAST_AI(npc_ruul_snowhoofAI, (creature->AI())))
pEscortAI->Start(true, false, player->GetGUID());
}
return true;
}
};
enum Muglash
{
SAY_MUG_START1 = -1800054,
SAY_MUG_START2 = -1800055,
SAY_MUG_BRAZIER = -1800056,
SAY_MUG_BRAZIER_WAIT = -1800057,
SAY_MUG_ON_GUARD = -1800058,
SAY_MUG_REST = -1800059,
SAY_MUG_DONE = -1800060,
SAY_MUG_GRATITUDE = -1800061,
SAY_MUG_PATROL = -1800062,
SAY_MUG_RETURN = -1800063,
QUEST_VORSHA = 6641,
GO_NAGA_BRAZIER = 178247,
NPC_WRATH_RIDER = 3713,
NPC_WRATH_SORCERESS = 3717,
NPC_WRATH_RAZORTAIL = 3712,
NPC_WRATH_PRIESTESS = 3944,
NPC_WRATH_MYRMIDON = 3711,
NPC_WRATH_SEAWITCH = 3715,
NPC_VORSHA = 12940,
NPC_MUGLASH = 12717
};
Position const FirstNagaCoord[3] =
{
{3603.504150f, 1122.631104f, 1.635f, 0.0f}, // rider
{3589.293945f, 1148.664063f, 5.565f, 0.0f}, // sorceress
{3609.925537f, 1168.759521f, -1.168f, 0.0f} // razortail
};
Position const SecondNagaCoord[3] =
{
{3609.925537f, 1168.759521f, -1.168f, 0.0f}, // witch
{3645.652100f, 1139.425415f, 1.322f, 0.0f}, // priest
{3583.602051f, 1128.405762f, 2.347f, 0.0f} // myrmidon
};
Position const VorshaCoord = {3633.056885f, 1172.924072f, -5.388f, 0.0f};
class npc_muglash : public CreatureScript
{
public:
npc_muglash() : CreatureScript("npc_muglash") { }
struct npc_muglashAI : public npc_escortAI
{
npc_muglashAI(Creature* creature) : npc_escortAI(creature) { }
uint8 WaveId;
uint32 EventTimer;
bool IsBrazierExtinguished;
void JustSummoned(Creature* summoned)
{
summoned->AI()->AttackStart(me);
}
void WaypointReached(uint32 waypointId)
{
if (Player* player = GetPlayerForEscort())
{
switch (waypointId)
{
case 0:
DoScriptText(SAY_MUG_START2, me, player);
break;
case 24:
DoScriptText(SAY_MUG_BRAZIER, me, player);
if (GameObject* go = GetClosestGameObjectWithEntry(me, GO_NAGA_BRAZIER, INTERACTION_DISTANCE*2))
{
go->RemoveFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_NOT_SELECTABLE);
SetEscortPaused(true);
}
break;
case 25:
DoScriptText(SAY_MUG_GRATITUDE, me);
player->GroupEventHappens(QUEST_VORSHA, me);
break;
case 26:
DoScriptText(SAY_MUG_PATROL, me);
break;
case 27:
DoScriptText(SAY_MUG_RETURN, me);
break;
}
}
}
void EnterCombat(Unit* /*who*/)
{
if (Player* player = GetPlayerForEscort())
if (HasEscortState(STATE_ESCORT_PAUSED))
{
if (urand(0, 1))
DoScriptText(SAY_MUG_ON_GUARD, me, player);
return;
}
}
void Reset()
{
EventTimer = 10000;
WaveId = 0;
IsBrazierExtinguished = false;
}
void JustDied(Unit* /*killer*/)
{
if (HasEscortState(STATE_ESCORT_ESCORTING))
if (Player* player = GetPlayerForEscort())
player->FailQuest(QUEST_VORSHA);
}
void DoWaveSummon()
{
switch (WaveId)
{
case 1:
me->SummonCreature(NPC_WRATH_RIDER, FirstNagaCoord[0], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
me->SummonCreature(NPC_WRATH_SORCERESS, FirstNagaCoord[1], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
me->SummonCreature(NPC_WRATH_RAZORTAIL, FirstNagaCoord[2], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
break;
case 2:
me->SummonCreature(NPC_WRATH_PRIESTESS, SecondNagaCoord[0], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
me->SummonCreature(NPC_WRATH_MYRMIDON, SecondNagaCoord[1], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
me->SummonCreature(NPC_WRATH_SEAWITCH, SecondNagaCoord[2], TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
break;
case 3:
me->SummonCreature(NPC_VORSHA, VorshaCoord, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
break;
case 4:
SetEscortPaused(false);
DoScriptText(SAY_MUG_DONE, me);
break;
}
}
void UpdateAI(const uint32 uiDiff)
{
npc_escortAI::UpdateAI(uiDiff);
if (!me->getVictim())
{
if (HasEscortState(STATE_ESCORT_PAUSED) && IsBrazierExtinguished)
{
if (EventTimer < uiDiff)
{
++WaveId;
DoWaveSummon();
EventTimer = 10000;
}
else
EventTimer -= uiDiff;
}
return;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_muglashAI(creature);
}
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest)
{
if (quest->GetQuestId() == QUEST_VORSHA)
{
if (npc_muglashAI* pEscortAI = CAST_AI(npc_muglashAI, creature->AI()))
{
DoScriptText(SAY_MUG_START1, creature);
creature->setFaction(113);
pEscortAI->Start(true, false, player->GetGUID());
}
}
return true;
}
};
class go_naga_brazier : public GameObjectScript
{
public:
go_naga_brazier() : GameObjectScript("go_naga_brazier") { }
bool OnGossipHello(Player* /*player*/, GameObject* go)
{
if (Creature* creature = GetClosestCreatureWithEntry(go, NPC_MUGLASH, INTERACTION_DISTANCE*2))
{
if (npc_muglash::npc_muglashAI* pEscortAI = CAST_AI(npc_muglash::npc_muglashAI, creature->AI()))
{
DoScriptText(SAY_MUG_BRAZIER_WAIT, creature);
pEscortAI->IsBrazierExtinguished = true;
return false;
}
}
return true;
}
};
void AddSC_ashenvale()
{
new npc_torek();
new npc_ruul_snowhoof();
new npc_muglash();
new go_naga_brazier();
}
| [
"[email protected]"
] | |
4d1e315aac7081045cc068c566bc8cf6551c50cf | cbd9eb545fb4c88d6661ceec33749ed21b3f737e | /csmtp.h | de04189a16873ee09a1736bfaa10867c308d63c1 | [] | no_license | Khachik96/FLChat | 04f6065e1558f95f3d6da3ff18c81a30b97cd682 | 4b1e66ea8eadbcfd32a404061feadca18953ff03 | refs/heads/master | 2020-03-18T02:25:21.249810 | 2018-05-20T22:15:40 | 2018-05-20T22:15:40 | 134,189,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80,707 | h |
#include <vector>
#include "openssl/err.h"
#include <cassert>
#include "MD5.h"
#ifdef __linux__
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <openssl/ssl.h>
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#ifndef HAVE__STRNICMP
#define HAVE__STRNICMP
#define _strnicmp strncasecmp
#endif
#define OutputDebugStringA(buf)
typedef unsigned short WORD;
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct hostent* LPHOSTENT;
typedef struct servent* LPSERVENT;
typedef struct in_addr* LPIN_ADDR;
typedef struct sockaddr* LPSOCKADDR;
#define LINUX
#else
#include <winsock2.h>
#include <time.h>
#pragma comment(lib, "ws2_32.lib")
//Add "openssl-0.9.8l\inc32" to Additional Include Directories
#include "openssl\ssl.h"
#if _MSC_VER < 1400
#define snprintf _snprintf
#else
#define snprintf sprintf_s
#endif
#endif
#define TIME_IN_SEC 3*60 // how long client will wait for server response in non-blocking mode
#define BUFFER_SIZE 10240 // SendData and RecvData buffers sizes
#define MSG_SIZE_IN_MB 25 // the maximum size of the message with all attachments
#define COUNTER_VALUE 100 // how many times program will try to receive data
const char BOUNDARY_TEXT[] = "__MESSAGE__ID__54yg6f6h6y456345";
enum CSmptXPriority
{
XPRIORITY_HIGH = 2,
XPRIORITY_NORMAL = 3,
XPRIORITY_LOW = 4
};
class ECSmtp
{
public:
enum CSmtpError
{
CSMTP_NO_ERROR = 0,
WSA_STARTUP = 100, // WSAGetLastError()
WSA_VER,
WSA_SEND,
WSA_RECV,
WSA_CONNECT,
WSA_GETHOSTBY_NAME_ADDR,
WSA_INVALID_SOCKET,
WSA_HOSTNAME,
WSA_IOCTLSOCKET,
WSA_SELECT,
BAD_IPV4_ADDR,
UNDEF_MSG_HEADER = 200,
UNDEF_MAIL_FROM,
UNDEF_SUBJECT,
UNDEF_RECIPIENTS,
UNDEF_LOGIN,
UNDEF_PASSWORD,
BAD_LOGIN_PASSWORD,
BAD_DIGEST_RESPONSE,
BAD_SERVER_NAME,
UNDEF_RECIPIENT_MAIL,
COMMAND_MAIL_FROM = 300,
COMMAND_EHLO,
COMMAND_AUTH_PLAIN,
COMMAND_AUTH_LOGIN,
COMMAND_AUTH_CRAMMD5,
COMMAND_AUTH_DIGESTMD5,
COMMAND_DIGESTMD5,
COMMAND_DATA,
COMMAND_QUIT,
COMMAND_RCPT_TO,
MSG_BODY_ERROR,
CONNECTION_CLOSED = 400, // by server
SERVER_NOT_READY, // remote server
SERVER_NOT_RESPONDING,
SELECT_TIMEOUT,
FILE_NOT_EXIST,
MSG_TOO_BIG,
BAD_LOGIN_PASS,
UNDEF_XYZ_RESPONSE,
LACK_OF_MEMORY,
TIME_ERROR,
RECVBUF_IS_EMPTY,
SENDBUF_IS_EMPTY,
OUT_OF_MSG_RANGE,
COMMAND_EHLO_STARTTLS,
SSL_PROBLEM,
COMMAND_DATABLOCK,
STARTTLS_NOT_SUPPORTED,
LOGIN_NOT_SUPPORTED
};
ECSmtp(CSmtpError err_) : ErrorCode(err_) {}
CSmtpError GetErrorNum(void) const {return ErrorCode;}
std::string GetErrorText(void) const;
private:
CSmtpError ErrorCode;
};
enum SMTP_COMMAND
{
command_INIT,
command_EHLO,
command_AUTHPLAIN,
command_AUTHLOGIN,
command_AUTHCRAMMD5,
command_AUTHDIGESTMD5,
command_DIGESTMD5,
command_USER,
command_PASSWORD,
command_MAILFROM,
command_RCPTTO,
command_DATA,
command_DATABLOCK,
command_DATAEND,
command_QUIT,
command_STARTTLS
};
// TLS/SSL extension
enum SMTP_SECURITY_TYPE
{
NO_SECURITY,
USE_TLS,
USE_SSL,
DO_NOT_SET
};
typedef struct tagCommand_Entry
{
SMTP_COMMAND command;
int send_timeout; // 0 means no send is required
int recv_timeout; // 0 means no recv is required
int valid_reply_code; // 0 means no recv is required, so no reply code
ECSmtp::CSmtpError error;
}Command_Entry;
class CSmtp
{
public:
CSmtp();
virtual ~CSmtp();
void AddRecipient(const char *email, const char *name=NULL);
void AddBCCRecipient(const char *email, const char *name=NULL);
void AddCCRecipient(const char *email, const char *name=NULL);
void AddAttachment(const char *path);
void AddMsgLine(const char* text);
void ClearMessage();
bool ConnectRemoteServer(const char* szServer, const unsigned short nPort_=0,
SMTP_SECURITY_TYPE securityType=DO_NOT_SET,
bool authenticate=true, const char* login=NULL,
const char* password=NULL);
void DisconnectRemoteServer();
void DelRecipients(void);
void DelBCCRecipients(void);
void DelCCRecipients(void);
void DelAttachments(void);
void DelMsgLines(void);
void DelMsgLine(unsigned int line);
void ModMsgLine(unsigned int line,const char* text);
unsigned int GetBCCRecipientCount() const;
unsigned int GetCCRecipientCount() const;
unsigned int GetRecipientCount() const;
const char* GetLocalHostIP() const;
const char* GetLocalHostName();
const char* GetMsgLineText(unsigned int line) const;
unsigned int GetMsgLines(void) const;
const char* GetReplyTo() const;
const char* GetMailFrom() const;
const char* GetSenderName() const;
const char* GetSubject() const;
const char* GetXMailer() const;
CSmptXPriority GetXPriority() const;
void Send();
void SetCharSet(const char *sCharSet);
void SetLocalHostName(const char *sLocalHostName);
void SetSubject(const char*);
void SetSenderName(const char*);
void SetSenderMail(const char*);
void SetReplyTo(const char*);
void SetReadReceipt(bool requestReceipt=true);
void SetXMailer(const char*);
void SetLogin(const char*);
void SetPassword(const char*);
void SetXPriority(CSmptXPriority);
void SetSMTPServer(const char* server, const unsigned short port=0, bool authenticate=true);
private:
std::string m_sLocalHostName;
std::string m_sMailFrom;
std::string m_sNameFrom;
std::string m_sSubject;
std::string m_sCharSet;
std::string m_sXMailer;
std::string m_sReplyTo;
bool m_bReadReceipt;
std::string m_sIPAddr;
std::string m_sLogin;
std::string m_sPassword;
std::string m_sSMTPSrvName;
unsigned short m_iSMTPSrvPort;
bool m_bAuthenticate;
CSmptXPriority m_iXPriority;
char *SendBuf;
char *RecvBuf;
SOCKET hSocket;
bool m_bConnected;
struct Recipient
{
std::string Name;
std::string Mail;
};
std::vector<Recipient> Recipients;
std::vector<Recipient> CCRecipients;
std::vector<Recipient> BCCRecipients;
std::vector<std::string> Attachments;
std::vector<std::string> MsgBody;
void ReceiveData(Command_Entry* pEntry);
void SendData(Command_Entry* pEntry);
void FormatHeader(char*);
int SmtpXYZdigits();
void SayHello();
void SayQuit();
// TLS/SSL extension
public:
SMTP_SECURITY_TYPE GetSecurityType() const
{ return m_type; }
void SetSecurityType(SMTP_SECURITY_TYPE type)
{ m_type = type; }
bool m_bHTML;
private:
SMTP_SECURITY_TYPE m_type;
SSL_CTX* m_ctx;
SSL* m_ssl;
void ReceiveResponse(Command_Entry* pEntry);
void InitOpenSSL();
void OpenSSLConnect();
void CleanupOpenSSL();
void ReceiveData_SSL(SSL* ssl, Command_Entry* pEntry);
void SendData_SSL(SSL* ssl, Command_Entry* pEntry);
void StartTls();
};
////////////////////////////////////////////////////////////////////////////////
// Original class CFastSmtp written by
// christopher w. backen <[email protected]>
// More details at: http://www.codeproject.com/KB/IP/zsmtp.aspx
//
// Modifications introduced by Jakub Piwowarczyk:
// 1. name of the class and functions
// 2. new functions added: SendData,ReceiveData and more
// 3. authentication added
// 4. attachments added
// 5 .comments added
// 6. DELAY_IN_MS removed (no delay during sending the message)
// 7. non-blocking mode
// More details at: http://www.codeproject.com/KB/mcpp/CSmtp.aspx
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// SSL/TLS support added by John Tang by making use of OpenSSL: http://www.openssl.org/
// More details at: http://www.codeproject.com/KB/IP/smtp_ssl.aspx
//
// PLAIN, CRAM-MD5 and DIGESTMD5 authentication added by David Johns
//
// Revision History:
// - Version 2.4: Updated with fixes reported as of 22 Oct 2015
// > Fixed issues with files being left opened and buffer not being deleted if an error occurs as discussed here: http://www.codeproject.com/Messages/4651730/Re-File-attachment.aspx
// - Thanks to Josep Sol�
// > Fixed issue with opening attachments as discussed here: http://www.codeproject.com/Messages/4640325/File-path-mistakenly-ommitted-from-file-name-when-.aspx
// - Thanks to Graham
// > Fixed potential memory leak as discussed here: http://www.codeproject.com/Messages/5010012/Memory-leaks.aspx
// - Thanks to LahPo
// > Made total message size limit larger as recommended here: http://stackoverflow.com/questions/22426686/csmtp-wont-send-an-e-mail-attachment-but-without-the-attachment-it-works-fine/28333737#28333737
// - Thanks to Stanislav
// > Fixed an issue with incomplete attachment file paths as discussed here: http://www.codeproject.com/Messages/5127588/Re-Attachment-does-not-come.aspx
// - Thanks to Member 11508846 and Member 11887128
// - Version 2.3: Updated with fixes reported as of 17 Aug 2013
// > Removed Bcc header so that recipients don't see who it was Bcc'd to as discussed here: http://www.codeproject.com/Messages/4633562/Bcc-and-mail-header.aspx
// - Thanks to o15s19
// > Fixed problem with attaching files that have unicode or reserved character filenames as discussed here: http://www.codeproject.com/Messages/4610174/Re-About-snprintf-FileName-255-Attachments-FileId-.aspx
// - Thanks to uni_gauldoth
// > Improved the method used for checking attachment file sizes as discussed here: http://www.codeproject.com/Messages/4562481/retreiving-file-size-for-attachments.aspx
// - Thanks to GKarRacer
// > Added #include <unistd.h> for linux compiles, which was required for gethostname as discussed here: http://www.codeproject.com/Messages/4551908/Works-on-Linux-CSmtp-cpp-needed-sharpinclude-unist.aspx
// - Thanks to jim fred
// - Version 2.2: Updated with fixes reported as of 6 May 2013
// > Fixed check on MsgBody.size() as discussed here: http://www.codeproject.com/Messages/4555663/Incorrect-range-check.aspx
// - Thanks to GKarRacer
// > Moved memory allocation and checking if attachments could be opened to before the MAIL command is
// issued to avoid throwing errors in a place where you can't terminate the connection gracefully without
// the email being sent corrupted
// > Changed all sprintf calls to snprintf to add greater security. #define'd snprintf to sprintf_s for
// MSVC. Also changed all strcpy to snprintf since that is the only way to use a secure function that
// is portable between standard C and MSVC since MS re-ordered the arguments between strcpy and
// strcpy_s
// > Fixed issue with SayQuit that could lead to infinite loop discussed here: http://www.codeproject.com/Messages/4451901/exception-in-SayQuit-could-lead-to-infinite-loop.aspx
// - Thanks to jcyangzh!
// > Fixed issue with AUTH PLAIN implementation discussed here: http://www.codeproject.com/Messages/4433069/looks-like-a-bug-in-plain-auth.aspx
// - Thanks to sbrytskyy!
// - Version 2.1: Updated with fixes reported as of 26 Mar 2012
// > Fixed issue in main.cpp with referring to USE_TLS in the wrong scope discussed here: http://www.codeproject.com/Messages/4151405/Re-USE_SSL-no-member-of-CSmtp.aspx
// - Thanks to Alan P Brown!
// > Added modifications to allow it to compile in Debian Linux discussed here: http://www.codeproject.com/Messages/4132697/linux-port-patch.aspx
// - Thanks to Oleg Dolgov!
// > Added ability to change the character set, inspired by this post: http://www.codeproject.com/Messages/4238701/Re-The-subject-contains-the-Chinese-letters-could-.aspx
// - Thanks to LeonHuang0726 and John TWC for the suggestion!
// > Added ability to request a read receipt by calling SetReadReceipt as proposed here: http://www.codeproject.com/Messages/3938944/Disposition-Notification-To.aspx
// - Thanks to Gospa for the suggestion!
// > Added check for Linux when adding paths of attachments in the MIME header as suggested here: http://www.codeproject.com/Messages/4357144/portability-bug-w-attachment-name.aspx
// - Thanks to Spike!
// > Switched method of setting private std::string variables to use the = operator as suggested here: http://www.codeproject.com/Messages/4356937/portability-bugs-w-std-string-and-exceptions.aspx
// - Thanks to Spike!
// > Added SetLocalHostName function proposed here: http://www.codeproject.com/Messages/4092347/bug-fixes-GetLocalHostName-Send.aspx
// - Thanks to jerko!
// > Added the modifications to allow it to compile in Linux described here: http://www.codeproject.com/Messages/3878620/My-vote-of-5.aspx
// - Thanks to korisk!
// > Added the fix that corrects behavior when m_sNameFrom is empty described here: http://www.codeproject.com/Messages/4196071/Bug-Mail-sent-by-mail-domain-com.aspx
// - Thanks to agenua.grupoi68!
// - Version 2.0: Updated to all fixes reported as of 23 Jun 2011:
// > Added the m_bAuthenticate member variable to be able to disable authentication
// even though it may be supported by the server. It defaults to true so if it is
// not set the library will act as it would have before the addition.
// > Added the ability to pass the security type, m_type, the new m_Authenticate flag,
// the login and password into the ConnectRemoteServer function. If these new arguments
// are not included in the call the function will work as it did before.
// > Added the ability to pass the new m_Authenticate flag into the SetSMTPServer function.
// If not provided, the function will act as it would before the addition.
// > Added fix described here: http://www.codeproject.com/Messages/3681792/Bug-when-reading-answer.aspx
// - Thanks to Martin Kjallman!
// > Added fixes described here: http://www.codeproject.com/Messages/3707662/Mistakes.aspx
// - Thanks to Karpov Andrey!
// > Added fixes described here: http://www.codeproject.com/Messages/3587166/Re-Possible-Solution-To-Misc-EHLO-Errors.aspx
// - Thanks to Jakub Piwowarczyk!
// - Version 1.9: Started with Revion 6 in code project http://www.codeproject.com/script/Articles/ListVersions.aspx?aid=98355
////////////////////////////////////////////////////////////////////////////////
Command_Entry command_list[] =
{
{command_INIT, 0, 5*60, 220, ECSmtp::SERVER_NOT_RESPONDING},
{command_EHLO, 5*60, 5*60, 250, ECSmtp::COMMAND_EHLO},
{command_AUTHPLAIN, 5*60, 5*60, 235, ECSmtp::COMMAND_AUTH_PLAIN},
{command_AUTHLOGIN, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_LOGIN},
{command_AUTHCRAMMD5, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_CRAMMD5},
{command_AUTHDIGESTMD5, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_DIGESTMD5},
{command_DIGESTMD5, 5*60, 5*60, 335, ECSmtp::COMMAND_DIGESTMD5},
{command_USER, 5*60, 5*60, 334, ECSmtp::UNDEF_XYZ_RESPONSE},
{command_PASSWORD, 5*60, 5*60, 235, ECSmtp::BAD_LOGIN_PASS},
{command_MAILFROM, 5*60, 5*60, 250, ECSmtp::COMMAND_MAIL_FROM},
{command_RCPTTO, 5*60, 5*60, 250, ECSmtp::COMMAND_RCPT_TO},
{command_DATA, 5*60, 2*60, 354, ECSmtp::COMMAND_DATA},
{command_DATABLOCK, 3*60, 0, 0, ECSmtp::COMMAND_DATABLOCK}, // Here the valid_reply_code is set to zero because there are no replies when sending data blocks
{command_DATAEND, 3*60, 10*60, 250, ECSmtp::MSG_BODY_ERROR},
{command_QUIT, 5*60, 5*60, 221, ECSmtp::COMMAND_QUIT},
{command_STARTTLS, 5*60, 5*60, 220, ECSmtp::COMMAND_EHLO_STARTTLS}
};
Command_Entry* FindCommandEntry(SMTP_COMMAND command)
{
Command_Entry* pEntry = NULL;
for(size_t i = 0; i < sizeof(command_list)/sizeof(command_list[0]); ++i)
{
if(command_list[i].command == command)
{
pEntry = &command_list[i];
break;
}
}
assert(pEntry != NULL);
return pEntry;
}
// A simple string match
bool IsKeywordSupported(const char* response, const char* keyword)
{
assert(response != NULL && keyword != NULL);
if(response == NULL || keyword == NULL)
return false;
int res_len = strlen(response);
int key_len = strlen(keyword);
if(res_len < key_len)
return false;
int pos = 0;
for(; pos < res_len - key_len + 1; ++pos)
{
if(_strnicmp(keyword, response+pos, key_len) == 0)
{
if(pos > 0 &&
(response[pos - 1] == '-' ||
response[pos - 1] == ' ' ||
response[pos - 1] == '='))
{
if(pos+key_len < res_len)
{
if(response[pos+key_len] == ' ' ||
response[pos+key_len] == '=')
{
return true;
}
else if(pos+key_len+1 < res_len)
{
if(response[pos+key_len] == '\r' &&
response[pos+key_len+1] == '\n')
{
return true;
}
}
}
}
}
}
return false;
}
unsigned char* CharToUnsignedChar(const char *strIn)
{
unsigned char *strOut;
unsigned long length,
i;
length = strlen(strIn);
strOut = new unsigned char[length+1];
if(!strOut) return NULL;
for(i=0; i<length; i++) strOut[i] = (unsigned char) strIn[i];
strOut[length]='\0';
return strOut;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: CSmtp
// DESCRIPTION: Constructor of CSmtp class.
// ARGUMENTS: none
// USES GLOBAL: none
// MODIFIES GL: m_iXPriority, m_iSMTPSrvPort, RecvBuf, SendBuf
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
CSmtp::CSmtp()
{
hSocket = INVALID_SOCKET;
m_bConnected = false;
m_iXPriority = XPRIORITY_NORMAL;
m_iSMTPSrvPort = 0;
m_bAuthenticate = true;
#ifndef LINUX
// Initialize WinSock
WSADATA wsaData;
WORD wVer = MAKEWORD(2,2);
if (WSAStartup(wVer,&wsaData) != NO_ERROR)
throw ECSmtp(ECSmtp::WSA_STARTUP);
if (LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup();
throw ECSmtp(ECSmtp::WSA_VER);
}
#endif
char hostname[255];
if(gethostname((char *) &hostname, 255) == SOCKET_ERROR) throw ECSmtp(ECSmtp::WSA_HOSTNAME);
m_sLocalHostName = hostname;
if((RecvBuf = new char[BUFFER_SIZE]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
if((SendBuf = new char[BUFFER_SIZE]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
m_type = NO_SECURITY;
m_ctx = NULL;
m_ssl = NULL;
m_bHTML = false;
m_bReadReceipt = false;
m_sCharSet = "US-ASCII";
}
////////////////////////////////////////////////////////////////////////////////
// NAME: CSmtp
// DESCRIPTION: Destructor of CSmtp class.
// ARGUMENTS: none
// USES GLOBAL: RecvBuf, SendBuf
// MODIFIES GL: RecvBuf, SendBuf
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
CSmtp::~CSmtp()
{
if(m_bConnected) DisconnectRemoteServer();
if(SendBuf)
{
delete[] SendBuf;
SendBuf = NULL;
}
if(RecvBuf)
{
delete[] RecvBuf;
RecvBuf = NULL;
}
CleanupOpenSSL();
#ifndef LINUX
WSACleanup();
#endif
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddAttachment
// DESCRIPTION: New attachment is added.
// ARGUMENTS: const char *Path - name of attachment added
// USES GLOBAL: Attachments
// MODIFIES GL: Attachments
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddAttachment(const char *Path)
{
assert(Path);
Attachments.insert(Attachments.end(), Path);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddRecipient
// DESCRIPTION: New recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the recipient
// const char *name - name of the recipient
// USES GLOBAL: Recipients
// MODIFIES GL: Recipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
Recipients.insert(Recipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddCCRecipient
// DESCRIPTION: New cc-recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the cc-recipient
// const char *name - name of the ccc-recipient
// USES GLOBAL: CCRecipients
// MODIFIES GL: CCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddCCRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
CCRecipients.insert(CCRecipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddBCCRecipient
// DESCRIPTION: New bcc-recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the bcc-recipient
// const char *name - name of the bccc-recipient
// USES GLOBAL: BCCRecipients
// MODIFIES GL: BCCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddBCCRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
BCCRecipients.insert(BCCRecipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddMsgLine
// DESCRIPTION: Adds new line in a message.
// ARGUMENTS: const char *Text - text of the new line
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddMsgLine(const char* Text)
{
MsgBody.insert(MsgBody.end(), Text);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelMsgLine
// DESCRIPTION: Deletes specified line in text message.. .
// ARGUMENTS: unsigned int Line - line to be delete
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelMsgLine(unsigned int Line)
{
if(Line >= MsgBody.size())
throw ECSmtp(ECSmtp::OUT_OF_MSG_RANGE);
MsgBody.erase(MsgBody.begin()+Line);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelRecipients
// DESCRIPTION: Deletes all recipients. .
// ARGUMENTS: void
// USES GLOBAL: Recipients
// MODIFIES GL: Recipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelRecipients()
{
Recipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelBCCRecipients
// DESCRIPTION: Deletes all BCC recipients. .
// ARGUMENTS: void
// USES GLOBAL: BCCRecipients
// MODIFIES GL: BCCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelBCCRecipients()
{
BCCRecipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelCCRecipients
// DESCRIPTION: Deletes all CC recipients. .
// ARGUMENTS: void
// USES GLOBAL: CCRecipients
// MODIFIES GL: CCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelCCRecipients()
{
CCRecipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelMsgLines
// DESCRIPTION: Deletes message text.
// ARGUMENTS: void
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelMsgLines()
{
MsgBody.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelAttachments
// DESCRIPTION: Deletes all recipients. .
// ARGUMENTS: void
// USES GLOBAL: Attchments
// MODIFIES GL: Attachments
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelAttachments()
{
Attachments.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ModMsgLine
// DESCRIPTION: Modifies a specific line of the message body
// ARGUMENTS: unsigned int Line - the line number to modify
// const char* Text - the new contents of the line
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::ModMsgLine(unsigned int Line,const char* Text)
{
if(Text)
{
if(Line >= MsgBody.size())
throw ECSmtp(ECSmtp::OUT_OF_MSG_RANGE);
MsgBody.at(Line) = std::string(Text);
}
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ClearMessage
// DESCRIPTION: Clears the recipients and message body
// ARGUMENTS: none
// RETURNS: none
// AUTHOR: David Johns
// AUTHOR/DATE: DRJ 2013-05-20
////////////////////////////////////////////////////////////////////////////////
void CSmtp::ClearMessage()
{
DelRecipients();
DelBCCRecipients();
DelCCRecipients();
DelAttachments();
DelMsgLines();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: Send
// DESCRIPTION: Sending the mail. .
// ARGUMENTS: none
// USES GLOBAL: m_sSMTPSrvName, m_iSMTPSrvPort, SendBuf, RecvBuf, m_sLogin,
// m_sPassword, m_sMailFrom, Recipients, CCRecipients,
// BCCRecipients, m_sMsgBody, Attachments,
// MODIFIES GL: SendBuf
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::Send()
{
unsigned int i,rcpt_count,res,FileId;
char *FileBuf = NULL;
FILE* hFile = NULL;
unsigned long int FileSize,TotalSize,MsgPart;
string FileName,EncodedFileName;
string::size_type pos;
// ***** CONNECTING TO SMTP SERVER *****
// connecting to remote host if not already connected:
if(hSocket==INVALID_SOCKET)
{
if(!ConnectRemoteServer(m_sSMTPSrvName.c_str(), m_iSMTPSrvPort, m_type, m_bAuthenticate))
throw ECSmtp(ECSmtp::WSA_INVALID_SOCKET);
}
try{
//Allocate memory
if((FileBuf = new char[55]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
//Check that any attachments specified can be opened
TotalSize = 0;
for(FileId=0;FileId<Attachments.size();FileId++)
{
// opening the file:
hFile = fopen(Attachments[FileId].c_str(), "rb");
if(hFile == NULL)
throw ECSmtp(ECSmtp::FILE_NOT_EXIST);
// checking file size:
fseek(hFile, 0, SEEK_END);
FileSize = ftell(hFile);
TotalSize += FileSize;
// sending the file:
if(TotalSize/1024 > MSG_SIZE_IN_MB*1024)
throw ECSmtp(ECSmtp::MSG_TOO_BIG);
fclose(hFile);
hFile=NULL;
}
// ***** SENDING E-MAIL *****
// MAIL <SP> FROM:<reverse-path> <CRLF>
if(!m_sMailFrom.size())
throw ECSmtp(ECSmtp::UNDEF_MAIL_FROM);
Command_Entry* pEntry = FindCommandEntry(command_MAILFROM);
snprintf(SendBuf, BUFFER_SIZE, "MAIL FROM:<%s>\r\n", m_sMailFrom.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
// RCPT <SP> TO:<forward-path> <CRLF>
if(!(rcpt_count = Recipients.size()))
throw ECSmtp(ECSmtp::UNDEF_RECIPIENTS);
pEntry = FindCommandEntry(command_RCPTTO);
for(i=0;i<Recipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (Recipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
for(i=0;i<CCRecipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (CCRecipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
for(i=0;i<BCCRecipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (BCCRecipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
pEntry = FindCommandEntry(command_DATA);
// DATA <CRLF>
snprintf(SendBuf, BUFFER_SIZE, "DATA\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
pEntry = FindCommandEntry(command_DATABLOCK);
// send header(s)
FormatHeader(SendBuf);
SendData(pEntry);
// send text message
if(GetMsgLines())
{
for(i=0;i<GetMsgLines();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",GetMsgLineText(i));
SendData(pEntry);
}
}
else
{
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n"," ");
SendData(pEntry);
}
// next goes attachments (if they are)
for(FileId=0;FileId<Attachments.size();FileId++)
{
#ifndef LINUX
pos = Attachments[FileId].find_last_of("\\");
#else
pos = Attachments[FileId].find_last_of("/");
#endif
if(pos == string::npos) FileName = Attachments[FileId];
else FileName = Attachments[FileId].substr(pos+1);
//RFC 2047 - Use UTF-8 charset,base64 encode.
EncodedFileName = "=?UTF-8?B?";
EncodedFileName += base64_encode((unsigned char *) FileName.c_str(), FileName.size());
EncodedFileName += "?=";
snprintf(SendBuf, BUFFER_SIZE, "--%s\r\n", BOUNDARY_TEXT);
strcat(SendBuf, "Content-Type: application/x-msdownload; name=\"");
strcat(SendBuf, EncodedFileName.c_str());
strcat(SendBuf, "\"\r\n");
strcat(SendBuf, "Content-Transfer-Encoding: base64\r\n");
strcat(SendBuf, "Content-Disposition: attachment; filename=\"");
strcat(SendBuf, EncodedFileName.c_str());
strcat(SendBuf, "\"\r\n");
strcat(SendBuf, "\r\n");
SendData(pEntry);
// opening the file:
hFile = fopen(Attachments[FileId].c_str(), "rb");
if(hFile == NULL)
throw ECSmtp(ECSmtp::FILE_NOT_EXIST);
// get file size:
fseek(hFile, 0, SEEK_END);
FileSize = ftell(hFile);
fseek (hFile,0,SEEK_SET);
MsgPart = 0;
for(i=0;i<FileSize/54+1;i++)
{
res = fread(FileBuf,sizeof(char),54,hFile);
MsgPart ? strcat(SendBuf,base64_encode(reinterpret_cast<const unsigned char*>(FileBuf),res).c_str())
: strcpy(SendBuf,base64_encode(reinterpret_cast<const unsigned char*>(FileBuf),res).c_str());
strcat(SendBuf,"\r\n");
MsgPart += res + 2;
if(MsgPart >= BUFFER_SIZE/2)
{ // sending part of the message
MsgPart = 0;
SendData(pEntry); // FileBuf, FileName, fclose(hFile);
}
}
if(MsgPart)
{
SendData(pEntry); // FileBuf, FileName, fclose(hFile);
}
fclose(hFile);
hFile=NULL;
}
delete[] FileBuf;
FileBuf=NULL;
// sending last message block (if there is one or more attachments)
if(Attachments.size())
{
snprintf(SendBuf, BUFFER_SIZE, "\r\n--%s--\r\n",BOUNDARY_TEXT);
SendData(pEntry);
}
pEntry = FindCommandEntry(command_DATAEND);
// <CRLF> . <CRLF>
snprintf(SendBuf, BUFFER_SIZE, "\r\n.\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
}
catch(const ECSmtp&)
{
if(hFile) fclose(hFile);
if(FileBuf) delete[] FileBuf;
DisconnectRemoteServer();
throw;
}
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ConnectRemoteServer
// DESCRIPTION: Connecting to the service running on the remote server.
// ARGUMENTS: const char *server - service name
// const unsigned short port - service port
// USES GLOBAL: m_pcSMTPSrvName, m_iSMTPSrvPort, SendBuf, RecvBuf, m_pcLogin,
// m_pcPassword, m_pcMailFrom, Recipients, CCRecipients,
// BCCRecipients, m_pcMsgBody, Attachments,
// MODIFIES GL: m_oError
// RETURNS: socket of the remote service
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
bool CSmtp::ConnectRemoteServer(const char* szServer, const unsigned short nPort_/*=0*/,
SMTP_SECURITY_TYPE securityType/*=DO_NOT_SET*/,
bool authenticate/*=true*/, const char* login/*=NULL*/,
const char* password/*=NULL*/)
{
unsigned short nPort = 0;
LPSERVENT lpServEnt;
SOCKADDR_IN sockAddr;
unsigned long ul = 1;
fd_set fdwrite,fdexcept;
timeval timeout;
int res = 0;
try
{
timeout.tv_sec = TIME_IN_SEC;
timeout.tv_usec = 0;
hSocket = INVALID_SOCKET;
if((hSocket = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET)
throw ECSmtp(ECSmtp::WSA_INVALID_SOCKET);
if(nPort_ != 0)
nPort = htons(nPort_);
else
{
lpServEnt = getservbyname("mail", 0);
if (lpServEnt == NULL)
nPort = htons(25);
else
nPort = lpServEnt->s_port;
}
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = nPort;
if((sockAddr.sin_addr.s_addr = inet_addr(szServer)) == INADDR_NONE)
{
LPHOSTENT host;
host = gethostbyname(szServer);
if (host)
memcpy(&sockAddr.sin_addr,host->h_addr_list[0],host->h_length);
else
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_GETHOSTBY_NAME_ADDR);
}
}
// start non-blocking mode for socket:
#ifdef LINUX
if(ioctl(hSocket,FIONBIO, (unsigned long*)&ul) == SOCKET_ERROR)
#else
if(ioctlsocket(hSocket,FIONBIO, (unsigned long*)&ul) == SOCKET_ERROR)
#endif
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_IOCTLSOCKET);
}
if(connect(hSocket,(LPSOCKADDR)&sockAddr,sizeof(sockAddr)) == SOCKET_ERROR)
{
#ifdef LINUX
if(errno != EINPROGRESS)
#else
if(WSAGetLastError() != WSAEWOULDBLOCK)
#endif
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_CONNECT);
}
}
else
return true;
while(true)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcept);
FD_SET(hSocket,&fdwrite);
FD_SET(hSocket,&fdexcept);
if((res = select(hSocket+1,NULL,&fdwrite,&fdexcept,&timeout)) == SOCKET_ERROR)
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::SELECT_TIMEOUT);
}
if(res && FD_ISSET(hSocket,&fdwrite))
break;
if(res && FD_ISSET(hSocket,&fdexcept))
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_SELECT);
}
} // while
FD_CLR(hSocket,&fdwrite);
FD_CLR(hSocket,&fdexcept);
if(securityType!=DO_NOT_SET) SetSecurityType(securityType);
if(GetSecurityType() == USE_TLS || GetSecurityType() == USE_SSL)
{
InitOpenSSL();
if(GetSecurityType() == USE_SSL)
{
OpenSSLConnect();
}
}
Command_Entry* pEntry = FindCommandEntry(command_INIT);
ReceiveResponse(pEntry);
SayHello();
if(GetSecurityType() == USE_TLS)
{
StartTls();
SayHello();
}
if(authenticate && IsKeywordSupported(RecvBuf, "AUTH") == true)
{
if(login) SetLogin(login);
if(!m_sLogin.size())
throw ECSmtp(ECSmtp::UNDEF_LOGIN);
if(password) SetPassword(password);
if(!m_sPassword.size())
throw ECSmtp(ECSmtp::UNDEF_PASSWORD);
if(IsKeywordSupported(RecvBuf, "LOGIN") == true)
{
pEntry = FindCommandEntry(command_AUTHLOGIN);
snprintf(SendBuf, BUFFER_SIZE, "AUTH LOGIN\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
// send login:
std::string encoded_login = base64_encode(reinterpret_cast<const unsigned char*>(m_sLogin.c_str()),m_sLogin.size());
pEntry = FindCommandEntry(command_USER);
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",encoded_login.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
// send password:
std::string encoded_password = base64_encode(reinterpret_cast<const unsigned char*>(m_sPassword.c_str()),m_sPassword.size());
pEntry = FindCommandEntry(command_PASSWORD);
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",encoded_password.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
else if(IsKeywordSupported(RecvBuf, "PLAIN") == true)
{
pEntry = FindCommandEntry(command_AUTHPLAIN);
snprintf(SendBuf, BUFFER_SIZE, "%s^%s^%s", m_sLogin.c_str(), m_sLogin.c_str(), m_sPassword.c_str());
unsigned int length = strlen(SendBuf);
unsigned char *ustrLogin = CharToUnsignedChar(SendBuf);
for(unsigned int i=0; i<length; i++)
{
if(ustrLogin[i]==94) ustrLogin[i]=0;
}
std::string encoded_login = base64_encode(ustrLogin, length);
delete[] ustrLogin;
snprintf(SendBuf, BUFFER_SIZE, "AUTH PLAIN %s\r\n", encoded_login.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
else if(IsKeywordSupported(RecvBuf, "CRAM-MD5") == true)
{
pEntry = FindCommandEntry(command_AUTHCRAMMD5);
snprintf(SendBuf, BUFFER_SIZE, "AUTH CRAM-MD5\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
std::string encoded_challenge = RecvBuf;
encoded_challenge = encoded_challenge.substr(4);
std::string decoded_challenge = base64_decode(encoded_challenge);
/////////////////////////////////////////////////////////////////////
//test data from RFC 2195
//decoded_challenge = "<[email protected]>";
//m_sLogin = "tim";
//m_sPassword = "tanstaaftanstaaf";
//MD5 should produce b913a602c7eda7a495b4e6e7334d3890
//should encode as dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
/////////////////////////////////////////////////////////////////////
unsigned char *ustrChallenge = CharToUnsignedChar(decoded_challenge.c_str());
unsigned char *ustrPassword = CharToUnsignedChar(m_sPassword.c_str());
if(!ustrChallenge || !ustrPassword)
throw ECSmtp(ECSmtp::BAD_LOGIN_PASSWORD);
// if ustrPassword is longer than 64 bytes reset it to ustrPassword=MD5(ustrPassword)
int passwordLength=m_sPassword.size();
if(passwordLength > 64){
MD5 md5password;
md5password.update(ustrPassword, passwordLength);
md5password.finalize();
ustrPassword = md5password.raw_digest();
passwordLength = 16;
}
//Storing ustrPassword in pads
unsigned char ipad[65], opad[65];
memset(ipad, 0, 64);
memset(opad, 0, 64);
memcpy(ipad, ustrPassword, passwordLength);
memcpy(opad, ustrPassword, passwordLength);
// XOR ustrPassword with ipad and opad values
for(int i=0; i<64; i++){
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
//perform inner MD5
MD5 md5pass1;
md5pass1.update(ipad, 64);
md5pass1.update(ustrChallenge, decoded_challenge.size());
md5pass1.finalize();
unsigned char *ustrResult = md5pass1.raw_digest();
//perform outer MD5
MD5 md5pass2;
md5pass2.update(opad, 64);
md5pass2.update(ustrResult, 16);
md5pass2.finalize();
decoded_challenge = md5pass2.hex_digest();
delete[] ustrChallenge;
delete[] ustrPassword;
delete[] ustrResult;
decoded_challenge = m_sLogin + " " + decoded_challenge;
encoded_challenge = base64_encode(reinterpret_cast<const unsigned char*>(decoded_challenge.c_str()),decoded_challenge.size());
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n", encoded_challenge.c_str());
pEntry = FindCommandEntry(command_PASSWORD);
SendData(pEntry);
ReceiveResponse(pEntry);
}
else if(IsKeywordSupported(RecvBuf, "DIGEST-MD5") == true)
{
pEntry = FindCommandEntry(command_DIGESTMD5);
snprintf(SendBuf, BUFFER_SIZE, "AUTH DIGEST-MD5\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
std::string encoded_challenge = RecvBuf;
encoded_challenge = encoded_challenge.substr(4);
std::string decoded_challenge = base64_decode(encoded_challenge);
/////////////////////////////////////////////////////////////////////
//Test data from RFC 2831
//To test jump into authenticate and read this line and the ones down to next test data section
//decoded_challenge = "realm=\"elwood.innosoft.com\",nonce=\"OA6MG9tEQGm2hh\",qop=\"auth\",algorithm=md5-sess,charset=utf-8";
/////////////////////////////////////////////////////////////////////
//Get the nonce (manditory)
int find = decoded_challenge.find("nonce");
if(find<0)
throw ECSmtp(ECSmtp::BAD_DIGEST_RESPONSE);
std::string nonce = decoded_challenge.substr(find+7);
find = nonce.find("\"");
if(find<0)
throw ECSmtp(ECSmtp::BAD_DIGEST_RESPONSE);
nonce = nonce.substr(0, find);
//Get the realm (optional)
std::string realm;
find = decoded_challenge.find("realm");
if(find>=0){
realm = decoded_challenge.substr(find+7);
find = realm.find("\"");
if(find<0)
throw ECSmtp(ECSmtp::BAD_DIGEST_RESPONSE);
realm = realm.substr(0, find);
}
//Create a cnonce
char cnonce[17], nc[9];
snprintf(cnonce, 17, "%x", (unsigned int) time(NULL));
//Set nonce count
snprintf(nc, 9, "%08d", 1);
//Set QOP
std::string qop = "auth";
//Get server address and set uri
//Skip this step during test
#ifdef __linux__
socklen_t len;
#else
int len;
#endif
struct sockaddr_storage addr;
len = sizeof addr;
if(!getpeername(hSocket, (struct sockaddr*)&addr, &len))
throw ECSmtp(ECSmtp::BAD_SERVER_NAME);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
std::string uri =inet_ntoa(s->sin_addr);
uri = "smtp/" + uri;
/////////////////////////////////////////////////////////////////////
//test data from RFC 2831
//m_sLogin = "chris";
//m_sPassword = "secret";
//snprintf(cnonce, 17, "OA6MHXh6VqTrRk");
//uri = "imap/elwood.innosoft.com";
//Should form the response:
// charset=utf-8,username="chris",
// realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",nc=00000001,
// cnonce="OA6MHXh6VqTrRk",digest-uri="imap/elwood.innosoft.com",
// response=d388dad90d4bbd760a152321f2143af7,qop=auth
//This encodes to:
// Y2hhcnNldD11dGYtOCx1c2VybmFtZT0iY2hyaXMiLHJlYWxtPSJlbHdvb2
// QuaW5ub3NvZnQuY29tIixub25jZT0iT0E2TUc5dEVRR20yaGgiLG5jPTAw
// MDAwMDAxLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLGRpZ2VzdC11cmk9Im
// ltYXAvZWx3b29kLmlubm9zb2Z0LmNvbSIscmVzcG9uc2U9ZDM4OGRhZDkw
// ZDRiYmQ3NjBhMTUyMzIxZjIxNDNhZjcscW9wPWF1dGg=
/////////////////////////////////////////////////////////////////////
//Calculate digest response
unsigned char *ustrRealm = CharToUnsignedChar(realm.c_str());
unsigned char *ustrUsername = CharToUnsignedChar(m_sLogin.c_str());
unsigned char *ustrPassword = CharToUnsignedChar(m_sPassword.c_str());
unsigned char *ustrNonce = CharToUnsignedChar(nonce.c_str());
unsigned char *ustrCNonce = CharToUnsignedChar(cnonce);
unsigned char *ustrUri = CharToUnsignedChar(uri.c_str());
unsigned char *ustrNc = CharToUnsignedChar(nc);
unsigned char *ustrQop = CharToUnsignedChar(qop.c_str());
if(!ustrRealm || !ustrUsername || !ustrPassword || !ustrNonce || !ustrCNonce || !ustrUri || !ustrNc || !ustrQop)
throw ECSmtp(ECSmtp::BAD_LOGIN_PASSWORD);
MD5 md5a1a;
md5a1a.update(ustrUsername, m_sLogin.size());
md5a1a.update((unsigned char*)":", 1);
md5a1a.update(ustrRealm, realm.size());
md5a1a.update((unsigned char*)":", 1);
md5a1a.update(ustrPassword, m_sPassword.size());
md5a1a.finalize();
unsigned char *ua1 = md5a1a.raw_digest();
MD5 md5a1b;
md5a1b.update(ua1, 16);
md5a1b.update((unsigned char*)":", 1);
md5a1b.update(ustrNonce, nonce.size());
md5a1b.update((unsigned char*)":", 1);
md5a1b.update(ustrCNonce, strlen(cnonce));
//authzid could be added here
md5a1b.finalize();
char *a1 = md5a1b.hex_digest();
MD5 md5a2;
md5a2.update((unsigned char*) "AUTHENTICATE:", 13);
md5a2.update(ustrUri, uri.size());
//authint and authconf add an additional line here
md5a2.finalize();
char *a2 = md5a2.hex_digest();
delete[] ua1;
ua1 = CharToUnsignedChar(a1);
unsigned char *ua2 = CharToUnsignedChar(a2);
//compute KD
MD5 md5;
md5.update(ua1, 32);
md5.update((unsigned char*)":", 1);
md5.update(ustrNonce, nonce.size());
md5.update((unsigned char*)":", 1);
md5.update(ustrNc, strlen(nc));
md5.update((unsigned char*)":", 1);
md5.update(ustrCNonce, strlen(cnonce));
md5.update((unsigned char*)":", 1);
md5.update(ustrQop, qop.size());
md5.update((unsigned char*)":", 1);
md5.update(ua2, 32);
md5.finalize();
decoded_challenge = md5.hex_digest();
delete[] ustrRealm;
delete[] ustrUsername;
delete[] ustrPassword;
delete[] ustrNonce;
delete[] ustrCNonce;
delete[] ustrUri;
delete[] ustrNc;
delete[] ustrQop;
delete[] ua1;
delete[] ua2;
delete[] a1;
delete[] a2;
//send the response
if(strstr(RecvBuf, "charset")>=0) snprintf(SendBuf, BUFFER_SIZE, "charset=utf-8,username=\"%s\"", m_sLogin.c_str());
else snprintf(SendBuf, BUFFER_SIZE, "username=\"%s\"", m_sLogin.c_str());
if(!realm.empty()){
snprintf(RecvBuf, BUFFER_SIZE, ",realm=\"%s\"", realm.c_str());
strcat(SendBuf, RecvBuf);
}
snprintf(RecvBuf, BUFFER_SIZE, ",nonce=\"%s\"", nonce.c_str());
strcat(SendBuf, RecvBuf);
snprintf(RecvBuf, BUFFER_SIZE, ",nc=%s", nc);
strcat(SendBuf, RecvBuf);
snprintf(RecvBuf, BUFFER_SIZE, ",cnonce=\"%s\"", cnonce);
strcat(SendBuf, RecvBuf);
snprintf(RecvBuf, BUFFER_SIZE, ",digest-uri=\"%s\"", uri.c_str());
strcat(SendBuf, RecvBuf);
snprintf(RecvBuf, BUFFER_SIZE, ",response=%s", decoded_challenge.c_str());
strcat(SendBuf, RecvBuf);
snprintf(RecvBuf, BUFFER_SIZE, ",qop=%s", qop.c_str());
strcat(SendBuf, RecvBuf);
unsigned char *ustrDigest = CharToUnsignedChar(SendBuf);
encoded_challenge = base64_encode(ustrDigest, strlen(SendBuf));
delete[] ustrDigest;
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n", encoded_challenge.c_str());
pEntry = FindCommandEntry(command_DIGESTMD5);
SendData(pEntry);
ReceiveResponse(pEntry);
//Send completion carraige return
snprintf(SendBuf, BUFFER_SIZE, "\r\n");
pEntry = FindCommandEntry(command_PASSWORD);
SendData(pEntry);
ReceiveResponse(pEntry);
}
else throw ECSmtp(ECSmtp::LOGIN_NOT_SUPPORTED);
}
}
catch(const ECSmtp&)
{
if(RecvBuf[0]=='5' && RecvBuf[1]=='3' && RecvBuf[2]=='0')
m_bConnected=false;
DisconnectRemoteServer();
throw;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DisconnectRemoteServer
// DESCRIPTION: Disconnects from the SMTP server and closes the socket
// ARGUMENTS: none
// USES GLOBAL: none
// MODIFIES GL: none
// RETURNS: void
// AUTHOR: David Johns
// AUTHOR/DATE: DRJ 2010-08-14
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DisconnectRemoteServer()
{
if(m_bConnected) SayQuit();
if(hSocket)
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
}
hSocket = INVALID_SOCKET;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SmtpXYZdigits
// DESCRIPTION: Converts three letters from RecvBuf to the number.
// ARGUMENTS: none
// USES GLOBAL: RecvBuf
// MODIFIES GL: none
// RETURNS: integer number
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
int CSmtp::SmtpXYZdigits()
{
assert(RecvBuf);
if(RecvBuf == NULL)
return 0;
return (RecvBuf[0]-'0')*100 + (RecvBuf[1]-'0')*10 + RecvBuf[2]-'0';
}
////////////////////////////////////////////////////////////////////////////////
// NAME: FormatHeader
// DESCRIPTION: Prepares a header of the message.
// ARGUMENTS: char* header - formated header string
// USES GLOBAL: Recipients, CCRecipients, BCCRecipients
// MODIFIES GL: none
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::FormatHeader(char* header)
{
char month[][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
size_t i;
std::string to;
std::string cc;
std::string bcc;
time_t rawtime;
struct tm* timeinfo;
// date/time check
if(time(&rawtime) > 0)
timeinfo = localtime(&rawtime);
else
throw ECSmtp(ECSmtp::TIME_ERROR);
// check for at least one recipient
if(Recipients.size())
{
for (i=0;i<Recipients.size();i++)
{
if(i > 0)
to.append(",");
to += Recipients[i].Name;
to.append("<");
to += Recipients[i].Mail;
to.append(">");
}
}
else
throw ECSmtp(ECSmtp::UNDEF_RECIPIENTS);
if(CCRecipients.size())
{
for (i=0;i<CCRecipients.size();i++)
{
if(i > 0)
cc. append(",");
cc += CCRecipients[i].Name;
cc.append("<");
cc += CCRecipients[i].Mail;
cc.append(">");
}
}
// Date: <SP> <dd> <SP> <mon> <SP> <yy> <SP> <hh> ":" <mm> ":" <ss> <SP> <zone> <CRLF>
snprintf(header, BUFFER_SIZE, "Date: %d %s %d %d:%d:%d\r\n", timeinfo->tm_mday,
month[timeinfo->tm_mon], timeinfo->tm_year+1900, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec);
// From: <SP> <sender> <SP> "<" <sender-email> ">" <CRLF>
if(!m_sMailFrom.size()) throw ECSmtp(ECSmtp::UNDEF_MAIL_FROM);
strcat(header,"From: ");
if(m_sNameFrom.size()) strcat(header, m_sNameFrom.c_str());
strcat(header," <");
strcat(header,m_sMailFrom.c_str());
strcat(header, ">\r\n");
// X-Mailer: <SP> <xmailer-app> <CRLF>
if(m_sXMailer.size())
{
strcat(header,"X-Mailer: ");
strcat(header, m_sXMailer.c_str());
strcat(header, "\r\n");
}
// Reply-To: <SP> <reverse-path> <CRLF>
if(m_sReplyTo.size())
{
strcat(header, "Reply-To: ");
strcat(header, m_sReplyTo.c_str());
strcat(header, "\r\n");
}
// Disposition-Notification-To: <SP> <reverse-path or sender-email> <CRLF>
if(m_bReadReceipt)
{
strcat(header, "Disposition-Notification-To: ");
if(m_sReplyTo.size()) strcat(header, m_sReplyTo.c_str());
else strcat(header, m_sNameFrom.c_str());
strcat(header, "\r\n");
}
// X-Priority: <SP> <number> <CRLF>
switch(m_iXPriority)
{
case XPRIORITY_HIGH:
strcat(header,"X-Priority: 2 (High)\r\n");
break;
case XPRIORITY_NORMAL:
strcat(header,"X-Priority: 3 (Normal)\r\n");
break;
case XPRIORITY_LOW:
strcat(header,"X-Priority: 4 (Low)\r\n");
break;
default:
strcat(header,"X-Priority: 3 (Normal)\r\n");
}
// To: <SP> <remote-user-mail> <CRLF>
strcat(header,"To: ");
strcat(header, to.c_str());
strcat(header, "\r\n");
// Cc: <SP> <remote-user-mail> <CRLF>
if(CCRecipients.size())
{
strcat(header,"Cc: ");
strcat(header, cc.c_str());
strcat(header, "\r\n");
}
if(BCCRecipients.size())
{
strcat(header,"Bcc: ");
strcat(header, bcc.c_str());
strcat(header, "\r\n");
}
// Subject: <SP> <subject-text> <CRLF>
if(!m_sSubject.size())
strcat(header, "Subject: ");
else
{
strcat(header, "Subject: ");
strcat(header, m_sSubject.c_str());
}
strcat(header, "\r\n");
// MIME-Version: <SP> 1.0 <CRLF>
strcat(header,"MIME-Version: 1.0\r\n");
if(!Attachments.size())
{ // no attachments
if(m_bHTML) strcat(header, "Content-Type: text/html; charset=\"");
else strcat(header, "Content-type: text/plain; charset=\"");
strcat(header, m_sCharSet.c_str());
strcat(header, "\"\r\n");
strcat(header,"Content-Transfer-Encoding: 7bit\r\n");
strcat(SendBuf,"\r\n");
}
else
{ // there is one or more attachments
strcat(header,"Content-Type: multipart/mixed; boundary=\"");
strcat(header,BOUNDARY_TEXT);
strcat(header,"\"\r\n");
strcat(header,"\r\n");
// first goes text message
strcat(SendBuf,"--");
strcat(SendBuf,BOUNDARY_TEXT);
strcat(SendBuf,"\r\n");
if(m_bHTML) strcat(SendBuf,"Content-type: text/html; charset=");
else strcat(SendBuf,"Content-type: text/plain; charset=");
strcat(header, m_sCharSet.c_str());
strcat(header, "\r\n");
strcat(SendBuf,"Content-Transfer-Encoding: 7bit\r\n");
strcat(SendBuf,"\r\n");
}
// done
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ReceiveData
// DESCRIPTION: Receives a row terminated '\n'.
// ARGUMENTS: none
// USES GLOBAL: RecvBuf
// MODIFIES GL: RecvBuf
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// MODIFICATION: Receives data as much as possible. Another function ReceiveResponse
// will ensure the received data contains '\n'
// AUTHOR/DATE: John Tang 2010-08-01
////////////////////////////////////////////////////////////////////////////////
void CSmtp::ReceiveData(Command_Entry* pEntry)
{
if(m_ssl != NULL)
{
ReceiveData_SSL(m_ssl, pEntry);
return;
}
int res = 0;
fd_set fdread;
timeval time;
time.tv_sec = pEntry->recv_timeout;
time.tv_usec = 0;
assert(RecvBuf);
if(RecvBuf == NULL)
throw ECSmtp(ECSmtp::RECVBUF_IS_EMPTY);
FD_ZERO(&fdread);
FD_SET(hSocket,&fdread);
if((res = select(hSocket+1, &fdread, NULL, NULL, &time)) == SOCKET_ERROR)
{
FD_CLR(hSocket,&fdread);
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
//timeout
FD_CLR(hSocket,&fdread);
throw ECSmtp(ECSmtp::SERVER_NOT_RESPONDING);
}
if(FD_ISSET(hSocket,&fdread))
{
res = recv(hSocket,RecvBuf,BUFFER_SIZE,0);
if(res == SOCKET_ERROR)
{
FD_CLR(hSocket,&fdread);
throw ECSmtp(ECSmtp::WSA_RECV);
}
}
FD_CLR(hSocket,&fdread);
RecvBuf[res] = 0;
if(res == 0)
{
throw ECSmtp(ECSmtp::CONNECTION_CLOSED);
}
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SendData
// DESCRIPTION: Sends data from SendBuf buffer.
// ARGUMENTS: none
// USES GLOBAL: SendBuf
// MODIFIES GL: none
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SendData(Command_Entry* pEntry)
{
if(m_ssl != NULL)
{
SendData_SSL(m_ssl, pEntry);
return;
}
int idx = 0,res,nLeft = strlen(SendBuf);
fd_set fdwrite;
timeval time;
time.tv_sec = pEntry->send_timeout;
time.tv_usec = 0;
assert(SendBuf);
if(SendBuf == NULL)
throw ECSmtp(ECSmtp::SENDBUF_IS_EMPTY);
while(nLeft > 0)
{
FD_ZERO(&fdwrite);
FD_SET(hSocket,&fdwrite);
if((res = select(hSocket+1,NULL,&fdwrite,NULL,&time)) == SOCKET_ERROR)
{
FD_CLR(hSocket,&fdwrite);
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
//timeout
FD_CLR(hSocket,&fdwrite);
throw ECSmtp(ECSmtp::SERVER_NOT_RESPONDING);
}
if(res && FD_ISSET(hSocket,&fdwrite))
{
res = send(hSocket,&SendBuf[idx],nLeft,0);
if(res == SOCKET_ERROR || res == 0)
{
FD_CLR(hSocket,&fdwrite);
throw ECSmtp(ECSmtp::WSA_SEND);
}
nLeft -= res;
idx += res;
}
}
OutputDebugStringA(SendBuf);
FD_CLR(hSocket,&fdwrite);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetLocalHostName
// DESCRIPTION: Returns local host name.
// ARGUMENTS: none
// USES GLOBAL: m_pcLocalHostName
// MODIFIES GL: m_oError, m_pcLocalHostName
// RETURNS: socket of the remote service
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetLocalHostName()
{
return m_sLocalHostName.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetRecipientCount
// DESCRIPTION: Returns the number of recipents.
// ARGUMENTS: none
// USES GLOBAL: Recipients
// MODIFIES GL: none
// RETURNS: number of recipents
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
unsigned int CSmtp::GetRecipientCount() const
{
return Recipients.size();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetBCCRecipientCount
// DESCRIPTION: Returns the number of bcc-recipents.
// ARGUMENTS: none
// USES GLOBAL: BCCRecipients
// MODIFIES GL: none
// RETURNS: number of bcc-recipents
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
unsigned int CSmtp::GetBCCRecipientCount() const
{
return BCCRecipients.size();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetCCRecipientCount
// DESCRIPTION: Returns the number of cc-recipents.
// ARGUMENTS: none
// USES GLOBAL: CCRecipients
// MODIFIES GL: none
// RETURNS: number of cc-recipents
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
unsigned int CSmtp::GetCCRecipientCount() const
{
return CCRecipients.size();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetReplyTo
// DESCRIPTION: Returns m_pcReplyTo string.
// ARGUMENTS: none
// USES GLOBAL: m_sReplyTo
// MODIFIES GL: none
// RETURNS: m_sReplyTo string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetReplyTo() const
{
return m_sReplyTo.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetMailFrom
// DESCRIPTION: Returns m_pcMailFrom string.
// ARGUMENTS: none
// USES GLOBAL: m_sMailFrom
// MODIFIES GL: none
// RETURNS: m_sMailFrom string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetMailFrom() const
{
return m_sMailFrom.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetSenderName
// DESCRIPTION: Returns m_pcNameFrom string.
// ARGUMENTS: none
// USES GLOBAL: m_sNameFrom
// MODIFIES GL: none
// RETURNS: m_sNameFrom string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetSenderName() const
{
return m_sNameFrom.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetSubject
// DESCRIPTION: Returns m_pcSubject string.
// ARGUMENTS: none
// USES GLOBAL: m_sSubject
// MODIFIES GL: none
// RETURNS: m_sSubject string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetSubject() const
{
return m_sSubject.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetXMailer
// DESCRIPTION: Returns m_pcXMailer string.
// ARGUMENTS: none
// USES GLOBAL: m_pcXMailer
// MODIFIES GL: none
// RETURNS: m_pcXMailer string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
const char* CSmtp::GetXMailer() const
{
return m_sXMailer.c_str();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetXPriority
// DESCRIPTION: Returns m_iXPriority string.
// ARGUMENTS: none
// USES GLOBAL: m_iXPriority
// MODIFIES GL: none
// RETURNS: CSmptXPriority m_pcXMailer
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
CSmptXPriority CSmtp::GetXPriority() const
{
return m_iXPriority;
}
const char* CSmtp::GetMsgLineText(unsigned int Line) const
{
if(Line >= MsgBody.size())
throw ECSmtp(ECSmtp::OUT_OF_MSG_RANGE);
return MsgBody.at(Line).c_str();
}
unsigned int CSmtp::GetMsgLines() const
{
return MsgBody.size();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetCharSet
// DESCRIPTION: Allows the character set to be changed from default of US-ASCII.
// ARGUMENTS: const char *sCharSet
// USES GLOBAL: m_sCharSet
// MODIFIES GL: m_sCharSet
// RETURNS: none
// AUTHOR: David Johns
// AUTHOR/DATE: DJ 2012-11-03
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetCharSet(const char *sCharSet)
{
m_sCharSet = sCharSet;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetLocalHostName
// DESCRIPTION: Allows the local host name to be set externally.
// ARGUMENTS: const char *sLocalHostName
// USES GLOBAL: m_sLocalHostName
// MODIFIES GL: m_sLocalHostName
// RETURNS: none
// AUTHOR: jerko
// AUTHOR/DATE: J 2011-12-01
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetLocalHostName(const char *sLocalHostName)
{
m_sLocalHostName = sLocalHostName;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetXPriority
// DESCRIPTION: Setting priority of the message.
// ARGUMENTS: CSmptXPriority priority - priority of the message ( XPRIORITY_HIGH,
// XPRIORITY_NORMAL, XPRIORITY_LOW)
// USES GLOBAL: none
// MODIFIES GL: m_iXPriority
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetXPriority(CSmptXPriority priority)
{
m_iXPriority = priority;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetReplyTo
// DESCRIPTION: Setting the return address.
// ARGUMENTS: const char *ReplyTo - return address
// USES GLOBAL: m_sReplyTo
// MODIFIES GL: m_sReplyTo
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetReplyTo(const char *ReplyTo)
{
m_sReplyTo = ReplyTo;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetReadReceipt
// DESCRIPTION: Setting whether to request a read receipt.
// ARGUMENTS: bool requestReceipt - whether or not to request a read receipt
// USES GLOBAL: m_bReadReceipt
// MODIFIES GL: m_bReadReceipt
// RETURNS: none
// AUTHOR: David Johns
// AUTHOR/DATE: DRJ 2012-11-03
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetReadReceipt(bool requestReceipt/*=true*/)
{
m_bReadReceipt = requestReceipt;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetSenderMail
// DESCRIPTION: Setting sender's mail.
// ARGUMENTS: const char *EMail - sender's e-mail
// USES GLOBAL: m_sMailFrom
// MODIFIES GL: m_sMailFrom
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetSenderMail(const char *EMail)
{
m_sMailFrom = EMail;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetSenderName
// DESCRIPTION: Setting sender's name.
// ARGUMENTS: const char *Name - sender's name
// USES GLOBAL: m_sNameFrom
// MODIFIES GL: m_sNameFrom
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetSenderName(const char *Name)
{
m_sNameFrom = Name;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetSubject
// DESCRIPTION: Setting subject of the message.
// ARGUMENTS: const char *Subject - subject of the message
// USES GLOBAL: m_sSubject
// MODIFIES GL: m_sSubject
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetSubject(const char *Subject)
{
m_sSubject = Subject;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetSubject
// DESCRIPTION: Setting the name of program which is sending the mail.
// ARGUMENTS: const char *XMailer - programe name
// USES GLOBAL: m_sXMailer
// MODIFIES GL: m_sXMailer
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetXMailer(const char *XMailer)
{
m_sXMailer = XMailer;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetLogin
// DESCRIPTION: Setting the login of SMTP account's owner.
// ARGUMENTS: const char *Login - login of SMTP account's owner
// USES GLOBAL: m_sLogin
// MODIFIES GL: m_sLogin
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetLogin(const char *Login)
{
m_sLogin = Login;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetPassword
// DESCRIPTION: Setting the password of SMTP account's owner.
// ARGUMENTS: const char *Password - password of SMTP account's owner
// USES GLOBAL: m_sPassword
// MODIFIES GL: m_sPassword
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetPassword(const char *Password)
{
m_sPassword = Password;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: SetSMTPServer
// DESCRIPTION: Setting the SMTP service name and port.
// ARGUMENTS: const char* SrvName - SMTP service name
// const unsigned short SrvPort - SMTO service port
// USES GLOBAL: m_sSMTPSrvName
// MODIFIES GL: m_sSMTPSrvName
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JO 2010-0708
////////////////////////////////////////////////////////////////////////////////
void CSmtp::SetSMTPServer(const char* SrvName, const unsigned short SrvPort, bool authenticate)
{
m_iSMTPSrvPort = SrvPort;
m_sSMTPSrvName = SrvName;
m_bAuthenticate = authenticate;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: GetErrorText (friend function)
// DESCRIPTION: Returns the string for specified error code.
// ARGUMENTS: CSmtpError ErrorId - error code
// USES GLOBAL: none
// MODIFIES GL: none
// RETURNS: error string
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
std::string ECSmtp::GetErrorText() const
{
switch(ErrorCode)
{
case ECSmtp::CSMTP_NO_ERROR:
return "";
case ECSmtp::WSA_STARTUP:
return "Unable to initialise winsock2";
case ECSmtp::WSA_VER:
return "Wrong version of the winsock2";
case ECSmtp::WSA_SEND:
return "Function send() failed";
case ECSmtp::WSA_RECV:
return "Function recv() failed";
case ECSmtp::WSA_CONNECT:
return "Function connect failed";
case ECSmtp::WSA_GETHOSTBY_NAME_ADDR:
return "Unable to determine remote server";
case ECSmtp::WSA_INVALID_SOCKET:
return "Invalid winsock2 socket";
case ECSmtp::WSA_HOSTNAME:
return "Function hostname() failed";
case ECSmtp::WSA_IOCTLSOCKET:
return "Function ioctlsocket() failed";
case ECSmtp::BAD_IPV4_ADDR:
return "Improper IPv4 address";
case ECSmtp::UNDEF_MSG_HEADER:
return "Undefined message header";
case ECSmtp::UNDEF_MAIL_FROM:
return "Undefined mail sender";
case ECSmtp::UNDEF_SUBJECT:
return "Undefined message subject";
case ECSmtp::UNDEF_RECIPIENTS:
return "Undefined at least one reciepent";
case ECSmtp::UNDEF_RECIPIENT_MAIL:
return "Undefined recipent mail";
case ECSmtp::UNDEF_LOGIN:
return "Undefined user login";
case ECSmtp::UNDEF_PASSWORD:
return "Undefined user password";
case ECSmtp::BAD_LOGIN_PASSWORD:
return "Invalid user login or password";
case ECSmtp::BAD_DIGEST_RESPONSE:
return "Server returned a bad digest MD5 response";
case ECSmtp::BAD_SERVER_NAME:
return "Unable to determine server name for digest MD5 response";
case ECSmtp::COMMAND_MAIL_FROM:
return "Server returned error after sending MAIL FROM";
case ECSmtp::COMMAND_EHLO:
return "Server returned error after sending EHLO";
case ECSmtp::COMMAND_AUTH_PLAIN:
return "Server returned error after sending AUTH PLAIN";
case ECSmtp::COMMAND_AUTH_LOGIN:
return "Server returned error after sending AUTH LOGIN";
case ECSmtp::COMMAND_AUTH_CRAMMD5:
return "Server returned error after sending AUTH CRAM-MD5";
case ECSmtp::COMMAND_AUTH_DIGESTMD5:
return "Server returned error after sending AUTH DIGEST-MD5";
case ECSmtp::COMMAND_DIGESTMD5:
return "Server returned error after sending MD5 DIGEST";
case ECSmtp::COMMAND_DATA:
return "Server returned error after sending DATA";
case ECSmtp::COMMAND_QUIT:
return "Server returned error after sending QUIT";
case ECSmtp::COMMAND_RCPT_TO:
return "Server returned error after sending RCPT TO";
case ECSmtp::MSG_BODY_ERROR:
return "Error in message body";
case ECSmtp::CONNECTION_CLOSED:
return "Server has closed the connection";
case ECSmtp::SERVER_NOT_READY:
return "Server is not ready";
case ECSmtp::SERVER_NOT_RESPONDING:
return "Server not responding";
case ECSmtp::FILE_NOT_EXIST:
return "Attachment file does not exist";
case ECSmtp::MSG_TOO_BIG:
return "Message is too big";
case ECSmtp::BAD_LOGIN_PASS:
return "Bad login or password";
case ECSmtp::UNDEF_XYZ_RESPONSE:
return "Undefined xyz SMTP response";
case ECSmtp::LACK_OF_MEMORY:
return "Lack of memory";
case ECSmtp::TIME_ERROR:
return "time() error";
case ECSmtp::RECVBUF_IS_EMPTY:
return "RecvBuf is empty";
case ECSmtp::SENDBUF_IS_EMPTY:
return "SendBuf is empty";
case ECSmtp::OUT_OF_MSG_RANGE:
return "Specified line number is out of message size";
case ECSmtp::COMMAND_EHLO_STARTTLS:
return "Server returned error after sending STARTTLS";
case ECSmtp::SSL_PROBLEM:
return "SSL problem";
case ECSmtp::COMMAND_DATABLOCK:
return "Failed to send data block";
case ECSmtp::STARTTLS_NOT_SUPPORTED:
return "The STARTTLS command is not supported by the server";
case ECSmtp::LOGIN_NOT_SUPPORTED:
return "AUTH LOGIN is not supported by the server";
default:
return "Undefined error id";
}
}
void CSmtp::SayHello()
{
Command_Entry* pEntry = FindCommandEntry(command_EHLO);
snprintf(SendBuf, BUFFER_SIZE, "EHLO %s\r\n", GetLocalHostName()!=NULL ? m_sLocalHostName.c_str() : "domain");
SendData(pEntry);
ReceiveResponse(pEntry);
m_bConnected=true;
}
void CSmtp::SayQuit()
{
// ***** CLOSING CONNECTION *****
Command_Entry* pEntry = FindCommandEntry(command_QUIT);
// QUIT <CRLF>
snprintf(SendBuf, BUFFER_SIZE, "QUIT\r\n");
m_bConnected=false;
SendData(pEntry);
ReceiveResponse(pEntry);
}
void CSmtp::StartTls()
{
if(IsKeywordSupported(RecvBuf, "STARTTLS") == false)
{
throw ECSmtp(ECSmtp::STARTTLS_NOT_SUPPORTED);
}
Command_Entry* pEntry = FindCommandEntry(command_STARTTLS);
snprintf(SendBuf, BUFFER_SIZE, "STARTTLS\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
OpenSSLConnect();
}
void CSmtp::ReceiveData_SSL(SSL* ssl, Command_Entry* pEntry)
{
int res = 0;
int offset = 0;
fd_set fdread;
fd_set fdwrite;
timeval time;
int read_blocked_on_write = 0;
time.tv_sec = pEntry->recv_timeout;
time.tv_usec = 0;
assert(RecvBuf);
if(RecvBuf == NULL)
throw ECSmtp(ECSmtp::RECVBUF_IS_EMPTY);
bool bFinish = false;
while(!bFinish)
{
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_SET(hSocket,&fdread);
if(read_blocked_on_write)
{
FD_SET(hSocket, &fdwrite);
}
if((res = select(hSocket+1, &fdread, &fdwrite, NULL, &time)) == SOCKET_ERROR)
{
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
//timeout
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
throw ECSmtp(ECSmtp::SERVER_NOT_RESPONDING);
}
if(FD_ISSET(hSocket,&fdread) || (read_blocked_on_write && FD_ISSET(hSocket,&fdwrite)) )
{
while(1)
{
read_blocked_on_write=0;
const int buff_len = 1024;
char buff[buff_len];
res = SSL_read(ssl, buff, buff_len);
int ssl_err = SSL_get_error(ssl, res);
if(ssl_err == SSL_ERROR_NONE)
{
if(offset + res > BUFFER_SIZE - 1)
{
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
}
memcpy(RecvBuf + offset, buff, res);
offset += res;
if(SSL_pending(ssl))
{
continue;
}
else
{
bFinish = true;
break;
}
}
else if(ssl_err == SSL_ERROR_ZERO_RETURN)
{
bFinish = true;
break;
}
else if(ssl_err == SSL_ERROR_WANT_READ)
{
break;
}
else if(ssl_err == SSL_ERROR_WANT_WRITE)
{
/* We get a WANT_WRITE if we're
trying to rehandshake and we block on
a write during that rehandshake.
We need to wait on the socket to be
writeable but reinitiate the read
when it is */
read_blocked_on_write=1;
break;
}
else
{
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
throw ECSmtp(ECSmtp::SSL_PROBLEM);
}
}
}
}
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
RecvBuf[offset] = 0;
if(offset == 0)
{
throw ECSmtp(ECSmtp::CONNECTION_CLOSED);
}
}
void CSmtp::ReceiveResponse(Command_Entry* pEntry)
{
std::string line;
int reply_code = 0;
bool bFinish = false;
while(!bFinish)
{
ReceiveData(pEntry);
line.append(RecvBuf);
size_t len = line.length();
size_t begin = 0;
size_t offset = 0;
while(1) // loop for all lines
{
while(offset + 1 < len)
{
if(line[offset] == '\r' && line[offset+1] == '\n')
break;
++offset;
}
if(offset + 1 < len) // we found a line
{
// see if this is the last line
// the last line must match the pattern: XYZ<SP>*<CRLF> or XYZ<CRLF> where XYZ is a string of 3 digits
offset += 2; // skip <CRLF>
if(offset - begin >= 5)
{
if(isdigit(line[begin]) && isdigit(line[begin+1]) && isdigit(line[begin+2]))
{
// this is the last line
if(offset - begin == 5 || line[begin+3] == ' ')
{
reply_code = (line[begin]-'0')*100 + (line[begin+1]-'0')*10 + line[begin+2]-'0';
bFinish = true;
break;
}
}
}
begin = offset; // try to find next line
}
else // we haven't received the last line, so we need to receive more data
{
break;
}
}
}
//snprintf(RecvBuf, BUFFER_SIZE, line.c_str());
OutputDebugStringA(RecvBuf);
if(reply_code != pEntry->valid_reply_code)
{
throw ECSmtp(pEntry->error);
}
}
void CSmtp::SendData_SSL(SSL* ssl, Command_Entry* pEntry)
{
int offset = 0,res,nLeft = strlen(SendBuf);
fd_set fdwrite;
fd_set fdread;
timeval time;
int write_blocked_on_read = 0;
time.tv_sec = pEntry->send_timeout;
time.tv_usec = 0;
assert(SendBuf);
if(SendBuf == NULL)
throw ECSmtp(ECSmtp::SENDBUF_IS_EMPTY);
while(nLeft > 0)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
FD_SET(hSocket,&fdwrite);
if(write_blocked_on_read)
{
FD_SET(hSocket, &fdread);
}
if((res = select(hSocket+1,&fdread,&fdwrite,NULL,&time)) == SOCKET_ERROR)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
//timeout
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
throw ECSmtp(ECSmtp::SERVER_NOT_RESPONDING);
}
if(FD_ISSET(hSocket,&fdwrite) || (write_blocked_on_read && FD_ISSET(hSocket, &fdread)) )
{
write_blocked_on_read=0;
/* Try to write */
res = SSL_write(ssl, SendBuf+offset, nLeft);
switch(SSL_get_error(ssl,res))
{
/* We wrote something*/
case SSL_ERROR_NONE:
nLeft -= res;
offset += res;
break;
/* We would have blocked */
case SSL_ERROR_WANT_WRITE:
break;
/* We get a WANT_READ if we're
trying to rehandshake and we block on
write during the current connection.
We need to wait on the socket to be readable
but reinitiate our write when it is */
case SSL_ERROR_WANT_READ:
write_blocked_on_read=1;
break;
/* Some other error */
default:
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
throw ECSmtp(ECSmtp::SSL_PROBLEM);
}
}
}
OutputDebugStringA(SendBuf);
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
}
void CSmtp::InitOpenSSL()
{
SSL_library_init();
SSL_load_error_strings();
m_ctx = SSL_CTX_new (SSLv23_client_method());
if(m_ctx == NULL)
throw ECSmtp(ECSmtp::SSL_PROBLEM);
}
void CSmtp::OpenSSLConnect()
{
if(m_ctx == NULL)
throw ECSmtp(ECSmtp::SSL_PROBLEM);
m_ssl = SSL_new (m_ctx);
if(m_ssl == NULL)
throw ECSmtp(ECSmtp::SSL_PROBLEM);
SSL_set_fd (m_ssl, (int)hSocket);
SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
int res = 0;
fd_set fdwrite;
fd_set fdread;
int write_blocked = 0;
int read_blocked = 0;
timeval time;
time.tv_sec = TIME_IN_SEC;
time.tv_usec = 0;
while(1)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
if(write_blocked)
FD_SET(hSocket, &fdwrite);
if(read_blocked)
FD_SET(hSocket, &fdread);
if(write_blocked || read_blocked)
{
write_blocked = 0;
read_blocked = 0;
if((res = select(hSocket+1,&fdread,&fdwrite,NULL,&time)) == SOCKET_ERROR)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
//timeout
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
throw ECSmtp(ECSmtp::SERVER_NOT_RESPONDING);
}
}
res = SSL_connect(m_ssl);
switch(SSL_get_error(m_ssl, res))
{
case SSL_ERROR_NONE:
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
return;
break;
case SSL_ERROR_WANT_WRITE:
write_blocked = 1;
break;
case SSL_ERROR_WANT_READ:
read_blocked = 1;
break;
default:
FD_ZERO(&fdwrite);
FD_ZERO(&fdread);
throw ECSmtp(ECSmtp::SSL_PROBLEM);
}
}
}
void CSmtp::CleanupOpenSSL()
{
if(m_ssl != NULL)
{
SSL_shutdown (m_ssl); /* send SSL/TLS close_notify */
SSL_free (m_ssl);
m_ssl = NULL;
}
if(m_ctx != NULL)
{
SSL_CTX_free (m_ctx);
m_ctx = NULL;
ERR_remove_state(0);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
}
}
| [
"[email protected]"
] | |
fdc605b750fa9c89f3e353a8b6a5c7a8a53f599e | b62e7086980cb97554b01dbfad64a040f9f80165 | /NtupleMacros/OSSusy2011/Configuration/CMS2.cc | dcac90da0a31e3942696deb82ab0f0d2fe7d4ee4 | [] | no_license | tastest/CMS2 | f819962e172c712abd82a8b213c4cb2286bcdcfe | e31e02d6037fbef206e216413b4def558ccefb39 | refs/heads/master | 2021-01-10T20:22:52.181267 | 2013-07-12T15:16:31 | 2013-07-12T15:16:31 | 10,772,930 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 75,771 | cc | #include "CMS2.h"
CMS2 cms2;
namespace tas {
TString &evt_CMS2tag() { return cms2.evt_CMS2tag(); }
TString &evt_dataset() { return cms2.evt_dataset(); }
vector<TString> &hlt_trigNames() { return cms2.hlt_trigNames(); }
vector<TString> &l1_techtrigNames() { return cms2.l1_techtrigNames(); }
vector<TString> &l1_trigNames() { return cms2.l1_trigNames(); }
vector<TString> &evt_errCategory() { return cms2.evt_errCategory(); }
vector<TString> &evt_errModule() { return cms2.evt_errModule(); }
vector<TString> &evt_errSeverity() { return cms2.evt_errSeverity(); }
bool &evt_eventHasHalo() { return cms2.evt_eventHasHalo(); }
bool &evt_hbheFilter() { return cms2.evt_hbheFilter(); }
vector<bool> &mus_tightMatch() { return cms2.mus_tightMatch(); }
vector<bool> &mus_updatedSta() { return cms2.mus_updatedSta(); }
vector<bool> &photons_haspixelSeed() { return cms2.photons_haspixelSeed(); }
vector<double> &jets_closestElectron_DR() { return cms2.jets_closestElectron_DR(); }
vector<double> &jets_closestMuon_DR() { return cms2.jets_closestMuon_DR(); }
float &evt_bs_Xwidth() { return cms2.evt_bs_Xwidth(); }
float &evt_bs_XwidthErr() { return cms2.evt_bs_XwidthErr(); }
float &evt_bs_Ywidth() { return cms2.evt_bs_Ywidth(); }
float &evt_bs_YwidthErr() { return cms2.evt_bs_YwidthErr(); }
float &evt_bs_dxdz() { return cms2.evt_bs_dxdz(); }
float &evt_bs_dxdzErr() { return cms2.evt_bs_dxdzErr(); }
float &evt_bs_dydz() { return cms2.evt_bs_dydz(); }
float &evt_bs_dydzErr() { return cms2.evt_bs_dydzErr(); }
float &evt_bs_sigmaZ() { return cms2.evt_bs_sigmaZ(); }
float &evt_bs_sigmaZErr() { return cms2.evt_bs_sigmaZErr(); }
float &evt_bs_xErr() { return cms2.evt_bs_xErr(); }
float &evt_bs_yErr() { return cms2.evt_bs_yErr(); }
float &evt_bs_zErr() { return cms2.evt_bs_zErr(); }
float &evthcal_dmetx() { return cms2.evthcal_dmetx(); }
float &evthcal_dmety() { return cms2.evthcal_dmety(); }
float &evthcal_dsumet() { return cms2.evthcal_dsumet(); }
float &evthf_dmetx() { return cms2.evthf_dmetx(); }
float &evthf_dmety() { return cms2.evthf_dmety(); }
float &evthf_dsumet() { return cms2.evthf_dsumet(); }
float &evt_bField() { return cms2.evt_bField(); }
float &evt_kfactor() { return cms2.evt_kfactor(); }
float &evt_scale1fb() { return cms2.evt_scale1fb(); }
float &evt_xsec_excl() { return cms2.evt_xsec_excl(); }
float &evt_xsec_incl() { return cms2.evt_xsec_incl(); }
float &gen_met() { return cms2.gen_met(); }
float &gen_metPhi() { return cms2.gen_metPhi(); }
float &genps_alphaQCD() { return cms2.genps_alphaQCD(); }
float &genps_pthat() { return cms2.genps_pthat(); }
float &genps_qScale() { return cms2.genps_qScale(); }
float &genps_weight() { return cms2.genps_weight(); }
float &gen_sumEt() { return cms2.gen_sumEt(); }
float &hcalnoise_eventChargeFraction() { return cms2.hcalnoise_eventChargeFraction(); }
float &hcalnoise_eventEMEnergy() { return cms2.hcalnoise_eventEMEnergy(); }
float &hcalnoise_eventEMFraction() { return cms2.hcalnoise_eventEMFraction(); }
float &hcalnoise_eventHadEnergy() { return cms2.hcalnoise_eventHadEnergy(); }
float &hcalnoise_eventTrackEnergy() { return cms2.hcalnoise_eventTrackEnergy(); }
float &hcalnoise_max10GeVHitTime() { return cms2.hcalnoise_max10GeVHitTime(); }
float &hcalnoise_max25GeVHitTime() { return cms2.hcalnoise_max25GeVHitTime(); }
float &hcalnoise_min10GeVHitTime() { return cms2.hcalnoise_min10GeVHitTime(); }
float &hcalnoise_min25GeVHitTime() { return cms2.hcalnoise_min25GeVHitTime(); }
float &hcalnoise_minE10TS() { return cms2.hcalnoise_minE10TS(); }
float &hcalnoise_minE2Over10TS() { return cms2.hcalnoise_minE2Over10TS(); }
float &hcalnoise_minE2TS() { return cms2.hcalnoise_minE2TS(); }
float &hcalnoise_minHPDEMF() { return cms2.hcalnoise_minHPDEMF(); }
float &hcalnoise_minRBXEMF() { return cms2.hcalnoise_minRBXEMF(); }
float &hcalnoise_rms10GeVHitTime() { return cms2.hcalnoise_rms10GeVHitTime(); }
float &hcalnoise_rms25GeVHitTime() { return cms2.hcalnoise_rms25GeVHitTime(); }
float &l1_met_etTot() { return cms2.l1_met_etTot(); }
float &l1_met_met() { return cms2.l1_met_met(); }
float &l1_mht_htTot() { return cms2.l1_mht_htTot(); }
float &l1_mht_mht() { return cms2.l1_mht_mht(); }
float &evt_ecalendcapm_met() { return cms2.evt_ecalendcapm_met(); }
float &evt_ecalendcapm_metPhi() { return cms2.evt_ecalendcapm_metPhi(); }
float &evt_ecalendcapp_met() { return cms2.evt_ecalendcapp_met(); }
float &evt_ecalendcapp_metPhi() { return cms2.evt_ecalendcapp_metPhi(); }
float &evt_ecalmet() { return cms2.evt_ecalmet(); }
float &evt_ecalmetPhi() { return cms2.evt_ecalmetPhi(); }
float &evt_endcapm_met() { return cms2.evt_endcapm_met(); }
float &evt_endcapm_metPhi() { return cms2.evt_endcapm_metPhi(); }
float &evt_endcapp_met() { return cms2.evt_endcapp_met(); }
float &evt_endcapp_metPhi() { return cms2.evt_endcapp_metPhi(); }
float &evt_hcalendcapm_met() { return cms2.evt_hcalendcapm_met(); }
float &evt_hcalendcapm_metPhi() { return cms2.evt_hcalendcapm_metPhi(); }
float &evt_hcalendcapp_met() { return cms2.evt_hcalendcapp_met(); }
float &evt_hcalendcapp_metPhi() { return cms2.evt_hcalendcapp_metPhi(); }
float &evt_hcalmet() { return cms2.evt_hcalmet(); }
float &evt_hcalmetPhi() { return cms2.evt_hcalmetPhi(); }
float &evt_met() { return cms2.evt_met(); }
float &evt_metHO() { return cms2.evt_metHO(); }
float &evt_metHOPhi() { return cms2.evt_metHOPhi(); }
float &evt_metHOSig() { return cms2.evt_metHOSig(); }
float &evt_metMuonCorr() { return cms2.evt_metMuonCorr(); }
float &evt_metMuonCorrPhi() { return cms2.evt_metMuonCorrPhi(); }
float &evt_metMuonCorrSig() { return cms2.evt_metMuonCorrSig(); }
float &evt_metMuonJESCorr() { return cms2.evt_metMuonJESCorr(); }
float &evt_metMuonJESCorrPhi() { return cms2.evt_metMuonJESCorrPhi(); }
float &evt_metMuonJESCorrSig() { return cms2.evt_metMuonJESCorrSig(); }
float &evt_metNoHF() { return cms2.evt_metNoHF(); }
float &evt_metNoHFHO() { return cms2.evt_metNoHFHO(); }
float &evt_metNoHFHOPhi() { return cms2.evt_metNoHFHOPhi(); }
float &evt_metNoHFHOSig() { return cms2.evt_metNoHFHOSig(); }
float &evt_metNoHFPhi() { return cms2.evt_metNoHFPhi(); }
float &evt_metNoHFSig() { return cms2.evt_metNoHFSig(); }
float &evt_metOpt() { return cms2.evt_metOpt(); }
float &evt_metOptHO() { return cms2.evt_metOptHO(); }
float &evt_metOptHOPhi() { return cms2.evt_metOptHOPhi(); }
float &evt_metOptHOSig() { return cms2.evt_metOptHOSig(); }
float &evt_metOptNoHF() { return cms2.evt_metOptNoHF(); }
float &evt_metOptNoHFHO() { return cms2.evt_metOptNoHFHO(); }
float &evt_metOptNoHFHOPhi() { return cms2.evt_metOptNoHFHOPhi(); }
float &evt_metOptNoHFHOSig() { return cms2.evt_metOptNoHFHOSig(); }
float &evt_metOptNoHFPhi() { return cms2.evt_metOptNoHFPhi(); }
float &evt_metOptNoHFSig() { return cms2.evt_metOptNoHFSig(); }
float &evt_metOptPhi() { return cms2.evt_metOptPhi(); }
float &evt_metOptSig() { return cms2.evt_metOptSig(); }
float &evt_metPhi() { return cms2.evt_metPhi(); }
float &evt_metSig() { return cms2.evt_metSig(); }
float &evt_sumet() { return cms2.evt_sumet(); }
float &evt_sumetHO() { return cms2.evt_sumetHO(); }
float &evt_sumetMuonCorr() { return cms2.evt_sumetMuonCorr(); }
float &evt_sumetNoHF() { return cms2.evt_sumetNoHF(); }
float &evt_sumetNoHFHO() { return cms2.evt_sumetNoHFHO(); }
float &evt_sumetOpt() { return cms2.evt_sumetOpt(); }
float &evt_sumetOptHO() { return cms2.evt_sumetOptHO(); }
float &evt_sumetOptNoHF() { return cms2.evt_sumetOptNoHF(); }
float &evt_sumetOptNoHFHO() { return cms2.evt_sumetOptNoHFHO(); }
float &met_pat_metCor() { return cms2.met_pat_metCor(); }
float &met_pat_metPhiCor() { return cms2.met_pat_metPhiCor(); }
float &met_pat_metPhiUncor() { return cms2.met_pat_metPhiUncor(); }
float &met_pat_metPhiUncorJES() { return cms2.met_pat_metPhiUncorJES(); }
float &met_pat_metPhiUncorMuon() { return cms2.met_pat_metPhiUncorMuon(); }
float &met_pat_metUncor() { return cms2.met_pat_metUncor(); }
float &met_pat_metUncorJES() { return cms2.met_pat_metUncorJES(); }
float &met_pat_metUncorMuon() { return cms2.met_pat_metUncorMuon(); }
float &pdfinfo_scale() { return cms2.pdfinfo_scale(); }
float &pdfinfo_x1() { return cms2.pdfinfo_x1(); }
float &pdfinfo_x2() { return cms2.pdfinfo_x2(); }
float &evt_pfmet() { return cms2.evt_pfmet(); }
float &evt_pfmetPhi() { return cms2.evt_pfmetPhi(); }
float &evt_pfmetSig() { return cms2.evt_pfmetSig(); }
float &evt_pfsumet() { return cms2.evt_pfsumet(); }
float &evt_pf_tcmet() { return cms2.evt_pf_tcmet(); }
float &evt_pf_tcmetPhi() { return cms2.evt_pf_tcmetPhi(); }
float &evt_pf_tcmetSig() { return cms2.evt_pf_tcmetSig(); }
float &evt_pf_tcsumet() { return cms2.evt_pf_tcsumet(); }
float &evt_tcmet() { return cms2.evt_tcmet(); }
float &evt_tcmetPhi() { return cms2.evt_tcmetPhi(); }
float &evt_tcmetSig() { return cms2.evt_tcmetSig(); }
float &evt_tcsumet() { return cms2.evt_tcsumet(); }
ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > &evt_bsp4() { return cms2.evt_bsp4(); }
ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > &l1_met_p4() { return cms2.l1_met_p4(); }
ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > &l1_mht_p4() { return cms2.l1_mht_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_mc_motherp4() { return cms2.els_mc_motherp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_mc_p4() { return cms2.els_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_mc_gp_p4() { return cms2.jets_mc_gp_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_mc_motherp4() { return cms2.jets_mc_motherp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_mc_p4() { return cms2.jets_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_mc_motherp4() { return cms2.mus_mc_motherp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_mc_p4() { return cms2.mus_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfjets_mc_gp_p4() { return cms2.pfjets_mc_gp_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfjets_mc_motherp4() { return cms2.pfjets_mc_motherp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfjets_mc_p4() { return cms2.pfjets_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &photons_mc_motherp4() { return cms2.photons_mc_motherp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &photons_mc_p4() { return cms2.photons_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trk_mcp4() { return cms2.trk_mcp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_conv_pos_p4() { return cms2.els_conv_pos_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_inner_position() { return cms2.els_inner_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_outer_position() { return cms2.els_outer_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_p4() { return cms2.els_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_p4In() { return cms2.els_p4In(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_p4Out() { return cms2.els_p4Out(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_trk_p4() { return cms2.els_trk_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_vertex_p4() { return cms2.els_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &genjets_p4() { return cms2.genjets_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &genps_p4() { return cms2.genps_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &genps_prod_vtx() { return cms2.genps_prod_vtx(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &gsftrks_inner_position() { return cms2.gsftrks_inner_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &gsftrks_outer_p4() { return cms2.gsftrks_outer_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &gsftrks_outer_position() { return cms2.gsftrks_outer_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &gsftrks_p4() { return cms2.gsftrks_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &gsftrks_vertex_p4() { return cms2.gsftrks_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_ll_p4() { return cms2.hyp_ll_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_ll_trk_p4() { return cms2.hyp_ll_trk_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_lt_p4() { return cms2.hyp_lt_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_lt_trk_p4() { return cms2.hyp_lt_trk_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_p4() { return cms2.hyp_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_FVFit_p4() { return cms2.hyp_FVFit_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_FVFit_v4() { return cms2.hyp_FVFit_v4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_ll_mc_p4() { return cms2.hyp_ll_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &hyp_lt_mc_p4() { return cms2.hyp_lt_mc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_p4() { return cms2.jets_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_vertex_p4() { return cms2.jets_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jpts_p4() { return cms2.jpts_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_emiso_p4() { return cms2.l1_emiso_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_emnoiso_p4() { return cms2.l1_emnoiso_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_jetsc_p4() { return cms2.l1_jetsc_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_jetsf_p4() { return cms2.l1_jetsf_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_jetst_p4() { return cms2.l1_jetst_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &l1_mus_p4() { return cms2.l1_mus_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_ecalpos_p4() { return cms2.mus_ecalpos_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_fitdefault_p4() { return cms2.mus_fitdefault_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_fitfirsthit_p4() { return cms2.mus_fitfirsthit_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_fitpicky_p4() { return cms2.mus_fitpicky_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_fittev_p4() { return cms2.mus_fittev_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_gfit_outerPos_p4() { return cms2.mus_gfit_outerPos_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_gfit_p4() { return cms2.mus_gfit_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_gfit_vertex_p4() { return cms2.mus_gfit_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_p4() { return cms2.mus_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_sta_p4() { return cms2.mus_sta_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_sta_vertex_p4() { return cms2.mus_sta_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_trk_p4() { return cms2.mus_trk_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_vertex_p4() { return cms2.mus_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_pat_genMotherP4() { return cms2.els_pat_genMotherP4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_pat_genP4() { return cms2.els_pat_genP4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &els_pat_p4() { return cms2.els_pat_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_pat_genJet_p4() { return cms2.jets_pat_genJet_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_pat_genPartonMother_p4() { return cms2.jets_pat_genPartonMother_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_pat_genParton_p4() { return cms2.jets_pat_genParton_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_pat_jet_p4() { return cms2.jets_pat_jet_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &jets_pat_jet_uncorp4() { return cms2.jets_pat_jet_uncorp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_pat_genMotherP4() { return cms2.mus_pat_genMotherP4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_pat_genP4() { return cms2.mus_pat_genP4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &mus_pat_p4() { return cms2.mus_pat_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfels_p4() { return cms2.pfels_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfels_posAtEcal_p4() { return cms2.pfels_posAtEcal_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfjets_p4() { return cms2.pfjets_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfmus_p4() { return cms2.pfmus_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &pfmus_posAtEcal_p4() { return cms2.pfmus_posAtEcal_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &photons_p4() { return cms2.photons_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &scs_p4() { return cms2.scs_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &scs_pos_p4() { return cms2.scs_pos_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &scs_vtx_p4() { return cms2.scs_vtx_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &svs_flight() { return cms2.svs_flight(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &svs_mc3_p4() { return cms2.svs_mc3_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &svs_p4() { return cms2.svs_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &svs_position() { return cms2.svs_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &svs_refitp4() { return cms2.svs_refitp4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trks_inner_position() { return cms2.trks_inner_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trks_outer_p4() { return cms2.trks_outer_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trks_outer_position() { return cms2.trks_outer_position(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trks_trk_p4() { return cms2.trks_trk_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trks_vertex_p4() { return cms2.trks_vertex_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &trkjets_p4() { return cms2.trkjets_p4(); }
vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > &vtxs_position() { return cms2.vtxs_position(); }
vector<vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > > &genps_lepdaughter_p4() { return cms2.genps_lepdaughter_p4(); }
vector<vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > > &hlt_trigObjs_p4() { return cms2.hlt_trigObjs_p4(); }
vector<vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > > &hyp_jets_p4() { return cms2.hyp_jets_p4(); }
vector<vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > > &hyp_other_jets_p4() { return cms2.hyp_other_jets_p4(); }
vector<float> &jpts_combinedSecondaryVertexBJetTag() { return cms2.jpts_combinedSecondaryVertexBJetTag(); }
vector<float> &jpts_combinedSecondaryVertexMVABJetTag() { return cms2.jpts_combinedSecondaryVertexMVABJetTag(); }
vector<float> &jpts_jetBProbabilityBJetTag() { return cms2.jpts_jetBProbabilityBJetTag(); }
vector<float> &jpts_jetProbabilityBJetTag() { return cms2.jpts_jetProbabilityBJetTag(); }
vector<float> &jpts_simpleSecondaryVertexHighEffBJetTag() { return cms2.jpts_simpleSecondaryVertexHighEffBJetTag(); }
vector<float> &jpts_simpleSecondaryVertexHighPurBJetTags() { return cms2.jpts_simpleSecondaryVertexHighPurBJetTags(); }
vector<float> &jpts_softElectronByIP3dBJetTag() { return cms2.jpts_softElectronByIP3dBJetTag(); }
vector<float> &jpts_softElectronByPtBJetTag() { return cms2.jpts_softElectronByPtBJetTag(); }
vector<float> &jpts_softMuonBJetTag() { return cms2.jpts_softMuonBJetTag(); }
vector<float> &jpts_softMuonByIP3dBJetTag() { return cms2.jpts_softMuonByIP3dBJetTag(); }
vector<float> &jpts_softMuonByPtBJetTag() { return cms2.jpts_softMuonByPtBJetTag(); }
vector<float> &jpts_trackCountingHighEffBJetTag() { return cms2.jpts_trackCountingHighEffBJetTag(); }
vector<float> &jpts_trackCountingHighPurBJetTag() { return cms2.jpts_trackCountingHighPurBJetTag(); }
vector<float> &jets_combinedSecondaryVertexBJetTag() { return cms2.jets_combinedSecondaryVertexBJetTag(); }
vector<float> &jets_combinedSecondaryVertexMVABJetTag() { return cms2.jets_combinedSecondaryVertexMVABJetTag(); }
vector<float> &jets_jetBProbabilityBJetTag() { return cms2.jets_jetBProbabilityBJetTag(); }
vector<float> &jets_jetProbabilityBJetTag() { return cms2.jets_jetProbabilityBJetTag(); }
vector<float> &jets_simpleSecondaryVertexHighEffBJetTag() { return cms2.jets_simpleSecondaryVertexHighEffBJetTag(); }
vector<float> &jets_simpleSecondaryVertexHighPurBJetTags() { return cms2.jets_simpleSecondaryVertexHighPurBJetTags(); }
vector<float> &jets_softElectronByIP3dBJetTag() { return cms2.jets_softElectronByIP3dBJetTag(); }
vector<float> &jets_softElectronByPtBJetTag() { return cms2.jets_softElectronByPtBJetTag(); }
vector<float> &jets_softMuonBJetTag() { return cms2.jets_softMuonBJetTag(); }
vector<float> &jets_softMuonByIP3dBJetTag() { return cms2.jets_softMuonByIP3dBJetTag(); }
vector<float> &jets_softMuonByPtBJetTag() { return cms2.jets_softMuonByPtBJetTag(); }
vector<float> &jets_trackCountingHighEffBJetTag() { return cms2.jets_trackCountingHighEffBJetTag(); }
vector<float> &jets_trackCountingHighPurBJetTag() { return cms2.jets_trackCountingHighPurBJetTag(); }
vector<float> &pfjets_combinedSecondaryVertexBJetTag() { return cms2.pfjets_combinedSecondaryVertexBJetTag(); }
vector<float> &pfjets_combinedSecondaryVertexMVABJetTag() { return cms2.pfjets_combinedSecondaryVertexMVABJetTag(); }
vector<float> &pfjets_jetBProbabilityBJetTag() { return cms2.pfjets_jetBProbabilityBJetTag(); }
vector<float> &pfjets_jetProbabilityBJetTag() { return cms2.pfjets_jetProbabilityBJetTag(); }
vector<float> &pfjets_simpleSecondaryVertexHighEffBJetTag() { return cms2.pfjets_simpleSecondaryVertexHighEffBJetTag(); }
vector<float> &pfjets_simpleSecondaryVertexHighPurBJetTags() { return cms2.pfjets_simpleSecondaryVertexHighPurBJetTags(); }
vector<float> &pfjets_softElectronByIP3dBJetTag() { return cms2.pfjets_softElectronByIP3dBJetTag(); }
vector<float> &pfjets_softElectronByPtBJetTag() { return cms2.pfjets_softElectronByPtBJetTag(); }
vector<float> &pfjets_softMuonBJetTag() { return cms2.pfjets_softMuonBJetTag(); }
vector<float> &pfjets_softMuonByIP3dBJetTag() { return cms2.pfjets_softMuonByIP3dBJetTag(); }
vector<float> &pfjets_softMuonByPtBJetTag() { return cms2.pfjets_softMuonByPtBJetTag(); }
vector<float> &pfjets_trackCountingHighEffBJetTag() { return cms2.pfjets_trackCountingHighEffBJetTag(); }
vector<float> &pfjets_trackCountingHighPurBJetTag() { return cms2.pfjets_trackCountingHighPurBJetTag(); }
vector<float> &trkjets_combinedSecondaryVertexBJetTag() { return cms2.trkjets_combinedSecondaryVertexBJetTag(); }
vector<float> &trkjets_combinedSecondaryVertexMVABJetTag() { return cms2.trkjets_combinedSecondaryVertexMVABJetTag(); }
vector<float> &trkjets_jetBProbabilityBJetTag() { return cms2.trkjets_jetBProbabilityBJetTag(); }
vector<float> &trkjets_jetProbabilityBJetTag() { return cms2.trkjets_jetProbabilityBJetTag(); }
vector<float> &trkjets_simpleSecondaryVertexHighEffBJetTag() { return cms2.trkjets_simpleSecondaryVertexHighEffBJetTag(); }
vector<float> &trkjets_simpleSecondaryVertexHighPurBJetTags() { return cms2.trkjets_simpleSecondaryVertexHighPurBJetTags(); }
vector<float> &trkjets_softElectronByIP3dBJetTag() { return cms2.trkjets_softElectronByIP3dBJetTag(); }
vector<float> &trkjets_softElectronByPtBJetTag() { return cms2.trkjets_softElectronByPtBJetTag(); }
vector<float> &trkjets_softMuonBJetTag() { return cms2.trkjets_softMuonBJetTag(); }
vector<float> &trkjets_softMuonByIP3dBJetTag() { return cms2.trkjets_softMuonByIP3dBJetTag(); }
vector<float> &trkjets_softMuonByPtBJetTag() { return cms2.trkjets_softMuonByPtBJetTag(); }
vector<float> &trkjets_trackCountingHighEffBJetTag() { return cms2.trkjets_trackCountingHighEffBJetTag(); }
vector<float> &trkjets_trackCountingHighPurBJetTag() { return cms2.trkjets_trackCountingHighPurBJetTag(); }
vector<float> &evt_bs_covMatrix() { return cms2.evt_bs_covMatrix(); }
vector<float> &els_mc3dr() { return cms2.els_mc3dr(); }
vector<float> &els_mcdr() { return cms2.els_mcdr(); }
vector<float> &jets_mc3dr() { return cms2.jets_mc3dr(); }
vector<float> &jets_mcdr() { return cms2.jets_mcdr(); }
vector<float> &jets_mc_emEnergy() { return cms2.jets_mc_emEnergy(); }
vector<float> &jets_mc_gpdr() { return cms2.jets_mc_gpdr(); }
vector<float> &jets_mc_hadEnergy() { return cms2.jets_mc_hadEnergy(); }
vector<float> &jets_mc_invEnergy() { return cms2.jets_mc_invEnergy(); }
vector<float> &jets_mc_otherEnergy() { return cms2.jets_mc_otherEnergy(); }
vector<float> &mus_mc3dr() { return cms2.mus_mc3dr(); }
vector<float> &mus_mcdr() { return cms2.mus_mcdr(); }
vector<float> &pfjets_mc3dr() { return cms2.pfjets_mc3dr(); }
vector<float> &pfjets_mcdr() { return cms2.pfjets_mcdr(); }
vector<float> &pfjets_mc_emEnergy() { return cms2.pfjets_mc_emEnergy(); }
vector<float> &pfjets_mc_gpdr() { return cms2.pfjets_mc_gpdr(); }
vector<float> &pfjets_mc_hadEnergy() { return cms2.pfjets_mc_hadEnergy(); }
vector<float> &pfjets_mc_invEnergy() { return cms2.pfjets_mc_invEnergy(); }
vector<float> &pfjets_mc_otherEnergy() { return cms2.pfjets_mc_otherEnergy(); }
vector<float> &photons_mc3dr() { return cms2.photons_mc3dr(); }
vector<float> &photons_mcdr() { return cms2.photons_mcdr(); }
vector<float> &trk_mc3dr() { return cms2.trk_mc3dr(); }
vector<float> &trk_mcdr() { return cms2.trk_mcdr(); }
vector<float> &trks_conv_dcot() { return cms2.trks_conv_dcot(); }
vector<float> &trks_conv_dist() { return cms2.trks_conv_dist(); }
vector<float> &els_ecalJuraIso() { return cms2.els_ecalJuraIso(); }
vector<float> &els_ecalJuraTowerIso() { return cms2.els_ecalJuraTowerIso(); }
vector<float> &els_hcalConeIso() { return cms2.els_hcalConeIso(); }
vector<float> &els_tkJuraIso() { return cms2.els_tkJuraIso(); }
vector<float> &els_jetdr() { return cms2.els_jetdr(); }
vector<float> &els_musdr() { return cms2.els_musdr(); }
vector<float> &els_chi2() { return cms2.els_chi2(); }
vector<float> &els_conv_dcot() { return cms2.els_conv_dcot(); }
vector<float> &els_conv_dist() { return cms2.els_conv_dist(); }
vector<float> &els_conv_radius() { return cms2.els_conv_radius(); }
vector<float> &els_d0() { return cms2.els_d0(); }
vector<float> &els_d0Err() { return cms2.els_d0Err(); }
vector<float> &els_d0corr() { return cms2.els_d0corr(); }
vector<float> &els_dEtaIn() { return cms2.els_dEtaIn(); }
vector<float> &els_dEtaOut() { return cms2.els_dEtaOut(); }
vector<float> &els_dPhiIn() { return cms2.els_dPhiIn(); }
vector<float> &els_dPhiInPhiOut() { return cms2.els_dPhiInPhiOut(); }
vector<float> &els_dPhiOut() { return cms2.els_dPhiOut(); }
vector<float> &els_deltaEtaEleClusterTrackAtCalo() { return cms2.els_deltaEtaEleClusterTrackAtCalo(); }
vector<float> &els_deltaPhiEleClusterTrackAtCalo() { return cms2.els_deltaPhiEleClusterTrackAtCalo(); }
vector<float> &els_e1x5() { return cms2.els_e1x5(); }
vector<float> &els_e2x5Max() { return cms2.els_e2x5Max(); }
vector<float> &els_e3x3() { return cms2.els_e3x3(); }
vector<float> &els_e5x5() { return cms2.els_e5x5(); }
vector<float> &els_eMax() { return cms2.els_eMax(); }
vector<float> &els_eOverPIn() { return cms2.els_eOverPIn(); }
vector<float> &els_eOverPOut() { return cms2.els_eOverPOut(); }
vector<float> &els_eSC() { return cms2.els_eSC(); }
vector<float> &els_eSCPresh() { return cms2.els_eSCPresh(); }
vector<float> &els_eSCRaw() { return cms2.els_eSCRaw(); }
vector<float> &els_eSeed() { return cms2.els_eSeed(); }
vector<float> &els_eSeedOverPIn() { return cms2.els_eSeedOverPIn(); }
vector<float> &els_eSeedOverPOut() { return cms2.els_eSeedOverPOut(); }
vector<float> &els_ecalEnergy() { return cms2.els_ecalEnergy(); }
vector<float> &els_ecalEnergyError() { return cms2.els_ecalEnergyError(); }
vector<float> &els_ecalIso() { return cms2.els_ecalIso(); }
vector<float> &els_ecalIso04() { return cms2.els_ecalIso04(); }
vector<float> &els_egamma_looseId() { return cms2.els_egamma_looseId(); }
vector<float> &els_egamma_robustHighEnergy() { return cms2.els_egamma_robustHighEnergy(); }
vector<float> &els_egamma_robustLooseId() { return cms2.els_egamma_robustLooseId(); }
vector<float> &els_egamma_robustTightId() { return cms2.els_egamma_robustTightId(); }
vector<float> &els_egamma_tightId() { return cms2.els_egamma_tightId(); }
vector<float> &els_electronMomentumError() { return cms2.els_electronMomentumError(); }
vector<float> &els_etaErr() { return cms2.els_etaErr(); }
vector<float> &els_etaSC() { return cms2.els_etaSC(); }
vector<float> &els_fbrem() { return cms2.els_fbrem(); }
vector<float> &els_hOverE() { return cms2.els_hOverE(); }
vector<float> &els_hcalDepth1OverEcal() { return cms2.els_hcalDepth1OverEcal(); }
vector<float> &els_hcalDepth1TowerSumEt() { return cms2.els_hcalDepth1TowerSumEt(); }
vector<float> &els_hcalDepth1TowerSumEt04() { return cms2.els_hcalDepth1TowerSumEt04(); }
vector<float> &els_hcalDepth2OverEcal() { return cms2.els_hcalDepth2OverEcal(); }
vector<float> &els_hcalDepth2TowerSumEt() { return cms2.els_hcalDepth2TowerSumEt(); }
vector<float> &els_hcalDepth2TowerSumEt04() { return cms2.els_hcalDepth2TowerSumEt04(); }
vector<float> &els_hcalIso() { return cms2.els_hcalIso(); }
vector<float> &els_hcalIso04() { return cms2.els_hcalIso04(); }
vector<float> &els_layer1_charge() { return cms2.els_layer1_charge(); }
vector<float> &els_mva() { return cms2.els_mva(); }
vector<float> &els_ndof() { return cms2.els_ndof(); }
vector<float> &els_phiErr() { return cms2.els_phiErr(); }
vector<float> &els_phiSC() { return cms2.els_phiSC(); }
vector<float> &els_ptErr() { return cms2.els_ptErr(); }
vector<float> &els_sigmaEtaEta() { return cms2.els_sigmaEtaEta(); }
vector<float> &els_sigmaIEtaIEta() { return cms2.els_sigmaIEtaIEta(); }
vector<float> &els_sigmaIEtaIEtaSC() { return cms2.els_sigmaIEtaIEtaSC(); }
vector<float> &els_sigmaIPhiIPhi() { return cms2.els_sigmaIPhiIPhi(); }
vector<float> &els_sigmaIPhiIPhiSC() { return cms2.els_sigmaIPhiIPhiSC(); }
vector<float> &els_sigmaPhiPhi() { return cms2.els_sigmaPhiPhi(); }
vector<float> &els_tkIso() { return cms2.els_tkIso(); }
vector<float> &els_tkIso04() { return cms2.els_tkIso04(); }
vector<float> &els_trackMomentumError() { return cms2.els_trackMomentumError(); }
vector<float> &els_trkdr() { return cms2.els_trkdr(); }
vector<float> &els_trkshFrac() { return cms2.els_trkshFrac(); }
vector<float> &els_z0() { return cms2.els_z0(); }
vector<float> &els_z0Err() { return cms2.els_z0Err(); }
vector<float> &els_z0corr() { return cms2.els_z0corr(); }
vector<float> &gsftrks_chi2() { return cms2.gsftrks_chi2(); }
vector<float> &gsftrks_d0() { return cms2.gsftrks_d0(); }
vector<float> &gsftrks_d0Err() { return cms2.gsftrks_d0Err(); }
vector<float> &gsftrks_d0corr() { return cms2.gsftrks_d0corr(); }
vector<float> &gsftrks_d0corrPhi() { return cms2.gsftrks_d0corrPhi(); }
vector<float> &gsftrks_d0phiCov() { return cms2.gsftrks_d0phiCov(); }
vector<float> &gsftrks_etaErr() { return cms2.gsftrks_etaErr(); }
vector<float> &gsftrks_layer1_charge() { return cms2.gsftrks_layer1_charge(); }
vector<float> &gsftrks_ndof() { return cms2.gsftrks_ndof(); }
vector<float> &gsftrks_phiErr() { return cms2.gsftrks_phiErr(); }
vector<float> &gsftrks_ptErr() { return cms2.gsftrks_ptErr(); }
vector<float> &gsftrks_z0() { return cms2.gsftrks_z0(); }
vector<float> &gsftrks_z0Err() { return cms2.gsftrks_z0Err(); }
vector<float> &gsftrks_z0corr() { return cms2.gsftrks_z0corr(); }
vector<float> &hyp_Ht() { return cms2.hyp_Ht(); }
vector<float> &hyp_dPhi_nJet_metMuonJESCorr() { return cms2.hyp_dPhi_nJet_metMuonJESCorr(); }
vector<float> &hyp_dPhi_nJet_muCorrMet() { return cms2.hyp_dPhi_nJet_muCorrMet(); }
vector<float> &hyp_dPhi_nJet_tcMet() { return cms2.hyp_dPhi_nJet_tcMet(); }
vector<float> &hyp_dPhi_nJet_unCorrMet() { return cms2.hyp_dPhi_nJet_unCorrMet(); }
vector<float> &hyp_ll_chi2() { return cms2.hyp_ll_chi2(); }
vector<float> &hyp_ll_d0() { return cms2.hyp_ll_d0(); }
vector<float> &hyp_ll_d0Err() { return cms2.hyp_ll_d0Err(); }
vector<float> &hyp_ll_d0corr() { return cms2.hyp_ll_d0corr(); }
vector<float> &hyp_ll_dPhi_metMuonJESCorr() { return cms2.hyp_ll_dPhi_metMuonJESCorr(); }
vector<float> &hyp_ll_dPhi_muCorrMet() { return cms2.hyp_ll_dPhi_muCorrMet(); }
vector<float> &hyp_ll_dPhi_tcMet() { return cms2.hyp_ll_dPhi_tcMet(); }
vector<float> &hyp_ll_dPhi_unCorrMet() { return cms2.hyp_ll_dPhi_unCorrMet(); }
vector<float> &hyp_ll_etaErr() { return cms2.hyp_ll_etaErr(); }
vector<float> &hyp_ll_ndof() { return cms2.hyp_ll_ndof(); }
vector<float> &hyp_ll_phiErr() { return cms2.hyp_ll_phiErr(); }
vector<float> &hyp_ll_ptErr() { return cms2.hyp_ll_ptErr(); }
vector<float> &hyp_ll_z0() { return cms2.hyp_ll_z0(); }
vector<float> &hyp_ll_z0Err() { return cms2.hyp_ll_z0Err(); }
vector<float> &hyp_ll_z0corr() { return cms2.hyp_ll_z0corr(); }
vector<float> &hyp_lt_chi2() { return cms2.hyp_lt_chi2(); }
vector<float> &hyp_lt_d0() { return cms2.hyp_lt_d0(); }
vector<float> &hyp_lt_d0Err() { return cms2.hyp_lt_d0Err(); }
vector<float> &hyp_lt_d0corr() { return cms2.hyp_lt_d0corr(); }
vector<float> &hyp_lt_dPhi_metMuonJESCorr() { return cms2.hyp_lt_dPhi_metMuonJESCorr(); }
vector<float> &hyp_lt_dPhi_muCorrMet() { return cms2.hyp_lt_dPhi_muCorrMet(); }
vector<float> &hyp_lt_dPhi_tcMet() { return cms2.hyp_lt_dPhi_tcMet(); }
vector<float> &hyp_lt_dPhi_unCorrMet() { return cms2.hyp_lt_dPhi_unCorrMet(); }
vector<float> &hyp_lt_etaErr() { return cms2.hyp_lt_etaErr(); }
vector<float> &hyp_lt_ndof() { return cms2.hyp_lt_ndof(); }
vector<float> &hyp_lt_phiErr() { return cms2.hyp_lt_phiErr(); }
vector<float> &hyp_lt_ptErr() { return cms2.hyp_lt_ptErr(); }
vector<float> &hyp_lt_z0() { return cms2.hyp_lt_z0(); }
vector<float> &hyp_lt_z0Err() { return cms2.hyp_lt_z0Err(); }
vector<float> &hyp_lt_z0corr() { return cms2.hyp_lt_z0corr(); }
vector<float> &hyp_mt2_metMuonJESCorr() { return cms2.hyp_mt2_metMuonJESCorr(); }
vector<float> &hyp_mt2_muCorrMet() { return cms2.hyp_mt2_muCorrMet(); }
vector<float> &hyp_mt2_tcMet() { return cms2.hyp_mt2_tcMet(); }
vector<float> &hyp_sumJetPt() { return cms2.hyp_sumJetPt(); }
vector<float> &hyp_FVFit_chi2ndf() { return cms2.hyp_FVFit_chi2ndf(); }
vector<float> &hyp_FVFit_prob() { return cms2.hyp_FVFit_prob(); }
vector<float> &hyp_FVFit_v4cxx() { return cms2.hyp_FVFit_v4cxx(); }
vector<float> &hyp_FVFit_v4cxy() { return cms2.hyp_FVFit_v4cxy(); }
vector<float> &hyp_FVFit_v4cyy() { return cms2.hyp_FVFit_v4cyy(); }
vector<float> &hyp_FVFit_v4czx() { return cms2.hyp_FVFit_v4czx(); }
vector<float> &hyp_FVFit_v4czy() { return cms2.hyp_FVFit_v4czy(); }
vector<float> &hyp_FVFit_v4czz() { return cms2.hyp_FVFit_v4czz(); }
vector<float> &hyp_ll_ecaliso() { return cms2.hyp_ll_ecaliso(); }
vector<float> &hyp_ll_trkiso() { return cms2.hyp_ll_trkiso(); }
vector<float> &hyp_lt_ecaliso() { return cms2.hyp_lt_ecaliso(); }
vector<float> &hyp_lt_trkiso() { return cms2.hyp_lt_trkiso(); }
vector<float> &jets_approximatefHPD() { return cms2.jets_approximatefHPD(); }
vector<float> &jets_approximatefRBX() { return cms2.jets_approximatefRBX(); }
vector<float> &jets_cor() { return cms2.jets_cor(); }
vector<float> &jets_emFrac() { return cms2.jets_emFrac(); }
vector<float> &jets_fHPD() { return cms2.jets_fHPD(); }
vector<float> &jets_fRBX() { return cms2.jets_fRBX(); }
vector<float> &jets_fSubDetector1() { return cms2.jets_fSubDetector1(); }
vector<float> &jets_fSubDetector2() { return cms2.jets_fSubDetector2(); }
vector<float> &jets_fSubDetector3() { return cms2.jets_fSubDetector3(); }
vector<float> &jets_fSubDetector4() { return cms2.jets_fSubDetector4(); }
vector<float> &jets_hitsInN90() { return cms2.jets_hitsInN90(); }
vector<float> &jets_n90Hits() { return cms2.jets_n90Hits(); }
vector<float> &jets_nECALTowers() { return cms2.jets_nECALTowers(); }
vector<float> &jets_nHCALTowers() { return cms2.jets_nHCALTowers(); }
vector<float> &jets_restrictedEMF() { return cms2.jets_restrictedEMF(); }
vector<float> &jpts_cor() { return cms2.jpts_cor(); }
vector<float> &jpts_emFrac() { return cms2.jpts_emFrac(); }
vector<float> &mus_met_deltax() { return cms2.mus_met_deltax(); }
vector<float> &mus_met_deltay() { return cms2.mus_met_deltay(); }
vector<float> &mus_eledr() { return cms2.mus_eledr(); }
vector<float> &mus_jetdr() { return cms2.mus_jetdr(); }
vector<float> &mus_caloCompatibility() { return cms2.mus_caloCompatibility(); }
vector<float> &mus_chi2() { return cms2.mus_chi2(); }
vector<float> &mus_d0() { return cms2.mus_d0(); }
vector<float> &mus_d0Err() { return cms2.mus_d0Err(); }
vector<float> &mus_d0corr() { return cms2.mus_d0corr(); }
vector<float> &mus_e_em() { return cms2.mus_e_em(); }
vector<float> &mus_e_emS9() { return cms2.mus_e_emS9(); }
vector<float> &mus_e_had() { return cms2.mus_e_had(); }
vector<float> &mus_e_hadS9() { return cms2.mus_e_hadS9(); }
vector<float> &mus_e_ho() { return cms2.mus_e_ho(); }
vector<float> &mus_e_hoS9() { return cms2.mus_e_hoS9(); }
vector<float> &mus_etaErr() { return cms2.mus_etaErr(); }
vector<float> &mus_gfit_chi2() { return cms2.mus_gfit_chi2(); }
vector<float> &mus_gfit_d0() { return cms2.mus_gfit_d0(); }
vector<float> &mus_gfit_d0Err() { return cms2.mus_gfit_d0Err(); }
vector<float> &mus_gfit_d0corr() { return cms2.mus_gfit_d0corr(); }
vector<float> &mus_gfit_ndof() { return cms2.mus_gfit_ndof(); }
vector<float> &mus_gfit_qoverp() { return cms2.mus_gfit_qoverp(); }
vector<float> &mus_gfit_qoverpError() { return cms2.mus_gfit_qoverpError(); }
vector<float> &mus_gfit_z0() { return cms2.mus_gfit_z0(); }
vector<float> &mus_gfit_z0Err() { return cms2.mus_gfit_z0Err(); }
vector<float> &mus_gfit_z0corr() { return cms2.mus_gfit_z0corr(); }
vector<float> &mus_iso03_emEt() { return cms2.mus_iso03_emEt(); }
vector<float> &mus_iso03_hadEt() { return cms2.mus_iso03_hadEt(); }
vector<float> &mus_iso03_hoEt() { return cms2.mus_iso03_hoEt(); }
vector<float> &mus_iso03_sumPt() { return cms2.mus_iso03_sumPt(); }
vector<float> &mus_iso05_emEt() { return cms2.mus_iso05_emEt(); }
vector<float> &mus_iso05_hadEt() { return cms2.mus_iso05_hadEt(); }
vector<float> &mus_iso05_hoEt() { return cms2.mus_iso05_hoEt(); }
vector<float> &mus_iso05_sumPt() { return cms2.mus_iso05_sumPt(); }
vector<float> &mus_iso_ecalvetoDep() { return cms2.mus_iso_ecalvetoDep(); }
vector<float> &mus_iso_hcalvetoDep() { return cms2.mus_iso_hcalvetoDep(); }
vector<float> &mus_iso_hovetoDep() { return cms2.mus_iso_hovetoDep(); }
vector<float> &mus_iso_trckvetoDep() { return cms2.mus_iso_trckvetoDep(); }
vector<float> &mus_ndof() { return cms2.mus_ndof(); }
vector<float> &mus_phiErr() { return cms2.mus_phiErr(); }
vector<float> &mus_ptErr() { return cms2.mus_ptErr(); }
vector<float> &mus_qoverp() { return cms2.mus_qoverp(); }
vector<float> &mus_qoverpError() { return cms2.mus_qoverpError(); }
vector<float> &mus_sta_chi2() { return cms2.mus_sta_chi2(); }
vector<float> &mus_sta_d0() { return cms2.mus_sta_d0(); }
vector<float> &mus_sta_d0Err() { return cms2.mus_sta_d0Err(); }
vector<float> &mus_sta_d0corr() { return cms2.mus_sta_d0corr(); }
vector<float> &mus_sta_ndof() { return cms2.mus_sta_ndof(); }
vector<float> &mus_sta_qoverp() { return cms2.mus_sta_qoverp(); }
vector<float> &mus_sta_qoverpError() { return cms2.mus_sta_qoverpError(); }
vector<float> &mus_sta_z0() { return cms2.mus_sta_z0(); }
vector<float> &mus_sta_z0Err() { return cms2.mus_sta_z0Err(); }
vector<float> &mus_sta_z0corr() { return cms2.mus_sta_z0corr(); }
vector<float> &mus_timeAtIpInOut() { return cms2.mus_timeAtIpInOut(); }
vector<float> &mus_timeAtIpInOutErr() { return cms2.mus_timeAtIpInOutErr(); }
vector<float> &mus_timeAtIpOutIn() { return cms2.mus_timeAtIpOutIn(); }
vector<float> &mus_timeAtIpOutInErr() { return cms2.mus_timeAtIpOutInErr(); }
vector<float> &mus_vertexphi() { return cms2.mus_vertexphi(); }
vector<float> &mus_z0() { return cms2.mus_z0(); }
vector<float> &mus_z0Err() { return cms2.mus_z0Err(); }
vector<float> &mus_z0corr() { return cms2.mus_z0corr(); }
vector<float> &els_pat_caloIso() { return cms2.els_pat_caloIso(); }
vector<float> &els_pat_ecalIso() { return cms2.els_pat_ecalIso(); }
vector<float> &els_pat_hcalIso() { return cms2.els_pat_hcalIso(); }
vector<float> &els_pat_looseId() { return cms2.els_pat_looseId(); }
vector<float> &els_pat_robustHighEnergy() { return cms2.els_pat_robustHighEnergy(); }
vector<float> &els_pat_robustLooseId() { return cms2.els_pat_robustLooseId(); }
vector<float> &els_pat_robustTightId() { return cms2.els_pat_robustTightId(); }
vector<float> &els_pat_scE1x5() { return cms2.els_pat_scE1x5(); }
vector<float> &els_pat_scE2x5Max() { return cms2.els_pat_scE2x5Max(); }
vector<float> &els_pat_scE5x5() { return cms2.els_pat_scE5x5(); }
vector<float> &els_pat_sigmaEtaEta() { return cms2.els_pat_sigmaEtaEta(); }
vector<float> &els_pat_sigmaIEtaIEta() { return cms2.els_pat_sigmaIEtaIEta(); }
vector<float> &els_pat_tightId() { return cms2.els_pat_tightId(); }
vector<float> &els_pat_trackIso() { return cms2.els_pat_trackIso(); }
vector<float> &jets_pat_combinedSecondaryVertexBJetTag() { return cms2.jets_pat_combinedSecondaryVertexBJetTag(); }
vector<float> &jets_pat_combinedSecondaryVertexMVABJetTag() { return cms2.jets_pat_combinedSecondaryVertexMVABJetTag(); }
vector<float> &jets_pat_coneIsolationTauJetTag() { return cms2.jets_pat_coneIsolationTauJetTag(); }
vector<float> &jets_pat_impactParameterMVABJetTag() { return cms2.jets_pat_impactParameterMVABJetTag(); }
vector<float> &jets_pat_jetBProbabilityBJetTag() { return cms2.jets_pat_jetBProbabilityBJetTag(); }
vector<float> &jets_pat_jetCharge() { return cms2.jets_pat_jetCharge(); }
vector<float> &jets_pat_jetProbabilityBJetTag() { return cms2.jets_pat_jetProbabilityBJetTag(); }
vector<float> &jets_pat_noCorrF() { return cms2.jets_pat_noCorrF(); }
vector<float> &jets_pat_simpleSecondaryVertexHighEffBJetTag() { return cms2.jets_pat_simpleSecondaryVertexHighEffBJetTag(); }
vector<float> &jets_pat_simpleSecondaryVertexHighPurBJetTag() { return cms2.jets_pat_simpleSecondaryVertexHighPurBJetTag(); }
vector<float> &jets_pat_softElectronByIP3dBJetTag() { return cms2.jets_pat_softElectronByIP3dBJetTag(); }
vector<float> &jets_pat_softElectronByPtBJetTag() { return cms2.jets_pat_softElectronByPtBJetTag(); }
vector<float> &jets_pat_softMuonBJetTag() { return cms2.jets_pat_softMuonBJetTag(); }
vector<float> &jets_pat_softMuonByIP3dBJetTag() { return cms2.jets_pat_softMuonByIP3dBJetTag(); }
vector<float> &jets_pat_softMuonByPtBJetTag() { return cms2.jets_pat_softMuonByPtBJetTag(); }
vector<float> &jets_pat_trackCountingHighEffBJetTag() { return cms2.jets_pat_trackCountingHighEffBJetTag(); }
vector<float> &jets_pat_trackCountingHighPurBJetTag() { return cms2.jets_pat_trackCountingHighPurBJetTag(); }
vector<float> &mus_pat_caloIso() { return cms2.mus_pat_caloIso(); }
vector<float> &mus_pat_calovetoDep() { return cms2.mus_pat_calovetoDep(); }
vector<float> &mus_pat_ecalIso() { return cms2.mus_pat_ecalIso(); }
vector<float> &mus_pat_ecalvetoDep() { return cms2.mus_pat_ecalvetoDep(); }
vector<float> &mus_pat_hcalIso() { return cms2.mus_pat_hcalIso(); }
vector<float> &mus_pat_hcalvetoDep() { return cms2.mus_pat_hcalvetoDep(); }
vector<float> &mus_pat_trackIso() { return cms2.mus_pat_trackIso(); }
vector<float> &mus_pat_trckvetoDep() { return cms2.mus_pat_trckvetoDep(); }
vector<float> &pfels_deltaP() { return cms2.pfels_deltaP(); }
vector<float> &pfels_ecalE() { return cms2.pfels_ecalE(); }
vector<float> &pfels_hcalE() { return cms2.pfels_hcalE(); }
vector<float> &pfels_isoChargedHadrons() { return cms2.pfels_isoChargedHadrons(); }
vector<float> &pfels_isoNeutralHadrons() { return cms2.pfels_isoNeutralHadrons(); }
vector<float> &pfels_isoPhotons() { return cms2.pfels_isoPhotons(); }
vector<float> &pfels_mva_emu() { return cms2.pfels_mva_emu(); }
vector<float> &pfels_mva_epi() { return cms2.pfels_mva_epi(); }
vector<float> &pfels_mva_nothing_gamma() { return cms2.pfels_mva_nothing_gamma(); }
vector<float> &pfels_mva_nothing_nh() { return cms2.pfels_mva_nothing_nh(); }
vector<float> &pfels_mva_pimu() { return cms2.pfels_mva_pimu(); }
vector<float> &pfels_pS1E() { return cms2.pfels_pS1E(); }
vector<float> &pfels_pS2E() { return cms2.pfels_pS2E(); }
vector<float> &pfels_rawEcalE() { return cms2.pfels_rawEcalE(); }
vector<float> &pfels_rawHcalE() { return cms2.pfels_rawHcalE(); }
vector<float> &pfjets_chargedEmE() { return cms2.pfjets_chargedEmE(); }
vector<float> &pfjets_chargedHadronE() { return cms2.pfjets_chargedHadronE(); }
vector<float> &pfjets_cor() { return cms2.pfjets_cor(); }
vector<float> &pfjets_neutralEmE() { return cms2.pfjets_neutralEmE(); }
vector<float> &pfjets_neutralHadronE() { return cms2.pfjets_neutralHadronE(); }
vector<float> &pfmus_deltaP() { return cms2.pfmus_deltaP(); }
vector<float> &pfmus_ecalE() { return cms2.pfmus_ecalE(); }
vector<float> &pfmus_hcalE() { return cms2.pfmus_hcalE(); }
vector<float> &pfmus_isoChargedHadrons() { return cms2.pfmus_isoChargedHadrons(); }
vector<float> &pfmus_isoNeutralHadrons() { return cms2.pfmus_isoNeutralHadrons(); }
vector<float> &pfmus_isoPhotons() { return cms2.pfmus_isoPhotons(); }
vector<float> &pfmus_mva_emu() { return cms2.pfmus_mva_emu(); }
vector<float> &pfmus_mva_epi() { return cms2.pfmus_mva_epi(); }
vector<float> &pfmus_mva_nothing_gamma() { return cms2.pfmus_mva_nothing_gamma(); }
vector<float> &pfmus_mva_nothing_nh() { return cms2.pfmus_mva_nothing_nh(); }
vector<float> &pfmus_mva_pimu() { return cms2.pfmus_mva_pimu(); }
vector<float> &pfmus_pS1E() { return cms2.pfmus_pS1E(); }
vector<float> &pfmus_pS2E() { return cms2.pfmus_pS2E(); }
vector<float> &pfmus_rawEcalE() { return cms2.pfmus_rawEcalE(); }
vector<float> &pfmus_rawHcalE() { return cms2.pfmus_rawHcalE(); }
vector<float> &photons_e1x5() { return cms2.photons_e1x5(); }
vector<float> &photons_e2x5Max() { return cms2.photons_e2x5Max(); }
vector<float> &photons_e3x3() { return cms2.photons_e3x3(); }
vector<float> &photons_e5x5() { return cms2.photons_e5x5(); }
vector<float> &photons_ecalIso03() { return cms2.photons_ecalIso03(); }
vector<float> &photons_ecalIso04() { return cms2.photons_ecalIso04(); }
vector<float> &photons_hOverE() { return cms2.photons_hOverE(); }
vector<float> &photons_hcalIso03() { return cms2.photons_hcalIso03(); }
vector<float> &photons_hcalIso04() { return cms2.photons_hcalIso04(); }
vector<float> &photons_ntkIsoHollow03() { return cms2.photons_ntkIsoHollow03(); }
vector<float> &photons_ntkIsoHollow04() { return cms2.photons_ntkIsoHollow04(); }
vector<float> &photons_ntkIsoSolid03() { return cms2.photons_ntkIsoSolid03(); }
vector<float> &photons_ntkIsoSolid04() { return cms2.photons_ntkIsoSolid04(); }
vector<float> &photons_sigmaEtaEta() { return cms2.photons_sigmaEtaEta(); }
vector<float> &photons_sigmaIEtaIEta() { return cms2.photons_sigmaIEtaIEta(); }
vector<float> &photons_swissSeed() { return cms2.photons_swissSeed(); }
vector<float> &photons_tkIsoHollow03() { return cms2.photons_tkIsoHollow03(); }
vector<float> &photons_tkIsoHollow04() { return cms2.photons_tkIsoHollow04(); }
vector<float> &photons_tkIsoSolid03() { return cms2.photons_tkIsoSolid03(); }
vector<float> &photons_tkIsoSolid04() { return cms2.photons_tkIsoSolid04(); }
vector<float> &puInfo_instLumi() { return cms2.puInfo_instLumi(); }
vector<float> &puInfo_sump_highpt() { return cms2.puInfo_sump_highpt(); }
vector<float> &puInfo_sumpt_lowpt() { return cms2.puInfo_sumpt_lowpt(); }
vector<float> &puInfo_zpositions() { return cms2.puInfo_zpositions(); }
vector<float> &scs_clustersSize() { return cms2.scs_clustersSize(); }
vector<float> &scs_crystalsSize() { return cms2.scs_crystalsSize(); }
vector<float> &scs_e1x3() { return cms2.scs_e1x3(); }
vector<float> &scs_e1x5() { return cms2.scs_e1x5(); }
vector<float> &scs_e2nd() { return cms2.scs_e2nd(); }
vector<float> &scs_e2x2() { return cms2.scs_e2x2(); }
vector<float> &scs_e2x5Max() { return cms2.scs_e2x5Max(); }
vector<float> &scs_e3x1() { return cms2.scs_e3x1(); }
vector<float> &scs_e3x2() { return cms2.scs_e3x2(); }
vector<float> &scs_e3x3() { return cms2.scs_e3x3(); }
vector<float> &scs_e4x4() { return cms2.scs_e4x4(); }
vector<float> &scs_e5x5() { return cms2.scs_e5x5(); }
vector<float> &scs_eMax() { return cms2.scs_eMax(); }
vector<float> &scs_eSeed() { return cms2.scs_eSeed(); }
vector<float> &scs_energy() { return cms2.scs_energy(); }
vector<float> &scs_eta() { return cms2.scs_eta(); }
vector<float> &scs_hoe() { return cms2.scs_hoe(); }
vector<float> &scs_phi() { return cms2.scs_phi(); }
vector<float> &scs_preshowerEnergy() { return cms2.scs_preshowerEnergy(); }
vector<float> &scs_rawEnergy() { return cms2.scs_rawEnergy(); }
vector<float> &scs_sigmaEtaEta() { return cms2.scs_sigmaEtaEta(); }
vector<float> &scs_sigmaEtaPhi() { return cms2.scs_sigmaEtaPhi(); }
vector<float> &scs_sigmaIEtaIEta() { return cms2.scs_sigmaIEtaIEta(); }
vector<float> &scs_sigmaIEtaIEtaSC() { return cms2.scs_sigmaIEtaIEtaSC(); }
vector<float> &scs_sigmaIEtaIPhi() { return cms2.scs_sigmaIEtaIPhi(); }
vector<float> &scs_sigmaIEtaIPhiSC() { return cms2.scs_sigmaIEtaIPhiSC(); }
vector<float> &scs_sigmaIPhiIPhi() { return cms2.scs_sigmaIPhiIPhi(); }
vector<float> &scs_sigmaIPhiIPhiSC() { return cms2.scs_sigmaIPhiIPhiSC(); }
vector<float> &scs_sigmaPhiPhi() { return cms2.scs_sigmaPhiPhi(); }
vector<float> &scs_timeSeed() { return cms2.scs_timeSeed(); }
vector<float> &svs_anglePV() { return cms2.svs_anglePV(); }
vector<float> &svs_chi2() { return cms2.svs_chi2(); }
vector<float> &svs_dist3Dsig() { return cms2.svs_dist3Dsig(); }
vector<float> &svs_dist3Dval() { return cms2.svs_dist3Dval(); }
vector<float> &svs_distXYsig() { return cms2.svs_distXYsig(); }
vector<float> &svs_distXYval() { return cms2.svs_distXYval(); }
vector<float> &svs_ndof() { return cms2.svs_ndof(); }
vector<float> &svs_prob() { return cms2.svs_prob(); }
vector<float> &svs_xError() { return cms2.svs_xError(); }
vector<float> &svs_yError() { return cms2.svs_yError(); }
vector<float> &svs_zError() { return cms2.svs_zError(); }
vector<float> &mus_tcmet_deltax() { return cms2.mus_tcmet_deltax(); }
vector<float> &mus_tcmet_deltay() { return cms2.mus_tcmet_deltay(); }
vector<float> &trks_chi2() { return cms2.trks_chi2(); }
vector<float> &trks_d0() { return cms2.trks_d0(); }
vector<float> &trks_d0Err() { return cms2.trks_d0Err(); }
vector<float> &trks_d0corr() { return cms2.trks_d0corr(); }
vector<float> &trks_d0corrPhi() { return cms2.trks_d0corrPhi(); }
vector<float> &trks_d0phiCov() { return cms2.trks_d0phiCov(); }
vector<float> &trks_etaErr() { return cms2.trks_etaErr(); }
vector<float> &trks_layer1_charge() { return cms2.trks_layer1_charge(); }
vector<float> &trks_ndof() { return cms2.trks_ndof(); }
vector<float> &trks_phiErr() { return cms2.trks_phiErr(); }
vector<float> &trks_ptErr() { return cms2.trks_ptErr(); }
vector<float> &trks_z0() { return cms2.trks_z0(); }
vector<float> &trks_z0Err() { return cms2.trks_z0Err(); }
vector<float> &trks_z0corr() { return cms2.trks_z0corr(); }
vector<float> &trkjets_cor() { return cms2.trkjets_cor(); }
vector<float> &trks_d0Errvtx() { return cms2.trks_d0Errvtx(); }
vector<float> &trks_d0vtx() { return cms2.trks_d0vtx(); }
vector<float> &vtxs_chi2() { return cms2.vtxs_chi2(); }
vector<float> &vtxs_ndof() { return cms2.vtxs_ndof(); }
vector<float> &vtxs_sumpt() { return cms2.vtxs_sumpt(); }
vector<float> &vtxs_xError() { return cms2.vtxs_xError(); }
vector<float> &vtxs_yError() { return cms2.vtxs_yError(); }
vector<float> &vtxs_zError() { return cms2.vtxs_zError(); }
vector<vector<float> > &vtxs_covMatrix() { return cms2.vtxs_covMatrix(); }
int &evt_cscLooseHaloId() { return cms2.evt_cscLooseHaloId(); }
int &evt_cscTightHaloId() { return cms2.evt_cscTightHaloId(); }
int &evt_ecalLooseHaloId() { return cms2.evt_ecalLooseHaloId(); }
int &evt_ecalTightHaloId() { return cms2.evt_ecalTightHaloId(); }
int &evt_extremeTightHaloId() { return cms2.evt_extremeTightHaloId(); }
int &evt_globalLooseHaloId() { return cms2.evt_globalLooseHaloId(); }
int &evt_globalTightHaloId() { return cms2.evt_globalTightHaloId(); }
int &evt_hcalLooseHaloId() { return cms2.evt_hcalLooseHaloId(); }
int &evt_hcalTightHaloId() { return cms2.evt_hcalTightHaloId(); }
int &evt_looseHaloId() { return cms2.evt_looseHaloId(); }
int &evt_nHaloLikeTracks() { return cms2.evt_nHaloLikeTracks(); }
int &evt_nHaloTriggerCandidates() { return cms2.evt_nHaloTriggerCandidates(); }
int &evt_tightHaloId() { return cms2.evt_tightHaloId(); }
int &evt_bsType() { return cms2.evt_bsType(); }
int &evt_bunchCrossing() { return cms2.evt_bunchCrossing(); }
int &evt_experimentType() { return cms2.evt_experimentType(); }
int &evt_isRealData() { return cms2.evt_isRealData(); }
int &evt_orbitNumber() { return cms2.evt_orbitNumber(); }
int &evt_storeNumber() { return cms2.evt_storeNumber(); }
int &hcalnoise_maxHPDHits() { return cms2.hcalnoise_maxHPDHits(); }
int &hcalnoise_maxRBXHits() { return cms2.hcalnoise_maxRBXHits(); }
int &hcalnoise_maxZeros() { return cms2.hcalnoise_maxZeros(); }
int &hcalnoise_noiseFilterStatus() { return cms2.hcalnoise_noiseFilterStatus(); }
int &hcalnoise_noiseType() { return cms2.hcalnoise_noiseType(); }
int &hcalnoise_num10GeVHits() { return cms2.hcalnoise_num10GeVHits(); }
int &hcalnoise_num25GeVHits() { return cms2.hcalnoise_num25GeVHits(); }
int &hcalnoise_numProblematicRBXs() { return cms2.hcalnoise_numProblematicRBXs(); }
int &hcalnoise_passHighLevelNoiseFilter() { return cms2.hcalnoise_passHighLevelNoiseFilter(); }
int &hcalnoise_passLooseNoiseFilter() { return cms2.hcalnoise_passLooseNoiseFilter(); }
int &hcalnoise_passTightNoiseFilter() { return cms2.hcalnoise_passTightNoiseFilter(); }
int &l1_nemiso() { return cms2.l1_nemiso(); }
int &l1_nemnoiso() { return cms2.l1_nemnoiso(); }
int &l1_njetsc() { return cms2.l1_njetsc(); }
int &l1_njetsf() { return cms2.l1_njetsf(); }
int &l1_njetst() { return cms2.l1_njetst(); }
int &l1_nmus() { return cms2.l1_nmus(); }
int &pdfinfo_id1() { return cms2.pdfinfo_id1(); }
int &pdfinfo_id2() { return cms2.pdfinfo_id2(); }
int &puInfo_nPUvertices() { return cms2.puInfo_nPUvertices(); }
vector<int> &evt_ecaliPhiSuspects() { return cms2.evt_ecaliPhiSuspects(); }
vector<int> &evt_globaliPhiSuspects() { return cms2.evt_globaliPhiSuspects(); }
vector<int> &evt_hcaliPhiSuspects() { return cms2.evt_hcaliPhiSuspects(); }
vector<int> &els_mc3_id() { return cms2.els_mc3_id(); }
vector<int> &els_mc3idx() { return cms2.els_mc3idx(); }
vector<int> &els_mc3_motherid() { return cms2.els_mc3_motherid(); }
vector<int> &els_mc3_motheridx() { return cms2.els_mc3_motheridx(); }
vector<int> &els_mc_id() { return cms2.els_mc_id(); }
vector<int> &els_mcidx() { return cms2.els_mcidx(); }
vector<int> &els_mc_motherid() { return cms2.els_mc_motherid(); }
vector<int> &jets_mc3_id() { return cms2.jets_mc3_id(); }
vector<int> &jets_mc3idx() { return cms2.jets_mc3idx(); }
vector<int> &jets_mc_gpidx() { return cms2.jets_mc_gpidx(); }
vector<int> &jets_mc_id() { return cms2.jets_mc_id(); }
vector<int> &jets_mcidx() { return cms2.jets_mcidx(); }
vector<int> &jets_mc_motherid() { return cms2.jets_mc_motherid(); }
vector<int> &mus_mc3_id() { return cms2.mus_mc3_id(); }
vector<int> &mus_mc3idx() { return cms2.mus_mc3idx(); }
vector<int> &mus_mc3_motherid() { return cms2.mus_mc3_motherid(); }
vector<int> &mus_mc3_motheridx() { return cms2.mus_mc3_motheridx(); }
vector<int> &mus_mc_id() { return cms2.mus_mc_id(); }
vector<int> &mus_mcidx() { return cms2.mus_mcidx(); }
vector<int> &mus_mc_motherid() { return cms2.mus_mc_motherid(); }
vector<int> &pfjets_mc3_id() { return cms2.pfjets_mc3_id(); }
vector<int> &pfjets_mc3idx() { return cms2.pfjets_mc3idx(); }
vector<int> &pfjets_mc_gpidx() { return cms2.pfjets_mc_gpidx(); }
vector<int> &pfjets_mc_id() { return cms2.pfjets_mc_id(); }
vector<int> &pfjets_mcidx() { return cms2.pfjets_mcidx(); }
vector<int> &pfjets_mc_motherid() { return cms2.pfjets_mc_motherid(); }
vector<int> &photons_mc3_id() { return cms2.photons_mc3_id(); }
vector<int> &photons_mc3idx() { return cms2.photons_mc3idx(); }
vector<int> &photons_mc3_motherid() { return cms2.photons_mc3_motherid(); }
vector<int> &photons_mc3_motheridx() { return cms2.photons_mc3_motheridx(); }
vector<int> &photons_mc_id() { return cms2.photons_mc_id(); }
vector<int> &photons_mcidx() { return cms2.photons_mcidx(); }
vector<int> &photons_mc_motherid() { return cms2.photons_mc_motherid(); }
vector<int> &trk_mc3_id() { return cms2.trk_mc3_id(); }
vector<int> &trk_mc3idx() { return cms2.trk_mc3idx(); }
vector<int> &trk_mc3_motherid() { return cms2.trk_mc3_motherid(); }
vector<int> &trk_mc3_motheridx() { return cms2.trk_mc3_motheridx(); }
vector<int> &trk_mc_id() { return cms2.trk_mc_id(); }
vector<int> &trk_mcidx() { return cms2.trk_mcidx(); }
vector<int> &trk_mc_motherid() { return cms2.trk_mc_motherid(); }
vector<int> &trks_conv_tkidx() { return cms2.trks_conv_tkidx(); }
vector<int> &els_exp_innerlayers39X() { return cms2.els_exp_innerlayers39X(); }
vector<int> &els_closestJet() { return cms2.els_closestJet(); }
vector<int> &els_closestMuon() { return cms2.els_closestMuon(); }
vector<int> &els_pfelsidx() { return cms2.els_pfelsidx(); }
vector<int> &els_category() { return cms2.els_category(); }
vector<int> &els_charge() { return cms2.els_charge(); }
vector<int> &els_class() { return cms2.els_class(); }
vector<int> &els_conv_tkidx() { return cms2.els_conv_tkidx(); }
vector<int> &els_exp_innerlayers() { return cms2.els_exp_innerlayers(); }
vector<int> &els_exp_outerlayers() { return cms2.els_exp_outerlayers(); }
vector<int> &els_fiduciality() { return cms2.els_fiduciality(); }
vector<int> &els_gsftrkidx() { return cms2.els_gsftrkidx(); }
vector<int> &els_layer1_det() { return cms2.els_layer1_det(); }
vector<int> &els_layer1_layer() { return cms2.els_layer1_layer(); }
vector<int> &els_layer1_sizerphi() { return cms2.els_layer1_sizerphi(); }
vector<int> &els_layer1_sizerz() { return cms2.els_layer1_sizerz(); }
vector<int> &els_lostHits() { return cms2.els_lostHits(); }
vector<int> &els_lost_pixelhits() { return cms2.els_lost_pixelhits(); }
vector<int> &els_nSeed() { return cms2.els_nSeed(); }
vector<int> &els_sccharge() { return cms2.els_sccharge(); }
vector<int> &els_scindex() { return cms2.els_scindex(); }
vector<int> &els_trk_charge() { return cms2.els_trk_charge(); }
vector<int> &els_trkidx() { return cms2.els_trkidx(); }
vector<int> &els_type() { return cms2.els_type(); }
vector<int> &els_validHits() { return cms2.els_validHits(); }
vector<int> &els_valid_pixelhits() { return cms2.els_valid_pixelhits(); }
vector<int> &genps_id() { return cms2.genps_id(); }
vector<int> &genps_id_mother() { return cms2.genps_id_mother(); }
vector<int> &genps_status() { return cms2.genps_status(); }
vector<int> &gsftrks_charge() { return cms2.gsftrks_charge(); }
vector<int> &gsftrks_exp_innerlayers() { return cms2.gsftrks_exp_innerlayers(); }
vector<int> &gsftrks_exp_outerlayers() { return cms2.gsftrks_exp_outerlayers(); }
vector<int> &gsftrks_layer1_det() { return cms2.gsftrks_layer1_det(); }
vector<int> &gsftrks_layer1_layer() { return cms2.gsftrks_layer1_layer(); }
vector<int> &gsftrks_layer1_sizerphi() { return cms2.gsftrks_layer1_sizerphi(); }
vector<int> &gsftrks_layer1_sizerz() { return cms2.gsftrks_layer1_sizerz(); }
vector<int> &gsftrks_lostHits() { return cms2.gsftrks_lostHits(); }
vector<int> &gsftrks_lost_pixelhits() { return cms2.gsftrks_lost_pixelhits(); }
vector<int> &gsftrks_nlayers() { return cms2.gsftrks_nlayers(); }
vector<int> &gsftrks_nlayers3D() { return cms2.gsftrks_nlayers3D(); }
vector<int> &gsftrks_nlayersLost() { return cms2.gsftrks_nlayersLost(); }
vector<int> &gsftrks_validHits() { return cms2.gsftrks_validHits(); }
vector<int> &gsftrks_valid_pixelhits() { return cms2.gsftrks_valid_pixelhits(); }
vector<int> &hyp_ll_charge() { return cms2.hyp_ll_charge(); }
vector<int> &hyp_ll_id() { return cms2.hyp_ll_id(); }
vector<int> &hyp_ll_index() { return cms2.hyp_ll_index(); }
vector<int> &hyp_ll_lostHits() { return cms2.hyp_ll_lostHits(); }
vector<int> &hyp_ll_validHits() { return cms2.hyp_ll_validHits(); }
vector<int> &hyp_lt_charge() { return cms2.hyp_lt_charge(); }
vector<int> &hyp_lt_id() { return cms2.hyp_lt_id(); }
vector<int> &hyp_lt_index() { return cms2.hyp_lt_index(); }
vector<int> &hyp_lt_lostHits() { return cms2.hyp_lt_lostHits(); }
vector<int> &hyp_lt_validHits() { return cms2.hyp_lt_validHits(); }
vector<int> &hyp_njets() { return cms2.hyp_njets(); }
vector<int> &hyp_nojets() { return cms2.hyp_nojets(); }
vector<int> &hyp_type() { return cms2.hyp_type(); }
vector<int> &hyp_FVFit_ndf() { return cms2.hyp_FVFit_ndf(); }
vector<int> &hyp_FVFit_status() { return cms2.hyp_FVFit_status(); }
vector<int> &hyp_ll_mc_id() { return cms2.hyp_ll_mc_id(); }
vector<int> &hyp_ll_mc_motherid() { return cms2.hyp_ll_mc_motherid(); }
vector<int> &hyp_lt_mc_id() { return cms2.hyp_lt_mc_id(); }
vector<int> &hyp_lt_mc_motherid() { return cms2.hyp_lt_mc_motherid(); }
vector<int> &hyp_quadlep_first_type() { return cms2.hyp_quadlep_first_type(); }
vector<int> &hyp_quadlep_fourth_type() { return cms2.hyp_quadlep_fourth_type(); }
vector<int> &hyp_quadlep_second_type() { return cms2.hyp_quadlep_second_type(); }
vector<int> &hyp_quadlep_third_type() { return cms2.hyp_quadlep_third_type(); }
vector<int> &hyp_trilep_first_type() { return cms2.hyp_trilep_first_type(); }
vector<int> &hyp_trilep_second_type() { return cms2.hyp_trilep_second_type(); }
vector<int> &hyp_trilep_third_type() { return cms2.hyp_trilep_third_type(); }
vector<int> &jets_closestElectron() { return cms2.jets_closestElectron(); }
vector<int> &jets_closestMuon() { return cms2.jets_closestMuon(); }
vector<int> &l1_emiso_ieta() { return cms2.l1_emiso_ieta(); }
vector<int> &l1_emiso_iphi() { return cms2.l1_emiso_iphi(); }
vector<int> &l1_emiso_rawId() { return cms2.l1_emiso_rawId(); }
vector<int> &l1_emiso_type() { return cms2.l1_emiso_type(); }
vector<int> &l1_emnoiso_ieta() { return cms2.l1_emnoiso_ieta(); }
vector<int> &l1_emnoiso_iphi() { return cms2.l1_emnoiso_iphi(); }
vector<int> &l1_emnoiso_rawId() { return cms2.l1_emnoiso_rawId(); }
vector<int> &l1_emnoiso_type() { return cms2.l1_emnoiso_type(); }
vector<int> &l1_jetsc_ieta() { return cms2.l1_jetsc_ieta(); }
vector<int> &l1_jetsc_iphi() { return cms2.l1_jetsc_iphi(); }
vector<int> &l1_jetsc_rawId() { return cms2.l1_jetsc_rawId(); }
vector<int> &l1_jetsc_type() { return cms2.l1_jetsc_type(); }
vector<int> &l1_jetsf_ieta() { return cms2.l1_jetsf_ieta(); }
vector<int> &l1_jetsf_iphi() { return cms2.l1_jetsf_iphi(); }
vector<int> &l1_jetsf_rawId() { return cms2.l1_jetsf_rawId(); }
vector<int> &l1_jetsf_type() { return cms2.l1_jetsf_type(); }
vector<int> &l1_jetst_ieta() { return cms2.l1_jetst_ieta(); }
vector<int> &l1_jetst_iphi() { return cms2.l1_jetst_iphi(); }
vector<int> &l1_jetst_rawId() { return cms2.l1_jetst_rawId(); }
vector<int> &l1_jetst_type() { return cms2.l1_jetst_type(); }
vector<int> &l1_mus_flags() { return cms2.l1_mus_flags(); }
vector<int> &l1_mus_q() { return cms2.l1_mus_q(); }
vector<int> &l1_mus_qual() { return cms2.l1_mus_qual(); }
vector<int> &l1_mus_qualFlags() { return cms2.l1_mus_qualFlags(); }
vector<int> &mus_met_flag() { return cms2.mus_met_flag(); }
vector<int> &mus_closestEle() { return cms2.mus_closestEle(); }
vector<int> &mus_closestJet() { return cms2.mus_closestJet(); }
vector<int> &mus_pfmusidx() { return cms2.mus_pfmusidx(); }
vector<int> &mus_charge() { return cms2.mus_charge(); }
vector<int> &mus_chi2LocalMomentum() { return cms2.mus_chi2LocalMomentum(); }
vector<int> &mus_chi2LocalPosition() { return cms2.mus_chi2LocalPosition(); }
vector<int> &mus_gfit_validHits() { return cms2.mus_gfit_validHits(); }
vector<int> &mus_gfit_validSTAHits() { return cms2.mus_gfit_validSTAHits(); }
vector<int> &mus_gfit_validSiHits() { return cms2.mus_gfit_validSiHits(); }
vector<int> &mus_glbKink() { return cms2.mus_glbKink(); }
vector<int> &mus_glbTrackProbability() { return cms2.mus_glbTrackProbability(); }
vector<int> &mus_globalDeltaEtaPhi() { return cms2.mus_globalDeltaEtaPhi(); }
vector<int> &mus_goodmask() { return cms2.mus_goodmask(); }
vector<int> &mus_iso03_ntrk() { return cms2.mus_iso03_ntrk(); }
vector<int> &mus_iso05_ntrk() { return cms2.mus_iso05_ntrk(); }
vector<int> &mus_localDistance() { return cms2.mus_localDistance(); }
vector<int> &mus_lostHits() { return cms2.mus_lostHits(); }
vector<int> &mus_nOverlaps() { return cms2.mus_nOverlaps(); }
vector<int> &mus_nmatches() { return cms2.mus_nmatches(); }
vector<int> &mus_overlap0() { return cms2.mus_overlap0(); }
vector<int> &mus_overlap1() { return cms2.mus_overlap1(); }
vector<int> &mus_pid_TM2DCompatibilityLoose() { return cms2.mus_pid_TM2DCompatibilityLoose(); }
vector<int> &mus_pid_TM2DCompatibilityTight() { return cms2.mus_pid_TM2DCompatibilityTight(); }
vector<int> &mus_pid_TMLastStationLoose() { return cms2.mus_pid_TMLastStationLoose(); }
vector<int> &mus_pid_TMLastStationTight() { return cms2.mus_pid_TMLastStationTight(); }
vector<int> &mus_staRelChi2() { return cms2.mus_staRelChi2(); }
vector<int> &mus_sta_validHits() { return cms2.mus_sta_validHits(); }
vector<int> &mus_timeDirection() { return cms2.mus_timeDirection(); }
vector<int> &mus_timeNumStationsUsed() { return cms2.mus_timeNumStationsUsed(); }
vector<int> &mus_trkKink() { return cms2.mus_trkKink(); }
vector<int> &mus_trkRelChi2() { return cms2.mus_trkRelChi2(); }
vector<int> &mus_trk_charge() { return cms2.mus_trk_charge(); }
vector<int> &mus_trkidx() { return cms2.mus_trkidx(); }
vector<int> &mus_type() { return cms2.mus_type(); }
vector<int> &mus_validHits() { return cms2.mus_validHits(); }
vector<int> &els_pat_genID() { return cms2.els_pat_genID(); }
vector<int> &els_pat_genMotherID() { return cms2.els_pat_genMotherID(); }
vector<int> &jets_pat_genPartonMother_id() { return cms2.jets_pat_genPartonMother_id(); }
vector<int> &jets_pat_genParton_id() { return cms2.jets_pat_genParton_id(); }
vector<int> &jets_pat_jetIDLoose() { return cms2.jets_pat_jetIDLoose(); }
vector<int> &jets_pat_jetIDLooseAOD() { return cms2.jets_pat_jetIDLooseAOD(); }
vector<int> &jets_pat_jetIDMinimal() { return cms2.jets_pat_jetIDMinimal(); }
vector<int> &jets_pat_jetIDTight() { return cms2.jets_pat_jetIDTight(); }
vector<int> &jets_pat_partonFlavour() { return cms2.jets_pat_partonFlavour(); }
vector<int> &mus_pat_genID() { return cms2.mus_pat_genID(); }
vector<int> &mus_pat_genMotherID() { return cms2.mus_pat_genMotherID(); }
vector<int> &pfels_elsidx() { return cms2.pfels_elsidx(); }
vector<int> &pfels_charge() { return cms2.pfels_charge(); }
vector<int> &pfels_flag() { return cms2.pfels_flag(); }
vector<int> &pfels_particleId() { return cms2.pfels_particleId(); }
vector<int> &pfjets_chargedMultiplicity() { return cms2.pfjets_chargedMultiplicity(); }
vector<int> &pfjets_muonMultiplicity() { return cms2.pfjets_muonMultiplicity(); }
vector<int> &pfjets_neutralMultiplicity() { return cms2.pfjets_neutralMultiplicity(); }
vector<int> &pfmus_musidx() { return cms2.pfmus_musidx(); }
vector<int> &pfmus_charge() { return cms2.pfmus_charge(); }
vector<int> &pfmus_flag() { return cms2.pfmus_flag(); }
vector<int> &pfmus_particleId() { return cms2.pfmus_particleId(); }
vector<int> &photons_fiduciality() { return cms2.photons_fiduciality(); }
vector<int> &photons_scindex() { return cms2.photons_scindex(); }
vector<int> &puInfo_ntrks_highpt() { return cms2.puInfo_ntrks_highpt(); }
vector<int> &puInfo_ntrks_lowpt() { return cms2.puInfo_ntrks_lowpt(); }
vector<int> &scs_detIdSeed() { return cms2.scs_detIdSeed(); }
vector<int> &scs_elsidx() { return cms2.scs_elsidx(); }
vector<int> &scs_severitySeed() { return cms2.scs_severitySeed(); }
vector<int> &svs_isKs() { return cms2.svs_isKs(); }
vector<int> &svs_isLambda() { return cms2.svs_isLambda(); }
vector<int> &svs_mc3_id() { return cms2.svs_mc3_id(); }
vector<int> &svs_nTrks() { return cms2.svs_nTrks(); }
vector<int> &mus_tcmet_flag() { return cms2.mus_tcmet_flag(); }
vector<int> &trks_algo() { return cms2.trks_algo(); }
vector<int> &trks_charge() { return cms2.trks_charge(); }
vector<int> &trks_exp_innerlayers() { return cms2.trks_exp_innerlayers(); }
vector<int> &trks_exp_outerlayers() { return cms2.trks_exp_outerlayers(); }
vector<int> &trks_layer1_det() { return cms2.trks_layer1_det(); }
vector<int> &trks_layer1_layer() { return cms2.trks_layer1_layer(); }
vector<int> &trks_layer1_sizerphi() { return cms2.trks_layer1_sizerphi(); }
vector<int> &trks_layer1_sizerz() { return cms2.trks_layer1_sizerz(); }
vector<int> &trks_lostHits() { return cms2.trks_lostHits(); }
vector<int> &trks_lost_pixelhits() { return cms2.trks_lost_pixelhits(); }
vector<int> &trks_nlayers() { return cms2.trks_nlayers(); }
vector<int> &trks_nlayers3D() { return cms2.trks_nlayers3D(); }
vector<int> &trks_nlayersLost() { return cms2.trks_nlayersLost(); }
vector<int> &trks_qualityMask() { return cms2.trks_qualityMask(); }
vector<int> &trks_validHits() { return cms2.trks_validHits(); }
vector<int> &trks_valid_pixelhits() { return cms2.trks_valid_pixelhits(); }
vector<int> &trks_elsidx() { return cms2.trks_elsidx(); }
vector<int> &trk_musidx() { return cms2.trk_musidx(); }
vector<int> &trkjets_ntrks() { return cms2.trkjets_ntrks(); }
vector<int> &trkjets_vtxs_idx() { return cms2.trkjets_vtxs_idx(); }
vector<int> &vtxs_isFake() { return cms2.vtxs_isFake(); }
vector<int> &vtxs_isValid() { return cms2.vtxs_isValid(); }
vector<int> &vtxs_tracksSize() { return cms2.vtxs_tracksSize(); }
vector<vector<int> > &genps_lepdaughter_id() { return cms2.genps_lepdaughter_id(); }
vector<vector<int> > &genps_lepdaughter_idx() { return cms2.genps_lepdaughter_idx(); }
vector<vector<int> > &hlt_trigObjs_id() { return cms2.hlt_trigObjs_id(); }
vector<vector<int> > &hyp_jets_idx() { return cms2.hyp_jets_idx(); }
vector<vector<int> > &hyp_other_jets_idx() { return cms2.hyp_other_jets_idx(); }
unsigned int &evt_nels() { return cms2.evt_nels(); }
unsigned int &evt_detectorStatus() { return cms2.evt_detectorStatus(); }
unsigned int &evt_event() { return cms2.evt_event(); }
unsigned int &evt_lumiBlock() { return cms2.evt_lumiBlock(); }
unsigned int &evt_run() { return cms2.evt_run(); }
unsigned int &genps_flavorHistoryFilterResult() { return cms2.genps_flavorHistoryFilterResult(); }
unsigned int &evt_ngenjets() { return cms2.evt_ngenjets(); }
unsigned int &genps_signalProcessID() { return cms2.genps_signalProcessID(); }
unsigned int &hlt_bits1() { return cms2.hlt_bits1(); }
unsigned int &hlt_bits2() { return cms2.hlt_bits2(); }
unsigned int &hlt_bits3() { return cms2.hlt_bits3(); }
unsigned int &hlt_bits4() { return cms2.hlt_bits4(); }
unsigned int &hlt_bits5() { return cms2.hlt_bits5(); }
unsigned int &hlt_bits6() { return cms2.hlt_bits6(); }
unsigned int &hlt_bits7() { return cms2.hlt_bits7(); }
unsigned int &hlt_bits8() { return cms2.hlt_bits8(); }
unsigned int &evt_njets() { return cms2.evt_njets(); }
unsigned int &evt_njpts() { return cms2.evt_njpts(); }
unsigned int &l1_bits1() { return cms2.l1_bits1(); }
unsigned int &l1_bits2() { return cms2.l1_bits2(); }
unsigned int &l1_bits3() { return cms2.l1_bits3(); }
unsigned int &l1_bits4() { return cms2.l1_bits4(); }
unsigned int &l1_techbits1() { return cms2.l1_techbits1(); }
unsigned int &l1_techbits2() { return cms2.l1_techbits2(); }
unsigned int &evt_nphotons() { return cms2.evt_nphotons(); }
unsigned int &evt_ecalRecoStatus() { return cms2.evt_ecalRecoStatus(); }
unsigned int &evt_nscs() { return cms2.evt_nscs(); }
unsigned int &evt_ntrkjets() { return cms2.evt_ntrkjets(); }
unsigned int &evt_nvtxs() { return cms2.evt_nvtxs(); }
vector<unsigned int> &hlt_prescales() { return cms2.hlt_prescales(); }
vector<unsigned int> &hyp_quadlep_bucket() { return cms2.hyp_quadlep_bucket(); }
vector<unsigned int> &hyp_quadlep_first_index() { return cms2.hyp_quadlep_first_index(); }
vector<unsigned int> &hyp_quadlep_fourth_index() { return cms2.hyp_quadlep_fourth_index(); }
vector<unsigned int> &hyp_quadlep_second_index() { return cms2.hyp_quadlep_second_index(); }
vector<unsigned int> &hyp_quadlep_third_index() { return cms2.hyp_quadlep_third_index(); }
vector<unsigned int> &hyp_trilep_bucket() { return cms2.hyp_trilep_bucket(); }
vector<unsigned int> &hyp_trilep_first_index() { return cms2.hyp_trilep_first_index(); }
vector<unsigned int> &hyp_trilep_second_index() { return cms2.hyp_trilep_second_index(); }
vector<unsigned int> &hyp_trilep_third_index() { return cms2.hyp_trilep_third_index(); }
vector<unsigned int> &l1_prescales() { return cms2.l1_prescales(); }
vector<unsigned int> &l1_techtrigprescales() { return cms2.l1_techtrigprescales(); }
vector<unsigned int> &els_pat_flag() { return cms2.els_pat_flag(); }
vector<unsigned int> &jets_pat_flag() { return cms2.jets_pat_flag(); }
vector<unsigned int> &mus_pat_flag() { return cms2.mus_pat_flag(); }
int &evt_nEvts() { return cms2.evt_nEvts(); }
float &evt_filt_eff() { return cms2.evt_filt_eff(); }
bool passHLTTrigger(TString trigName) { return cms2.passHLTTrigger(trigName); }
bool passL1Trigger(TString trigName) { return cms2.passL1Trigger(trigName); }
}
| [
"benhoob"
] | benhoob |
3f50d57c8fadce77be4befbe7ed8939d7728146c | fbe77e9e2a53a4600a1d9b00b5f2c29ee3e8c59a | /externals/binaryen/test/emscripten/tests/box2d/glui/glui_node.cpp | 96aa1dd951dd42a681bdf8eede63e6cd4b43736e | [
"LGPL-2.0-or-later",
"Zlib",
"Apache-2.0",
"MIT",
"NCSA",
"BSD-3-Clause"
] | permissive | AcuteAngleCloud/Acute-Angle-Chain | 8d4a1ad714f6de1493954326e109b6af112561b9 | 5ea50bee042212ccff797ece5018c64f3f50ceff | refs/heads/master | 2021-04-26T21:52:25.560457 | 2020-03-21T07:29:06 | 2020-03-21T07:29:06 | 124,164,376 | 10 | 5 | MIT | 2020-07-16T07:14:45 | 2018-03-07T02:03:53 | C++ | UTF-8 | C++ | false | false | 7,099 | cpp | /****************************************************************************
GLUI User Interface Toolkit
---------------------------
glui_node.cpp - linked-list tree structure
--------------------------------------------------
Copyright (c) 1998 Paul Rademacher
WWW: http://sourceforge.net/projects/glui/
Forums: http://sourceforge.net/forum/?group_id=92496
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*****************************************************************************/
#include "glui.h"
#include "glui_internal.h"
/********************************************* GLUI_Node::GLUI_Node() *******/
GLUI_Node::GLUI_Node()
:
parent_node(NULL),
child_head(NULL),
child_tail(NULL),
next_sibling(NULL),
prev_sibling(NULL)
{
}
/********************************************* GLUI_Node::first() *******/
/* Returns first sibling in 'this' node's sibling list */
GLUI_Node *GLUI_Node::first_sibling( void )
{
if ( parent_node == NULL )
return this; /* root node has no siblings */
else
return parent_node->child_head;
}
/******************************************** GLUI_Node::next() ********/
/* Returns next sibling in 'this' node's sibling list */
GLUI_Node *GLUI_Node::next( void )
{
return next_sibling;
}
/******************************************** GLUI_Node::prev() ********/
/* Returns prev sibling in 'this' node's sibling list */
GLUI_Node *GLUI_Node::prev( void )
{
return prev_sibling;
}
/********************************************* GLUI_Node::last() *******/
/* Returns last sibling in 'this' node's sibling list */
GLUI_Node *GLUI_Node::last_sibling( void )
{
if ( parent_node == NULL )
return this; /* root node has no siblings */
else
return parent_node->child_tail;
}
/*************************** GLUI_Node::link_this_to_parent_last() *******/
/* Links as last child of parent */
void GLUI_Node::link_this_to_parent_last( GLUI_Node *new_parent )
{
if ( new_parent->child_tail == NULL ) { /* parent has no children */
new_parent->child_head = this;
new_parent->child_tail = this;
this->parent_node = new_parent;
}
else { /* parent has children */
new_parent->child_tail->next_sibling = this;
this->prev_sibling = new_parent->child_tail;
new_parent->child_tail = this;
this->parent_node = new_parent;
}
}
/*************************** GLUI_Node::link_this_to_parent_first() *******/
/* Links as first child of parent */
void GLUI_Node::link_this_to_parent_first( GLUI_Node *new_parent )
{
if ( new_parent->child_head == NULL ) { /* parent has no children */
new_parent->child_head = this;
new_parent->child_tail = this;
this->parent_node = new_parent;
}
else { /* parent has children */
new_parent->child_head->prev_sibling = this;
this->next_sibling = new_parent->child_head;
new_parent->child_head = this;
this->parent_node = new_parent;
}
}
/**************************** GLUI_Node::link_this_to_sibling_next() *****/
void GLUI_Node::link_this_to_sibling_next( GLUI_Node *sibling )
{
if ( sibling->next_sibling == NULL ) { /* node has no next sibling */
sibling->next_sibling = this;
this->prev_sibling = sibling;
/* This was the parent's last child, so update that as well */
if ( sibling->parent_node != NULL ) {
sibling->parent_node->child_tail = this;
}
}
else { /* node already has a next sibling */
sibling->next_sibling->prev_sibling = this;
this->next_sibling = sibling->next_sibling;
sibling->next_sibling = this;
this->prev_sibling = sibling;
}
this->parent_node = sibling->parent_node;
}
/**************************** GLUI_Node::link_this_to_sibling_prev() *****/
void GLUI_Node::link_this_to_sibling_prev( GLUI_Node *sibling )
{
if ( sibling->prev_sibling == NULL ) { /* node has no prev sibling */
sibling->prev_sibling = this;
this->next_sibling = sibling;
/* This was the parent's first child, so update that as well */
if ( sibling->parent_node != NULL ) {
sibling->parent_node->child_head = this;
}
}
else { /* node already has a prev sibling */
sibling->prev_sibling->next_sibling = this;
this->prev_sibling = sibling->prev_sibling;
sibling->prev_sibling = this;
this->next_sibling = sibling;
}
this->parent_node = sibling->parent_node;
}
/**************************************** GLUI_Node::unlink() **************/
void GLUI_Node::unlink( void )
{
/* Unlink from prev sibling */
if ( this->prev_sibling != NULL ) {
this->prev_sibling->next_sibling = this->next_sibling;
}
else { /* No prev sibling: this was parent's first child */
this->parent_node->child_head = this->next_sibling;
}
/* Unlink from next sibling */
if ( this->next_sibling != NULL ) {
this->next_sibling->prev_sibling = this->prev_sibling;
}
else { /* No next sibling: this was parent's last child */
this->parent_node->child_tail = this->prev_sibling;
}
this->parent_node = NULL;
this->next_sibling = NULL;
this->prev_sibling = NULL;
this->child_head = NULL;
this->child_tail = NULL;
}
/**************************************** GLUI_Node::dump() **************/
void GLUI_Node::dump( FILE *out, const char *name )
{
fprintf( out, "GLUI_node: %s\n", name );
fprintf( out, " parent: %p child_head: %p child_tail: %p\n",
(void *) parent_node,
(void *) child_head,
(void *) child_tail );
fprintf( out, " next: %p prev: %p\n",
(void *) next_sibling,
(void *) prev_sibling );
}
| [
"[email protected]"
] | |
6e3a6e218423afbc8b1eb8816cc1610f17f0d0cf | 11a09372cf812213ee88a5059e9f868f97faf309 | /Hackerrank/SinglyLinkedList.cpp | 51bd33e946c4d2dcd817338a93137976e7354a0f | [] | no_license | RavirajWalke/online-contests | 52a755ae064caa9e70d0c847a64f2e9869090073 | bb61acd82ba852fdc2f8700ea27002a1a0215805 | refs/heads/master | 2020-03-14T02:58:02.353799 | 2018-04-28T13:13:23 | 2018-04-28T13:13:23 | 131,410,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,939 | cpp | /**
*
* @author Ravi
*/
/*
* C++ Program to Implement Singly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *next;
}*start;
/*
* Class Declaration
*/
class single_llist
{
public:
node* create_node(int);
void insert_begin();
void insert_pos();
void insert_last();
void delete_pos();
void sort();
void search();
void update();
void reverse();
void display();
single_llist()
{
start = NULL;
}
};
/*
* Main :contains menu
*/
main()
{
int choice, nodes, element, position, i;
single_llist sl;
start = NULL;
while (1)
{
cout<<endl<<"---------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------"<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl;
cout<<"3.Insert node at position"<<endl;
cout<<"4.Sort Link List"<<endl;
cout<<"5.Delete a Particular Node"<<endl;
cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl;
cout<<"8.Display Linked List"<<endl;
cout<<"9.Reverse Linked List "<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break;
case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last();
cout<<endl;
break;
case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break;
case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
cout<<endl;
break;
case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break;
case 6:
cout<<"Update Node Value:"<<endl;
sl.update();
cout<<endl;
break;
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search();
cout<<endl;
break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display();
cout<<endl;
break;
case 9:
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl;
break;
case 10:
cout<<"Exiting..."<<endl;
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
/*
* Creating Node
*/
node *single_llist::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
/*
* Inserting element in beginning
*/
void single_llist::insert_begin()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
p = start;
start = temp;
start->next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}
/*
* Inserting Node at last
*/
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
}
/*
* Insertion of node at a given position
*/
void single_llist::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if (pos > 1 && pos <= counter)
{
s = start;
for (i = 1; i < pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
}
}
/*
* Sorting Link List
*/
void single_llist::sort()
{
struct node *ptr, *s;
int value;
if (start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}
ptr = start;
while (ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->info > s->info)
{
value = ptr->info;
ptr->info = s->info;
s->info = value;
}
}
ptr = ptr->next;
}
}
/*
* Delete element at a given position
*/
void single_llist::delete_pos()
{
int pos, i, counter = 0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
/*
* Update a given Node
*/
void single_llist::update()
{
int value, pos, i;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start->info = value;
}
else
{
for (i = 0;i < pos - 1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return;
}
s = s->next;
}
s->info = value;
}
cout<<"Node Updated"<<endl;
}
/*
* Searching an element
*/
void single_llist::search()
{
int value, pos = 0;
bool flag = false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->info == value)
{
flag = true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
}
s = s->next;
}
if (!flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
}
/*
* Reverse Link List
*/
void single_llist::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{
return;
}
ptr1 = start;
ptr2 = ptr1->next;
ptr3 = ptr2->next;
ptr1->next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)
{
ptr1 = ptr2;
ptr2 = ptr3;
ptr3 = ptr3->next;
ptr2->next = ptr1;
}
start = ptr2;
}
/*
* Display Elements of a link list
*/
void single_llist::display()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
| [
"[email protected]"
] | |
0ce0c2375794f9d15b8a9491271656db23f48041 | f24c8ebbb716d10eeba9b2fc6d231635ecd91f95 | /smiesd2/lab05/1001.cpp | 04df4b0bf793b78c49b0d3d8b0117f8649a851d2 | [] | no_license | zhiqiu/sicily | b6f7de28e7bbe9cddef5d11592017ea9b2df052b | f874a31af950148583101d6e5c96305afbe79d5b | refs/heads/master | 2021-01-22T17:14:29.776931 | 2015-10-10T01:59:16 | 2015-10-10T01:59:16 | 26,812,506 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include <iostream>
using namespace std;
class student{
private:
int id;
int score;
public:
student(){
id = 0;
score = 0;
}
student(int a, int b): id(a), score(b){}
void set(int a, int b){
this->id = a;
this->score = b;
}
int getid(){
return id;
}
int getscore(){
return score;
}
};
int main() {
student sd[5];
for(int i = 0; i < 5; i++){
int sid, score;
cin >> sid >> score;
sd[i].set(sid, score);
}
for(int i = 0; i < 5; i += 2){
cout << (sd+i) -> getid() <<" " << (sd+i) -> getscore() << endl;
}
return 0;
}
| [
"[email protected]"
] | |
d9e6f38225a7e204cc5e2406e9dd82b95e7f09d2 | aa3d6a8a6e8e75d968786ed1900564baaad1bb62 | /AOJ/V21/2101.cpp | 8bdfa9f7e7a85a0add1453ed8cbce0924548a84b | [] | no_license | Halksel/Competition | 418b18981d4eb30572e6f24401f53968c5e9c354 | ce9ea74410a63ad2c4de23dee33698d23afb01b1 | refs/heads/master | 2021-01-23T21:46:52.925976 | 2019-08-25T13:07:44 | 2019-08-25T13:07:44 | 59,487,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | #include <bits/stdc++.h>
using namespace std ;
#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) (r).begin(),(r).end()
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init))
#define mp(a,b) make_pair(a,b)
#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;
const int mod = 1000000007;
constexpr int inf = ((1<<30)-1)*2+1 ;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};
inline bool value(int x,int y,int w,int h){
return (x >= 0 && x < w && y >= 0 && y < h);
}
template<typename T>
void Unique(vector<T> &v){
sort(all(v));
v.erase(unique(all(v)),v.end());
}
template<typename T>
T ston(string& str, T n){
istringstream sin(str) ;
T num ;
sin >> num ;
return num ;
}
void solve(int k){
ll res = 0;
REP(i,1,sqrt(k)+1){
if(k % i == 0 && k != i){
res += i;
if(i != k/i && k/i != k){
res += k/i;
}
}
}
string s[3] = {"deficient number","abundant number","perfect number"};
if(k == res) cout << s[2] << endl;
else if(k < res) cout << s[1] << endl;
else cout << s[0] << endl;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll n;
while(cin >> n && n){
solve(n);
}
return 0;
}
| [
"[email protected]"
] | |
f05ae8c88eebd8bf3d53ee4d888fa97a665de4d7 | b4a537160bc8aee055534280b8564992d05d4245 | /11000/11066.cpp | 59c6425605525aced69476ab4ed780e69500ca78 | [] | no_license | kadragon/acmicpc | c90d8658969d9bcbecd7ac45a188ac1ad4ad1dd3 | b76bb7b545256631212ea0a2010d2c485dbd3e40 | refs/heads/master | 2021-07-13T01:45:03.963267 | 2021-04-18T07:33:08 | 2021-04-18T07:33:08 | 244,813,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | //
// Created by kangdonguk on 2020/04/04.
//
// https://www.acmicpc.net/problem/11066
// 파일 합치기
#define min(a, b) ((a) < (b) ? (a): (b))
#include <stdio.h>
int dp[501][501], d[501], sum[501];
int f(int s, int e) {
if (dp[s][e])
return dp[s][e];
if (s == e)
return 0;
if (e - s == 1)
return d[s] + d[e];
dp[s][e] = 987654321;
for (int i = s; i <= e; i++)
dp[s][e] = min(f(s, i) + f(i+1, e) + sum[e] - sum[s-1], dp[s][e]);
return dp[s][e];
}
int main() {
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &d[i]);
sum[i] = d[i] + sum[i-1];
for (int j = 1; j <= n; j++)
dp[i][j] = 0;
}
printf("%d\n", f(1, n));
}
} | [
"[email protected]"
] | |
1b190f5483f3fef4d4f1a8befe2755cf82301919 | 0f753714aab2b0e90469f17af834e94e2faa9c0f | /src/progs/recon_shell_real.cpp | a236c7eff8c71fc33150da67c38f2c795c3e8140 | [] | no_license | npadmana/baorecon | b90ee4f2fb3738beb9e8ea1d5e654f6f4a0dc8eb | 1147c4b9f3a46c3b84a6c2f25960d70402e57390 | refs/heads/master | 2016-09-08T01:22:03.082693 | 2014-11-28T02:40:44 | 2014-11-28T02:40:44 | 2,431,362 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,562 | cpp | #include <iostream>
#include <cmath>
#include <sstream>
#include <fstream>
#include <iomanip>
#include "Recon.h"
static char help[] = "recon_shell_real -configfn <configuration file>\n";
using namespace std;
int main(int argc, char *args[]) {
PetscErrorCode ierr;
ierr=PetscInitialize(&argc,&args,(char *) 0, help); CHKERRQ(ierr);
{
// Get MPI rank
int rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// Read in configuration file
char configfn[200];
PetscBool flg;
// See if we need help
PetscOptionsHasName(NULL, "-help", &flg);
if (flg) exit(0);
PetscOptionsGetString(NULL, "-configfn", configfn, 200, &flg);
if (!flg) RAISE_ERR(99,"Specify configuration file");
// Read in parameters
ShellParams pars(string(configfn), "shellreal");
/****************************
* Define seeds
****************************/
int const_seed=2147; int randompart_seed=8271;
/******************************************
* Define the mask and delta
******************************************/
Shell maskss(pars.shell.xcen, pars.shell.ycen, pars.shell.zcen, pars.shell.rmin, pars.shell.rmax);
Delta del1(pars.Ngrid, pars.Lbox, pars.shell.nover, pars.shell.thresh, maskss);
/********************************************
* Read in pk prior
*******************************************/
vector<double> kvec, pkvec;
int nk;
// Rank 0 job reads in pk function and broadcasts to everyone
if (rank == 0) {
double k1, pk1;
ifstream fp(pars.pkprior.fn.c_str());
do {
fp >> k1 >> pk1;
if (fp) {
kvec.push_back(k1);
pkvec.push_back(pars.pkprior.bias*pk1 + pars.pkprior.noise);
}
} while (fp);
fp.close();
nk = kvec.size();
}
MPI_Bcast(&nk, 1, MPI_INT, 0, PETSC_COMM_WORLD);
if (rank !=0) {kvec.resize(nk, 0.0); pkvec.resize(nk, 0.0);}
MPI_Bcast(&kvec[0], nk, MPI_DOUBLE, 0, PETSC_COMM_WORLD);
MPI_Bcast(&pkvec[0], nk, MPI_DOUBLE, 0, PETSC_COMM_WORLD);
PetscPrintf(PETSC_COMM_WORLD, "%d lines read in from %s...\n",nk, pars.pkprior.fn.c_str());
// Define the potential solver
PotentialSolve psolve(pars.Ngrid, pars.Lbox, pars.recon.maxit);
psolve.SetupOperator(REALPBC);
// Loop over files
list<ShellParams::fn>::iterator files;
for (files = pars.fnlist.begin(); files !=pars.fnlist.end(); ++files)
{
/* ******************************
* First we get the various options and print out useful information
* ********************************/
ostringstream hdr;
hdr << "# Input file is " << files->in << endl;
hdr << "# Output file is " << files->out << endl;
hdr << "# Ngrid=" << setw(5) << pars.Ngrid << endl;
hdr << "# boxsize=" << setw(8) << fixed << setprecision(2) << pars.Lbox << endl;
hdr << "# bias=" << setw(8) << setprecision(2) << pars.recon.bias << endl;
hdr << "# smooth=" << setw(8) << setprecision(2) << pars.recon.smooth << endl;
hdr << "# " << setw(4) << pars.xi.Nbins << " Xi bins from " << setw(8) << setprecision(2) << pars.xi.rmin
<< " with spacing of " << pars.xi.dr << endl;
hdr << "# " << "Correlation function smoothed with a smoothing scale of" << setw(8) << setprecision(2)
<< pars.xi.smooth << endl;
hdr << "# " << "Survey shell centered at the origin, rmin=" << setprecision(2) << pars.shell.rmin << ", rmax=" << pars.shell.rmax << endl;
hdr << "# " << "Shell center at " << setprecision(3) << pars.shell.xcen << ", " << pars.shell.ycen << ", " << pars.shell.zcen << endl;
hdr << "# Mask threshold =" << pars.shell.thresh << endl;
PetscPrintf(PETSC_COMM_WORLD, (hdr.str()).c_str());
/****************************************
* Read in the particle data here and slab decompose
****************************************/
Particle pp;
DensityGrid dg(pars.Ngrid, pars.Lbox);
pp.TPMReadSerial(files->in.c_str(), pars.Lbox);
PetscPrintf(PETSC_COMM_WORLD,"Read in %i particles.....\n",pp.npart);
pp.SlabDecompose(dg);
// Test slab decomp
bool good = dg.TestSlabDecompose(pp);
if (good)
{PetscSynchronizedPrintf(PETSC_COMM_WORLD,"Slab decomposition succeeded on process %i\n",rank);}
else
{PetscSynchronizedPrintf(PETSC_COMM_WORLD,"Slab decomposition FAILED on process %i\n",rank);}
PetscSynchronizedFlush(PETSC_COMM_WORLD);
if (!good) RAISE_ERR(99, "Slab decomposition failed");
/*************************************************
* Now we start working on the grid
* ***********************************************/
Vec grid;
PkStruct xi1(pars.xi.rmin, pars.xi.dr, pars.xi.Nbins);
grid=dg.Allocate();
//CIC
dg.CIC(grid, pp);
dg.XiFFT(grid, pars.xi.smooth, xi1);
PetscPrintf(PETSC_COMM_WORLD,"Initial correlation function computed....\n");
VecDestroy(&grid);
/*************************************************
* Generate the density field and constrained realization
*************************************************/
del1.BuildDensityGridSmooth(pars.recon.smooth, pp, grid);
PetscPrintf(PETSC_COMM_WORLD, "Density grid computed.....\n");
del1.HoffmanRibak(grid, kvec, pkvec, const_seed); const_seed+=1;
PetscPrintf(PETSC_COMM_WORLD, "Constrained realization computed.....\n");
/************************************************
* Now we solve for the potential
************************************************/
// Allocate potential solver
Vec pot;
pot = dg.Allocate();
if (psolve.Solve(grid, pot, pars.recon.bias)) {
// If the potential calculation converged
PetscPrintf(PETSC_COMM_WORLD,"Potential calculated....\n");
/************************************************
* Now we shift data and randoms
************************************************/
// Generate random particles
Vec dp, qx, qy, qz;
Particle pr;
pr.RandomInit(pp.npart*pars.recon.nrandomfac, pars.Lbox, randompart_seed); randompart_seed +=1;
pr.SlabDecompose(dg);
pr.TrimMask(maskss);
// Compute derivatives at data positions and shift
dp = dg.Deriv(pot, 0); qx = dg.Interp3d(dp, pp); _mydestroy(dp);
dp = dg.Deriv(pot, 1); qy = dg.Interp3d(dp, pp); _mydestroy(dp);
dp = dg.Deriv(pot, 2); qz = dg.Interp3d(dp, pp); _mydestroy(dp);
// Print some statistics
double sum[3];
VecSum(qx,&sum[0]); VecSum(qy, &sum[1]); VecSum(qz, &sum[2]);
for (int ii=0; ii < 3; ++ii) sum[ii] /= pp.npart;
PetscPrintf(PETSC_COMM_WORLD, "Mean x,y,z displacements on particles is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]);
VecNorm(qx,NORM_2,&sum[0]); VecNorm(qy, NORM_2,&sum[1]); VecNorm(qz, NORM_2,&sum[2]);
for (int ii=0; ii < 3; ++ii) sum[ii] /= sqrt(pp.npart);
PetscPrintf(PETSC_COMM_WORLD, "RMS x,y,z displacements on particles is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]);
VecAXPY(pp.px, -1.0, qx);
VecAXPY(pp.py, -1.0, qy);
VecAXPY(pp.pz, -1.0, qz);
// Cleanup
_mydestroy(qx); _mydestroy(qy); _mydestroy(qz);
// Do the same for the randoms
dp = dg.Deriv(pot, 0); qx = dg.Interp3d(dp, pr); _mydestroy(dp);
dp = dg.Deriv(pot, 1); qy = dg.Interp3d(dp, pr); _mydestroy(dp);
dp = dg.Deriv(pot, 2); qz = dg.Interp3d(dp, pr); _mydestroy(dp);
VecSum(qx,&sum[0]); VecSum(qy, &sum[1]); VecSum(qz, &sum[2]);
for (int ii=0; ii < 3; ++ii) sum[ii] /= pr.npart;
PetscPrintf(PETSC_COMM_WORLD, "Mean x,y,z displacements on randoms is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]);
VecNorm(qx,NORM_2,&sum[0]); VecNorm(qy, NORM_2,&sum[1]); VecNorm(qz, NORM_2,&sum[2]);
for (int ii=0; ii < 3; ++ii) sum[ii] /= sqrt(pr.npart);
PetscPrintf(PETSC_COMM_WORLD, "RMS x,y,z displacements on randoms is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]);
VecAXPY(pr.px, -1.0, qx);
VecAXPY(pr.py, -1.0, qy);
VecAXPY(pr.pz, -1.0, qz);
PetscPrintf(PETSC_COMM_WORLD,"Displacements calculated....\n");
// Clean up
_mydestroy(qx); _mydestroy(qy); _mydestroy(qz);
// Shifted data and random grid
Vec gridr=PETSC_NULL;
del1.BuildDensityGrid(pp, grid);
del1.BuildDensityGrid(pr, gridr);
VecAXPY(grid, -1.0, gridr);
// Correlation fn
PkStruct xi2(pars.xi.rmin, pars.xi.dr, pars.xi.Nbins);
dg.XiFFT_W(grid, del1.W, pars.xi.smooth, xi2);
_mydestroy(gridr);
// Outputs
FILE *fp;
double _rvec, _xi1, _xi2, _n1;
PetscFOpen(PETSC_COMM_WORLD,files->out.c_str(),"w", &fp);
PetscFPrintf(PETSC_COMM_WORLD, fp, (hdr.str()).c_str());
for (int ii = xi1.lo; ii < xi1.hi; ++ii) {
_xi1 = xi1(ii, _rvec, _n1);
_xi2 = xi2(ii);
if (_n1>0) PetscSynchronizedFPrintf(PETSC_COMM_WORLD, fp, "%6i %9.3f %15.8e %15.8e\n",ii,_rvec,_xi1,_xi2);
}
PetscSynchronizedFlush(PETSC_COMM_WORLD);
PetscFClose(PETSC_COMM_WORLD,fp);
}
// Cleanup
_mydestroy(grid); _mydestroy(pot);
}
}
// Only call this when everything is out of scope
ierr=PetscFinalize(); CHKERRQ(ierr);
}
| [
"[email protected]"
] | |
29f877a3f938e4d509ae3c2432fee08f0c78b70b | 8a1ad6e4a32112c6227e928b74f9d419623ff869 | /ZinJpeg decoder throw/ZinJpeg decoder throw/zinjpeg_hamming.hh | b0760127bbbf49548e89d48480e52d410140b2a9 | [] | no_license | GreenIOur/ZinJpeg | f62081b988761736faec1275045705cababa332a | 034d8ef0e4f5af4ccedb2c550fb2bad4d673c5e2 | refs/heads/master | 2021-01-22T13:41:43.313122 | 2015-07-29T13:30:03 | 2015-07-29T13:30:03 | 39,894,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | hh | #ifndef _SECDED_
#define _SECDED_
short get_safety_level();
uint64_t SECDED_decoder(uint64_t *rdata);
void SECDED_encoder(uint32_t data, uint64_t *out);
#endif | [
"[email protected]"
] | |
c8d55bd8fc65e7bc7c0c18f235a1bbd9c1521819 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13996/function13996_schedule_17/function13996_schedule_17.cpp | 1b59c2d39a2db92e6ec069e3696343876fb036ab | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,190 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function13996_schedule_17");
constant c0("c0", 512), c1("c1", 1024), c2("c2", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i1, i2}, p_int32);
input input01("input01", {i0, i2}, p_int32);
input input02("input02", {i2}, p_int32);
computation comp0("comp0", {i0, i1, i2}, input00(i1, i2) + input01(i0, i2) + input02(i2));
comp0.tile(i0, i1, i2, 32, 64, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {1024, 64}, p_int32, a_input);
buffer buf01("buf01", {512, 64}, p_int32, a_input);
buffer buf02("buf02", {64}, p_int32, a_input);
buffer buf0("buf0", {512, 1024, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf0}, "../data/programs/function13996/function13996_schedule_17/function13996_schedule_17.o");
return 0;
} | [
"[email protected]"
] | |
bbda0e498bf5fbe274d81ec0c9e8ffaf92edf542 | 245afd9f4adb8d868fa1228ac5898083e4140d4a | /Class_Set_Template/Class_Set_Template.cpp | 78615212f0c7760d6c85865b9b936db6533a6da3 | [] | no_license | Ars-eniy-Cheis/ProgramLanguages | 3e50c5eaa7d0f2c2bcdda7651d873484c912c78e | 3b79cef726a347188bb25d468b092e0c59ef6ecf | refs/heads/master | 2021-01-01T11:29:51.555886 | 2020-12-21T16:58:16 | 2020-12-21T16:58:16 | 239,254,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,975 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <math.h>
using namespace std;
template <typename T>
class Set
{
int size;
T* set;
bool isSet(T a);
public:
Set(int n = 0);
Set(const Set& copy);
~Set();
void insert(T a);
Set Union(Set& a);
Set Intersection(Set& a);
bool Find(T a);
Set operator= (const Set& a);
template<typename T1> friend istream& operator>> (istream& in, Set& a);
template<typename T1> friend ostream& operator<< (ostream& out, Set& a);
};
void menu();
int main()
{
menu();
int num = 1;
while (num != 0)
{
cin >> num;
switch (num)
{
case 1:
{
menu();
break;
}
case 0:
{
return 0;
}
}
}
}
void menu()
{
cout << endl << "MENU" << endl << endl << "1. Intersection" << endl << "2. Insert" << endl << "0. EXIT" << endl;
}
template<typename T>
bool Set<T>::isSet(T a)
{
if (1)
{
return true;
}
else
{
return false;
}
}
template<typename T>
Set<T>::Set(int n)
{
size = n;
set = new T[size];
}
template<typename T>
Set<T>::Set(const Set& copy)
{
size = copy.size;
set = new T[size];
for (int i = 0; i < size; i++)
{
set[i] = copy.set[i];
}
}
template<typename T>
Set<T>::~Set()
{
delete[] set;
}
template<typename T>
void Set<T>::insert(T a)
{
if (this->isSet(a))
{
if (!this->Find())
{
Set Temp = *this;
delete[] this->set;
set = new T[++size];
for (int i = 0; i < size - 1; i++)
{
set[i] = Temp.set[i];
}
set[size - 1] = a;
}
else
{
cout << "Alredy exsist!" << endl;
}
}
else
{
cout << "Can't be part of Set!" << endl;
}
}
template<typename T>
Set<T> Set<T>::Union(Set& a)
{
int n = size + a.size;
int k = size;
Set Temp(n);
for (int i = 0; i < size; i++)
{
Temp.set[i] = set[i];
}
for (int i = 0; i < a.size; i++)
{
if (!Temp.Find(a.set[i]))
{
Temp.set[k++] = a.set[i];
}
}
Set Buf(k);
for (int i = 0; i < k; i++)
{
Buf.set[i] = Temp.set[i];
}
return Buf;
}
template<typename T>
Set<T> Set<T>::Intersection(Set& a)
{
Set Temp(size);
int k = 0;
for (int i = 0; i < size; i++)
{
if (a.Find(set[i]))
{
Temp.set[k++] = set[i];
}
}
Set Buf(k);
for (int i = 0; i < k; i++)
{
Buf.set[i] = Temp.set[i];
}
return Buf;
}
template<typename T>
bool Set<T>::Find(T a)
{
for (int i = 0; i < size; i++)
{
if (a == set[i])
return true;
}
return false;
}
template<typename T>
Set<T> Set<T>::operator=(const Set<T>& a)
{
delete[] set;
size = a.size;
set = new T[size];
for (int i = 0; i < size; i++)
{
set[i] = a.set[i];
}
return Set;
}
template <typename T>
istream& operator>> (istream& in, Set<T>& a)
{
cout << "Enter size: ";
in >> a.size;
if (a.size < 2)
{
do
{
cout << "Size should be >= 2. Try again" << endl;
in >> a.size;
} while (a.size < 2);
}
a.set = new T[a.size];
for (int i = 0; i < size; i++)
{
cout << "Enter number: ";
in >> a.set[i];
if (a.Find(a.set[i]))
{
do
{
cout << "Already exsists!" << endl;
in >> a.set[i];
} while (a.Find(a.set[i]));
}
}
return in;
}
template <typename T>
ostream& operator<< (ostream& out, Set<T>& a)
{
for (int i = 0; i < size; i++)
{
out << set[i] << " ";
}
out << endl;
return out;
}
| [
"[email protected]"
] | |
86ea51f147e3c72d74fc4fd09b44303fba3db994 | 26f31517349cd3ca820e872facc4e51dc2f1fa8b | /identifyuber.h | 83fff2138ba65538c4b0662b6a7d5aaa21e0589f | [] | no_license | kajakIYD/PSS_Proj | bc373b142a393661a606b0446ce0e1070d7c1fe9 | 83f17dc248bcb2cb1a4c78c46a9122830d20d51b | refs/heads/master | 2020-03-13T11:36:37.771310 | 2018-11-20T17:02:13 | 2018-11-20T17:02:13 | 131,104,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | h | #ifndef IDENTIFYUBER_H
#define IDENTIFYUBER_H
#include <cmath>
#include <deque>
#include <vector>
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
class IdentifyUber
{
public:
IdentifyUber();
virtual ~IdentifyUber() {};
virtual void Identify_step(double u, double y) = 0;
/*!
* \brief Get_param
* Getter function to get identify parameters
* double input -
*/
virtual deque<double> Get_param() = 0;
/*!
* \brief Get_A
* Getter function to get A polynomial
*/
virtual std::vector<double> Get_A() = 0;
/*!
* \brief Get_B
* Getter function to get B polynomial
*/
virtual std::vector<double> Get_B() = 0;
/*!
* \brief Get_B
* Getter function to get B polynomial
*/
virtual std::vector<double> Get_C() = 0;
};
#endif // IDENTIFYUBER_H
| [
"[email protected]"
] | |
112c7055186d4d30e14ecb165a9d207375ca9a69 | ac34cad5e20b8f46c0b0aa67df829f55ed90dcb6 | /src/ballistica/scene_v1/node/node_attribute.h | a6ffb74716a6f5157fef6d0adffbe4cb0cd388a8 | [
"MIT"
] | permissive | sudo-logic/ballistica | fd3bf54a043717f874b71f4b2ccd551d61c65008 | 9aa73cd20941655e96b0e626017a7395ccb40062 | refs/heads/master | 2023-07-26T19:52:06.113981 | 2023-07-12T21:32:56 | 2023-07-12T21:37:46 | 262,056,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,129 | h | // Released under the MIT License. See LICENSE for details.
#ifndef BALLISTICA_SCENE_V1_NODE_NODE_ATTRIBUTE_H_
#define BALLISTICA_SCENE_V1_NODE_NODE_ATTRIBUTE_H_
#include <string>
#include <vector>
#include "ballistica/scene_v1/scene_v1.h"
namespace ballistica::scene_v1 {
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedMacroInspection"
// Unbound node attribute; these are statically stored in a node type
// and contain logic to get/set a particular attribute on a node
// in various ways.
class NodeAttributeUnbound {
public:
static auto GetNodeAttributeTypeName(NodeAttributeType) -> std::string;
NodeAttributeUnbound(NodeType* node_type, NodeAttributeType type,
std::string name, uint32_t flags);
// Attrs should override the calls they support; by default
// these all raise exceptions.
// Generally attrs are get/set as their native type,
// but in cases of attr connections a 'get' corresponding
// to the native type of the dst attr is made on the src attr
// (so if connecting float attr foo to int attr bar,
// the update will essentially be: bar.set(foo.GetAsInt()) )
virtual auto GetAsFloat(Node* node) -> float;
virtual void Set(Node* node, float value);
virtual auto GetAsInt(Node* node) -> int64_t;
virtual void Set(Node* node, int64_t value);
virtual auto GetAsBool(Node* node) -> bool;
virtual void Set(Node* node, bool value);
virtual auto GetAsString(Node* node) -> std::string;
virtual void Set(Node* node, const std::string& value);
virtual auto GetAsFloats(Node* node) -> std::vector<float>;
virtual void Set(Node* node, const std::vector<float>& value);
virtual auto GetAsInts(Node* node) -> std::vector<int64_t>;
virtual void Set(Node* node, const std::vector<int64_t>& value);
virtual auto GetAsNode(Node* node) -> Node*;
virtual void Set(Node* node, Node* value);
virtual auto GetAsNodes(Node* node) -> std::vector<Node*>;
virtual void Set(Node* node, const std::vector<Node*>& values);
virtual auto GetAsPlayer(Node* node) -> Player*;
virtual void Set(Node* node, Player* value);
virtual auto GetAsMaterials(Node* node) -> std::vector<Material*>;
virtual void Set(Node* node, const std::vector<Material*>& value);
virtual auto GetAsTexture(Node* node) -> SceneTexture*;
virtual void Set(Node* node, SceneTexture* value);
virtual auto GetAsTextures(Node* node) -> std::vector<SceneTexture*>;
virtual void Set(Node* node, const std::vector<SceneTexture*>& values);
virtual auto GetAsSound(Node* node) -> SceneSound*;
virtual void Set(Node* node, SceneSound* value);
virtual auto GetAsSounds(Node* node) -> std::vector<SceneSound*>;
virtual void Set(Node* node, const std::vector<SceneSound*>& values);
virtual auto GetAsMesh(Node* node) -> SceneMesh*;
virtual void Set(Node* node, SceneMesh* value);
virtual auto GetAsMeshes(Node* node) -> std::vector<SceneMesh*>;
virtual void Set(Node* node, const std::vector<SceneMesh*>& values);
virtual auto GetAsCollisionMesh(Node* node) -> SceneCollisionMesh*;
virtual void Set(Node* node, SceneCollisionMesh* value);
virtual auto GetAsCollisionMeshes(Node* node)
-> std::vector<SceneCollisionMesh*>;
virtual void Set(Node* node, const std::vector<SceneCollisionMesh*>& values);
auto is_read_only() const -> bool {
return static_cast<bool>(flags_ & kNodeAttributeFlagReadOnly);
}
auto type() const -> NodeAttributeType { return type_; }
auto GetTypeName() const -> std::string {
return GetNodeAttributeTypeName(type_);
}
auto name() const -> const std::string& { return name_; }
auto node_type() const -> NodeType* { return node_type_; }
auto index() const -> int { return index_; }
void DisconnectIncoming(Node* node);
protected:
void NotReadableError(Node* node);
void NotWritableError(Node* node);
private:
NodeType* node_type_;
NodeAttributeType type_;
std::string name_;
uint32_t flags_;
int index_;
};
// Simple node-attribute pair; used as a convenience measure.
// Note that this simply stores pointers; it does not check to
// ensure the node is still valid or anything like that.
class NodeAttribute {
public:
void assign(Node* node_in, NodeAttributeUnbound* attr_in) {
node = node_in;
attr = attr_in;
}
NodeAttribute() = default;
NodeAttribute(Node* node_in, NodeAttributeUnbound* attr_in)
: node(node_in), attr(attr_in) {}
Node* node = nullptr;
NodeAttributeUnbound* attr = nullptr;
auto type() const -> NodeAttributeType { return attr->type(); }
auto GetTypeName() const -> std::string { return attr->GetTypeName(); }
auto name() const -> const std::string& { return attr->name(); }
auto node_type() const -> NodeType* { return attr->node_type(); }
auto index() const -> int { return attr->index(); }
void DisconnectIncoming() { attr->DisconnectIncoming(node); }
auto is_read_only() const -> bool { return attr->is_read_only(); }
auto GetAsFloat() const -> float { return attr->GetAsFloat(node); }
void Set(float value) const { attr->Set(node, value); }
auto GetAsInt() const -> int64_t { return attr->GetAsInt(node); }
void Set(int64_t value) const { attr->Set(node, value); }
auto GetAsBool() const -> bool { return attr->GetAsBool(node); }
void Set(bool value) const { attr->Set(node, value); }
auto GetAsString() const -> std::string { return attr->GetAsString(node); }
void Set(const std::string& value) const { attr->Set(node, value); }
auto GetAsFloats() const -> std::vector<float> {
return attr->GetAsFloats(node);
}
void Set(const std::vector<float>& value) const { attr->Set(node, value); }
auto GetAsInts() const -> std::vector<int64_t> {
return attr->GetAsInts(node);
}
void Set(const std::vector<int64_t>& value) const { attr->Set(node, value); }
auto GetAsNode() const -> Node* { return attr->GetAsNode(node); }
void Set(Node* value) const { attr->Set(node, value); }
auto GetAsNodes() const -> std::vector<Node*> {
return attr->GetAsNodes(node);
}
void Set(const std::vector<Node*>& value) const { attr->Set(node, value); }
auto GetAsPlayer() const -> Player* { return attr->GetAsPlayer(node); }
void Set(Player* value) const { attr->Set(node, value); }
auto GetAsMaterials() const -> std::vector<Material*> {
return attr->GetAsMaterials(node);
}
void Set(const std::vector<Material*>& value) const {
attr->Set(node, value);
}
auto GetAsTexture() const -> SceneTexture* {
return attr->GetAsTexture(node);
}
void Set(SceneTexture* value) const { attr->Set(node, value); }
auto GetAsTextures() const -> std::vector<SceneTexture*> {
return attr->GetAsTextures(node);
}
void Set(const std::vector<SceneTexture*>& values) const {
attr->Set(node, values);
}
auto GetAsSound() const -> SceneSound* { return attr->GetAsSound(node); }
void Set(SceneSound* value) const { attr->Set(node, value); }
auto GetAsSounds() const -> std::vector<SceneSound*> {
return attr->GetAsSounds(node);
}
void Set(const std::vector<SceneSound*>& values) const {
attr->Set(node, values);
}
auto GetAsMesh() const -> SceneMesh* { return attr->GetAsMesh(node); }
void Set(SceneMesh* value) const { attr->Set(node, value); }
auto GetAsMeshes() const -> std::vector<SceneMesh*> {
return attr->GetAsMeshes(node);
}
void Set(const std::vector<SceneMesh*>& values) const {
attr->Set(node, values);
}
auto GetAsCollisionMesh() const -> SceneCollisionMesh* {
return attr->GetAsCollisionMesh(node);
}
void Set(SceneCollisionMesh* value) const { attr->Set(node, value); }
auto GetAsCollisionMeshes() const -> std::vector<SceneCollisionMesh*> {
return attr->GetAsCollisionMeshes(node);
}
void Set(const std::vector<SceneCollisionMesh*>& values) const {
attr->Set(node, values);
}
};
// Single float attr; subclasses just need to override float get/set
// and this will provide the other numeric get/sets based on that.
class NodeAttributeUnboundFloat : public NodeAttributeUnbound {
public:
NodeAttributeUnboundFloat(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kFloat, name,
flags) {}
// Override these:
auto GetAsFloat(Node* node) -> float override {
NotReadableError(node);
return 0.0f;
}
void Set(Node* node, float val) override { NotWritableError(node); }
// These are handled automatically:
auto GetAsInt(Node* node) -> int64_t final {
return static_cast<int64_t>(GetAsFloat(node));
}
auto GetAsBool(Node* node) -> bool final {
return static_cast<bool>(GetAsFloat(node));
}
void Set(Node* node, int64_t val) final {
Set(node, static_cast<float>(val));
}
void Set(Node* node, bool val) final { Set(node, static_cast<float>(val)); }
};
// Float array attr.
class NodeAttributeUnboundFloatArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundFloatArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kFloatArray, name,
flags) {}
// Override these:
auto GetAsFloats(Node* node) -> std::vector<float> override {
NotReadableError(node);
return std::vector<float>();
}
void Set(Node* node, const std::vector<float>& vals) override {
NotWritableError(node);
}
};
// Single int attr; subclasses just need to override int get/set
// and this will provide the other numeric get/sets based on that.
class NodeAttributeUnboundInt : public NodeAttributeUnbound {
public:
NodeAttributeUnboundInt(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kInt, name, flags) {}
// Override these:
auto GetAsInt(Node* node) -> int64_t override {
NotReadableError(node);
return 0;
}
void Set(Node* node, int64_t val) override { NotWritableError(node); }
// These are handled automatically:
auto GetAsFloat(Node* node) -> float final { return GetAsInt(node); }
auto GetAsBool(Node* node) -> bool final {
return static_cast<bool>(GetAsInt(node));
}
void Set(Node* node, float val) final {
Set(node, static_cast<int64_t>(val));
}
void Set(Node* node, bool val) final { Set(node, static_cast<int64_t>(val)); }
};
// Int array attr.
class NodeAttributeUnboundIntArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundIntArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kIntArray, name,
flags) {}
// Override these:
auto GetAsInts(Node* node) -> std::vector<int64_t> override {
NotReadableError(node);
return std::vector<int64_t>();
}
void Set(Node* node, const std::vector<int64_t>& vals) override = 0;
};
// Single bool attr; subclasses just need to override bool get/set
// and this will provide the other numeric get/sets based on that.
class NodeAttributeUnboundBool : public NodeAttributeUnbound {
public:
NodeAttributeUnboundBool(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kBool, name, flags) {
}
// Override these:
auto GetAsBool(Node* node) -> bool override {
NotReadableError(node);
return false;
};
void Set(Node* node, bool val) override { NotWritableError(node); }
// These are handled automatically:
auto GetAsFloat(Node* node) -> float final {
return GetAsBool(node) ? 1.0f : 0.0f;
}
auto GetAsInt(Node* node) -> int64_t final { return GetAsBool(node) ? 1 : 0; }
void Set(Node* node, float val) final { Set(node, val != 0.0f); }
void Set(Node* node, int64_t val) final { Set(node, val != 0); }
};
// String attr.
class NodeAttributeUnboundString : public NodeAttributeUnbound {
public:
NodeAttributeUnboundString(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kString, name,
flags) {}
// Override these:
auto GetAsString(Node* node) -> std::string override {
NotReadableError(node);
return "";
};
void Set(Node* node, const std::string& val) override {
NotWritableError(node);
}
};
// Node attr.
class NodeAttributeUnboundNode : public NodeAttributeUnbound {
public:
NodeAttributeUnboundNode(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kNode, name, flags) {
}
// Override these:
auto GetAsNode(Node* node) -> Node* override {
NotReadableError(node);
return nullptr;
};
void Set(Node* node, Node* val) override { NotWritableError(node); }
};
// Node array attr.
class NodeAttributeUnboundNodeArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundNodeArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kNodeArray, name,
flags) {}
// Override these:
auto GetAsNodes(Node* node) -> std::vector<Node*> override {
NotReadableError(node);
return std::vector<Node*>();
};
void Set(Node* node, const std::vector<Node*>& vals) override {
NotWritableError(node);
}
};
// Player attr.
class NodeAttributeUnboundPlayer : public NodeAttributeUnbound {
public:
NodeAttributeUnboundPlayer(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kPlayer, name,
flags) {}
// override these:
auto GetAsPlayer(Node* node) -> Player* override {
NotReadableError(node);
return nullptr;
}
void Set(Node* node, Player* val) override { NotWritableError(node); }
};
// Material array attr.
class NodeAttributeUnboundMaterialArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundMaterialArray(NodeType* node_type,
const std::string& name, uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kMaterialArray, name,
flags) {}
// override these:
auto GetAsMaterials(Node* node) -> std::vector<Material*> override {
NotReadableError(node);
return std::vector<Material*>();
}
void Set(Node* node, const std::vector<Material*>& materials) override {
NotWritableError(node);
}
};
// Texture attr.
class NodeAttributeUnboundTexture : public NodeAttributeUnbound {
public:
NodeAttributeUnboundTexture(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kTexture, name,
flags) {}
// Override these:
auto GetAsTexture(Node* node) -> SceneTexture* override {
NotReadableError(node);
return nullptr;
}
void Set(Node* node, SceneTexture* val) override { NotWritableError(node); }
};
// Texture array attr.
class NodeAttributeUnboundTextureArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundTextureArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kTextureArray, name,
flags) {}
// Override these:
auto GetAsTextures(Node* node) -> std::vector<SceneTexture*> override {
NotReadableError(node);
return std::vector<SceneTexture*>();
}
void Set(Node* node, const std::vector<SceneTexture*>& vals) override {
NotWritableError(node);
}
};
// Sound attr.
class NodeAttributeUnboundSound : public NodeAttributeUnbound {
public:
NodeAttributeUnboundSound(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kSound, name,
flags) {}
// override these:
auto GetAsSound(Node* node) -> SceneSound* override {
NotReadableError(node);
return nullptr;
}
void Set(Node* node, SceneSound* val) override { NotWritableError(node); }
};
// Sound array attr.
class NodeAttributeUnboundSoundArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundSoundArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kSoundArray, name,
flags) {}
// Override these:
auto GetAsSounds(Node* node) -> std::vector<SceneSound*> override {
NotReadableError(node);
return std::vector<SceneSound*>();
}
void Set(Node* node, const std::vector<SceneSound*>& vals) override {
NotWritableError(node);
}
};
// Mesh attr.
class NodeAttributeUnboundMesh : public NodeAttributeUnbound {
public:
NodeAttributeUnboundMesh(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kMesh, name, flags) {
}
// Override these:
auto GetAsMesh(Node* node) -> SceneMesh* override {
NotReadableError(node);
return nullptr;
}
void Set(Node* node, SceneMesh* val) override { NotWritableError(node); }
};
// Mesh array attr.
class NodeAttributeUnboundMeshArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundMeshArray(NodeType* node_type, const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kMeshArray, name,
flags) {}
// Override these:
auto GetAsMeshes(Node* node) -> std::vector<SceneMesh*> override {
NotReadableError(node);
return std::vector<SceneMesh*>();
}
void Set(Node* node, const std::vector<SceneMesh*>& vals) override {
NotWritableError(node);
}
};
// Collision-mesh attr.
class NodeAttributeUnboundCollisionMesh : public NodeAttributeUnbound {
public:
NodeAttributeUnboundCollisionMesh(NodeType* node_type,
const std::string& name, uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kCollisionMesh, name,
flags) {}
// Override these:
auto GetAsCollisionMesh(Node* node) -> SceneCollisionMesh* override {
NotReadableError(node);
return nullptr;
}
void Set(Node* node, SceneCollisionMesh* val) override {
NotWritableError(node);
}
};
// Collision-mesh array attr.
class NodeAttributeUnboundCollisionMeshArray : public NodeAttributeUnbound {
public:
NodeAttributeUnboundCollisionMeshArray(NodeType* node_type,
const std::string& name,
uint32_t flags)
: NodeAttributeUnbound(node_type, NodeAttributeType::kCollisionMeshArray,
name, flags) {}
// Override these:
auto GetAsCollisionMeshes(Node* node)
-> std::vector<SceneCollisionMesh*> override {
NotReadableError(node);
return std::vector<SceneCollisionMesh*>();
}
void Set(Node* node, const std::vector<SceneCollisionMesh*>& vals) override {
NotWritableError(node);
}
};
// Defines a float attr subclass that interfaces with specific getter/setter
// calls.
#define BA_FLOAT_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundFloat { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundFloat(node_type, #NAME, 0) {} \
auto GetAsFloat(Node* node) -> float override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, float val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a float attr subclass that interfaces with specific getter/setter
// calls.
#define BA_FLOAT_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundFloat { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundFloat(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsFloat(Node* node) -> float override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines a float-array attr subclass that interfaces with specific
// getter/setter calls.
#define BA_FLOAT_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundFloatArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundFloatArray(node_type, #NAME, 0) {} \
auto GetAsFloats(Node* node) -> std::vector<float> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<float>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
// Defines a float-array attr subclass that interfaces with specific
// getter/setter calls.
#define BA_FLOAT_ARRAY_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundFloatArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundFloatArray(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsFloats(Node* node) -> std::vector<float> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines an int attr subclass that interfaces with specific getter/setter
// calls.
#define BA_INT_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundInt { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundInt(node_type, #NAME, 0) {} \
auto GetAsInt(Node* node) -> int64_t override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, int64_t val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(static_cast_check_fit<int>(val)); \
} \
}; \
Attr_##NAME NAME;
// Defines an int attr subclass that interfaces with specific getter/setter
// calls.
#define BA_INT_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundInt { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundInt(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsInt(Node* node) -> int64_t override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines an int attr subclass that interfaces with specific getter/setter
// calls.
#define BA_INT64_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundInt { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundInt(node_type, #NAME, 0) {} \
auto GetAsInt(Node* node) -> int64_t override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, int64_t val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines an int attr subclass that interfaces with specific getter/setter
// calls.
#define BA_INT64_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundInt { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundInt(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsInt(Node* node) -> int64_t override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines an int-array attr subclass that interfaces with specific
// getter/setter calls.
#define BA_INT64_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundIntArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundIntArray(node_type, #NAME, 0) {} \
auto GetAsInts(Node* node) -> std::vector<int64_t> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<int64_t>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
// Defines a bool attr subclass that interfaces with specific getter/setter
// calls.
#define BA_BOOL_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundBool { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundBool(node_type, #NAME, 0) {} \
auto GetAsBool(Node* node) -> bool override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, bool val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a bool attr subclass that interfaces with specific getter/setter
// calls.
#define BA_BOOL_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundBool { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundBool(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsBool(Node* node) -> bool override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines a string attr subclass that interfaces with specific getter/setter
// calls.
#define BA_STRING_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundString { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundString(node_type, #NAME, 0) {} \
auto GetAsString(Node* node) -> std::string override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::string& val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a string attr subclass that interfaces with specific getter/setter
// calls.
#define BA_STRING_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundString { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundString(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsString(Node* node) -> std::string override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines a node attr subclass that interfaces with specific getter/setter
// calls.
#define BA_NODE_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundNode { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundNode(node_type, #NAME, 0) {} \
auto GetAsNode(Node* node) -> Node* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, Node* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a node-array attr subclass that interfaces with specific
// getter/setter calls.
#define BA_NODE_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundNodeArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundNodeArray(node_type, #NAME, 0) {} \
auto GetAsNodes(Node* node) -> std::vector<Node*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<Node*>& val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a player attr subclass that interfaces with specific getter/setter
// calls.
#define BA_PLAYER_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundPlayer { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundPlayer(node_type, #NAME, 0) {} \
auto GetAsPlayer(Node* node) -> Player* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, Player* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a material-array attr subclass that interfaces with specific
// getter/setter calls.
#define BA_MATERIAL_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundMaterialArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundMaterialArray(node_type, #NAME, 0) {} \
auto GetAsMaterials(Node* node) -> std::vector<Material*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<Material*>& val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a texture attr subclass that interfaces with specific getter/setter
// calls.
#define BA_TEXTURE_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundTexture { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundTexture(node_type, #NAME, 0) {} \
auto GetAsTexture(Node* node) -> SceneTexture* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, SceneTexture* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a texture attr subclass that interfaces with specific getter/setter
// calls.
#define BA_TEXTURE_ATTR_READONLY(NAME, GETTER) \
class Attr_##NAME : public NodeAttributeUnboundTexture { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundTexture(node_type, #NAME, \
kNodeAttributeFlagReadOnly) {} \
auto GetAsTexture(Node* node) -> SceneTexture* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
}; \
Attr_##NAME NAME;
// Defines a texture attr subclass that interfaces with specific getter/setter
// calls.
#define BA_TEXTURE_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundTextureArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundTextureArray(node_type, #NAME, 0) {} \
auto GetAsTextures(Node* node) -> std::vector<SceneTexture*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<SceneTexture*>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
// Defines a sound attr subclass that interfaces with specific getter/setter
// calls.
#define BA_SOUND_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundSound { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundSound(node_type, #NAME, 0) {} \
auto GetAsSound(Node* node) -> SceneSound* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, SceneSound* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a sound attr subclass that interfaces with specific getter/setter
// calls.
#define BA_SOUND_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundSoundArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundSoundArray(node_type, #NAME, 0) {} \
auto GetAsSounds(Node* node) -> std::vector<SceneSound*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<SceneSound*>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
// Defines a mesh attr subclass that interfaces with specific getter/setter
// calls.
#define BA_MESH_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundMesh { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundMesh(node_type, #NAME, 0) {} \
auto GetAsMesh(Node* node) -> SceneMesh* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, SceneMesh* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a mesh attr subclass that interfaces with specific getter/setter
// calls.
#define BA_MESH_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundMeshArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundMeshArray(node_type, #NAME, 0) {} \
auto GetAsMeshes(Node* node) -> std::vector<SceneMesh*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<SceneMesh*>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
// Defines a collision_mesh attr subclass that interfaces with specific
// getter/setter calls.
#define BA_COLLISION_MESH_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundCollisionMesh { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundCollisionMesh(node_type, #NAME, 0) {} \
auto GetAsCollisionMesh(Node* node) -> SceneCollisionMesh* override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, SceneCollisionMesh* val) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(val); \
} \
}; \
Attr_##NAME NAME;
// Defines a collision_mesh attr subclass that interfaces with specific
// getter/setter calls.
#define BA_COLLISION_MESH_ARRAY_ATTR(NAME, GETTER, SETTER) \
class Attr_##NAME : public NodeAttributeUnboundCollisionMeshArray { \
public: \
explicit Attr_##NAME(NodeType* node_type) \
: NodeAttributeUnboundCollisionMeshArray(node_type, #NAME, 0) {} \
auto GetAsCollisionMeshes(Node* node) \
-> std::vector<CollisionMesh*> override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
return tnode->GETTER(); \
} \
void Set(Node* node, const std::vector<CollisionMesh*>& vals) override { \
BA_NODE_TYPE_CLASS* tnode = static_cast<BA_NODE_TYPE_CLASS*>(node); \
assert(dynamic_cast<BA_NODE_TYPE_CLASS*>(node) == tnode); \
tnode->SETTER(vals); \
} \
}; \
Attr_##NAME NAME;
#pragma clang diagnostic pop
} // namespace ballistica::scene_v1
#endif // BALLISTICA_SCENE_V1_NODE_NODE_ATTRIBUTE_H_
| [
"[email protected]"
] | |
b141a9ac1fff134ad77d974783dc43f8b6088279 | 187f6bb6b568e8bb42bafab8f81133d4ad5f383b | /Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/ConstantBuffer/D3D11/ConstantBufferDetail_D3D11.hpp | 23f0f620db0b015c61fda62fb3f752b59be612ee | [
"MIT"
] | permissive | Reputeless/OpenSiv3D | f2938ea8f5c8de2e6e3b200046943f3e5398a2a1 | 7d02aa0f4824d1ecbd50ea1c00737cc932332b0a | refs/heads/main | 2023-07-29T06:57:44.541422 | 2023-07-13T03:41:37 | 2023-07-13T03:41:37 | 306,929,779 | 0 | 0 | MIT | 2021-09-02T10:37:00 | 2020-10-24T16:55:13 | C++ | UTF-8 | C++ | false | false | 830 | hpp | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2023 Ryo Suzuki
// Copyright (c) 2016-2023 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Common/D3D11.hpp>
# include <Siv3D/ConstantBuffer/IConstantBufferDetail.hpp>
namespace s3d
{
class ConstantBufferDetail_D3D11 final : public IConstantBufferDetail
{
private:
mutable ID3D11DeviceContext* m_context = nullptr;
size_t m_bufferSize = 0;
mutable ComPtr<ID3D11Buffer> m_buffer;
bool init() const;
public:
explicit ConstantBufferDetail_D3D11(size_t size);
bool update(const void* data, size_t size) override;
ID3D11Buffer* const* getBufferPtr() const;
};
}
| [
"[email protected]"
] | |
039fc6ddb8a8c7d039fbf9cfba9039f76db2fb18 | bb09adfc7e4fdba48a7cd34ad8c6354c20ae5cf0 | /src/main.cpp | bce143e58d99326e9d0182d680e568a757feb51c | [
"MIT"
] | permissive | cacoin/coocacoin | aafd691ddb67c98d83994bdef11b76d80dff4336 | 1ab7650b490b8dddb335556e7b4387c12a7d952b | refs/heads/master | 2021-01-18T22:17:39.108228 | 2016-07-23T14:30:20 | 2016-07-23T14:40:50 | 64,012,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161,269 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "scrypt_mine.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 16);
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 20);
static CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 12);
static CBigNum bnProofOfStakeLimitTestNet(~uint256(0) >> 20);
unsigned int nStakeMinAge = 60 * 60 * 24 * 365 * 100; // minimum age for coin age: 1h
unsigned int nStakeMaxAge = 60 * 60 * 24 * 365 * 100; // stake age of full weight: 10 y
unsigned int nStakeTargetSpacing = 60; // 60 sec block spacing
int64 nChainStartTime = 1462460659;
int nCoinbaseMaturity = 80;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainTrust = 0;
CBigNum bnBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "ChinafricaCoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = MIN_TX_FEE;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION)
return false;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
// 2014-04-19 Adriano https://bitcointalk.org/index.php?action=profile;u=112568
// The following address was lost during distribution with 196780608.602771 coins in it. Blocking just in case :-)
static const CBitcoinAddress lostWallet ("CKGK6MFmBkreG7k5sU8gDEJNVJ57QZtN3H");
uint256 hashBlock;
CTransaction txPrev;
if(GetTransaction(txin.prevout.hash, txPrev, hashBlock)){ // get the vin's previous transaction
CTxDestination source;
if (ExtractDestination(txPrev.vout[txin.prevout.n].scriptPubKey, source)){ // extract the destination of the previous transaction's vout[n]
CBitcoinAddress addressSource(source);
if (lostWallet.Get() == addressSource.Get()){
error("Banned Address %s tried to send a transaction (rejecting it).", addressSource.ToString().c_str());
return false;
}
}
}
}
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey))
return false;
if (txout.nValue == 0)
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
/*
if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
*/
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
/*int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
enum GetMinFee_mode mode) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);// Coin Control
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}*/
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
enum GetMinFee_mode mode, unsigned int nBytes) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
/*
int generateMTRandom(unsigned int s, int range)
{
random::mt19937 gen(s);
random::uniform_int_distribution<> dist(0, range);
return dist(gen);
}
*/
// miner's coin base reward based on nBits
int64 GetProofOfWorkReward(int nHeight, int64 nFees, uint256 prevHash)
{
int64 nSubsidy = 0.0 * COIN;
if(nHeight >= 1 && nHeight <= 100)
{
nSubsidy = 5000000 * COIN;
}
else if(nHeight > 100 && nHeight <= 10512000)
{
nSubsidy = 47.5 * COIN;
}
return nSubsidy + nFees;
}
// miner's coin stake reward based on nBits and coin age spent (coin-days)
// simple algorithm, not depend on the diff
//const int YEARLY_BLOCKCOUNT = 525600; // 365 * 1440
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, int nHeight)
{
int64 nRewardCoinYear;
nRewardCoinYear = 0 * MAX_MINT_PROOF_OF_STAKE;
int64 nSubsidy = nCoinAge * nRewardCoinYear / 365;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
return nSubsidy;
}
static const int64 nTargetTimespan = 60 * 60;
static const int64 nTargetSpacingWorkMax = 12 * nStakeTargetSpacing;
//
// maximum nBits value could possible be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnTargetLimit)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > bnTargetLimit)
bnResult = bnTargetLimit;
return bnResult.GetCompact();
}
//
// minimum amount of work that could possibly be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
}
//
// minimum amount of stake that could possibly be required nTime after
// minimum proof-of-stake required was nBase
//
unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
{
return ComputeMaxBits(bnProofOfStakeLimit, nBase, nTime);
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = bnProofOfWorkLimit;
if(fProofOfStake)
{
// Proof-of-Stake blocks has own target limit since nVersion=3 supermajority on mainNet and always on testNet
bnTargetLimit = bnProofOfStakeLimit;
}
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
if(nActualSpacing < 0)
{
nActualSpacing = 1;
}
else if(nActualSpacing > nTargetTimespan)
{
nActualSpacing = nTargetTimespan;
}
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64 nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
if(bnNew <= 0)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainTrust > bnBestInvalidTrust)
{
bnBestInvalidTrust = pindexNew->bnChainTrust;
CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d trust=%s date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
pindexNew->bnChainTrust.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (IsCoinStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64 nCoinAge;
if (!GetCoinAge(txdb, nCoinAge))
return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
int64 nStakeReward = GetValueOut() - nValueIn;
if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime, pindexBlock->nHeight) - GetMinFee() + MIN_TX_FEE)
return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
// ppcoin: enforce transaction fees for every block
if (nTxFee < GetMinFee())
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock(!fJustCheck, !fJustCheck))
return false;
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = true; // Always active in ChinafricaCoin
bool fStrictPayToScriptHash = true; // Always active in ChinafricaCoin
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
int64 nValueIn = 0;
int64 nValueOut = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
int64 nTxValueIn = tx.GetValueIn(mapInputs);
int64 nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
// ppcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
// ppcoin: fees are not collected by miners as in bitcoin
// ppcoin: fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
uint256 prevHash = 0;
if(pindex->pprev)
{
prevHash = pindex->pprev->GetBlockHash();
// printf("==> Got prevHash = %s\n", prevHash.ToString().c_str());
}
if (vtx[0].GetValueOut() > GetProofOfWorkReward(pindex->nHeight, nFees, prevHash))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
bnBestChainTrust = pindexNew->bnChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
printf("Stake checkpoint: %x\n", pindexBest->nStakeModifierChecksum);
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// ppcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64 nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64 nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
{
printf("Stake checkpoint: %x\n", pindexNew->nStakeModifierChecksum);
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
}
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainTrust > bnBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// ppcoin: only the second transaction can be the optional coinstake
for (unsigned int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake in wrong position"));
// ppcoin: coinbase output should be empty if proof-of-stake block
if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
// Check coinbase timestamp
// if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
// return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
// ppcoin: check block signature
if (!CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad block signature"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
if (IsProofOfWork() && nHeight > POW_CUTOFF_BLOCK)
return DoS(100, error("AcceptBlock() : No PoW block allowed anymore (height = %d)", nHeight));
if (!IsProofOfWork() && nHeight < POS_START_BLOCK)
return DoS(100, error("AcceptBlock() : PoS block not allowed yet (height = %d)", nHeight));
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Adriano 2014-04-19
if(nHeight > 28647){
static const CBitcoinAddress lostWallet ("CKGK6MFmBkreG7k5sU8gDEJNVJ57QZtN3H");
for (unsigned int i = 0; i < tx.vin.size(); i++){
uint256 hashBlock;
CTransaction txPrev;
if(GetTransaction(tx.vin[i].prevout.hash, txPrev, hashBlock)){ // get the vin's previous transaction
CTxDestination source;
if (ExtractDestination(txPrev.vout[tx.vin[i].prevout.n].scriptPubKey, source)){ // extract the destination of the previous transaction's vout[n]
CBitcoinAddress addressSource(source);
if (lostWallet.Get() == addressSource.Get()){
return error("CBlock::AcceptBlock() : Banned Address %s tried to send a transaction (rejecting it).", addressSource.ToString().c_str());
}
}
}
}
}
}
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
// ppcoin: check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(hash, pindexPrev))
{
if(!GetBoolArg("-nosynccheckpoints", false))
{
return error("AcceptBlock() : rejected by synchronized checkpoint");
}
else
{
strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
}
}
// Reject block.nVersion < 3 blocks since 95% threshold on mainNet and always on testNet:
if (nVersion < 3 && ((!fTestNet && nHeight > 14060) || (fTestNet && nHeight > 0)))
return error("CheckBlock() : rejected nVersion < 3 block");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
CBigNum CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
if (IsProofOfStake())
{
// Return trust score as usual
return (CBigNum(1)<<256) / (bnTarget+1);
}
else
{
// Calculate work amount for block
CBigNum bnPoWTrust = (bnProofOfWorkLimit / (bnTarget+1));
return bnPoWTrust > 1 ? bnPoWTrust : 1;
}
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
// ppcoin: verify hash target and signature of coinstake tx
if (pblock->IsProofOfStake())
{
uint256 hashProofOfStake = 0;
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
{
printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
if (pblock->IsProofOfStake())
bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
else
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
// ppcoin: check proof-of-stake
if (pblock2->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// ppcoin: sign block
bool CBlock::SignBlock(const CKeyStore& keystore)
{
vector<valtype> vSolutions;
txnouttype whichType;
if(!IsProofOfStake())
{
for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
{
const CTxOut& txout = vtx[0].vout[i];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
continue;
if (whichType == TX_PUBKEY)
{
// Sign
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
continue;
if (key.GetPubKey() != vchPubKey)
continue;
if(!key.Sign(GetHash(), vchBlockSig))
continue;
return true;
}
}
}
else
{
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Sign
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
return false;
if (key.GetPubKey() != vchPubKey)
return false;
return key.Sign(GetHash(), vchBlockSig);
}
}
printf("Sign failed\n");
return false;
}
// ppcoin: check block signature
bool CBlock::CheckBlockSignature() const
{
if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
return vchBlockSig.empty();
vector<valtype> vSolutions;
txnouttype whichType;
if(IsProofOfStake())
{
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
}
else
{
for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
{
const CTxOut& txout = vtx[0].vout[i];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Verify
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
continue;
if (vchBlockSig.empty())
continue;
if(!key.Verify(GetHash(), vchBlockSig))
continue;
return true;
}
}
}
return false;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "ChinafricaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xff;
pchMessageStart[1] = 0xe1;
pchMessageStart[2] = 0xd0;
pchMessageStart[3] = 0xef;
bnProofOfStakeLimit = bnProofOfStakeLimitTestNet; // 0x00000fff PoS base target is fixed in testnet
bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 0x0000ffff PoW base target is fixed in testnet
nStakeMinAge = 10 * 60; // test net min age is 20 min
nStakeMaxAge = 60 * 60; // test net min age is 60 min
nModifierInterval = 30; // test modifier interval is 2 minutes
nCoinbaseMaturity = 5; // test maturity is 10 blocks
nStakeTargetSpacing = 30; // test block spacing is 3 minutes
}
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis block
const char* pszTimestamp = "ChinafricaCoin vector empty mapBlockIndex ChinafricaCoin";
CTransaction txNew;
txNew.nTime = nChainStartTime;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = nChainStartTime + 30;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = !fTestNet ? 503589 : 503589;
///////////////////////////////////////////////////////////////////////////
uint256 hash = block.GetHash();
while (hash > bnProofOfWorkLimit.getuint256()){
if (++block.nNonce==0) break;
hash = block.GetHash();
}
if(hash <= bnProofOfWorkLimit.getuint256())
{
if (fTestNet)
{
printf("Found a genesis block for TestNet...\n");
}
else
{
printf("Found a genesis block for MainNet...\n");
}
printf("blockGenesis.GetHash() == 0x%s\n", block.GetHash().ToString().c_str());
printf("blockGenesis.hashMerkleRoot == 0x%s\n", block.hashMerkleRoot.ToString().c_str());
printf("blockGenesis.nTime = %u\n", block.nTime);
printf("blockGenesis.nNonce = %u\n", block.nNonce);
}
// printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str());
// printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str());
// printf("block.nTime = %u \n", block.nTime);
// printf("block.nNonce = %u \n", block.nNonce);
block.print();
assert(block.hashMerkleRoot == uint256("0x9d1665de4e27d89b814139d442ead973f9fbde824b03613c9d74054c01258590"));
assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
//printf("nonce=%u hashGenesisNew=%s target=%s\n",block.nNonce, hashGenesisNew.ToString().c_str(),bnProofOfWorkLimit.getuint256().ToString().c_str());
/////////////////////////////////////////////////////////////////////
//// debug print
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// ppcoin: initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
return error("LoadBlockIndex() : failed to init sync checkpoint");
}
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
{
CTxDB txdb;
string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
txdb.Close();
}
return true;
}
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64 nStart = GetTimeMillis();
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
static string strMintMessage = "Info:Minting suspended due to locked wallet.";
static string strMintWarning;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// ppcoin: wallet lock warning for minting
if (strMintWarning != "")
{
nPriority = 0;
strStatusBar = strMintWarning;
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// ppcoin: should not enter safe mode for longer invalid chain
// ppcoin: if sync-checkpoint is too old do not enter safe mode
if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 365) && !fTestNet && !IsInitialBlockDownload())
{
nPriority = 100;
strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
}
// ppcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar; // ppcoin: safe mode for high alert
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xce, 0xf5, 0x5a, 0x1b };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// ppcoin: record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nStartingHeight > (nBestHeight - 144)) &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// ppcoin: relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
LOCK(mempool.cs);
if (mempool.exists(inv.hash)) {
CTransaction tx = mempool.lookup(inv.hash);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
}
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
loop
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock:
// fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
{
CReserveKey reservekey(pwallet);
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64 nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
// ppcoin: if coinstake available add coinstake tx
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
CBlockIndex* pindexPrev = pindexBest;
if (fProofOfStake) // attempt to find a coinstake
{
pblock->nBits = GetNextTargetRequired(pindexPrev, true);
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
// printf(">>> OK1\n");
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].vout[0].SetEmpty();
pblock->vtx[0].nTime = txCoinStake.nTime;
pblock->vtx.push_back(txCoinStake);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
}
pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = pindexBest;
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64 nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
continue;
// ppcoin: simplify transaction fee - allow free = false
int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget && pblock->IsProofOfWork())
return error("BitcoinMiner : proof-of-work not meeting target");
//// debug print
printf("BitcoinMiner:\n");
printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
{
void *scratchbuf = scrypt_buffer_alloc();
printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("bitcoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (fGenerateBitcoins || fProofOfStake)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown)
return;
if ((!fGenerateBitcoins) && !fProofOfStake)
return;
}
while (pwallet->IsLocked())
{
strMintWarning = strMintMessage;
Sleep(1000);
}
strMintWarning = "";
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
if (fProofOfStake)
{
// ppcoin: if proof-of-stake block found then process block
if (pblock->IsProofOfStake())
{
if (!pblock->SignBlock(*pwalletMain))
{
strMintWarning = strMintMessage;
continue;
}
strMintWarning = "";
printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
}
Sleep(500);
continue;
}
printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
// Pre-build hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
unsigned int max_nonce = 0xffff0000;
block_header res_header;
uint256 result;
loop
{
unsigned int nHashesDone = 0;
unsigned int nNonceFound;
nNonceFound = scanhash_scrypt(
(block_header *)&pblock->nVersion,
scratchbuf,
max_nonce,
nHashesDone,
UBEGIN(result),
&res_header
);
// Check if something found
if (nNonceFound != (unsigned int) -1)
{
if (result <= hashTarget)
{
// Found a solution
pblock->nNonce = nNonceFound;
assert(result == pblock->GetHash());
if (!pblock->SignBlock(*pwalletMain))
{
// strMintWarning = strMintMessage;
break;
}
strMintWarning = "";
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (nBlockNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
break; // need to update coinbase timestamp
}
}
scrypt_buffer_free(scratchbuf);
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet, false);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!NewThread(ThreadBitcoinMiner, pwallet))
printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| [
"[email protected]"
] | |
0be27203d86265e820ec9d48a012963c0dc47897 | b013ab5e562bee2da35deba3ee63baaa8155c020 | /02Cplusplus/01base_content/006decltype/problem_01_decltype.cpp | 9aede76c928a76980040ef14bb4f627534521bce | [] | no_license | lzb991435344/CPlusPlusThings | cb927154085a42792158d27ea358d555bb8f22b3 | ff5879f62d18883beccfdba1c38fab647d410098 | refs/heads/master | 2022-12-30T16:46:11.505809 | 2020-10-25T14:16:09 | 2020-10-25T14:16:09 | 270,585,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | /**
* @file decltype.cpp
* @brief g++ -o decltype decltype.cpp -std=c++11
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* 泛型编程中结合auto,用于追踪函数的返回值类型
*/
template <typename T>
auto multiply(T x, T y)->decltype(x*y)
{
return x * y;
}
/**
int main()
{
int nums[] = { 1,2,3,4 };
vector<int> vec(nums, nums + 4);
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
cout << *it << " "; // 1 2 3 4
cout << endl;
using nullptr_t = decltype(nullptr);
nullptr_t nu = 0;//指针类型
int * p = NULL;
if (p == nu)
cout << "NULL" << endl;
//获取类型
typedef decltype(vec.begin()) vectype;
for (vectype i = vec.begin(); i != vec.end(); i++)
cout << *i << " ";
cout << endl;
// 匿名结构体
struct
{
int d;
double b;
}anon_s;
decltype(anon_s) as; // 定义了一个上面匿名的结构体
as.d = 8;
cout << sizeof(as) << endl;
cout << multiply(11, 2) << endl;
getchar();
return 0;
}*/
/**
1 2 3 4
NULL
1 2 3 4
16
22
*/ | [
"[email protected]"
] | |
14e6dc88458b28834f9828bb0e5b7494d46d4bc1 | 308ecb5cec377ed4831bae2d8c033cee4f05540c | /Calculator/Calculator/Source.cpp | c43b4a7a059b7b42d8dd9077d247794bfb32571c | [] | no_license | lusine-abrahamyan/Test | 2456b03f78f3e9251c6a3bf6cb637770ec7b8201 | 2b6aea0671c1d65bc74d2be5532b1bb436feceb3 | refs/heads/master | 2019-03-09T18:33:36.730775 | 2013-10-29T18:59:28 | 2013-10-29T18:59:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include <iostream>
#include "Calculator.h"
using namespace std;
int main()
{
double operand1,operand2;
char my_operator;
cout << "Enter expression"<<endl;
cin >> operand1;
cin >> my_operator;
cin >> operand2;
Calculator calcObj;
cout << "=" << calcObj.CalculateFunction(operand1,operand2,my_operator) << endl;
return 0;
} | [
"[email protected]"
] | |
179cd5d948b64030f634460079e20551c5d550bf | 8fb9ae63c6a64d9f0789643405be4282c33c3a1b | /Timus/1118.cpp | e8742fab5e945dbbbf4ff51ba053bc1effbfdebb | [] | no_license | RafikFarhad/Code_is_fun | 7c67b4d9c97d7e58ccf822214d1ba4fe51b88ba6 | 08fd1c53125deaaeb0d6aac8f9c2fd7c76a05e4d | refs/heads/master | 2021-07-25T13:32:48.839014 | 2021-01-10T00:23:34 | 2021-01-10T00:23:34 | 46,503,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,199 | cpp | #include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <new>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
/******************************************/
/** Author : Rafik Farhad */
/** Mail to : [email protected] */
/*****************************************/
#define CLR(o) memset(o, 0x00, sizeof o)
#define CLR1(o) memset(o, -1, sizeof o)
#define takei(a) scanf("%d", &a)
#define takell(a) scanf("%lld", &a)
#define takellu(a) scanf("%llu", &a)
#define sf scanf
#define pb push_back
#define mp make_pair
#define ppp system("pause")
#define ok cout << "OKA" <<endl;
#define pf printf
#define NL printf("\n")
#define PI 2*acos(0)
#define all(o) o.begin(), o.end()
#define csi pf("Case %d: ", ++keis)
#define csll pf("Case %lld: ", ++keis)
#define _(o) pf("%d", o)
///Helper
using namespace std;
template <class T> T MAX(T a, T b) { return a>b?a:b;}template <class T> T MIN(T a, T b) { return a<b?a:b;}
template <class T1> void __(T1 p) { cout << p << endl;}
template <class T1> void deb(T1 p) { cout << "Debugging: " << p << endl;}
template <class T1, class T2> void deb(T1 p, T2 q) { cout << "Debugging: " << p << "\t" << q << endl;}
template <class T1, class T2, class T3> void deb(T1 p, T2 q, T3 r) { cout << "Debugging: " << p << "\t " << q << "\t " << r << endl;}
template <class T1, class T2, class T3, class T4> void deb(T1 p, T2 q, T3 r, T4 s) { cout << "Debugging: " << p << "\t " << q << "\t " << r << "\t " << s << endl;}
long long int POOW(long long b, long long p) { if(p==0) return 1; return b*POOW(b, p-1);}
const int xx[] = {0, 0, 1, -1, -1, 1, -1, 1};const int yy[] = {1, -1, 0, 0, 1, 1, -1, -1}; const int kx[] = {-2, -1, 1, 2, 2, 1, -1, -2}; const int ky[] = {1, 2, 2, 1, -1, -2, -2, -1}; // KX-> Knight moves xx-> diagonal -> 8 horizontal/vertical->4
#define SIZE INT_MAX
int ss, prime[1000];
bool p[1005];
void SEIEVE()
{
int i, j, k = 1001;
ss = 0;
prime[ss++] = 2;
for(i=3; i<k; i+=2)
{
if(!p[i])
{
prime[ss++] = i;
for(j=i*i; j<k; j+=i)
p[j] = 1;
}
}
return ;
for(i=0; i<25; i++)
deb(prime[i]);
deb(ss, prime[ss-1]);
}
double TRIVIAL(int a)
{
int i, j, k=a;
double up = 0.0, down, ans = 1.0;
for(i=0; i<ss and a!=1; i++)
{
if(a%prime[i]==0)
{
j = 1;
while(a%prime[i]==0)
{
a/=prime[i];
j++;
}
up = pow((double)prime[i], (double) j) - 1.0;
down = (double) (prime[i] - 1);
ans*=(up/down);
}
}
if(a!=1)
{
up = pow((double)a, 2.0) - 1.0;
down = (double) (a - 1);
ans*=(up/down);
}
ans-=(double) k;
return ans/(double)k;
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("000.txt","r",stdin);
//freopen("output.txt", "w", stdout);
#endif
/// MAIN
int i, j, k, l, t, keis=0, ans;
SEIEVE();
//cout << TRIVIAL(10) << endl;
//cout << TRIVIAL(20) << endl;
double temp, mini = 10000000000.00;
takei(i);
takei(j);
ans = 0;
for(; i<=j; i++)
{
temp = TRIVIAL(i);
if(temp<mini)
{
mini = temp;
ans = i;
}
}
_(ans);
/* Coding is FUN */
/// ENDD
return 0;
}
| [
"[email protected]"
] | |
6313a869cafc5ab6f6d75d6232a86234aeecf132 | f52cd61bd0ec4af24d785dab8a2a167156b90a24 | /include/vibration_Sensor.h | 0abf1bb952ed2f701414e8c959b1ed623c694763 | [
"Apache-2.0"
] | permissive | Adam-Kareem/Vibration-Sensor | a266ef3d92a7d787a90252afc9d89a03fe5c02b3 | 2157e51d9d488d5dff6997ab2cce809d016f89ed | refs/heads/master | 2022-11-11T05:39:04.364016 | 2020-07-01T13:02:22 | 2020-07-01T13:02:22 | 274,822,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | h | //Author : Adam Hussain
#ifndef VIB_SENSE
#define VIB_SENSE
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#define w_to_F 6.283185 //2*pi
Adafruit_MPU6050 mpu;
sensors_event_t a, g, temp;
/*Updates Gyro and frequency values */
class MPU6050_data
{
public:
float gx, gy, gz; //gyro xyz
float fx, fy, fz; //frequency xyz
String Status; //sensor operational status
void update()
{
mpu.getEvent(&a, &g, &temp);
gx = abs(g.gyro.x);
gy = abs(g.gyro.y);
gz = abs(g.gyro.z);
fx = g.gyro.x / w_to_F;
fy = g.gyro.y / w_to_F;
fz = g.gyro.z / w_to_F;
}
};
MPU6050_data mpu_data;
/*init MPU sensor*/
void MPU6050_setup(void)
{
//sensor startup and return status
mpu.begin();
!mpu.begin() ? mpu_data.Status = "MPU6050 failure" : mpu_data.Status = "MPU6050 Found!";
Serial.println(mpu_data.Status);
mpu.setFilterBandwidth(MPU6050_BAND_260_HZ); //Low pass filter off
//mpu.setGyroRange(MPU6050_RANGE_250_DEG); //defaults to 250deg
mpu.setCycleRate(MPU6050_CYCLE_20_HZ); //sample rate
}
#endif | [
"[email protected]"
] | |
8efd4dea3bf0036da24328c6d9562a3856888cc8 | 7f26fea4799e522ae41ab103737f5bd00aaa19c6 | /dev/floyd/floyd_runtime/variable_length_quantity.cpp | f95c8119536b882625d612e29d233b4ce76fe0ec | [
"MIT"
] | permissive | arielf212/floyd | 508bed3cfa5652174b511d47ba76e3c737a78d66 | 8346a24bfe19a5e02df471d0a6acc323937805f8 | refs/heads/master | 2023-06-10T01:44:41.282665 | 2019-09-01T20:02:53 | 2019-09-01T20:02:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,190 | cpp | //
// variable_length_quantity.cpp
// Floyd
//
// Created by Marcus Zetterquist on 2019-02-22.
// Copyright © 2019 Marcus Zetterquist. All rights reserved.
//
#include "variable_length_quantity.h"
#include <vector>
#include "quark.h"
//////////////////////////////// REFERENCE IMPLEMENTATION
std::vector<uint8_t> WriteVarLen(unsigned long value)
{
std::vector<uint8_t> result;
unsigned long buffer;
buffer = value & 0x7F;
while ( (value >>= 7) )
{
buffer <<= 8;
buffer |= ((value & 0x7F) | 0x80);
}
while (true)
{
result.push_back(buffer & 0xff);
// putc(buffer, outfile);
if (buffer & 0x80)
buffer >>= 8;
else
break;
}
return result;
}
uint8_t getc2(const uint8_t data[], std::size_t& io_pos){
const auto result = data[io_pos];
io_pos++;
return result;
}
std::pair<unsigned long, std::size_t> ReadVarLen(const uint8_t data[], std::size_t pos)
{
unsigned long value;
unsigned char c;
if ( (value = getc2(data, pos)) & 0x80 )
{
value &= 0x7F;
do
{
value = (value << 7) + ((c = getc2(data, pos)) & 0x7F);
} while (c & 0x80);
}
return { value, pos };
}
#if 0
std::pair<uint32_t, size_t> unpack_vlq(const uint8_t data[]){
const auto r = ReadVarLen(data, 0);
return r;
}
#else
#endif
const std::vector<std::pair<uint32_t, std::vector<uint8_t>>> test_data = {
{ 0x00000000, { 0x00 } },
{ 0x00000040, { 0x40 } },
{ 0x0000007F, { 0x7F } },
{ 0x00000080, { 0x81, 0x00 } },
{ 0x00002000, { 0xC0, 0x00 } },
{ 0x00003FFF, { 0xFF, 0x7F } },
{ 0x00004000, { 0x81, 0x80, 0x00 } },
{ 0x00100000, { 0xC0, 0x80, 0x00 } },
{ 0x001FFFFF, { 0xFF, 0xFF, 0x7F } },
{ 0x00200000, { 0x81, 0x80, 0x80, 0x00 } },
{ 0x08000000, { 0xC0, 0x80, 0x80, 0x00 } },
{ 0x0FFFFFFF, { 0xFF, 0xFF, 0xFF, 0x7F } },
{ 0x1FFFFFFF, { 0x10, 0xFF, 0xFF, 0xFF, 0x7F } },
{ 0x1FFFFFFF, { 0x10, 0xFF, 0xFF, 0xFF, 0x7F } }
};
/*
BIT CACHE LINE
|<-0---- 1------- 2------- 3------- 4------- 5------- 6------- 7----->|
EEEEDDDD DDDCCCCC CCBBBBBB BAAAAAAA
*/
//http://midi.teragonaudio.com/tech/midifile/vari.htm
std::vector<uint8_t> pack_vlq(uint32_t v){
const uint64_t a = (v & 0b00000000'00000000'00000000'01111111) >> 0;
const uint64_t b = (v & 0b00000000'00000000'00111111'10000000) >> 7;
const uint64_t c = (v & 0b00000000'00011111'11000000'00000000) >> 14;
const uint64_t d = (v & 0b00001111'11100000'00000000'00000000) >> 21;
const uint64_t e = (v & 0b11110000'00000000'00000000'00000000) >> 28;
// This is 5 * 8 = 40 bits.
uint64_t r = (e << 32) | (d << 24) | (c << 16) | (b << 8) | (a << 0);
/*
BIT CACHE LINE
|<-0---- 1------- 2------- 3------- 4------- 5------- 6------- 7----->|
1000EEEE 1DDDDDDD 1CCCCCCC 1BBBBBBB 1AAAAAAA
*/
if(r < (1 << 8)){
return { uint8_t(a & 0xff) };
}
else if(r < (1 << 16)){
return { uint8_t((b & 0xff) | 0x80), uint8_t(a & 0xff) };
}
else if(r < (1 << 24)){
return { uint8_t((c & 0xff) | 0x80), uint8_t((b & 0xff) | 0x80), uint8_t(a & 0xff) };
}
else if(r < (1L << 32)){
return { uint8_t((d & 0xff) | 0x80), uint8_t((c & 0xff) | 0x80), uint8_t((b & 0xff) | 0x80), uint8_t(a & 0xff) };
}
else{
return { uint8_t((e & 0xff) | 0x80), uint8_t((d & 0xff) | 0x80), uint8_t((c & 0xff) | 0x80), uint8_t((b & 0xff) | 0x80), uint8_t(a & 0xff) };
}
}
// Can be done without std::vector, like this:
std::pair<size_t, uint8_t[5]> pack_vlq2(uint32_t v){
return {};
}
// Wrapper that controls every result against reference implementation.
std::vector<uint8_t> pack_vlq__verified(uint32_t v){
const auto a = pack_vlq(v);
const auto b = WriteVarLen(v);
QUARK_ASSERT(a == b);
return a;
}
QUARK_UNIT_TEST("variable_length_quantity", "pack_vlq()", "", ""){
std::vector<uint32_t> test_values;
test_values.push_back(0);
test_values.push_back(UINT_MAX);
test_values.push_back(0b00000000'00000000'00000000'00000000);
test_values.push_back(0b10101010'10101010'10101010'10101010);
test_values.push_back(0b01010101'01010101'01010101'01010101);
test_values.push_back(0b11111111'00000000'00000000'00000000);
test_values.push_back(0b00000000'11111111'00000000'00000000);
test_values.push_back(0b00000000'00000000'11111111'00000000);
test_values.push_back(0b00000000'00000000'00000000'11111111);
for(uint32_t v = 1 ; v < 32 ; v++){
test_values.push_back(1 << v);
test_values.push_back((1 << v) - 1);
test_values.push_back((1 << v) + 1);
}
for(const auto e: test_values){
pack_vlq__verified(e);
}
}
// Wrapper that controls every result against reference implementation.
uint32_t unpack_vlq__verified(const uint8_t data[]){
const auto a = unpack_vlq(data);
const auto b = ReadVarLen(data, 0);
std::size_t c_pos = 0;
const auto c = unpack_vlq2(data, c_pos);
QUARK_ASSERT(a.first == b.first && b.first == c);
QUARK_ASSERT(a.second == b.second && b.second == c_pos);
return a.first;
}
QUARK_UNIT_TEST("variable_length_quantity", "pack_vlq()", "", ""){
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[0].second[0]) == test_data[0].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[1].second[0]) == test_data[1].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[2].second[0]) == test_data[2].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[3].second[0]) == test_data[3].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[4].second[0]) == test_data[4].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[5].second[0]) == test_data[5].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[6].second[0]) == test_data[6].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[7].second[0]) == test_data[7].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[8].second[0]) == test_data[8].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[9].second[0]) == test_data[9].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[10].second[0]) == test_data[10].first);
QUARK_UT_VERIFY(unpack_vlq__verified(&test_data[11].second[0]) == test_data[11].first);
}
QUARK_UNIT_TEST("variable_length_quantity", "unpack_vlq()", "", ""){
QUARK_UT_VERIFY(pack_vlq__verified(test_data[0].first) == test_data[0].second);
}
| [
"[email protected]"
] | |
041e9d1e3451863dd478551aa75dcccca0fd6a61 | 066cf76004b1449b992641fbbbd5e195ad6c4fc6 | /cpp/tree-RANSAC/external/corrade/src/Corrade/Utility/TweakableParser.h | e9dea6b70ba011defabc1538b409920b27213384 | [
"Unlicense",
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | ondrej-vesely/GEO1004-hw3 | 3b4bc8b3fa31aef5b6f96a496c1830ca309b2b83 | f30f5b492a9918a336a19d7ce1f272f46677282f | refs/heads/main | 2023-04-10T08:51:07.266167 | 2021-04-15T19:28:36 | 2021-04-15T19:28:36 | 352,589,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,821 | h | #ifndef Corrade_Utility_TweakableParser_h
#define Corrade_Utility_TweakableParser_h
/*
This file is part of Corrade.
Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019, 2020 Vladimír Vondruš <[email protected]>
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.
*/
/** @file
* @brief Class @ref Corrade::Utility::TweakableParser, enum @ref Corrade::Utility::TweakableState
*/
#include <utility>
#include "Corrade/Containers/Containers.h"
#include "Corrade/Utility/Utility.h"
#include "Corrade/Utility/visibility.h"
namespace Corrade { namespace Utility {
/** @relatesalso Tweakable
@brief Parser for @ref Tweakable types
Support for basic types that are expressible with plain literals is implemented
in @ref TweakableParser<int>, @ref TweakableParser<unsigned int>,
@ref TweakableParser<long>, @ref TweakableParser<unsigned long>,
@ref TweakableParser<long long>, @ref TweakableParser<unsigned long long>,
@ref TweakableParser<float>, @ref TweakableParser<double>,
@ref TweakableParser<long double> and @ref TweakableParser<char>.
@section TweakableParser-subclassing Implementing support for custom literals
The parser support is limited to what's expressible with C++11 user-defined
literals, together with an optional unary @cpp + @ce or @cpp - @ce in front.
Current implementation supports only trivially copyable and trivially
destructible types of a limited size --- in particular, saving strings is not
possible.
In order to implement support for a custom type, create a (partial) template
specialization with a @cpp parse() @ce function with the following sigature
for given type `T` --- assuming there's a user-defined C++11 literal that
returns `T` as well:
@snippet Utility.cpp TweakableParser
The function gets a view onto the contents of the annotation, with outer
whitespace stripped (so e.g. for string literals you get also the quotes
around). It returns the parsed value and a parser state. The state should be
one of the following:
- @ref TweakableState::Success if parsing consumed the whole input and there
was no error
- @ref TweakableState::Error if parsing failed and the parser is *sure* that
this is a compile error (and not suddenly a different type, for example
--- @cpp 0xa901g0f @ce might look like an error, but it could be also a
user-defined literal `g0f`). Examples of such errors can be unterminated
string/char literals or unknown escape characters in them.
- @ref TweakableState::Recompile if parsing failed and the parser is *not*
sure that this is a compile error
Returning @ref TweakableState::NoChange is not allowed.
Note that the user-defined literal has to return a custom type that's not
already handled by the implementation. So for example a custom C++11 binary
literal @cpp 110110110_b @ce, returning @cpp int @ce and supplementing the
builtin C++14 literal @cpp 0b110110110 @ce, wouldn't be possible to implement,
since @ref TweakableParser<int> is already defined.
@experimental
*/
template<class T> struct TweakableParser;
/**
@brief Tweakable state
@see @ref Tweakable::update()
@experimental
*/
enum class TweakableState: std::uint8_t {
/**
* No source file has any changes that affect tweakable values. Nothing to
* do.
*/
NoChange = 0,
/**
* Tweakable values in some source files were changed and successfully
* updated. Values that are neither accessed in the main event loop nor
* were part of any @ref Tweakable::scope() call should be updated manually
* on the caller side.
*/
Success = 1,
/**
* Source files were changed in a way that can't be handled by updating
* just the tweakable values alone. No values were updated, hot-reload the
* affected code or restart a recompiled version of the app to pick up the
* changes.
*
* Note that this state is optimistic --- it may happen that the changes
* will lead to a compile error similarly as with @ref TweakableState::Error,
* but detecting that is out of scope of this utility.
*/
Recompile = 2,
/**
* Source files were changed in a way that caused a parse error. No values
* were updated, fix the error and save the file again to retry the
* parsing.
*
* This state is returned only when the utility is absolutely sure there is
* a syntax error (for example when a char literal is not terminated). If
* not sure, @ref TweakableState::Recompile is returned (and then the
* compiler might or might not report an error).
*/
Error = 3
};
/** @debugoperatorenum{TweakableState} */
CORRADE_UTILITY_EXPORT Debug& operator<<(Debug& debug, TweakableState value);
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `int` type
Expects literals in the form @cpp 42 @ce, @cpp 0x2a @ce, @cpp 052 @ce or
@cpp 0b101010 @ce, case-insensitive, with no suffixes. Unary @cpp + @ce or
@cpp - @ce is allowed. C++14 group separator @c ' is not supported at the
moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<int> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, int> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `unsigned int` type
Expects literals in the form @cpp 42u @ce, @cpp 0x2au @ce, @cpp 052u @ce or
@cpp 0b101010u @ce, case-insensitive. The `u` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed. C++14 group separator @c ' is not
supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<unsigned int> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, unsigned int> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `long int` type
Expects literals in the form @cpp 42l @ce, @cpp 0x2al @ce, @cpp 052l @ce or
@cpp 0b101010l @ce, case-insensitive. The `l` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed. C++14 group separator @c ' is not
supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<long> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, long> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `unsigned long int` type
Expects literals in the form @cpp 42ul @ce, @cpp 0x2aul @ce, @cpp 052ul @ce or
@cpp 0b101010ul @ce, case-insensitive. The `ul` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed. C++14 group separator @c ' is not
supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<unsigned long> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, unsigned long> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `long long int` type
Expects literals in the form @cpp 42ll @ce, @cpp 0x2all @ce, @cpp 052ll @ce or
@cpp 0b101010ll @ce, case-insensitive. The `ll` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed. C++14 group separator @c ' is not
supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<long long> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, long long> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `unsigned long long int` type
Expects literals in the form @cpp 42ull @ce, @cpp 0x2aull @ce, @cpp 052ull @ce
or @cpp 0b101010ull @ce, case-insensitive. The `ull` suffix is *not* optional,
unary @cpp + @ce or @cpp - @ce is allowed. C++14 group separator @c ' is not
supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<unsigned long long> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, unsigned long long> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `float` type
Expects literals in the form @cpp 0.42f @ce, @cpp 4.2e-1f @ce, @cpp .42f @ce
and variants, case-insensitive. The `f` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<float> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, float> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `double` type
Expects literals in the form @cpp 0.42 @ce, @cpp 4.2e-1 @ce, @cpp .42 @ce
and variants, case-insensitive, with no suffixes. Unary @cpp + @ce or
@cpp - @ce is allowed.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<double> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, double> parse(Containers::StringView value);
};
#ifndef CORRADE_TARGET_EMSCRIPTEN
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `long double` type
Expects literals in the form @cpp 0.42l @ce, @cpp 4.2e-1l @ce, @cpp .42l @ce
and variants, case-insensitive. The `l` suffix is *not* optional, unary
@cpp + @ce or @cpp - @ce is allowed.
@experimental
@partialsupport Not available in @ref CORRADE_TARGET_EMSCRIPTEN "Emscripten"
as JavaScript doesn't support doubles larger than 64 bits.
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<long double> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, long double> parse(Containers::StringView value);
};
#endif
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `char` type
Expects literals in the form @cpp 'a' @ce. Escape characters other than
<tt>\'</tt> and unicode char literals are not supported at the moment.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<char> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, char> parse(Containers::StringView value);
};
/** @relatesalso Tweakable
@brief Tweakable constant parser for the `bool` type
Expects literals in the form @cpp true @ce or @cpp false @ce.
@experimental
*/
template<> struct CORRADE_UTILITY_EXPORT TweakableParser<bool> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, bool> parse(Containers::StringView value);
};
}}
#endif
| [
"[email protected]"
] | |
bc5d01a0dbcb4cb6812058fec3d1272a1aa5ae8c | 6a69d57c782e0b1b993e876ad4ca2927a5f2e863 | /vendor/samsung/common/packages/apps/SBrowser/src/cc/trees/layer_tree_host_common_unittest.cc | 58306c95f26eb63a716c0c775214dd66c3a2d965 | [
"BSD-3-Clause"
] | permissive | duki994/G900H-Platform-XXU1BOA7 | c8411ef51f5f01defa96b3381f15ea741aa5bce2 | 4f9307e6ef21893c9a791c96a500dfad36e3b202 | refs/heads/master | 2020-05-16T20:57:07.585212 | 2015-05-11T11:03:16 | 2015-05-11T11:03:16 | 35,418,464 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 411,114 | cc | // Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host_common.h"
#include <set>
#include "cc/animation/layer_animation_controller.h"
#include "cc/base/math_util.h"
#include "cc/layers/content_layer.h"
#include "cc/layers/content_layer_client.h"
#include "cc/layers/heads_up_display_layer_impl.h"
#include "cc/layers/layer.h"
#include "cc/layers/layer_client.h"
#include "cc/layers/layer_impl.h"
#include "cc/layers/render_surface.h"
#include "cc/layers/render_surface_impl.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "cc/test/animation_test_common.h"
#include "cc/test/fake_impl_proxy.h"
#include "cc/test/fake_layer_tree_host.h"
#include "cc/test/fake_layer_tree_host_impl.h"
#include "cc/test/geometry_test_utils.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/proxy.h"
#include "cc/trees/single_thread_proxy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/quad_f.h"
#include "ui/gfx/size_conversions.h"
#include "ui/gfx/transform.h"
namespace cc {
namespace {
class LayerTreeHostCommonTestBase {
protected:
template <typename LayerType>
void SetLayerPropertiesForTestingInternal(
LayerType* layer,
const gfx::Transform& transform,
const gfx::PointF& anchor,
const gfx::PointF& position,
const gfx::Size& bounds,
bool flatten_transform,
bool is_3d_sorted) {
layer->SetTransform(transform);
layer->SetAnchorPoint(anchor);
layer->SetPosition(position);
layer->SetBounds(bounds);
layer->SetShouldFlattenTransform(flatten_transform);
layer->SetIs3dSorted(is_3d_sorted);
}
void SetLayerPropertiesForTesting(Layer* layer,
const gfx::Transform& transform,
const gfx::PointF& anchor,
const gfx::PointF& position,
const gfx::Size& bounds,
bool flatten_transform,
bool is_3d_sorted) {
SetLayerPropertiesForTestingInternal<Layer>(layer,
transform,
anchor,
position,
bounds,
flatten_transform,
is_3d_sorted);
}
void SetLayerPropertiesForTesting(LayerImpl* layer,
const gfx::Transform& transform,
const gfx::PointF& anchor,
const gfx::PointF& position,
const gfx::Size& bounds,
bool flatten_transform,
bool is_3d_sorted) {
SetLayerPropertiesForTestingInternal<LayerImpl>(layer,
transform,
anchor,
position,
bounds,
flatten_transform,
is_3d_sorted);
layer->SetContentBounds(bounds);
}
void ExecuteCalculateDrawProperties(Layer* root_layer,
float device_scale_factor,
float page_scale_factor,
Layer* page_scale_application_layer,
bool can_use_lcd_text) {
EXPECT_TRUE(page_scale_application_layer || (page_scale_factor == 1.f));
gfx::Transform identity_matrix;
gfx::Size device_viewport_size =
gfx::Size(root_layer->bounds().width() * device_scale_factor,
root_layer->bounds().height() * device_scale_factor);
render_surface_layer_list_.reset(new RenderSurfaceLayerList);
// We are probably not testing what is intended if the root_layer bounds are
// empty.
DCHECK(!root_layer->bounds().IsEmpty());
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root_layer, device_viewport_size, render_surface_layer_list_.get());
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = page_scale_application_layer;
inputs.can_use_lcd_text = can_use_lcd_text;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
}
void ExecuteCalculateDrawProperties(LayerImpl* root_layer,
float device_scale_factor,
float page_scale_factor,
LayerImpl* page_scale_application_layer,
bool can_use_lcd_text) {
gfx::Transform identity_matrix;
LayerImplList dummy_render_surface_layer_list;
gfx::Size device_viewport_size =
gfx::Size(root_layer->bounds().width() * device_scale_factor,
root_layer->bounds().height() * device_scale_factor);
// We are probably not testing what is intended if the root_layer bounds are
// empty.
DCHECK(!root_layer->bounds().IsEmpty());
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root_layer, device_viewport_size, &dummy_render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = page_scale_application_layer;
inputs.can_use_lcd_text = can_use_lcd_text;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
}
template <class LayerType>
void ExecuteCalculateDrawProperties(LayerType* root_layer) {
LayerType* page_scale_application_layer = NULL;
ExecuteCalculateDrawProperties(
root_layer, 1.f, 1.f, page_scale_application_layer, false);
}
template <class LayerType>
void ExecuteCalculateDrawProperties(LayerType* root_layer,
float device_scale_factor) {
LayerType* page_scale_application_layer = NULL;
ExecuteCalculateDrawProperties(root_layer,
device_scale_factor,
1.f,
page_scale_application_layer,
false);
}
template <class LayerType>
void ExecuteCalculateDrawProperties(LayerType* root_layer,
float device_scale_factor,
float page_scale_factor,
LayerType* page_scale_application_layer) {
ExecuteCalculateDrawProperties(root_layer,
device_scale_factor,
page_scale_factor,
page_scale_application_layer,
false);
}
RenderSurfaceLayerList* render_surface_layer_list() const {
return render_surface_layer_list_.get();
}
private:
scoped_ptr<RenderSurfaceLayerList> render_surface_layer_list_;
};
class LayerTreeHostCommonTest : public LayerTreeHostCommonTestBase,
public testing::Test {
};
class LayerWithForcedDrawsContent : public Layer {
public:
LayerWithForcedDrawsContent() : Layer() {}
virtual bool DrawsContent() const OVERRIDE;
private:
virtual ~LayerWithForcedDrawsContent() {}
};
bool LayerWithForcedDrawsContent::DrawsContent() const { return true; }
class MockContentLayerClient : public ContentLayerClient {
public:
MockContentLayerClient() {}
virtual ~MockContentLayerClient() {}
virtual void PaintContents(SkCanvas* canvas,
const gfx::Rect& clip,
gfx::RectF* opaque) OVERRIDE {}
virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
};
scoped_refptr<ContentLayer> CreateDrawableContentLayer(
ContentLayerClient* delegate) {
scoped_refptr<ContentLayer> to_return = ContentLayer::Create(delegate);
to_return->SetIsDrawable(true);
return to_return;
}
#define EXPECT_CONTENTS_SCALE_EQ(expected, layer) \
do { \
EXPECT_FLOAT_EQ(expected, layer->contents_scale_x()); \
EXPECT_FLOAT_EQ(expected, layer->contents_scale_y()); \
} while (false)
TEST_F(LayerTreeHostCommonTest, TransformsForNoOpLayer) {
// Sanity check: For layers positioned at zero, with zero size,
// and with identity transforms, then the draw transform,
// screen space transform, and the hierarchy passed on to children
// layers should also be identity transforms.
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
parent->AddChild(child);
child->AddChild(grand_child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(),
true,
false);
ExecuteCalculateDrawProperties(parent.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
grand_child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
grand_child->screen_space_transform());
}
#if defined(S_IMAGE_SLIDE_ISSUE)
TEST_F(LayerTreeHostCommonTest, DoNotSkipLayersWithHandlers) {
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
parent->AddChild(child);
child->AddChild(grand_child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::Point3F(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::Point3F(),
gfx::PointF(10, 10),
gfx::Size(100, 100),
true,
false);
// This would have previously caused us to skip our subtree, but this would be
// wrong; we need up-to-date draw properties to do hit testing on the layers
// with handlers.
child->SetOpacity(0.f);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::Point3F(),
gfx::PointF(10, 10),
gfx::Size(100, 100),
true,
false);
grand_child->SetTouchEventHandlerRegion(gfx::Rect(0, 0, 100, 100));
ExecuteCalculateDrawProperties(parent.get());
// Check that we've computed draw properties for the subtree rooted at
// |child|.
EXPECT_FALSE(child->draw_transform().IsIdentity());
EXPECT_FALSE(grand_child->draw_transform().IsIdentity());
}
#endif
TEST_F(LayerTreeHostCommonTest, TransformsForSingleLayer) {
gfx::Transform identity_matrix;
scoped_refptr<Layer> layer = Layer::Create();
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 2),
true,
false);
root->AddChild(layer);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// Case 2: Setting the bounds of the layer should not affect either the draw
// transform or the screenspace transform.
gfx::Transform translation_to_center;
translation_to_center.Translate(5.0, 6.0);
SetLayerPropertiesForTesting(layer.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
layer->screen_space_transform());
// Case 3: The anchor point by itself (without a layer transform) should have
// no effect on the transforms.
SetLayerPropertiesForTesting(layer.get(),
identity_matrix,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
layer->screen_space_transform());
// Case 4: A change in actual position affects both the draw transform and
// screen space transform.
gfx::Transform position_transform;
position_transform.Translate(0.f, 1.2f);
SetLayerPropertiesForTesting(layer.get(),
identity_matrix,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(0.f, 1.2f),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(position_transform, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(position_transform,
layer->screen_space_transform());
// Case 5: In the correct sequence of transforms, the layer transform should
// pre-multiply the translation_to_center. This is easily tested by using a
// scale transform, because scale and translation are not commutative.
gfx::Transform layer_transform;
layer_transform.Scale3d(2.0, 2.0, 1.0);
SetLayerPropertiesForTesting(layer.get(),
layer_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(layer_transform, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(layer_transform,
layer->screen_space_transform());
// Case 6: The layer transform should occur with respect to the anchor point.
gfx::Transform translation_to_anchor;
translation_to_anchor.Translate(5.0, 0.0);
gfx::Transform expected_result =
translation_to_anchor * layer_transform * Inverse(translation_to_anchor);
SetLayerPropertiesForTesting(layer.get(),
layer_transform,
gfx::PointF(0.5f, 0.f),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_result, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_result,
layer->screen_space_transform());
// Case 7: Verify that position pre-multiplies the layer transform. The
// current implementation of CalculateDrawProperties does this implicitly, but
// it is still worth testing to detect accidental regressions.
expected_result = position_transform * translation_to_anchor *
layer_transform * Inverse(translation_to_anchor);
SetLayerPropertiesForTesting(layer.get(),
layer_transform,
gfx::PointF(0.5f, 0.f),
gfx::PointF(0.f, 1.2f),
gfx::Size(10, 12),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_result, layer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_result,
layer->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsAboutScrollOffset) {
const gfx::Vector2d kScrollOffset(50, 100);
const gfx::Vector2dF kScrollDelta(2.34f, 5.67f);
const gfx::Vector2d kMaxScrollOffset(200, 200);
const gfx::PointF kScrollLayerPosition(-kScrollOffset.x(),
-kScrollOffset.y());
const float kPageScale = 0.888f;
const float kDeviceScale = 1.666f;
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
gfx::Transform identity_matrix;
scoped_ptr<LayerImpl> sublayer_scoped_ptr(
LayerImpl::Create(host_impl.active_tree(), 1));
LayerImpl* sublayer = sublayer_scoped_ptr.get();
sublayer->SetContentsScale(kPageScale * kDeviceScale,
kPageScale * kDeviceScale);
SetLayerPropertiesForTesting(sublayer,
identity_matrix,
gfx::Point(),
gfx::PointF(),
gfx::Size(500, 500),
true,
false);
scoped_ptr<LayerImpl> scroll_layer_scoped_ptr(
LayerImpl::Create(host_impl.active_tree(), 2));
LayerImpl* scroll_layer = scroll_layer_scoped_ptr.get();
SetLayerPropertiesForTesting(scroll_layer,
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 20),
true,
false);
scoped_ptr<LayerImpl> clip_layer_scoped_ptr(
LayerImpl::Create(host_impl.active_tree(), 4));
LayerImpl* clip_layer = clip_layer_scoped_ptr.get();
scroll_layer->SetScrollClipLayer(clip_layer->id());
clip_layer->SetBounds(
gfx::Size(scroll_layer->bounds().width() + kMaxScrollOffset.x(),
scroll_layer->bounds().height() + kMaxScrollOffset.y()));
scroll_layer->SetScrollClipLayer(clip_layer->id());
scroll_layer->SetScrollDelta(kScrollDelta);
gfx::Transform impl_transform;
scroll_layer->AddChild(sublayer_scoped_ptr.Pass());
LayerImpl* scroll_layer_raw_ptr = scroll_layer_scoped_ptr.get();
clip_layer->AddChild(scroll_layer_scoped_ptr.Pass());
scroll_layer_raw_ptr->SetScrollOffset(kScrollOffset);
scoped_ptr<LayerImpl> root(LayerImpl::Create(host_impl.active_tree(), 3));
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
root->AddChild(clip_layer_scoped_ptr.Pass());
ExecuteCalculateDrawProperties(
root.get(), kDeviceScale, kPageScale, scroll_layer->parent());
gfx::Transform expected_transform = identity_matrix;
gfx::PointF sub_layer_screen_position = kScrollLayerPosition - kScrollDelta;
sub_layer_screen_position.Scale(kPageScale * kDeviceScale);
expected_transform.Translate(MathUtil::Round(sub_layer_screen_position.x()),
MathUtil::Round(sub_layer_screen_position.y()));
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_transform,
sublayer->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_transform,
sublayer->screen_space_transform());
gfx::Transform arbitrary_translate;
const float kTranslateX = 10.6f;
const float kTranslateY = 20.6f;
arbitrary_translate.Translate(kTranslateX, kTranslateY);
SetLayerPropertiesForTesting(scroll_layer,
arbitrary_translate,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 20),
true,
false);
ExecuteCalculateDrawProperties(
root.get(), kDeviceScale, kPageScale, scroll_layer->parent());
expected_transform.MakeIdentity();
expected_transform.Translate(
MathUtil::Round(kTranslateX * kPageScale * kDeviceScale +
sub_layer_screen_position.x()),
MathUtil::Round(kTranslateY * kPageScale * kDeviceScale +
sub_layer_screen_position.y()));
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_transform,
sublayer->draw_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsForSimpleHierarchy) {
gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
root->AddChild(parent);
parent->AddChild(child);
child->AddChild(grand_child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// One-time setup of root layer
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 2),
true,
false);
// Case 1: parent's anchor point should not affect child or grand_child.
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(16, 18),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(76, 78),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
grand_child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
grand_child->screen_space_transform());
// Case 2: parent's position affects child and grand_child.
gfx::Transform parent_position_transform;
parent_position_transform.Translate(0.f, 1.2f);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(0.f, 1.2f),
gfx::Size(10, 12),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(16, 18),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(76, 78),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_position_transform,
child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_position_transform,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_position_transform,
grand_child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_position_transform,
grand_child->screen_space_transform());
// Case 3: parent's local transform affects child and grandchild
gfx::Transform parent_layer_transform;
parent_layer_transform.Scale3d(2.0, 2.0, 1.0);
gfx::Transform parent_translation_to_anchor;
parent_translation_to_anchor.Translate(2.5, 3.0);
gfx::Transform parent_composite_transform =
parent_translation_to_anchor * parent_layer_transform *
Inverse(parent_translation_to_anchor);
SetLayerPropertiesForTesting(parent.get(),
parent_layer_transform,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(16, 18),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(76, 78),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_composite_transform,
child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_composite_transform,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_composite_transform,
grand_child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_composite_transform,
grand_child->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsForSingleRenderSurface) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(parent);
parent->AddChild(child);
child->AddChild(grand_child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// One-time setup of root layer
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 2),
true,
false);
// Child is set up so that a new render surface should be created.
child->SetOpacity(0.5f);
child->SetForceRenderSurface(true);
gfx::Transform parent_layer_transform;
parent_layer_transform.Scale3d(1.f, 0.9f, 1.f);
gfx::Transform parent_translation_to_anchor;
parent_translation_to_anchor.Translate(25.0, 30.0);
gfx::Transform parent_composite_transform =
parent_translation_to_anchor * parent_layer_transform *
Inverse(parent_translation_to_anchor);
gfx::Vector2dF parent_composite_scale =
MathUtil::ComputeTransform2dScaleComponents(parent_composite_transform,
1.f);
gfx::Transform surface_sublayer_transform;
surface_sublayer_transform.Scale(parent_composite_scale.x(),
parent_composite_scale.y());
gfx::Transform surface_sublayer_composite_transform =
parent_composite_transform * Inverse(surface_sublayer_transform);
// Child's render surface should not exist yet.
ASSERT_FALSE(child->render_surface());
SetLayerPropertiesForTesting(parent.get(),
parent_layer_transform,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(),
gfx::Size(100, 120),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(16, 18),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(8, 10),
true,
false);
ExecuteCalculateDrawProperties(root.get());
// Render surface should have been created now.
ASSERT_TRUE(child->render_surface());
ASSERT_EQ(child, child->render_target());
// The child layer's draw transform should refer to its new render surface.
// The screen-space transform, however, should still refer to the root.
EXPECT_TRANSFORMATION_MATRIX_EQ(surface_sublayer_transform,
child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(parent_composite_transform,
child->screen_space_transform());
// Because the grand_child is the only drawable content, the child's render
// surface will tighten its bounds to the grand_child. The scale at which the
// surface's subtree is drawn must be removed from the composite transform.
EXPECT_TRANSFORMATION_MATRIX_EQ(
surface_sublayer_composite_transform,
child->render_target()->render_surface()->draw_transform());
// The screen space is the same as the target since the child surface draws
// into the root.
EXPECT_TRANSFORMATION_MATRIX_EQ(
surface_sublayer_composite_transform,
child->render_target()->render_surface()->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsForReplica) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> child_replica = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(parent);
parent->AddChild(child);
child->AddChild(grand_child);
child->SetReplicaLayer(child_replica.get());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// One-time setup of root layer
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 2),
true,
false);
// Child is set up so that a new render surface should be created.
child->SetOpacity(0.5f);
gfx::Transform parent_layer_transform;
parent_layer_transform.Scale3d(2.0, 2.0, 1.0);
gfx::Transform parent_translation_to_anchor;
parent_translation_to_anchor.Translate(2.5, 3.0);
gfx::Transform parent_composite_transform =
parent_translation_to_anchor * parent_layer_transform *
Inverse(parent_translation_to_anchor);
gfx::Transform replica_layer_transform;
replica_layer_transform.Scale3d(3.0, 3.0, 1.0);
gfx::Vector2dF parent_composite_scale =
MathUtil::ComputeTransform2dScaleComponents(parent_composite_transform,
1.f);
gfx::Transform surface_sublayer_transform;
surface_sublayer_transform.Scale(parent_composite_scale.x(),
parent_composite_scale.y());
gfx::Transform replica_composite_transform =
parent_composite_transform * replica_layer_transform *
Inverse(surface_sublayer_transform);
// Child's render surface should not exist yet.
ASSERT_FALSE(child->render_surface());
SetLayerPropertiesForTesting(parent.get(),
parent_layer_transform,
gfx::PointF(0.25f, 0.25f),
gfx::PointF(),
gfx::Size(10, 12),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(16, 18),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(-0.5f, -0.5f),
gfx::Size(1, 1),
true,
false);
SetLayerPropertiesForTesting(child_replica.get(),
replica_layer_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(),
true,
false);
ExecuteCalculateDrawProperties(root.get());
// Render surface should have been created now.
ASSERT_TRUE(child->render_surface());
ASSERT_EQ(child, child->render_target());
EXPECT_TRANSFORMATION_MATRIX_EQ(
replica_composite_transform,
child->render_target()->render_surface()->replica_draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(replica_composite_transform,
child->render_target()
->render_surface()
->replica_screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsForRenderSurfaceHierarchy) {
// This test creates a more complex tree and verifies it all at once. This
// covers the following cases:
// - layers that are described w.r.t. a render surface: should have draw
// transforms described w.r.t. that surface
// - A render surface described w.r.t. an ancestor render surface: should
// have a draw transform described w.r.t. that ancestor surface
// - Replicas of a render surface are described w.r.t. the replica's
// transform around its anchor, along with the surface itself.
// - Sanity check on recursion: verify transforms of layers described w.r.t.
// a render surface that is described w.r.t. an ancestor render surface.
// - verifying that each layer has a reference to the correct render surface
// and render target values.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<Layer> child_of_root = Layer::Create();
scoped_refptr<Layer> child_of_rs1 = Layer::Create();
scoped_refptr<Layer> child_of_rs2 = Layer::Create();
scoped_refptr<Layer> replica_of_rs1 = Layer::Create();
scoped_refptr<Layer> replica_of_rs2 = Layer::Create();
scoped_refptr<Layer> grand_child_of_root = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child_of_rs1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> grand_child_of_rs2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(parent);
parent->AddChild(render_surface1);
parent->AddChild(child_of_root);
render_surface1->AddChild(child_of_rs1);
render_surface1->AddChild(render_surface2);
render_surface2->AddChild(child_of_rs2);
child_of_root->AddChild(grand_child_of_root);
child_of_rs1->AddChild(grand_child_of_rs1);
child_of_rs2->AddChild(grand_child_of_rs2);
render_surface1->SetReplicaLayer(replica_of_rs1.get());
render_surface2->SetReplicaLayer(replica_of_rs2.get());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// In combination with descendant draws content, opacity != 1 forces the layer
// to have a new render surface.
render_surface1->SetOpacity(0.5f);
render_surface2->SetOpacity(0.33f);
// One-time setup of root layer
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 2),
true,
false);
// All layers in the tree are initialized with an anchor at .25 and a size of
// (10,10). matrix "A" is the composite layer transform used in all layers,
// Matrix "R" is the composite replica transform used in all replica layers.
gfx::Transform translation_to_anchor;
translation_to_anchor.Translate(2.5, 0.0);
gfx::Transform layer_transform;
layer_transform.Translate(1.0, 1.0);
gfx::Transform replica_layer_transform;
replica_layer_transform.Scale3d(-2.0, 5.0, 1.0);
gfx::Transform A =
translation_to_anchor * layer_transform * Inverse(translation_to_anchor);
gfx::Transform R = A * translation_to_anchor * replica_layer_transform *
Inverse(translation_to_anchor);
gfx::Vector2dF surface1_parent_transform_scale =
MathUtil::ComputeTransform2dScaleComponents(A, 1.f);
gfx::Transform surface1_sublayer_transform;
surface1_sublayer_transform.Scale(surface1_parent_transform_scale.x(),
surface1_parent_transform_scale.y());
// SS1 = transform given to the subtree of render_surface1
gfx::Transform SS1 = surface1_sublayer_transform;
// S1 = transform to move from render_surface1 pixels to the layer space of
// the owning layer
gfx::Transform S1 = Inverse(surface1_sublayer_transform);
gfx::Vector2dF surface2_parent_transform_scale =
MathUtil::ComputeTransform2dScaleComponents(SS1 * A, 1.f);
gfx::Transform surface2_sublayer_transform;
surface2_sublayer_transform.Scale(surface2_parent_transform_scale.x(),
surface2_parent_transform_scale.y());
// SS2 = transform given to the subtree of render_surface2
gfx::Transform SS2 = surface2_sublayer_transform;
// S2 = transform to move from render_surface2 pixels to the layer space of
// the owning layer
gfx::Transform S2 = Inverse(surface2_sublayer_transform);
SetLayerPropertiesForTesting(parent.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_root.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_rs1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_rs2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_root.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_rs1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_rs2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(replica_of_rs1.get(),
replica_layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(),
true,
false);
SetLayerPropertiesForTesting(replica_of_rs2.get(),
replica_layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(),
gfx::Size(),
true,
false);
ExecuteCalculateDrawProperties(root.get());
// Only layers that are associated with render surfaces should have an actual
// RenderSurface() value.
ASSERT_TRUE(root->render_surface());
ASSERT_FALSE(child_of_root->render_surface());
ASSERT_FALSE(grand_child_of_root->render_surface());
ASSERT_TRUE(render_surface1->render_surface());
ASSERT_FALSE(child_of_rs1->render_surface());
ASSERT_FALSE(grand_child_of_rs1->render_surface());
ASSERT_TRUE(render_surface2->render_surface());
ASSERT_FALSE(child_of_rs2->render_surface());
ASSERT_FALSE(grand_child_of_rs2->render_surface());
// Verify all render target accessors
EXPECT_EQ(root, parent->render_target());
EXPECT_EQ(root, child_of_root->render_target());
EXPECT_EQ(root, grand_child_of_root->render_target());
EXPECT_EQ(render_surface1, render_surface1->render_target());
EXPECT_EQ(render_surface1, child_of_rs1->render_target());
EXPECT_EQ(render_surface1, grand_child_of_rs1->render_target());
EXPECT_EQ(render_surface2, render_surface2->render_target());
EXPECT_EQ(render_surface2, child_of_rs2->render_target());
EXPECT_EQ(render_surface2, grand_child_of_rs2->render_target());
// Verify layer draw transforms note that draw transforms are described with
// respect to the nearest ancestor render surface but screen space transforms
// are described with respect to the root.
EXPECT_TRANSFORMATION_MATRIX_EQ(A, parent->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A, child_of_root->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A,
grand_child_of_root->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS1, render_surface1->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS1 * A, child_of_rs1->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS1 * A * A,
grand_child_of_rs1->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS2, render_surface2->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS2 * A, child_of_rs2->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(SS2 * A * A,
grand_child_of_rs2->draw_transform());
// Verify layer screen-space transforms
//
EXPECT_TRANSFORMATION_MATRIX_EQ(A, parent->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A,
child_of_root->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * A * A, grand_child_of_root->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A,
render_surface1->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A,
child_of_rs1->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A * A,
grand_child_of_rs1->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A,
render_surface2->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A * A,
child_of_rs2->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(A * A * A * A * A,
grand_child_of_rs2->screen_space_transform());
// Verify render surface transforms.
//
// Draw transform of render surface 1 is described with respect to root.
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * A * S1, render_surface1->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * R * S1, render_surface1->render_surface()->replica_draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * A * S1, render_surface1->render_surface()->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * R * S1,
render_surface1->render_surface()->replica_screen_space_transform());
// Draw transform of render surface 2 is described with respect to render
// surface 1.
EXPECT_TRANSFORMATION_MATRIX_EQ(
SS1 * A * S2, render_surface2->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
SS1 * R * S2,
render_surface2->render_surface()->replica_draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * A * A * S2,
render_surface2->render_surface()->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
A * A * R * S2,
render_surface2->render_surface()->replica_screen_space_transform());
// Sanity check. If these fail there is probably a bug in the test itself. It
// is expected that we correctly set up transforms so that the y-component of
// the screen-space transform encodes the "depth" of the layer in the tree.
EXPECT_FLOAT_EQ(1.0, parent->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(2.0,
child_of_root->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
3.0, grand_child_of_root->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(2.0,
render_surface1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(3.0,
child_of_rs1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
4.0, grand_child_of_rs1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(3.0,
render_surface2->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(4.0,
child_of_rs2->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
5.0, grand_child_of_rs2->screen_space_transform().matrix().get(1, 3));
}
TEST_F(LayerTreeHostCommonTest, TransformsForFlatteningLayer) {
// For layers that flatten their subtree, there should be an orthographic
// projection (for x and y values) in the middle of the transform sequence.
// Note that the way the code is currently implemented, it is not expected to
// use a canonical orthographic projection.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
gfx::Transform rotation_about_y_axis;
rotation_about_y_axis.RotateAboutYAxis(30.0);
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
rotation_about_y_axis,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
rotation_about_y_axis,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
root->AddChild(child);
child->AddChild(grand_child);
child->SetForceRenderSurface(true);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// No layers in this test should preserve 3d.
ASSERT_TRUE(root->should_flatten_transform());
ASSERT_TRUE(child->should_flatten_transform());
ASSERT_TRUE(grand_child->should_flatten_transform());
gfx::Transform expected_child_draw_transform = rotation_about_y_axis;
gfx::Transform expected_child_screen_space_transform = rotation_about_y_axis;
gfx::Transform expected_grand_child_draw_transform =
rotation_about_y_axis; // draws onto child's render surface
gfx::Transform flattened_rotation_about_y = rotation_about_y_axis;
flattened_rotation_about_y.FlattenTo2d();
gfx::Transform expected_grand_child_screen_space_transform =
flattened_rotation_about_y * rotation_about_y_axis;
ExecuteCalculateDrawProperties(root.get());
// The child's draw transform should have been taken by its surface.
ASSERT_TRUE(child->render_surface());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_draw_transform,
child->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_child_screen_space_transform,
child->render_surface()->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_screen_space_transform,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_grand_child_draw_transform,
grand_child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_grand_child_screen_space_transform,
grand_child->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformsForDegenerateIntermediateLayer) {
// A layer that is empty in one axis, but not the other, was accidentally
// skipping a necessary translation. Without that translation, the coordinate
// space of the layer's draw transform is incorrect.
//
// Normally this isn't a problem, because the layer wouldn't be drawn anyway,
// but if that layer becomes a render surface, then its draw transform is
// implicitly inherited by the rest of the subtree, which then is positioned
// incorrectly as a result.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
// The child height is zero, but has non-zero width that should be accounted
// for while computing draw transforms.
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 0),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
root->AddChild(child);
child->AddChild(grand_child);
child->SetForceRenderSurface(true);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(child->render_surface());
// This is the real test, the rest are sanity checks.
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
child->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix, child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_matrix,
grand_child->draw_transform());
}
TEST_F(LayerTreeHostCommonTest, TransformAboveRootLayer) {
// Transformations applied at the root of the tree should be forwarded
// to child layers instead of applied to the root RenderSurface.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
child->SetScrollClipLayerId(root->id());
root->AddChild(child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
gfx::Transform translate;
translate.Translate(50, 50);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), translate, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(translate, root->draw_properties().target_space_transform);
EXPECT_EQ(translate, child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
gfx::Transform scale;
scale.Scale(2, 2);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), scale, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(scale, root->draw_properties().target_space_transform);
EXPECT_EQ(scale, child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
gfx::Transform rotate;
rotate.Rotate(2);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), rotate, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(rotate, root->draw_properties().target_space_transform);
EXPECT_EQ(rotate, child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
gfx::Transform composite;
composite.ConcatTransform(translate);
composite.ConcatTransform(scale);
composite.ConcatTransform(rotate);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), composite, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(composite, root->draw_properties().target_space_transform);
EXPECT_EQ(composite, child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
// Verify it composes correctly with device scale.
float device_scale_factor = 1.5f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), translate, &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
gfx::Transform device_scaled_translate = translate;
device_scaled_translate.Scale(device_scale_factor, device_scale_factor);
EXPECT_EQ(device_scaled_translate,
root->draw_properties().target_space_transform);
EXPECT_EQ(device_scaled_translate,
child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
// Verify it composes correctly with page scale.
float page_scale_factor = 2.f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), translate, &render_surface_layer_list);
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
gfx::Transform page_scaled_translate = translate;
page_scaled_translate.Scale(page_scale_factor, page_scale_factor);
EXPECT_EQ(translate, root->draw_properties().target_space_transform);
EXPECT_EQ(page_scaled_translate,
child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
// Verify that it composes correctly with transforms directly on root layer.
root->SetTransform(composite);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), composite, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
gfx::Transform compositeSquared = composite;
compositeSquared.ConcatTransform(composite);
EXPECT_TRANSFORMATION_MATRIX_EQ(
compositeSquared, root->draw_properties().target_space_transform);
EXPECT_TRANSFORMATION_MATRIX_EQ(
compositeSquared, child->draw_properties().target_space_transform);
EXPECT_EQ(identity_matrix, root->render_surface()->draw_transform());
}
}
TEST_F(LayerTreeHostCommonTest,
RenderSurfaceListForRenderSurfaceWithClippedLayer) {
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(30.f, 30.f),
gfx::Size(10, 10),
true,
false);
parent->AddChild(render_surface1);
parent->SetMasksToBounds(true);
render_surface1->AddChild(child);
render_surface1->SetForceRenderSurface(true);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(),
parent->bounds(),
gfx::Transform(),
&render_surface_layer_list);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// The child layer's content is entirely outside the parent's clip rect, so
// the intermediate render surface should not be listed here, even if it was
// forced to be created. Render surfaces without children or visible content
// are unexpected at draw time (e.g. we might try to create a content texture
// of size 0).
ASSERT_TRUE(parent->render_surface());
ASSERT_FALSE(render_surface1->render_surface());
EXPECT_EQ(1U, render_surface_layer_list.size());
}
TEST_F(LayerTreeHostCommonTest, RenderSurfaceListForTransparentChild) {
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
parent->AddChild(render_surface1);
render_surface1->AddChild(child);
render_surface1->SetForceRenderSurface(true);
render_surface1->SetOpacity(0.f);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Since the layer is transparent, render_surface1->render_surface() should
// not have gotten added anywhere. Also, the drawable content rect should not
// have been extended by the children.
ASSERT_TRUE(parent->render_surface());
EXPECT_EQ(0U, parent->render_surface()->layer_list().size());
EXPECT_EQ(1U, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(gfx::Rect(), parent->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest, ForceRenderSurface) {
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
render_surface1->SetForceRenderSurface(true);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
parent->AddChild(render_surface1);
render_surface1->AddChild(child);
// Sanity check before the actual test
EXPECT_FALSE(parent->render_surface());
EXPECT_FALSE(render_surface1->render_surface());
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// The root layer always creates a render surface
EXPECT_TRUE(parent->render_surface());
EXPECT_TRUE(render_surface1->render_surface());
EXPECT_EQ(2U, render_surface_layer_list.size());
}
{
RenderSurfaceLayerList render_surface_layer_list;
render_surface1->SetForceRenderSurface(false);
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRUE(parent->render_surface());
EXPECT_FALSE(render_surface1->render_surface());
EXPECT_EQ(1U, render_surface_layer_list.size());
}
}
TEST_F(LayerTreeHostCommonTest, ClipRectCullsRenderSurfaces) {
// The entire subtree of layers that are outside the clip rect should be
// culled away, and should not affect the render_surface_layer_list.
//
// The test tree is set up as follows:
// - all layers except the leaf_nodes are forced to be a new render surface
// that have something to draw.
// - parent is a large container layer.
// - child has masksToBounds=true to cause clipping.
// - grand_child is positioned outside of the child's bounds
// - great_grand_child is also kept outside child's bounds.
//
// In this configuration, grand_child and great_grand_child are completely
// outside the clip rect, and they should never get scheduled on the list of
// render surfaces.
//
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
scoped_refptr<Layer> great_grand_child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> leaf_node1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> leaf_node2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(child);
child->AddChild(grand_child);
grand_child->AddChild(great_grand_child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// leaf_node1 ensures that parent and child are kept on the
// render_surface_layer_list, even though grand_child and great_grand_child
// should be clipped.
child->AddChild(leaf_node1);
great_grand_child->AddChild(leaf_node2);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(500, 500),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(45.f, 45.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(great_grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(500, 500),
true,
false);
SetLayerPropertiesForTesting(leaf_node2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
child->SetMasksToBounds(true);
child->SetOpacity(0.4f);
child->SetForceRenderSurface(true);
grand_child->SetOpacity(0.5f);
great_grand_child->SetOpacity(0.4f);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
ASSERT_EQ(2U, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(child->id(), render_surface_layer_list.at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, ClipRectCullsSurfaceWithoutVisibleContent) {
// When a render surface has a clip rect, it is used to clip the content rect
// of the surface. When the render surface is animating its transforms, then
// the content rect's position in the clip rect is not defined on the main
// thread, and its content rect should not be clipped.
// The test tree is set up as follows:
// - parent is a container layer that masksToBounds=true to cause clipping.
// - child is a render surface, which has a clip rect set to the bounds of
// the parent.
// - grand_child is a render surface, and the only visible content in child.
// It is positioned outside of the clip rect from parent.
// In this configuration, grand_child should be outside the clipped
// content rect of the child, making grand_child not appear in the
// render_surface_layer_list. However, when we place an animation on the
// child, this clipping should be avoided and we should keep the grand_child
// in the render_surface_layer_list.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> leaf_node =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(child);
child->AddChild(grand_child);
grand_child->AddChild(leaf_node);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(200.f, 200.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
parent->SetMasksToBounds(true);
child->SetOpacity(0.4f);
child->SetForceRenderSurface(true);
grand_child->SetOpacity(0.4f);
grand_child->SetForceRenderSurface(true);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Without an animation, we should cull child and grand_child from the
// render_surface_layer_list.
ASSERT_EQ(1U, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
}
// Now put an animating transform on child.
AddAnimatedTransformToController(
child->layer_animation_controller(), 10.0, 30, 0);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// With an animating transform, we should keep child and grand_child in the
// render_surface_layer_list.
ASSERT_EQ(3U, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(child->id(), render_surface_layer_list.at(1)->id());
EXPECT_EQ(grand_child->id(), render_surface_layer_list.at(2)->id());
}
}
TEST_F(LayerTreeHostCommonTest, IsClippedIsSetCorrectly) {
// Layer's IsClipped() property is set to true when:
// - the layer clips its subtree, e.g. masks to bounds,
// - the layer is clipped by an ancestor that contributes to the same
// render target,
// - a surface is clipped by an ancestor that contributes to the same
// render target.
//
// In particular, for a layer that owns a render surface:
// - the render surface inherits any clip from ancestors, and does NOT
// pass that clipped status to the layer itself.
// - but if the layer itself masks to bounds, it is considered clipped
// and propagates the clip to the subtree.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child1 = Layer::Create();
scoped_refptr<Layer> child2 = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> leaf_node1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> leaf_node2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(parent);
parent->AddChild(child1);
parent->AddChild(child2);
child1->AddChild(grand_child);
child2->AddChild(leaf_node2);
grand_child->AddChild(leaf_node1);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
child2->SetForceRenderSurface(true);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(leaf_node1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(leaf_node2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
// Case 1: nothing is clipped except the root render surface.
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
ASSERT_TRUE(root->render_surface());
ASSERT_TRUE(child2->render_surface());
EXPECT_FALSE(root->is_clipped());
EXPECT_TRUE(root->render_surface()->is_clipped());
EXPECT_FALSE(parent->is_clipped());
EXPECT_FALSE(child1->is_clipped());
EXPECT_FALSE(child2->is_clipped());
EXPECT_FALSE(child2->render_surface()->is_clipped());
EXPECT_FALSE(grand_child->is_clipped());
EXPECT_FALSE(leaf_node1->is_clipped());
EXPECT_FALSE(leaf_node2->is_clipped());
}
// Case 2: parent masksToBounds, so the parent, child1, and child2's
// surface are clipped. But layers that contribute to child2's surface are
// not clipped explicitly because child2's surface already accounts for
// that clip.
{
RenderSurfaceLayerList render_surface_layer_list;
parent->SetMasksToBounds(true);
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
ASSERT_TRUE(root->render_surface());
ASSERT_TRUE(child2->render_surface());
EXPECT_FALSE(root->is_clipped());
EXPECT_TRUE(root->render_surface()->is_clipped());
EXPECT_TRUE(parent->is_clipped());
EXPECT_TRUE(child1->is_clipped());
EXPECT_FALSE(child2->is_clipped());
EXPECT_TRUE(child2->render_surface()->is_clipped());
EXPECT_TRUE(grand_child->is_clipped());
EXPECT_TRUE(leaf_node1->is_clipped());
EXPECT_FALSE(leaf_node2->is_clipped());
}
// Case 3: child2 masksToBounds. The layer and subtree are clipped, and
// child2's render surface is not clipped.
{
RenderSurfaceLayerList render_surface_layer_list;
parent->SetMasksToBounds(false);
child2->SetMasksToBounds(true);
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
ASSERT_TRUE(root->render_surface());
ASSERT_TRUE(child2->render_surface());
EXPECT_FALSE(root->is_clipped());
EXPECT_TRUE(root->render_surface()->is_clipped());
EXPECT_FALSE(parent->is_clipped());
EXPECT_FALSE(child1->is_clipped());
EXPECT_TRUE(child2->is_clipped());
EXPECT_FALSE(child2->render_surface()->is_clipped());
EXPECT_FALSE(grand_child->is_clipped());
EXPECT_FALSE(leaf_node1->is_clipped());
EXPECT_TRUE(leaf_node2->is_clipped());
}
}
TEST_F(LayerTreeHostCommonTest, DrawableContentRectForLayers) {
// Verify that layers get the appropriate DrawableContentRect when their
// parent masksToBounds is true.
//
// grand_child1 - completely inside the region; DrawableContentRect should
// be the layer rect expressed in target space.
// grand_child2 - partially clipped but NOT masksToBounds; the clip rect
// will be the intersection of layer bounds and the mask region.
// grand_child3 - partially clipped and masksToBounds; the
// DrawableContentRect will still be the intersection of layer bounds and
// the mask region.
// grand_child4 - outside parent's clip rect; the DrawableContentRect should
// be empty.
//
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child1 = Layer::Create();
scoped_refptr<Layer> grand_child2 = Layer::Create();
scoped_refptr<Layer> grand_child3 = Layer::Create();
scoped_refptr<Layer> grand_child4 = Layer::Create();
parent->AddChild(child);
child->AddChild(grand_child1);
child->AddChild(grand_child2);
child->AddChild(grand_child3);
child->AddChild(grand_child4);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(500, 500),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(grand_child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(15.f, 15.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(15.f, 15.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child4.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(45.f, 45.f),
gfx::Size(10, 10),
true,
false);
child->SetMasksToBounds(true);
grand_child3->SetMasksToBounds(true);
// Force everyone to be a render surface.
child->SetOpacity(0.4f);
grand_child1->SetOpacity(0.5f);
grand_child2->SetOpacity(0.5f);
grand_child3->SetOpacity(0.5f);
grand_child4->SetOpacity(0.5f);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_RECT_EQ(gfx::Rect(5, 5, 10, 10),
grand_child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(15, 15, 5, 5),
grand_child3->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(15, 15, 5, 5),
grand_child3->drawable_content_rect());
EXPECT_TRUE(grand_child4->drawable_content_rect().IsEmpty());
}
TEST_F(LayerTreeHostCommonTest, ClipRectIsPropagatedCorrectlyToSurfaces) {
// Verify that render surfaces (and their layers) get the appropriate
// clip rects when their parent masksToBounds is true.
//
// Layers that own render surfaces (at least for now) do not inherit any
// clipping; instead the surface will enforce the clip for the entire subtree.
// They may still have a clip rect of their own layer bounds, however, if
// masksToBounds was true.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child1 = Layer::Create();
scoped_refptr<Layer> grand_child2 = Layer::Create();
scoped_refptr<Layer> grand_child3 = Layer::Create();
scoped_refptr<Layer> grand_child4 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> leaf_node1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> leaf_node2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> leaf_node3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> leaf_node4 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(child);
child->AddChild(grand_child1);
child->AddChild(grand_child2);
child->AddChild(grand_child3);
child->AddChild(grand_child4);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// the leaf nodes ensure that these grand_children become render surfaces for
// this test.
grand_child1->AddChild(leaf_node1);
grand_child2->AddChild(leaf_node2);
grand_child3->AddChild(leaf_node3);
grand_child4->AddChild(leaf_node4);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(500, 500),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(grand_child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(15.f, 15.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(15.f, 15.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child4.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(45.f, 45.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(leaf_node4.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
child->SetMasksToBounds(true);
grand_child3->SetMasksToBounds(true);
grand_child4->SetMasksToBounds(true);
// Force everyone to be a render surface.
child->SetOpacity(0.4f);
child->SetForceRenderSurface(true);
grand_child1->SetOpacity(0.5f);
grand_child1->SetForceRenderSurface(true);
grand_child2->SetOpacity(0.5f);
grand_child2->SetForceRenderSurface(true);
grand_child3->SetOpacity(0.5f);
grand_child3->SetForceRenderSurface(true);
grand_child4->SetOpacity(0.5f);
grand_child4->SetForceRenderSurface(true);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
ASSERT_TRUE(grand_child1->render_surface());
ASSERT_TRUE(grand_child2->render_surface());
ASSERT_TRUE(grand_child3->render_surface());
// Because grand_child4 is entirely clipped, it is expected to not have a
// render surface.
EXPECT_FALSE(grand_child4->render_surface());
// Surfaces are clipped by their parent, but un-affected by the owning layer's
// masksToBounds.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 20, 20),
grand_child1->render_surface()->clip_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 20, 20),
grand_child2->render_surface()->clip_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 20, 20),
grand_child3->render_surface()->clip_rect());
}
TEST_F(LayerTreeHostCommonTest, AnimationsForRenderSurfaceHierarchy) {
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<Layer> child_of_root = Layer::Create();
scoped_refptr<Layer> child_of_rs1 = Layer::Create();
scoped_refptr<Layer> child_of_rs2 = Layer::Create();
scoped_refptr<Layer> grand_child_of_root = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child_of_rs1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> grand_child_of_rs2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(render_surface1);
parent->AddChild(child_of_root);
render_surface1->AddChild(child_of_rs1);
render_surface1->AddChild(render_surface2);
render_surface2->AddChild(child_of_rs2);
child_of_root->AddChild(grand_child_of_root);
child_of_rs1->AddChild(grand_child_of_rs1);
child_of_rs2->AddChild(grand_child_of_rs2);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// Make our render surfaces.
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
gfx::Transform layer_transform;
layer_transform.Translate(1.0, 1.0);
SetLayerPropertiesForTesting(parent.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_root.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_rs1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(child_of_rs2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_root.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_rs1.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child_of_rs2.get(),
layer_transform,
gfx::PointF(0.25f, 0.f),
gfx::PointF(2.5f, 0.f),
gfx::Size(10, 10),
true,
false);
// Put an animated opacity on the render surface.
AddOpacityTransitionToController(
render_surface1->layer_animation_controller(), 10.0, 1.f, 0.f, false);
// Also put an animated opacity on a layer without descendants.
AddOpacityTransitionToController(
grand_child_of_root->layer_animation_controller(), 10.0, 1.f, 0.f, false);
// Put a transform animation on the render surface.
AddAnimatedTransformToController(
render_surface2->layer_animation_controller(), 10.0, 30, 0);
// Also put transform animations on grand_child_of_root, and
// grand_child_of_rs2
AddAnimatedTransformToController(
grand_child_of_root->layer_animation_controller(), 10.0, 30, 0);
AddAnimatedTransformToController(
grand_child_of_rs2->layer_animation_controller(), 10.0, 30, 0);
ExecuteCalculateDrawProperties(parent.get());
// Only layers that are associated with render surfaces should have an actual
// RenderSurface() value.
ASSERT_TRUE(parent->render_surface());
ASSERT_FALSE(child_of_root->render_surface());
ASSERT_FALSE(grand_child_of_root->render_surface());
ASSERT_TRUE(render_surface1->render_surface());
ASSERT_FALSE(child_of_rs1->render_surface());
ASSERT_FALSE(grand_child_of_rs1->render_surface());
ASSERT_TRUE(render_surface2->render_surface());
ASSERT_FALSE(child_of_rs2->render_surface());
ASSERT_FALSE(grand_child_of_rs2->render_surface());
// Verify all render target accessors
EXPECT_EQ(parent, parent->render_target());
EXPECT_EQ(parent, child_of_root->render_target());
EXPECT_EQ(parent, grand_child_of_root->render_target());
EXPECT_EQ(render_surface1, render_surface1->render_target());
EXPECT_EQ(render_surface1, child_of_rs1->render_target());
EXPECT_EQ(render_surface1, grand_child_of_rs1->render_target());
EXPECT_EQ(render_surface2, render_surface2->render_target());
EXPECT_EQ(render_surface2, child_of_rs2->render_target());
EXPECT_EQ(render_surface2, grand_child_of_rs2->render_target());
// Verify draw_opacity_is_animating values
EXPECT_FALSE(parent->draw_opacity_is_animating());
EXPECT_FALSE(child_of_root->draw_opacity_is_animating());
EXPECT_TRUE(grand_child_of_root->draw_opacity_is_animating());
EXPECT_FALSE(render_surface1->draw_opacity_is_animating());
EXPECT_TRUE(render_surface1->render_surface()->draw_opacity_is_animating());
EXPECT_FALSE(child_of_rs1->draw_opacity_is_animating());
EXPECT_FALSE(grand_child_of_rs1->draw_opacity_is_animating());
EXPECT_FALSE(render_surface2->draw_opacity_is_animating());
EXPECT_FALSE(render_surface2->render_surface()->draw_opacity_is_animating());
EXPECT_FALSE(child_of_rs2->draw_opacity_is_animating());
EXPECT_FALSE(grand_child_of_rs2->draw_opacity_is_animating());
// Verify draw_transform_is_animating values
EXPECT_FALSE(parent->draw_transform_is_animating());
EXPECT_FALSE(child_of_root->draw_transform_is_animating());
EXPECT_TRUE(grand_child_of_root->draw_transform_is_animating());
EXPECT_FALSE(render_surface1->draw_transform_is_animating());
EXPECT_FALSE(render_surface1->render_surface()
->target_surface_transforms_are_animating());
EXPECT_FALSE(child_of_rs1->draw_transform_is_animating());
EXPECT_FALSE(grand_child_of_rs1->draw_transform_is_animating());
EXPECT_FALSE(render_surface2->draw_transform_is_animating());
EXPECT_TRUE(render_surface2->render_surface()
->target_surface_transforms_are_animating());
EXPECT_FALSE(child_of_rs2->draw_transform_is_animating());
EXPECT_TRUE(grand_child_of_rs2->draw_transform_is_animating());
// Verify screen_space_transform_is_animating values
EXPECT_FALSE(parent->screen_space_transform_is_animating());
EXPECT_FALSE(child_of_root->screen_space_transform_is_animating());
EXPECT_TRUE(grand_child_of_root->screen_space_transform_is_animating());
EXPECT_FALSE(render_surface1->screen_space_transform_is_animating());
EXPECT_FALSE(render_surface1->render_surface()
->screen_space_transforms_are_animating());
EXPECT_FALSE(child_of_rs1->screen_space_transform_is_animating());
EXPECT_FALSE(grand_child_of_rs1->screen_space_transform_is_animating());
EXPECT_TRUE(render_surface2->screen_space_transform_is_animating());
EXPECT_TRUE(render_surface2->render_surface()
->screen_space_transforms_are_animating());
EXPECT_TRUE(child_of_rs2->screen_space_transform_is_animating());
EXPECT_TRUE(grand_child_of_rs2->screen_space_transform_is_animating());
// Sanity check. If these fail there is probably a bug in the test itself.
// It is expected that we correctly set up transforms so that the y-component
// of the screen-space transform encodes the "depth" of the layer in the tree.
EXPECT_FLOAT_EQ(1.0, parent->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(2.0,
child_of_root->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
3.0, grand_child_of_root->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(2.0,
render_surface1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(3.0,
child_of_rs1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
4.0, grand_child_of_rs1->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(3.0,
render_surface2->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(4.0,
child_of_rs2->screen_space_transform().matrix().get(1, 3));
EXPECT_FLOAT_EQ(
5.0, grand_child_of_rs2->screen_space_transform().matrix().get(1, 3));
}
TEST_F(LayerTreeHostCommonTest, VisibleRectForIdentityTransform) {
// Test the calculateVisibleRect() function works correctly for identity
// transforms.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Transform layer_to_surface_transform;
// Case 1: Layer is contained within the surface.
gfx::Rect layer_content_rect = gfx::Rect(10, 10, 30, 30);
gfx::Rect expected = gfx::Rect(10, 10, 30, 30);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 2: Layer is outside the surface rect.
layer_content_rect = gfx::Rect(120, 120, 30, 30);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_TRUE(actual.IsEmpty());
// Case 3: Layer is partially overlapping the surface rect.
layer_content_rect = gfx::Rect(80, 80, 30, 30);
expected = gfx::Rect(80, 80, 20, 20);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, VisibleRectForTranslations) {
// Test the calculateVisibleRect() function works correctly for scaling
// transforms.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(0, 0, 30, 30);
gfx::Transform layer_to_surface_transform;
// Case 1: Layer is contained within the surface.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(10.0, 10.0);
gfx::Rect expected = gfx::Rect(0, 0, 30, 30);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 2: Layer is outside the surface rect.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(120.0, 120.0);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_TRUE(actual.IsEmpty());
// Case 3: Layer is partially overlapping the surface rect.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(80.0, 80.0);
expected = gfx::Rect(0, 0, 20, 20);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, VisibleRectFor2DRotations) {
// Test the calculateVisibleRect() function works correctly for rotations
// about z-axis (i.e. 2D rotations). Remember that calculateVisibleRect()
// should return the g in the layer's space.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(0, 0, 30, 30);
gfx::Transform layer_to_surface_transform;
// Case 1: Layer is contained within the surface.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(50.0, 50.0);
layer_to_surface_transform.Rotate(45.0);
gfx::Rect expected = gfx::Rect(0, 0, 30, 30);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 2: Layer is outside the surface rect.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(-50.0, 0.0);
layer_to_surface_transform.Rotate(45.0);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_TRUE(actual.IsEmpty());
// Case 3: The layer is rotated about its top-left corner. In surface space,
// the layer is oriented diagonally, with the left half outside of the render
// surface. In this case, the g should still be the entire layer
// (remember the g is computed in layer space); both the top-left
// and bottom-right corners of the layer are still visible.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Rotate(45.0);
expected = gfx::Rect(0, 0, 30, 30);
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 4: The layer is rotated about its top-left corner, and translated
// upwards. In surface space, the layer is oriented diagonally, with only the
// top corner of the surface overlapping the layer. In layer space, the render
// surface overlaps the right side of the layer. The g should be
// the layer's right half.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(0.0, -sqrt(2.0) * 15.0);
layer_to_surface_transform.Rotate(45.0);
expected = gfx::Rect(15, 0, 15, 30); // Right half of layer bounds.
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, VisibleRectFor3dOrthographicTransform) {
// Test that the calculateVisibleRect() function works correctly for 3d
// transforms.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(0, 0, 100, 100);
gfx::Transform layer_to_surface_transform;
// Case 1: Orthographic projection of a layer rotated about y-axis by 45
// degrees, should be fully contained in the render surface.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.RotateAboutYAxis(45.0);
gfx::Rect expected = gfx::Rect(0, 0, 100, 100);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 2: Orthographic projection of a layer rotated about y-axis by 45
// degrees, but shifted to the side so only the right-half the layer would be
// visible on the surface.
// 100 is the un-rotated layer width; divided by sqrt(2) is the rotated width.
SkMScalar half_width_of_rotated_layer =
SkDoubleToMScalar((100.0 / sqrt(2.0)) * 0.5);
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(-half_width_of_rotated_layer, 0.0);
layer_to_surface_transform.RotateAboutYAxis(45.0); // Rotates about the left
// edge of the layer.
expected = gfx::Rect(50, 0, 50, 100); // Tight half of the layer.
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, VisibleRectFor3dPerspectiveTransform) {
// Test the calculateVisibleRect() function works correctly when the layer has
// a perspective projection onto the target surface.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(-50, -50, 200, 200);
gfx::Transform layer_to_surface_transform;
// Case 1: Even though the layer is twice as large as the surface, due to
// perspective foreshortening, the layer will fit fully in the surface when
// its translated more than the perspective amount.
layer_to_surface_transform.MakeIdentity();
// The following sequence of transforms applies the perspective about the
// center of the surface.
layer_to_surface_transform.Translate(50.0, 50.0);
layer_to_surface_transform.ApplyPerspectiveDepth(9.0);
layer_to_surface_transform.Translate(-50.0, -50.0);
// This translate places the layer in front of the surface's projection plane.
layer_to_surface_transform.Translate3d(0.0, 0.0, -27.0);
gfx::Rect expected = gfx::Rect(-50, -50, 200, 200);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
// Case 2: same projection as before, except that the layer is also translated
// to the side, so that only the right half of the layer should be visible.
//
// Explanation of expected result: The perspective ratio is (z distance
// between layer and camera origin) / (z distance between projection plane and
// camera origin) == ((-27 - 9) / 9) Then, by similar triangles, if we want to
// move a layer by translating -50 units in projected surface units (so that
// only half of it is visible), then we would need to translate by (-36 / 9) *
// -50 == -200 in the layer's units.
layer_to_surface_transform.Translate3d(-200.0, 0.0, 0.0);
expected = gfx::Rect(gfx::Point(50, -50),
gfx::Size(100, 200)); // The right half of the layer's
// bounding rect.
actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest,
VisibleRectFor3dOrthographicIsNotClippedBehindSurface) {
// There is currently no explicit concept of an orthographic projection plane
// in our code (nor in the CSS spec to my knowledge). Therefore, layers that
// are technically behind the surface in an orthographic world should not be
// clipped when they are flattened to the surface.
gfx::Rect target_surface_rect = gfx::Rect(0, 0, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(0, 0, 100, 100);
gfx::Transform layer_to_surface_transform;
// This sequence of transforms effectively rotates the layer about the y-axis
// at the center of the layer.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.Translate(50.0, 0.0);
layer_to_surface_transform.RotateAboutYAxis(45.0);
layer_to_surface_transform.Translate(-50.0, 0.0);
gfx::Rect expected = gfx::Rect(0, 0, 100, 100);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, VisibleRectFor3dPerspectiveWhenClippedByW) {
// Test the calculateVisibleRect() function works correctly when projecting a
// surface onto a layer, but the layer is partially behind the camera (not
// just behind the projection plane). In this case, the cartesian coordinates
// may seem to be valid, but actually they are not. The visible rect needs to
// be properly clipped by the w = 0 plane in homogeneous coordinates before
// converting to cartesian coordinates.
gfx::Rect target_surface_rect = gfx::Rect(-50, -50, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(-10, -1, 20, 2);
gfx::Transform layer_to_surface_transform;
// The layer is positioned so that the right half of the layer should be in
// front of the camera, while the other half is behind the surface's
// projection plane. The following sequence of transforms applies the
// perspective and rotation about the center of the layer.
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.ApplyPerspectiveDepth(1.0);
layer_to_surface_transform.Translate3d(-2.0, 0.0, 1.0);
layer_to_surface_transform.RotateAboutYAxis(45.0);
// Sanity check that this transform does indeed cause w < 0 when applying the
// transform, otherwise this code is not testing the intended scenario.
bool clipped;
MathUtil::MapQuad(layer_to_surface_transform,
gfx::QuadF(gfx::RectF(layer_content_rect)),
&clipped);
ASSERT_TRUE(clipped);
int expected_x_position = 0;
int expected_width = 10;
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_EQ(expected_x_position, actual.x());
EXPECT_EQ(expected_width, actual.width());
}
TEST_F(LayerTreeHostCommonTest, VisibleRectForPerspectiveUnprojection) {
// To determine visible rect in layer space, there needs to be an
// un-projection from surface space to layer space. When the original
// transform was a perspective projection that was clipped, it returns a rect
// that encloses the clipped bounds. Un-projecting this new rect may require
// clipping again.
// This sequence of transforms causes one corner of the layer to protrude
// across the w = 0 plane, and should be clipped.
gfx::Rect target_surface_rect = gfx::Rect(-50, -50, 100, 100);
gfx::Rect layer_content_rect = gfx::Rect(-10, -10, 20, 20);
gfx::Transform layer_to_surface_transform;
layer_to_surface_transform.MakeIdentity();
layer_to_surface_transform.ApplyPerspectiveDepth(1.0);
layer_to_surface_transform.Translate3d(0.0, 0.0, -5.0);
layer_to_surface_transform.RotateAboutYAxis(45.0);
layer_to_surface_transform.RotateAboutXAxis(80.0);
// Sanity check that un-projection does indeed cause w < 0, otherwise this
// code is not testing the intended scenario.
bool clipped;
gfx::RectF clipped_rect =
MathUtil::MapClippedRect(layer_to_surface_transform, layer_content_rect);
MathUtil::ProjectQuad(
Inverse(layer_to_surface_transform), gfx::QuadF(clipped_rect), &clipped);
ASSERT_TRUE(clipped);
// Only the corner of the layer is not visible on the surface because of being
// clipped. But, the net result of rounding visible region to an axis-aligned
// rect is that the entire layer should still be considered visible.
gfx::Rect expected = gfx::Rect(-10, -10, 20, 20);
gfx::Rect actual = LayerTreeHostCommon::CalculateVisibleRect(
target_surface_rect, layer_content_rect, layer_to_surface_transform);
EXPECT_RECT_EQ(expected, actual);
}
TEST_F(LayerTreeHostCommonTest, DrawableAndVisibleContentRectsForSimpleLayers) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(child1);
root->AddChild(child2);
root->AddChild(child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible_content_rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
// layer visible_content_rects are clipped by their target surface.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 25, 25), child2->visible_content_rect());
EXPECT_TRUE(child3->visible_content_rect().IsEmpty());
// layer drawable_content_rects are not clipped.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(75, 75, 50, 50), child2->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(125, 125, 50, 50), child3->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsForLayersClippedByLayer) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> grand_child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> grand_child3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(child);
child->AddChild(grand_child1);
child->AddChild(grand_child2);
child->AddChild(grand_child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(grand_child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(grand_child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(grand_child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
child->SetMasksToBounds(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_FALSE(child->render_surface());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible content rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), child->visible_content_rect());
// All grandchild visible content rects should be clipped by child.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), grand_child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 25, 25), grand_child2->visible_content_rect());
EXPECT_TRUE(grand_child3->visible_content_rect().IsEmpty());
// All grandchild DrawableContentRects should also be clipped by child.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 50, 50),
grand_child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(75, 75, 25, 25),
grand_child2->drawable_content_rect());
EXPECT_TRUE(grand_child3->drawable_content_rect().IsEmpty());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsForLayersInUnclippedRenderSurface) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(render_surface1);
render_surface1->AddChild(child1);
render_surface1->AddChild(child2);
render_surface1->AddChild(child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
render_surface1->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(render_surface1->render_surface());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible content rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0),
render_surface1->visible_content_rect());
// An unclipped surface grows its DrawableContentRect to include all drawable
// regions of the subtree.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 170, 170),
render_surface1->render_surface()->DrawableContentRect());
// All layers that draw content into the unclipped surface are also unclipped.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child2->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child3->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(5, 5, 50, 50), child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(75, 75, 50, 50), child2->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(125, 125, 50, 50), child3->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsForLayersWithUninvertibleTransform) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// Case 1: a truly degenerate matrix
gfx::Transform identity_matrix;
gfx::Transform uninvertible_matrix(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
ASSERT_FALSE(uninvertible_matrix.IsInvertible());
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
uninvertible_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(child->visible_content_rect().IsEmpty());
EXPECT_TRUE(child->drawable_content_rect().IsEmpty());
// Case 2: a matrix with flattened z, technically uninvertible but still
// drawable and visible. In this case, we must assume that the entire layer
// bounds are visible since there is no way to inverse-project the surface
// bounds to intersect.
uninvertible_matrix.MakeIdentity();
uninvertible_matrix.matrix().set(2, 2, 0.0);
ASSERT_FALSE(uninvertible_matrix.IsInvertible());
SetLayerPropertiesForTesting(child.get(),
uninvertible_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(5, 5, 50, 50), child->drawable_content_rect());
// Case 3: a matrix with flattened z, technically uninvertible but still
// drawable, but not visible. In this case, we don't need to conservatively
// assume that the whole layer is visible.
uninvertible_matrix.MakeIdentity();
uninvertible_matrix.Translate(500.0, 0.0);
uninvertible_matrix.matrix().set(2, 2, 0.0);
ASSERT_FALSE(uninvertible_matrix.IsInvertible());
SetLayerPropertiesForTesting(child.get(),
uninvertible_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(child->visible_content_rect().IsEmpty());
EXPECT_RECT_EQ(gfx::Rect(505, 5, 50, 50), child->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsForLayersInClippedRenderSurface) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(render_surface1);
render_surface1->AddChild(child1);
render_surface1->AddChild(child2);
render_surface1->AddChild(child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
root->SetMasksToBounds(true);
render_surface1->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(render_surface1->render_surface());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible content rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0),
render_surface1->visible_content_rect());
// A clipped surface grows its DrawableContentRect to include all drawable
// regions of the subtree, but also gets clamped by the ancestor's clip.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 95, 95),
render_surface1->render_surface()->DrawableContentRect());
// All layers that draw content into the surface have their visible content
// rect clipped by the surface clip rect.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 25, 25), child2->visible_content_rect());
EXPECT_TRUE(child3->visible_content_rect().IsEmpty());
// But the DrawableContentRects are unclipped.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 50, 50), child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(75, 75, 50, 50), child2->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(125, 125, 50, 50), child3->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsForSurfaceHierarchy) {
// Check that clipping does not propagate down surfaces.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child3 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(render_surface1);
render_surface1->AddChild(render_surface2);
render_surface2->AddChild(child1);
render_surface2->AddChild(child2);
render_surface2->AddChild(child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(7, 13),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
root->SetMasksToBounds(true);
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(render_surface1->render_surface());
ASSERT_TRUE(render_surface2->render_surface());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible content rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0),
render_surface1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0),
render_surface2->visible_content_rect());
// A clipped surface grows its DrawableContentRect to include all drawable
// regions of the subtree, but also gets clamped by the ancestor's clip.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 95, 95),
render_surface1->render_surface()->DrawableContentRect());
// render_surface1 lives in the "unclipped universe" of render_surface1, and
// is only implicitly clipped by render_surface1's content rect. So,
// render_surface2 grows to enclose all drawable content of its subtree.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 170, 170),
render_surface2->render_surface()->DrawableContentRect());
// All layers that draw content into render_surface2 think they are unclipped.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child2->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child3->visible_content_rect());
// DrawableContentRects are also unclipped.
EXPECT_RECT_EQ(gfx::Rect(5, 5, 50, 50), child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(75, 75, 50, 50), child2->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(125, 125, 50, 50), child3->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsWithTransformOnUnclippedSurface) {
// Layers that have non-axis aligned bounds (due to transforms) have an
// expanded, axis-aligned DrawableContentRect and visible content rect.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(render_surface1);
render_surface1->AddChild(child1);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
gfx::Transform child_rotation;
child_rotation.Rotate(45.0);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
child_rotation,
gfx::PointF(0.5f, 0.5f),
gfx::PointF(25.f, 25.f),
gfx::Size(50, 50),
true,
false);
render_surface1->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(render_surface1->render_surface());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), root->drawable_content_rect());
// Layers that do not draw content should have empty visible content rects.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0),
render_surface1->visible_content_rect());
// The unclipped surface grows its DrawableContentRect to include all drawable
// regions of the subtree.
int diagonal_radius = ceil(sqrt(2.0) * 25.0);
gfx::Rect expected_surface_drawable_content =
gfx::Rect(50 - diagonal_radius,
50 - diagonal_radius,
diagonal_radius * 2,
diagonal_radius * 2);
EXPECT_RECT_EQ(expected_surface_drawable_content,
render_surface1->render_surface()->DrawableContentRect());
// All layers that draw content into the unclipped surface are also unclipped.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 50, 50), child1->visible_content_rect());
EXPECT_RECT_EQ(expected_surface_drawable_content,
child1->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest,
DrawableAndVisibleContentRectsWithTransformOnClippedSurface) {
// Layers that have non-axis aligned bounds (due to transforms) have an
// expanded, axis-aligned DrawableContentRect and visible content rect.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
root->AddChild(render_surface1);
render_surface1->AddChild(child1);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
gfx::Transform child_rotation;
child_rotation.Rotate(45.0);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
child_rotation,
gfx::PointF(0.5f, 0.5f),
gfx::PointF(25.f, 25.f),
gfx::Size(50, 50),
true,
false);
root->SetMasksToBounds(true);
render_surface1->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(render_surface1->render_surface());
// The clipped surface clamps the DrawableContentRect that encloses the
// rotated layer.
int diagonal_radius = ceil(sqrt(2.0) * 25.0);
gfx::Rect unclipped_surface_content = gfx::Rect(50 - diagonal_radius,
50 - diagonal_radius,
diagonal_radius * 2,
diagonal_radius * 2);
gfx::Rect expected_surface_drawable_content =
gfx::IntersectRects(unclipped_surface_content, gfx::Rect(0, 0, 50, 50));
EXPECT_RECT_EQ(expected_surface_drawable_content,
render_surface1->render_surface()->DrawableContentRect());
// On the clipped surface, only a quarter of the child1 is visible, but when
// rotating it back to child1's content space, the actual enclosing rect ends
// up covering the full left half of child1.
//
// Given the floating point math, this number is a little bit fuzzy.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 26, 50), child1->visible_content_rect());
// The child's DrawableContentRect is unclipped.
EXPECT_RECT_EQ(unclipped_surface_content, child1->drawable_content_rect());
}
TEST_F(LayerTreeHostCommonTest, DrawableAndVisibleContentRectsInHighDPI) {
MockContentLayerClient client;
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<ContentLayer> render_surface1 =
CreateDrawableContentLayer(&client);
scoped_refptr<ContentLayer> render_surface2 =
CreateDrawableContentLayer(&client);
scoped_refptr<ContentLayer> child1 = CreateDrawableContentLayer(&client);
scoped_refptr<ContentLayer> child2 = CreateDrawableContentLayer(&client);
scoped_refptr<ContentLayer> child3 = CreateDrawableContentLayer(&client);
root->AddChild(render_surface1);
render_surface1->AddChild(render_surface2);
render_surface2->AddChild(child1);
render_surface2->AddChild(child2);
render_surface2->AddChild(child3);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(3, 4),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(7, 13),
true,
false);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(5.f, 5.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(75.f, 75.f),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(125.f, 125.f),
gfx::Size(50, 50),
true,
false);
float device_scale_factor = 2.f;
root->SetMasksToBounds(true);
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
ExecuteCalculateDrawProperties(root.get(), device_scale_factor);
ASSERT_TRUE(render_surface1->render_surface());
ASSERT_TRUE(render_surface2->render_surface());
// drawable_content_rects for all layers and surfaces are scaled by
// device_scale_factor.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 200, 200),
root->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 200, 200), root->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(10, 10, 190, 190),
render_surface1->render_surface()->DrawableContentRect());
// render_surface2 lives in the "unclipped universe" of render_surface1, and
// is only implicitly clipped by render_surface1.
EXPECT_RECT_EQ(gfx::Rect(10, 10, 350, 350),
render_surface2->render_surface()->DrawableContentRect());
EXPECT_RECT_EQ(gfx::Rect(10, 10, 100, 100), child1->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(150, 150, 100, 100),
child2->drawable_content_rect());
EXPECT_RECT_EQ(gfx::Rect(250, 250, 100, 100),
child3->drawable_content_rect());
// The root layer does not actually draw content of its own.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root->visible_content_rect());
// All layer visible content rects are expressed in content space of each
// layer, so they are also scaled by the device_scale_factor.
EXPECT_RECT_EQ(gfx::Rect(0, 0, 6, 8),
render_surface1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 14, 26),
render_surface2->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), child1->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), child2->visible_content_rect());
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), child3->visible_content_rect());
}
TEST_F(LayerTreeHostCommonTest, BackFaceCullingWithoutPreserves3d) {
// Verify the behavior of back-face culling when there are no preserve-3d
// layers. Note that 3d transforms still apply in this case, but they are
// "flattened" to each parent layer according to current W3C spec.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> front_facing_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> back_facing_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
front_facing_child_of_front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
back_facing_child_of_front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
front_facing_child_of_back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
back_facing_child_of_back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(front_facing_child);
parent->AddChild(back_facing_child);
parent->AddChild(front_facing_surface);
parent->AddChild(back_facing_surface);
front_facing_surface->AddChild(front_facing_child_of_front_facing_surface);
front_facing_surface->AddChild(back_facing_child_of_front_facing_surface);
back_facing_surface->AddChild(front_facing_child_of_back_facing_surface);
back_facing_surface->AddChild(back_facing_child_of_back_facing_surface);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// Nothing is double-sided
front_facing_child->SetDoubleSided(false);
back_facing_child->SetDoubleSided(false);
front_facing_surface->SetDoubleSided(false);
back_facing_surface->SetDoubleSided(false);
front_facing_child_of_front_facing_surface->SetDoubleSided(false);
back_facing_child_of_front_facing_surface->SetDoubleSided(false);
front_facing_child_of_back_facing_surface->SetDoubleSided(false);
back_facing_child_of_back_facing_surface->SetDoubleSided(false);
gfx::Transform backface_matrix;
backface_matrix.Translate(50.0, 50.0);
backface_matrix.RotateAboutYAxis(180.0);
backface_matrix.Translate(-50.0, -50.0);
// Having a descendant and opacity will force these to have render surfaces.
front_facing_surface->SetOpacity(0.5f);
back_facing_surface->SetOpacity(0.5f);
// Nothing preserves 3d. According to current W3C CSS gfx::Transforms spec,
// these layers should blindly use their own local transforms to determine
// back-face culling.
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(front_facing_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(back_facing_child.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(front_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(back_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(front_facing_child_of_front_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(back_facing_child_of_front_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(front_facing_child_of_back_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(back_facing_child_of_back_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Verify which render surfaces were created.
EXPECT_FALSE(front_facing_child->render_surface());
EXPECT_FALSE(back_facing_child->render_surface());
EXPECT_TRUE(front_facing_surface->render_surface());
EXPECT_TRUE(back_facing_surface->render_surface());
EXPECT_FALSE(front_facing_child_of_front_facing_surface->render_surface());
EXPECT_FALSE(back_facing_child_of_front_facing_surface->render_surface());
EXPECT_FALSE(front_facing_child_of_back_facing_surface->render_surface());
EXPECT_FALSE(back_facing_child_of_back_facing_surface->render_surface());
// Verify the render_surface_layer_list.
ASSERT_EQ(3u, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(front_facing_surface->id(), render_surface_layer_list.at(1)->id());
// Even though the back facing surface LAYER gets culled, the other
// descendants should still be added, so the SURFACE should not be culled.
EXPECT_EQ(back_facing_surface->id(), render_surface_layer_list.at(2)->id());
// Verify root surface's layer list.
ASSERT_EQ(
3u,
render_surface_layer_list.at(0)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_child->id(),
render_surface_layer_list.at(0)
->render_surface()
->layer_list()
.at(0)
->id());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(0)
->render_surface()
->layer_list()
.at(1)
->id());
EXPECT_EQ(back_facing_surface->id(),
render_surface_layer_list.at(0)
->render_surface()
->layer_list()
.at(2)
->id());
// Verify front_facing_surface's layer list.
ASSERT_EQ(
2u,
render_surface_layer_list.at(1)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(1)
->render_surface()
->layer_list()
.at(0)
->id());
EXPECT_EQ(front_facing_child_of_front_facing_surface->id(),
render_surface_layer_list.at(1)
->render_surface()
->layer_list()
.at(1)
->id());
// Verify back_facing_surface's layer list; its own layer should be culled
// from the surface list.
ASSERT_EQ(
1u,
render_surface_layer_list.at(2)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_child_of_back_facing_surface->id(),
render_surface_layer_list.at(2)
->render_surface()
->layer_list()
.at(0)
->id());
}
TEST_F(LayerTreeHostCommonTest, BackFaceCullingWithPreserves3d) {
// Verify the behavior of back-face culling when preserves-3d transform style
// is used.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> front_facing_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> back_facing_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
front_facing_child_of_front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
back_facing_child_of_front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
front_facing_child_of_back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent>
back_facing_child_of_back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> dummy_replica_layer1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> dummy_replica_layer2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(front_facing_child);
parent->AddChild(back_facing_child);
parent->AddChild(front_facing_surface);
parent->AddChild(back_facing_surface);
front_facing_surface->AddChild(front_facing_child_of_front_facing_surface);
front_facing_surface->AddChild(back_facing_child_of_front_facing_surface);
back_facing_surface->AddChild(front_facing_child_of_back_facing_surface);
back_facing_surface->AddChild(back_facing_child_of_back_facing_surface);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// Nothing is double-sided
front_facing_child->SetDoubleSided(false);
back_facing_child->SetDoubleSided(false);
front_facing_surface->SetDoubleSided(false);
back_facing_surface->SetDoubleSided(false);
front_facing_child_of_front_facing_surface->SetDoubleSided(false);
back_facing_child_of_front_facing_surface->SetDoubleSided(false);
front_facing_child_of_back_facing_surface->SetDoubleSided(false);
back_facing_child_of_back_facing_surface->SetDoubleSided(false);
gfx::Transform backface_matrix;
backface_matrix.Translate(50.0, 50.0);
backface_matrix.RotateAboutYAxis(180.0);
backface_matrix.Translate(-50.0, -50.0);
// Opacity will not force creation of render surfaces in this case because of
// the preserve-3d transform style. Instead, an example of when a surface
// would be created with preserve-3d is when there is a replica layer.
front_facing_surface->SetReplicaLayer(dummy_replica_layer1.get());
back_facing_surface->SetReplicaLayer(dummy_replica_layer2.get());
// Each surface creates its own new 3d rendering context (as defined by W3C
// spec). According to current W3C CSS gfx::Transforms spec, layers in a 3d
// rendering context should use the transform with respect to that context.
// This 3d rendering context occurs when (a) parent's transform style is flat
// and (b) the layer's transform style is preserve-3d.
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false); // parent transform style is flat.
SetLayerPropertiesForTesting(front_facing_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(back_facing_child.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
// surface transform style is preserve-3d.
SetLayerPropertiesForTesting(front_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
// surface transform style is preserve-3d.
SetLayerPropertiesForTesting(back_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
SetLayerPropertiesForTesting(front_facing_child_of_front_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true);
SetLayerPropertiesForTesting(back_facing_child_of_front_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true);
SetLayerPropertiesForTesting(front_facing_child_of_back_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true);
SetLayerPropertiesForTesting(back_facing_child_of_back_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Verify which render surfaces were created.
EXPECT_FALSE(front_facing_child->render_surface());
EXPECT_FALSE(back_facing_child->render_surface());
EXPECT_TRUE(front_facing_surface->render_surface());
EXPECT_FALSE(back_facing_surface->render_surface());
EXPECT_FALSE(front_facing_child_of_front_facing_surface->render_surface());
EXPECT_FALSE(back_facing_child_of_front_facing_surface->render_surface());
EXPECT_FALSE(front_facing_child_of_back_facing_surface->render_surface());
EXPECT_FALSE(back_facing_child_of_back_facing_surface->render_surface());
// Verify the render_surface_layer_list. The back-facing surface should be
// culled.
ASSERT_EQ(2u, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(front_facing_surface->id(), render_surface_layer_list.at(1)->id());
// Verify root surface's layer list.
ASSERT_EQ(
2u,
render_surface_layer_list.at(0)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_child->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(1)->id());
// Verify front_facing_surface's layer list.
ASSERT_EQ(
2u,
render_surface_layer_list.at(1)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(front_facing_child_of_front_facing_surface->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, BackFaceCullingWithAnimatingTransforms) {
// Verify that layers are appropriately culled when their back face is showing
// and they are not double sided, while animations are going on.
//
// Layers that are animating do not get culled on the main thread, as their
// transforms should be treated as "unknown" so we can not be sure that their
// back face is really showing.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> animating_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child_of_animating_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> animating_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(child);
parent->AddChild(animating_surface);
animating_surface->AddChild(child_of_animating_surface);
parent->AddChild(animating_child);
parent->AddChild(child2);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// Nothing is double-sided
child->SetDoubleSided(false);
child2->SetDoubleSided(false);
animating_surface->SetDoubleSided(false);
child_of_animating_surface->SetDoubleSided(false);
animating_child->SetDoubleSided(false);
gfx::Transform backface_matrix;
backface_matrix.Translate(50.0, 50.0);
backface_matrix.RotateAboutYAxis(180.0);
backface_matrix.Translate(-50.0, -50.0);
// Make our render surface.
animating_surface->SetForceRenderSurface(true);
// Animate the transform on the render surface.
AddAnimatedTransformToController(
animating_surface->layer_animation_controller(), 10.0, 30, 0);
// This is just an animating layer, not a surface.
AddAnimatedTransformToController(
animating_child->layer_animation_controller(), 10.0, 30, 0);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(animating_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child_of_animating_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(animating_child.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_FALSE(child->render_surface());
EXPECT_TRUE(animating_surface->render_surface());
EXPECT_FALSE(child_of_animating_surface->render_surface());
EXPECT_FALSE(animating_child->render_surface());
EXPECT_FALSE(child2->render_surface());
// Verify that the animating_child and child_of_animating_surface were not
// culled, but that child was.
ASSERT_EQ(2u, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(animating_surface->id(), render_surface_layer_list.at(1)->id());
// The non-animating child be culled from the layer list for the parent render
// surface.
ASSERT_EQ(
3u,
render_surface_layer_list.at(0)->render_surface()->layer_list().size());
EXPECT_EQ(animating_surface->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(animating_child->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(1)->id());
EXPECT_EQ(child2->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(2)->id());
ASSERT_EQ(
2u,
render_surface_layer_list.at(1)->render_surface()->layer_list().size());
EXPECT_EQ(animating_surface->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(child_of_animating_surface->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(1)->id());
EXPECT_FALSE(child2->visible_content_rect().IsEmpty());
// The animating layers should have a visible content rect that represents the
// area of the front face that is within the viewport.
EXPECT_EQ(animating_child->visible_content_rect(),
gfx::Rect(animating_child->content_bounds()));
EXPECT_EQ(animating_surface->visible_content_rect(),
gfx::Rect(animating_surface->content_bounds()));
// And layers in the subtree of the animating layer should have valid visible
// content rects also.
EXPECT_EQ(child_of_animating_surface->visible_content_rect(),
gfx::Rect(child_of_animating_surface->content_bounds()));
}
TEST_F(LayerTreeHostCommonTest,
BackFaceCullingWithPreserves3dForFlatteningSurface) {
// Verify the behavior of back-face culling for a render surface that is
// created when it flattens its subtree, and its parent has preserves-3d.
const gfx::Transform identity_matrix;
scoped_refptr<Layer> parent = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> front_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> back_facing_surface =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child1 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
scoped_refptr<LayerWithForcedDrawsContent> child2 =
make_scoped_refptr(new LayerWithForcedDrawsContent());
parent->AddChild(front_facing_surface);
parent->AddChild(back_facing_surface);
front_facing_surface->AddChild(child1);
back_facing_surface->AddChild(child2);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
// RenderSurfaces are not double-sided
front_facing_surface->SetDoubleSided(false);
back_facing_surface->SetDoubleSided(false);
gfx::Transform backface_matrix;
backface_matrix.Translate(50.0, 50.0);
backface_matrix.RotateAboutYAxis(180.0);
backface_matrix.Translate(-50.0, -50.0);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true); // parent transform style is preserve3d.
SetLayerPropertiesForTesting(front_facing_surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true); // surface transform style is flat.
SetLayerPropertiesForTesting(back_facing_surface.get(),
backface_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
true); // surface transform style is flat.
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
front_facing_surface->SetIs3dSorted(true);
back_facing_surface->SetIs3dSorted(true);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Verify which render surfaces were created.
EXPECT_TRUE(front_facing_surface->render_surface());
EXPECT_FALSE(
back_facing_surface->render_surface()); // because it should be culled
EXPECT_FALSE(child1->render_surface());
EXPECT_FALSE(child2->render_surface());
// Verify the render_surface_layer_list. The back-facing surface should be
// culled.
ASSERT_EQ(2u, render_surface_layer_list.size());
EXPECT_EQ(parent->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(front_facing_surface->id(), render_surface_layer_list.at(1)->id());
// Verify root surface's layer list.
ASSERT_EQ(
1u,
render_surface_layer_list.at(0)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(0)
->render_surface()->layer_list().at(0)->id());
// Verify front_facing_surface's layer list.
ASSERT_EQ(
2u,
render_surface_layer_list.at(1)->render_surface()->layer_list().size());
EXPECT_EQ(front_facing_surface->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(child1->id(),
render_surface_layer_list.at(1)
->render_surface()->layer_list().at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForEmptyLayerList) {
// Hit testing on an empty render_surface_layer_list should return a null
// pointer.
LayerImplList render_surface_layer_list;
gfx::Point test_point(0, 0);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 20);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSingleLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit testing for a point outside the layer should return a null pointer.
gfx::Point test_point(101, 101);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(-1, -1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the root layer.
test_point = gfx::Point(1, 1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(99, 99);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSingleLayerAndHud) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
scoped_ptr<HeadsUpDisplayLayerImpl> hud =
HeadsUpDisplayLayerImpl::Create(host_impl.active_tree(), 11111);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
// Create hud and add it as a child of root.
gfx::Size hud_bounds(200, 200);
SetLayerPropertiesForTesting(hud.get(),
identity_matrix,
anchor,
position,
hud_bounds,
true,
false);
hud->SetDrawsContent(true);
host_impl.active_tree()->set_hud_layer(hud.get());
root->AddChild(hud.PassAs<LayerImpl>());
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), hud_bounds, &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
// Hit testing for a point inside HUD, but outside root should return null
gfx::Point test_point(101, 101);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(-1, -1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the root layer, never the HUD
// layer.
test_point = gfx::Point(1, 1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(99, 99);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForUninvertibleTransform) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform uninvertible_transform;
uninvertible_transform.matrix().set(0, 0, 0.0);
uninvertible_transform.matrix().set(1, 1, 0.0);
uninvertible_transform.matrix().set(2, 2, 0.0);
uninvertible_transform.matrix().set(3, 3, 0.0);
ASSERT_FALSE(uninvertible_transform.IsInvertible());
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
uninvertible_transform,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
ASSERT_FALSE(root->screen_space_transform().IsInvertible());
// Hit testing any point should not hit the layer. If the invertible matrix is
// accidentally ignored and treated like an identity, then the hit testing
// will incorrectly hit the layer when it shouldn't.
gfx::Point test_point(1, 1);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 10);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 30);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(50, 50);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(67, 48);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(99, 99);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(-1, -1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSinglePositionedLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
gfx::PointF anchor;
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(50.f, 50.f);
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit testing for a point outside the layer should return a null pointer.
gfx::Point test_point(49, 49);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Even though the layer exists at (101, 101), it should not be visible there
// since the root render surface would clamp it.
test_point = gfx::Point(101, 101);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the root layer.
test_point = gfx::Point(51, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(99, 99);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSingleRotatedLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
gfx::Transform rotation45_degrees_about_center;
rotation45_degrees_about_center.Translate(50.0, 50.0);
rotation45_degrees_about_center.RotateAboutZAxis(45.0);
rotation45_degrees_about_center.Translate(-50.0, -50.0);
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
rotation45_degrees_about_center,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit testing for points outside the layer.
// These corners would have been inside the un-transformed layer, but they
// should not hit the correctly transformed layer.
gfx::Point test_point(99, 99);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(1, 1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the root layer.
test_point = gfx::Point(1, 50);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
// Hit testing the corners that would overlap the unclipped layer, but are
// outside the clipped region.
test_point = gfx::Point(50, -1);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_FALSE(result_layer);
test_point = gfx::Point(-1, 50);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_FALSE(result_layer);
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSinglePerspectiveLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
// perspective_projection_about_center * translation_by_z is designed so that
// the 100 x 100 layer becomes 50 x 50, and remains centered at (50, 50).
gfx::Transform perspective_projection_about_center;
perspective_projection_about_center.Translate(50.0, 50.0);
perspective_projection_about_center.ApplyPerspectiveDepth(1.0);
perspective_projection_about_center.Translate(-50.0, -50.0);
gfx::Transform translation_by_z;
translation_by_z.Translate3d(0.0, 0.0, -1.0);
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(
root.get(),
perspective_projection_about_center * translation_by_z,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit testing for points outside the layer.
// These corners would have been inside the un-transformed layer, but they
// should not hit the correctly transformed layer.
gfx::Point test_point(24, 24);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(76, 76);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the root layer.
test_point = gfx::Point(26, 26);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(74, 74);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSingleLayerWithScaledContents) {
// A layer's visible content rect is actually in the layer's content space.
// The screen space transform converts from the layer's origin space to screen
// space. This test makes sure that hit testing works correctly accounts for
// the contents scale. A contents scale that is not 1 effectively forces a
// non-identity transform between layer's content space and layer's origin
// space. The hit testing code must take this into account.
//
// To test this, the layer is positioned at (25, 25), and is size (50, 50). If
// contents scale is ignored, then hit testing will mis-interpret the visible
// content rect as being larger than the actual bounds of the layer.
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
gfx::PointF position(25.f, 25.f);
gfx::Size bounds(50, 50);
scoped_ptr<LayerImpl> test_layer =
LayerImpl::Create(host_impl.active_tree(), 12345);
SetLayerPropertiesForTesting(test_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
// override content bounds and contents scale
test_layer->SetContentBounds(gfx::Size(100, 100));
test_layer->SetContentsScale(2, 2);
test_layer->SetDrawsContent(true);
root->AddChild(test_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
// The visible content rect for test_layer is actually 100x100, even though
// its layout size is 50x50, positioned at 25x25.
LayerImpl* test_layer = root->children()[0];
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100),
test_layer->visible_content_rect());
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit testing for a point outside the layer should return a null pointer (the
// root layer does not draw content, so it will not be hit tested either).
gfx::Point test_point(101, 101);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(24, 24);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(76, 76);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the test layer.
test_point = gfx::Point(26, 26);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(74, 74);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForSimpleClippedLayer) {
// Test that hit-testing will only work for the visible portion of a layer,
// and not the entire layer bounds. Here we just test the simple axis-aligned
// case.
gfx::Transform identity_matrix;
gfx::PointF anchor;
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
scoped_ptr<LayerImpl> clipping_layer =
LayerImpl::Create(host_impl.active_tree(), 123);
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(25.f, 25.f);
gfx::Size bounds(50, 50);
SetLayerPropertiesForTesting(clipping_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
clipping_layer->SetMasksToBounds(true);
scoped_ptr<LayerImpl> child =
LayerImpl::Create(host_impl.active_tree(), 456);
position = gfx::PointF(-50.f, -50.f);
bounds = gfx::Size(300, 300);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child->SetDrawsContent(true);
clipping_layer->AddChild(child.Pass());
root->AddChild(clipping_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
ASSERT_EQ(456, root->render_surface()->layer_list().at(0)->id());
// Hit testing for a point outside the layer should return a null pointer.
// Despite the child layer being very large, it should be clipped to the root
// layer's bounds.
gfx::Point test_point(24, 24);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Even though the layer exists at (101, 101), it should not be visible there
// since the clipping_layer would clamp it.
test_point = gfx::Point(76, 76);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the child layer.
test_point = gfx::Point(26, 26);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
test_point = gfx::Point(74, 74);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForMultiClippedRotatedLayer) {
// This test checks whether hit testing correctly avoids hit testing with
// multiple ancestors that clip in non axis-aligned ways. To pass this test,
// the hit testing algorithm needs to recognize that multiple parent layers
// may clip the layer, and should not actually hit those clipped areas.
//
// The child and grand_child layers are both initialized to clip the
// rotated_leaf. The child layer is rotated about the top-left corner, so that
// the root + child clips combined create a triangle. The rotated_leaf will
// only be visible where it overlaps this triangle.
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 123);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetMasksToBounds(true);
{
scoped_ptr<LayerImpl> child =
LayerImpl::Create(host_impl.active_tree(), 456);
scoped_ptr<LayerImpl> grand_child =
LayerImpl::Create(host_impl.active_tree(), 789);
scoped_ptr<LayerImpl> rotated_leaf =
LayerImpl::Create(host_impl.active_tree(), 2468);
position = gfx::PointF(10.f, 10.f);
bounds = gfx::Size(80, 80);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child->SetMasksToBounds(true);
gfx::Transform rotation45_degrees_about_corner;
rotation45_degrees_about_corner.RotateAboutZAxis(45.0);
// remember, positioned with respect to its parent which is already at 10,
// 10
position = gfx::PointF();
bounds =
gfx::Size(200, 200); // to ensure it covers at least sqrt(2) * 100.
SetLayerPropertiesForTesting(grand_child.get(),
rotation45_degrees_about_corner,
anchor,
position,
bounds,
true,
false);
grand_child->SetMasksToBounds(true);
// Rotates about the center of the layer
gfx::Transform rotated_leaf_transform;
rotated_leaf_transform.Translate(
-10.0, -10.0); // cancel out the grand_parent's position
rotated_leaf_transform.RotateAboutZAxis(
-45.0); // cancel out the corner 45-degree rotation of the parent.
rotated_leaf_transform.Translate(50.0, 50.0);
rotated_leaf_transform.RotateAboutZAxis(45.0);
rotated_leaf_transform.Translate(-50.0, -50.0);
position = gfx::PointF();
bounds = gfx::Size(100, 100);
SetLayerPropertiesForTesting(rotated_leaf.get(),
rotated_leaf_transform,
anchor,
position,
bounds,
true,
false);
rotated_leaf->SetDrawsContent(true);
grand_child->AddChild(rotated_leaf.Pass());
child->AddChild(grand_child.Pass());
root->AddChild(child.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
// The grand_child is expected to create a render surface because it
// MasksToBounds and is not axis aligned.
ASSERT_EQ(2u, render_surface_layer_list.size());
ASSERT_EQ(
1u,
render_surface_layer_list.at(0)->render_surface()->layer_list().size());
ASSERT_EQ(789,
render_surface_layer_list.at(0)->render_surface()->layer_list().at(
0)->id()); // grand_child's surface.
ASSERT_EQ(
1u,
render_surface_layer_list.at(1)->render_surface()->layer_list().size());
ASSERT_EQ(
2468,
render_surface_layer_list[1]->render_surface()->layer_list().at(0)->id());
// (11, 89) is close to the the bottom left corner within the clip, but it is
// not inside the layer.
gfx::Point test_point(11, 89);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Closer inwards from the bottom left will overlap the layer.
test_point = gfx::Point(25, 75);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(2468, result_layer->id());
// (4, 50) is inside the unclipped layer, but that corner of the layer should
// be clipped away by the grandparent and should not get hit. If hit testing
// blindly uses visible content rect without considering how parent may clip
// the layer, then hit testing would accidentally think that the point
// successfully hits the layer.
test_point = gfx::Point(4, 50);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// (11, 50) is inside the layer and within the clipped area.
test_point = gfx::Point(11, 50);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(2468, result_layer->id());
// Around the middle, just to the right and up, would have hit the layer
// except that that area should be clipped away by the parent.
test_point = gfx::Point(51, 49);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Around the middle, just to the left and down, should successfully hit the
// layer.
test_point = gfx::Point(49, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(2468, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForNonClippingIntermediateLayer) {
// This test checks that hit testing code does not accidentally clip to layer
// bounds for a layer that actually does not clip.
gfx::Transform identity_matrix;
gfx::PointF anchor;
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
scoped_ptr<LayerImpl> intermediate_layer =
LayerImpl::Create(host_impl.active_tree(), 123);
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(10.f, 10.f);
gfx::Size bounds(50, 50);
SetLayerPropertiesForTesting(intermediate_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
// Sanity check the intermediate layer should not clip.
ASSERT_FALSE(intermediate_layer->masks_to_bounds());
ASSERT_FALSE(intermediate_layer->mask_layer());
// The child of the intermediate_layer is translated so that it does not
// overlap intermediate_layer at all. If child is incorrectly clipped, we
// would not be able to hit it successfully.
scoped_ptr<LayerImpl> child =
LayerImpl::Create(host_impl.active_tree(), 456);
position = gfx::PointF(60.f, 60.f); // 70, 70 in screen space
bounds = gfx::Size(20, 20);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child->SetDrawsContent(true);
intermediate_layer->AddChild(child.Pass());
root->AddChild(intermediate_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
ASSERT_EQ(456, root->render_surface()->layer_list().at(0)->id());
// Hit testing for a point outside the layer should return a null pointer.
gfx::Point test_point(69, 69);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(91, 91);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit testing for a point inside should return the child layer.
test_point = gfx::Point(71, 71);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
test_point = gfx::Point(89, 89);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForMultipleLayers) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
{
// child 1 and child2 are initialized to overlap between x=50 and x=60.
// grand_child is set to overlap both child1 and child2 between y=50 and
// y=60. The expected stacking order is: (front) child2, (second)
// grand_child, (third) child1, and (back) the root layer behind all other
// layers.
scoped_ptr<LayerImpl> child1 =
LayerImpl::Create(host_impl.active_tree(), 2);
scoped_ptr<LayerImpl> child2 =
LayerImpl::Create(host_impl.active_tree(), 3);
scoped_ptr<LayerImpl> grand_child1 =
LayerImpl::Create(host_impl.active_tree(), 4);
position = gfx::PointF(10.f, 10.f);
bounds = gfx::Size(50, 50);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child1->SetDrawsContent(true);
position = gfx::PointF(50.f, 10.f);
bounds = gfx::Size(50, 50);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child2->SetDrawsContent(true);
// Remember that grand_child is positioned with respect to its parent (i.e.
// child1). In screen space, the intended position is (10, 50), with size
// 100 x 50.
position = gfx::PointF(0.f, 40.f);
bounds = gfx::Size(100, 50);
SetLayerPropertiesForTesting(grand_child1.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
grand_child1->SetDrawsContent(true);
child1->AddChild(grand_child1.Pass());
root->AddChild(child1.Pass());
root->AddChild(child2.Pass());
}
LayerImpl* child1 = root->children()[0];
LayerImpl* child2 = root->children()[1];
LayerImpl* grand_child1 = child1->children()[0];
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_TRUE(child1);
ASSERT_TRUE(child2);
ASSERT_TRUE(grand_child1);
ASSERT_EQ(1u, render_surface_layer_list.size());
RenderSurfaceImpl* root_render_surface = root->render_surface();
ASSERT_EQ(4u, root_render_surface->layer_list().size());
ASSERT_EQ(1, root_render_surface->layer_list().at(0)->id()); // root layer
ASSERT_EQ(2, root_render_surface->layer_list().at(1)->id()); // child1
ASSERT_EQ(4, root_render_surface->layer_list().at(2)->id()); // grand_child1
ASSERT_EQ(3, root_render_surface->layer_list().at(3)->id()); // child2
// Nothing overlaps the root_layer at (1, 1), so hit testing there should find
// the root layer.
gfx::Point test_point = gfx::Point(1, 1);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(1, result_layer->id());
// At (15, 15), child1 and root are the only layers. child1 is expected to be
// on top.
test_point = gfx::Point(15, 15);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(2, result_layer->id());
// At (51, 20), child1 and child2 overlap. child2 is expected to be on top.
test_point = gfx::Point(51, 20);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (80, 51), child2 and grand_child1 overlap. child2 is expected to be on
// top.
test_point = gfx::Point(80, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (51, 51), all layers overlap each other. child2 is expected to be on top
// of all other layers.
test_point = gfx::Point(51, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (20, 51), child1 and grand_child1 overlap. grand_child1 is expected to
// be on top.
test_point = gfx::Point(20, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(4, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForMultipleLayerLists) {
//
// The geometry is set up similarly to the previous case, but
// all layers are forced to be render surfaces now.
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
{
// child 1 and child2 are initialized to overlap between x=50 and x=60.
// grand_child is set to overlap both child1 and child2 between y=50 and
// y=60. The expected stacking order is: (front) child2, (second)
// grand_child, (third) child1, and (back) the root layer behind all other
// layers.
scoped_ptr<LayerImpl> child1 =
LayerImpl::Create(host_impl.active_tree(), 2);
scoped_ptr<LayerImpl> child2 =
LayerImpl::Create(host_impl.active_tree(), 3);
scoped_ptr<LayerImpl> grand_child1 =
LayerImpl::Create(host_impl.active_tree(), 4);
position = gfx::PointF(10.f, 10.f);
bounds = gfx::Size(50, 50);
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child1->SetDrawsContent(true);
child1->SetForceRenderSurface(true);
position = gfx::PointF(50.f, 10.f);
bounds = gfx::Size(50, 50);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child2->SetDrawsContent(true);
child2->SetForceRenderSurface(true);
// Remember that grand_child is positioned with respect to its parent (i.e.
// child1). In screen space, the intended position is (10, 50), with size
// 100 x 50.
position = gfx::PointF(0.f, 40.f);
bounds = gfx::Size(100, 50);
SetLayerPropertiesForTesting(grand_child1.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
grand_child1->SetDrawsContent(true);
grand_child1->SetForceRenderSurface(true);
child1->AddChild(grand_child1.Pass());
root->AddChild(child1.Pass());
root->AddChild(child2.Pass());
}
LayerImpl* child1 = root->children()[0];
LayerImpl* child2 = root->children()[1];
LayerImpl* grand_child1 = child1->children()[0];
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_TRUE(child1);
ASSERT_TRUE(child2);
ASSERT_TRUE(grand_child1);
ASSERT_TRUE(child1->render_surface());
ASSERT_TRUE(child2->render_surface());
ASSERT_TRUE(grand_child1->render_surface());
ASSERT_EQ(4u, render_surface_layer_list.size());
// The root surface has the root layer, and child1's and child2's render
// surfaces.
ASSERT_EQ(3u, root->render_surface()->layer_list().size());
// The child1 surface has the child1 layer and grand_child1's render surface.
ASSERT_EQ(2u, child1->render_surface()->layer_list().size());
ASSERT_EQ(1u, child2->render_surface()->layer_list().size());
ASSERT_EQ(1u, grand_child1->render_surface()->layer_list().size());
ASSERT_EQ(1, render_surface_layer_list.at(0)->id()); // root layer
ASSERT_EQ(2, render_surface_layer_list[1]->id()); // child1
ASSERT_EQ(4, render_surface_layer_list.at(2)->id()); // grand_child1
ASSERT_EQ(3, render_surface_layer_list[3]->id()); // child2
// Nothing overlaps the root_layer at (1, 1), so hit testing there should find
// the root layer.
gfx::Point test_point = gfx::Point(1, 1);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(1, result_layer->id());
// At (15, 15), child1 and root are the only layers. child1 is expected to be
// on top.
test_point = gfx::Point(15, 15);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(2, result_layer->id());
// At (51, 20), child1 and child2 overlap. child2 is expected to be on top.
test_point = gfx::Point(51, 20);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (80, 51), child2 and grand_child1 overlap. child2 is expected to be on
// top.
test_point = gfx::Point(80, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (51, 51), all layers overlap each other. child2 is expected to be on top
// of all other layers.
test_point = gfx::Point(51, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// At (20, 51), child1 and grand_child1 overlap. grand_child1 is expected to
// be on top.
test_point = gfx::Point(20, 51);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(4, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest, HitTestingForEmptyLayers) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
// Layer 1 - root
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
{
// Layer 2 - empty: drawsContent=false
gfx::PointF position(10.f, 10.f);
gfx::Size bounds(30, 30);
scoped_ptr<LayerImpl> empty_layer =
LayerImpl::Create(host_impl.active_tree(), 2);
SetLayerPropertiesForTesting(empty_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
empty_layer->SetDrawsContent(false);
root->AddChild(empty_layer.Pass());
}
{
// Layer 3 - empty, but has touch handler
gfx::PointF position(10.f, 60.f);
gfx::Size bounds(30, 30);
scoped_ptr<LayerImpl> test_layer =
LayerImpl::Create(host_impl.active_tree(), 3);
SetLayerPropertiesForTesting(test_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
test_layer->SetDrawsContent(false);
Region touch_handler_region(gfx::Rect(10, 10, 10, 10));
test_layer->SetTouchEventHandlerRegion(touch_handler_region);
root->AddChild(test_layer.Pass());
}
{
// Layer 4 - empty, but has mousewheel handler
gfx::PointF position(60.f, 60.f);
gfx::Size bounds(30, 30);
scoped_ptr<LayerImpl> test_layer =
LayerImpl::Create(host_impl.active_tree(), 4);
SetLayerPropertiesForTesting(test_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
test_layer->SetDrawsContent(false);
test_layer->SetHaveWheelEventHandlers(true);
root->AddChild(test_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Verify that the root layer and empty layers with touch/wheel handlers
// (but not the empty layer without a touch handler) are in the RSSL.
ASSERT_EQ(1u, render_surface_layer_list.size());
EXPECT_EQ(1, render_surface_layer_list[0]->id());
ASSERT_EQ(3u, root->render_surface()->layer_list().size());
EXPECT_EQ(1, root->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(3, root->render_surface()->layer_list().at(1)->id());
EXPECT_EQ(4, root->render_surface()->layer_list().at(2)->id());
// Hit testing for a point inside the empty no-handlers layer should return
// the root layer.
gfx::Point test_point = gfx::Point(15, 15);
LayerImpl* result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(1, result_layer->id());
// Hit testing for a point inside the touch handler layer should return it.
test_point = gfx::Point(15, 75);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(3, result_layer->id());
// Hit testing for a point inside the mousewheel layer should return it.
test_point = gfx::Point(75, 75);
result_layer = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(4, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForEmptyLayerList) {
// Hit checking on an empty render_surface_layer_list should return a null
// pointer.
LayerImplList render_surface_layer_list;
gfx::Point test_point(0, 0);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 20);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
}
TEST_F(LayerTreeHostCommonTest, HitCheckingTouchHandlerRegionsForSingleLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
Region touch_handler_region(gfx::Rect(10, 10, 50, 50));
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit checking for any point should return a null pointer for a layer without
// any touch event handler regions.
gfx::Point test_point(11, 11);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
root->SetTouchEventHandlerRegion(touch_handler_region);
// Hit checking for a point outside the layer should return a null pointer.
test_point = gfx::Point(101, 101);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(-1, -1);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the layer, but outside the touch handler
// region should return a null pointer.
test_point = gfx::Point(1, 1);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(99, 99);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the touch event handler region should
// return the root layer.
test_point = gfx::Point(11, 11);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(59, 59);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForUninvertibleTransform) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform uninvertible_transform;
uninvertible_transform.matrix().set(0, 0, 0.0);
uninvertible_transform.matrix().set(1, 1, 0.0);
uninvertible_transform.matrix().set(2, 2, 0.0);
uninvertible_transform.matrix().set(3, 3, 0.0);
ASSERT_FALSE(uninvertible_transform.IsInvertible());
gfx::Transform identity_matrix;
Region touch_handler_region(gfx::Rect(10, 10, 50, 50));
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
uninvertible_transform,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
root->SetTouchEventHandlerRegion(touch_handler_region);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
ASSERT_FALSE(root->screen_space_transform().IsInvertible());
// Hit checking any point should not hit the touch handler region on the
// layer. If the invertible matrix is accidentally ignored and treated like an
// identity, then the hit testing will incorrectly hit the layer when it
// shouldn't.
gfx::Point test_point(1, 1);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 10);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(10, 30);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(50, 50);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(67, 48);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(99, 99);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(-1, -1);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForSinglePositionedLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
gfx::Transform identity_matrix;
Region touch_handler_region(gfx::Rect(10, 10, 50, 50));
gfx::PointF anchor;
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(50.f, 50.f);
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
root->SetTouchEventHandlerRegion(touch_handler_region);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit checking for a point outside the layer should return a null pointer.
gfx::Point test_point(49, 49);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Even though the layer has a touch handler region containing (101, 101), it
// should not be visible there since the root render surface would clamp it.
test_point = gfx::Point(101, 101);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the layer, but outside the touch handler
// region should return a null pointer.
test_point = gfx::Point(51, 51);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the touch event handler region should
// return the root layer.
test_point = gfx::Point(61, 61);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(99, 99);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForSingleLayerWithScaledContents) {
// A layer's visible content rect is actually in the layer's content space.
// The screen space transform converts from the layer's origin space to screen
// space. This test makes sure that hit testing works correctly accounts for
// the contents scale. A contents scale that is not 1 effectively forces a
// non-identity transform between layer's content space and layer's origin
// space. The hit testing code must take this into account.
//
// To test this, the layer is positioned at (25, 25), and is size (50, 50). If
// contents scale is ignored, then hit checking will mis-interpret the visible
// content rect as being larger than the actual bounds of the layer.
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
Region touch_handler_region(gfx::Rect(10, 10, 30, 30));
gfx::PointF position(25.f, 25.f);
gfx::Size bounds(50, 50);
scoped_ptr<LayerImpl> test_layer =
LayerImpl::Create(host_impl.active_tree(), 12345);
SetLayerPropertiesForTesting(test_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
// override content bounds and contents scale
test_layer->SetContentBounds(gfx::Size(100, 100));
test_layer->SetContentsScale(2, 2);
test_layer->SetDrawsContent(true);
test_layer->SetTouchEventHandlerRegion(touch_handler_region);
root->AddChild(test_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
// The visible content rect for test_layer is actually 100x100, even though
// its layout size is 50x50, positioned at 25x25.
LayerImpl* test_layer = root->children()[0];
EXPECT_RECT_EQ(gfx::Rect(0, 0, 100, 100), test_layer->visible_content_rect());
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Hit checking for a point outside the layer should return a null pointer
// (the root layer does not draw content, so it will not be tested either).
gfx::Point test_point(76, 76);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the layer, but outside the touch handler
// region should return a null pointer.
test_point = gfx::Point(26, 26);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(34, 34);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(65, 65);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(74, 74);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the touch event handler region should
// return the root layer.
test_point = gfx::Point(35, 35);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(64, 64);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForSingleLayerWithDeviceScale) {
// The layer's device_scale_factor and page_scale_factor should scale the
// content rect and we should be able to hit the touch handler region by
// scaling the points accordingly.
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
gfx::Transform identity_matrix;
gfx::PointF anchor;
// Set the bounds of the root layer big enough to fit the child when scaled.
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
Region touch_handler_region(gfx::Rect(10, 10, 30, 30));
gfx::PointF position(25.f, 25.f);
gfx::Size bounds(50, 50);
scoped_ptr<LayerImpl> test_layer =
LayerImpl::Create(host_impl.active_tree(), 12345);
SetLayerPropertiesForTesting(test_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
test_layer->SetDrawsContent(true);
test_layer->SetTouchEventHandlerRegion(touch_handler_region);
root->AddChild(test_layer.Pass());
}
LayerImplList render_surface_layer_list;
float device_scale_factor = 3.f;
float page_scale_factor = 5.f;
gfx::Size scaled_bounds_for_root = gfx::ToCeiledSize(
gfx::ScaleSize(root->bounds(), device_scale_factor * page_scale_factor));
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), scaled_bounds_for_root, &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
// The visible content rect for test_layer is actually 100x100, even though
// its layout size is 50x50, positioned at 25x25.
LayerImpl* test_layer = root->children()[0];
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
// Check whether the child layer fits into the root after scaled.
EXPECT_RECT_EQ(gfx::Rect(test_layer->content_bounds()),
test_layer->visible_content_rect());
// Hit checking for a point outside the layer should return a null pointer
// (the root layer does not draw content, so it will not be tested either).
gfx::PointF test_point(76.f, 76.f);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the layer, but outside the touch handler
// region should return a null pointer.
test_point = gfx::Point(26, 26);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(34, 34);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(65, 65);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(74, 74);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the touch event handler region should
// return the root layer.
test_point = gfx::Point(35, 35);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
test_point = gfx::Point(64, 64);
test_point =
gfx::ScalePoint(test_point, device_scale_factor * page_scale_factor);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(12345, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerRegionsForSimpleClippedLayer) {
// Test that hit-checking will only work for the visible portion of a layer,
// and not the entire layer bounds. Here we just test the simple axis-aligned
// case.
gfx::Transform identity_matrix;
gfx::PointF anchor;
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
scoped_ptr<LayerImpl> clipping_layer =
LayerImpl::Create(host_impl.active_tree(), 123);
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(25.f, 25.f);
gfx::Size bounds(50, 50);
SetLayerPropertiesForTesting(clipping_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
clipping_layer->SetMasksToBounds(true);
scoped_ptr<LayerImpl> child =
LayerImpl::Create(host_impl.active_tree(), 456);
Region touch_handler_region(gfx::Rect(10, 10, 50, 50));
position = gfx::PointF(-50.f, -50.f);
bounds = gfx::Size(300, 300);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child->SetDrawsContent(true);
child->SetTouchEventHandlerRegion(touch_handler_region);
clipping_layer->AddChild(child.Pass());
root->AddChild(clipping_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
ASSERT_EQ(456, root->render_surface()->layer_list().at(0)->id());
// Hit checking for a point outside the layer should return a null pointer.
// Despite the child layer being very large, it should be clipped to the root
// layer's bounds.
gfx::Point test_point(24, 24);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the layer, but outside the touch handler
// region should return a null pointer.
test_point = gfx::Point(35, 35);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(74, 74);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
// Hit checking for a point inside the touch event handler region should
// return the root layer.
test_point = gfx::Point(25, 25);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
test_point = gfx::Point(34, 34);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(456, result_layer->id());
}
TEST_F(LayerTreeHostCommonTest,
HitCheckingTouchHandlerOverlappingRegions) {
gfx::Transform identity_matrix;
gfx::PointF anchor;
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
{
scoped_ptr<LayerImpl> touch_layer =
LayerImpl::Create(host_impl.active_tree(), 123);
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position;
gfx::Size bounds(50, 50);
SetLayerPropertiesForTesting(touch_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
touch_layer->SetDrawsContent(true);
touch_layer->SetTouchEventHandlerRegion(gfx::Rect(0, 0, 50, 50));
root->AddChild(touch_layer.Pass());
}
{
scoped_ptr<LayerImpl> notouch_layer =
LayerImpl::Create(host_impl.active_tree(), 1234);
// this layer is positioned, and hit testing should correctly know where the
// layer is located.
gfx::PointF position(0, 25);
gfx::Size bounds(50, 50);
SetLayerPropertiesForTesting(notouch_layer.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
notouch_layer->SetDrawsContent(true);
root->AddChild(notouch_layer.Pass());
}
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// Sanity check the scenario we just created.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
ASSERT_EQ(123, root->render_surface()->layer_list().at(0)->id());
ASSERT_EQ(1234, root->render_surface()->layer_list().at(1)->id());
gfx::Point test_point(35, 35);
LayerImpl* result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
test_point = gfx::Point(35, 15);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
ASSERT_TRUE(result_layer);
EXPECT_EQ(123, result_layer->id());
test_point = gfx::Point(35, 65);
result_layer =
LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
test_point, render_surface_layer_list);
EXPECT_FALSE(result_layer);
}
class NoScaleContentLayer : public ContentLayer {
public:
static scoped_refptr<NoScaleContentLayer> Create(ContentLayerClient* client) {
return make_scoped_refptr(new NoScaleContentLayer(client));
}
virtual void CalculateContentsScale(float ideal_contents_scale,
float device_scale_factor,
float page_scale_factor,
bool animating_transform_to_screen,
float* contents_scale_x,
float* contents_scale_y,
gfx::Size* content_bounds) OVERRIDE {
// Skip over the ContentLayer to the base Layer class.
Layer::CalculateContentsScale(ideal_contents_scale,
device_scale_factor,
page_scale_factor,
animating_transform_to_screen,
contents_scale_x,
contents_scale_y,
content_bounds);
}
protected:
explicit NoScaleContentLayer(ContentLayerClient* client)
: ContentLayer(client) {}
virtual ~NoScaleContentLayer() {}
};
scoped_refptr<NoScaleContentLayer> CreateNoScaleDrawableContentLayer(
ContentLayerClient* delegate) {
scoped_refptr<NoScaleContentLayer> to_return =
NoScaleContentLayer::Create(delegate);
to_return->SetIsDrawable(true);
return to_return;
}
TEST_F(LayerTreeHostCommonTest, LayerTransformsInHighDPI) {
// Verify draw and screen space transforms of layers not in a surface.
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> child = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> child_empty =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_empty.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(),
false,
true);
scoped_refptr<NoScaleContentLayer> child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_no_scale.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
parent->AddChild(child);
parent->AddChild(child_empty);
parent->AddChild(child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
float device_scale_factor = 2.5f;
float page_scale_factor = 1.f;
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, child);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
EXPECT_EQ(1u, render_surface_layer_list.size());
// Verify parent transforms
gfx::Transform expected_parent_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->draw_transform());
// Verify results of transformed parent rects
gfx::RectF parent_content_bounds(parent->content_bounds());
gfx::RectF parent_draw_rect =
MathUtil::MapClippedRect(parent->draw_transform(), parent_content_bounds);
gfx::RectF parent_screen_space_rect = MathUtil::MapClippedRect(
parent->screen_space_transform(), parent_content_bounds);
gfx::RectF expected_parent_draw_rect(parent->bounds());
expected_parent_draw_rect.Scale(device_scale_factor);
EXPECT_FLOAT_RECT_EQ(expected_parent_draw_rect, parent_draw_rect);
EXPECT_FLOAT_RECT_EQ(expected_parent_draw_rect, parent_screen_space_rect);
// Verify child and child_empty transforms. They should match.
gfx::Transform expected_child_transform;
expected_child_transform.Translate(
device_scale_factor * child->position().x(),
device_scale_factor * child->position().y());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child_empty->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child_empty->screen_space_transform());
// Verify results of transformed child and child_empty rects. They should
// match.
gfx::RectF child_content_bounds(child->content_bounds());
gfx::RectF child_draw_rect =
MathUtil::MapClippedRect(child->draw_transform(), child_content_bounds);
gfx::RectF child_screen_space_rect = MathUtil::MapClippedRect(
child->screen_space_transform(), child_content_bounds);
gfx::RectF child_empty_draw_rect = MathUtil::MapClippedRect(
child_empty->draw_transform(), child_content_bounds);
gfx::RectF child_empty_screen_space_rect = MathUtil::MapClippedRect(
child_empty->screen_space_transform(), child_content_bounds);
gfx::RectF expected_child_draw_rect(child->position(), child->bounds());
expected_child_draw_rect.Scale(device_scale_factor);
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_draw_rect);
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_screen_space_rect);
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_empty_draw_rect);
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_empty_screen_space_rect);
// Verify child_no_scale transforms
gfx::Transform expected_child_no_scale_transform = child->draw_transform();
// All transforms operate on content rects. The child's content rect
// incorporates device scale, but the child_no_scale does not; add it here.
expected_child_no_scale_transform.Scale(device_scale_factor,
device_scale_factor);
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_no_scale_transform,
child_no_scale->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_no_scale_transform,
child_no_scale->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, SurfaceLayerTransformsInHighDPI) {
// Verify draw and screen space transforms of layers in a surface.
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform perspective_matrix;
perspective_matrix.ApplyPerspectiveDepth(2.0);
gfx::Transform scale_small_matrix;
scale_small_matrix.Scale(SK_MScalar1 / 10.f, SK_MScalar1 / 12.f);
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> perspective_surface =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(perspective_surface.get(),
perspective_matrix * scale_small_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> scale_surface =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(scale_surface.get(),
scale_small_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
perspective_surface->SetForceRenderSurface(true);
scale_surface->SetForceRenderSurface(true);
parent->AddChild(perspective_surface);
parent->AddChild(scale_surface);
root->AddChild(parent);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
float device_scale_factor = 2.5f;
float page_scale_factor = 3.f;
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), parent->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
perspective_surface);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
scale_surface);
EXPECT_EQ(3u, render_surface_layer_list.size());
gfx::Transform expected_parent_draw_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_draw_transform,
parent->draw_transform());
// The scaled surface is rendered at its appropriate scale, and drawn 1:1
// into its target.
gfx::Transform expected_scale_surface_draw_transform;
expected_scale_surface_draw_transform.Translate(
device_scale_factor * page_scale_factor * scale_surface->position().x(),
device_scale_factor * page_scale_factor * scale_surface->position().y());
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_scale_surface_draw_transform,
scale_surface->render_surface()->draw_transform());
gfx::Transform expected_scale_surface_layer_draw_transform =
scale_small_matrix;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_scale_surface_layer_draw_transform,
scale_surface->draw_transform());
// The scale for the perspective surface is not known, so it is rendered 1:1
// with the screen, and then scaled during drawing.
gfx::Transform expected_perspective_surface_draw_transform;
expected_perspective_surface_draw_transform.Translate(
device_scale_factor * page_scale_factor *
perspective_surface->position().x(),
device_scale_factor * page_scale_factor *
perspective_surface->position().y());
expected_perspective_surface_draw_transform.PreconcatTransform(
perspective_matrix);
expected_perspective_surface_draw_transform.PreconcatTransform(
scale_small_matrix);
gfx::Transform expected_perspective_surface_layer_draw_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_perspective_surface_draw_transform,
perspective_surface->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_perspective_surface_layer_draw_transform,
perspective_surface->draw_transform());
}
TEST_F(LayerTreeHostCommonTest,
LayerTransformsInHighDPIAccurateScaleZeroChildPosition) {
// Verify draw and screen space transforms of layers not in a surface.
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(133, 133),
false,
true);
scoped_refptr<ContentLayer> child = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(13, 13),
false,
true);
scoped_refptr<NoScaleContentLayer> child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_no_scale.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(13, 13),
false,
true);
parent->AddChild(child);
parent->AddChild(child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
float device_scale_factor = 1.7f;
float page_scale_factor = 1.f;
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = parent.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, child);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
EXPECT_EQ(1u, render_surface_layer_list.size());
// Verify parent transforms
gfx::Transform expected_parent_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->draw_transform());
// Verify results of transformed parent rects
gfx::RectF parent_content_bounds(parent->content_bounds());
gfx::RectF parent_draw_rect =
MathUtil::MapClippedRect(parent->draw_transform(), parent_content_bounds);
gfx::RectF parent_screen_space_rect = MathUtil::MapClippedRect(
parent->screen_space_transform(), parent_content_bounds);
gfx::RectF expected_parent_draw_rect(parent->bounds());
expected_parent_draw_rect.Scale(device_scale_factor);
expected_parent_draw_rect.set_width(ceil(expected_parent_draw_rect.width()));
expected_parent_draw_rect.set_height(
ceil(expected_parent_draw_rect.height()));
EXPECT_FLOAT_RECT_EQ(expected_parent_draw_rect, parent_draw_rect);
EXPECT_FLOAT_RECT_EQ(expected_parent_draw_rect, parent_screen_space_rect);
// Verify child transforms
gfx::Transform expected_child_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_transform,
child->screen_space_transform());
// Verify results of transformed child rects
gfx::RectF child_content_bounds(child->content_bounds());
gfx::RectF child_draw_rect =
MathUtil::MapClippedRect(child->draw_transform(), child_content_bounds);
gfx::RectF child_screen_space_rect = MathUtil::MapClippedRect(
child->screen_space_transform(), child_content_bounds);
gfx::RectF expected_child_draw_rect(child->bounds());
expected_child_draw_rect.Scale(device_scale_factor);
expected_child_draw_rect.set_width(ceil(expected_child_draw_rect.width()));
expected_child_draw_rect.set_height(ceil(expected_child_draw_rect.height()));
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_draw_rect);
EXPECT_FLOAT_RECT_EQ(expected_child_draw_rect, child_screen_space_rect);
// Verify child_no_scale transforms
gfx::Transform expected_child_no_scale_transform = child->draw_transform();
// All transforms operate on content rects. The child's content rect
// incorporates device scale, but the child_no_scale does not; add it here.
expected_child_no_scale_transform.Scale(device_scale_factor,
device_scale_factor);
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_no_scale_transform,
child_no_scale->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_child_no_scale_transform,
child_no_scale->screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, ContentsScale) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 1.75;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 1.25;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> child_empty =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_empty.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(),
false,
true);
scoped_refptr<NoScaleContentLayer> child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(12.f, 12.f),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(child_scale);
parent->AddChild(child_empty);
parent->AddChild(child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
float device_scale_factor = 2.5f;
float page_scale_factor = 1.f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
// The parent is scaled up and shouldn't need to scale during draw. The
// child that can scale its contents should also not need to scale during
// draw. This shouldn't change if the child has empty bounds. The other
// children should.
EXPECT_FLOAT_EQ(1.0, parent->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, parent->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(1.0, child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, child_scale->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(1.0, child_empty->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, child_empty->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_no_scale->draw_transform().matrix().get(1, 1));
}
// If the device_scale_factor or page_scale_factor changes, then it should be
// updated using the initial transform as the raster scale.
device_scale_factor = 2.25f;
page_scale_factor = 1.25f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
}
// If the transform changes, we expect the raster scale to be reset to 1.0.
SkMScalar second_child_scale = 1.75;
child_scale_matrix.Scale(second_child_scale / initial_child_scale,
second_child_scale / initial_child_scale);
child_scale->SetTransform(child_scale_matrix);
child_empty->SetTransform(child_scale_matrix);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale,
parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
}
// If the device_scale_factor or page_scale_factor changes, then it should be
// updated, but still using 1.0 as the raster scale.
device_scale_factor = 2.75f;
page_scale_factor = 1.75f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale,
parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
}
}
TEST_F(LayerTreeHostCommonTest,
ContentsScale_LayerTransformsDontAffectContentsScale) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 1.75;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 1.25;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> child_empty =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_empty.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(),
false,
true);
scoped_refptr<NoScaleContentLayer> child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(12.f, 12.f),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(child_scale);
parent->AddChild(child_empty);
parent->AddChild(child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
float device_scale_factor = 2.5f;
float page_scale_factor = 1.f;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get(),
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
child_empty);
EXPECT_CONTENTS_SCALE_EQ(1, child_no_scale);
// Since the transform scale does not affect contents scale, it should affect
// the draw transform instead.
EXPECT_FLOAT_EQ(initial_parent_scale,
parent->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(initial_parent_scale,
parent->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(initial_parent_scale * initial_child_scale,
child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(initial_parent_scale * initial_child_scale,
child_scale->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(initial_parent_scale * initial_child_scale,
child_empty->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(initial_parent_scale * initial_child_scale,
child_empty->draw_transform().matrix().get(1, 1));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
child_no_scale->draw_transform().matrix().get(1, 1));
}
TEST_F(LayerTreeHostCommonTest, SmallContentsScale) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 1.75;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 0.25;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(child_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
float device_scale_factor = 2.5f;
float page_scale_factor = 0.01f;
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale,
parent);
// The child's scale is < 1, so we should not save and use that scale
// factor.
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor * 1,
child_scale);
}
// When chilld's total scale becomes >= 1, we should save and use that scale
// factor.
child_scale_matrix.MakeIdentity();
SkMScalar final_child_scale = 0.75;
child_scale_matrix.Scale(final_child_scale, final_child_scale);
child_scale->SetTransform(child_scale_matrix);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale,
parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * final_child_scale,
child_scale);
}
}
TEST_F(LayerTreeHostCommonTest, ContentsScaleForSurfaces) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 2.0;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 3.0;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> surface_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> surface_scale_child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale_child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_scale_child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale_child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(12.f, 12.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> surface_no_scale_child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale_child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_no_scale_child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale_child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(surface_scale);
parent->AddChild(surface_no_scale);
surface_scale->SetForceRenderSurface(true);
surface_scale->AddChild(surface_scale_child_scale);
surface_scale->AddChild(surface_scale_child_no_scale);
surface_no_scale->SetForceRenderSurface(true);
surface_no_scale->AddChild(surface_no_scale_child_scale);
surface_no_scale->AddChild(surface_no_scale_child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
SkMScalar device_scale_factor = 5;
SkMScalar page_scale_factor = 7;
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale, parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
surface_scale);
EXPECT_CONTENTS_SCALE_EQ(1, surface_no_scale);
EXPECT_CONTENTS_SCALE_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_scale_child_scale);
EXPECT_CONTENTS_SCALE_EQ(1, surface_scale_child_no_scale);
EXPECT_CONTENTS_SCALE_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_no_scale_child_scale);
EXPECT_CONTENTS_SCALE_EQ(1, surface_no_scale_child_no_scale);
// The parent is scaled up and shouldn't need to scale during draw.
EXPECT_FLOAT_EQ(1.0, parent->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, parent->draw_transform().matrix().get(1, 1));
// RenderSurfaces should always be 1:1 with their target.
EXPECT_FLOAT_EQ(
1.0,
surface_scale->render_surface()->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
1.0,
surface_scale->render_surface()->draw_transform().matrix().get(1, 1));
// The surface_scale can apply contents scale so the layer shouldn't need to
// scale during draw.
EXPECT_FLOAT_EQ(1.0, surface_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, surface_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_scale can apply contents scale so it shouldn't need
// to scale during draw.
EXPECT_FLOAT_EQ(
1.0, surface_scale_child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
1.0, surface_scale_child_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_no_scale can not apply contents scale, so it needs
// to be scaled during draw.
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_scale_child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_scale_child_no_scale->draw_transform().matrix().get(1, 1));
// RenderSurfaces should always be 1:1 with their target.
EXPECT_FLOAT_EQ(
1.0,
surface_no_scale->render_surface()->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
1.0,
surface_no_scale->render_surface()->draw_transform().matrix().get(1, 1));
// The surface_no_scale layer can not apply contents scale, so it needs to be
// scaled during draw.
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
surface_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor *
initial_parent_scale * initial_child_scale,
surface_no_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_scale can apply contents scale so it shouldn't need
// to scale during draw.
EXPECT_FLOAT_EQ(
1.0, surface_no_scale_child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
1.0, surface_no_scale_child_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_no_scale can not apply contents scale, so it needs
// to be scaled during draw.
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_no_scale_child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_parent_scale *
initial_child_scale * initial_child_scale,
surface_no_scale_child_no_scale->draw_transform().matrix().get(1, 1));
}
TEST_F(LayerTreeHostCommonTest,
ContentsScaleForSurfaces_LayerTransformsDontAffectContentsScale) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 2.0;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 3.0;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> surface_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> surface_scale_child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale_child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_scale_child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_scale_child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(12.f, 12.f),
gfx::Size(10, 10),
false,
true);
scoped_refptr<ContentLayer> surface_no_scale_child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale_child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
scoped_refptr<NoScaleContentLayer> surface_no_scale_child_no_scale =
CreateNoScaleDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(surface_no_scale_child_no_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(surface_scale);
parent->AddChild(surface_no_scale);
surface_scale->SetForceRenderSurface(true);
surface_scale->AddChild(surface_scale_child_scale);
surface_scale->AddChild(surface_scale_child_no_scale);
surface_no_scale->SetForceRenderSurface(true);
surface_no_scale->AddChild(surface_no_scale_child_scale);
surface_no_scale->AddChild(surface_no_scale_child_no_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
SkMScalar device_scale_factor = 5.0;
SkMScalar page_scale_factor = 7.0;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.page_scale_factor = page_scale_factor;
inputs.page_scale_application_layer = root.get();
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
parent);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
surface_scale);
EXPECT_CONTENTS_SCALE_EQ(1.f, surface_no_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
surface_scale_child_scale);
EXPECT_CONTENTS_SCALE_EQ(1.f, surface_scale_child_no_scale);
EXPECT_CONTENTS_SCALE_EQ(device_scale_factor * page_scale_factor,
surface_no_scale_child_scale);
EXPECT_CONTENTS_SCALE_EQ(1.f, surface_no_scale_child_no_scale);
// The parent is scaled up during draw, since its contents are not scaled by
// the transform hierarchy.
EXPECT_FLOAT_EQ(initial_parent_scale,
parent->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(initial_parent_scale,
parent->draw_transform().matrix().get(1, 1));
// The child surface is scaled up during draw since its subtree is not scaled
// by the transform hierarchy.
EXPECT_FLOAT_EQ(
initial_parent_scale * initial_child_scale,
surface_scale->render_surface()->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
initial_parent_scale * initial_child_scale,
surface_scale->render_surface()->draw_transform().matrix().get(1, 1));
// The surface_scale's RenderSurface is scaled during draw, so the layer does
// not need to be scaled when drawing into its surface.
EXPECT_FLOAT_EQ(1.0, surface_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(1.0, surface_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_scale is scaled when drawing into its surface,
// since its content bounds are not scaled by the transform hierarchy.
EXPECT_FLOAT_EQ(
initial_child_scale,
surface_scale_child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
initial_child_scale,
surface_scale_child_scale->draw_transform().matrix().get(1, 1));
// The surface_scale_child_no_scale has a fixed contents scale of 1, so it
// needs to be scaled by the device and page scale factors, along with the
// transform hierarchy.
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_child_scale,
surface_scale_child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_child_scale,
surface_scale_child_no_scale->draw_transform().matrix().get(1, 1));
// The child surface is scaled up during draw since its subtree is not scaled
// by the transform hierarchy.
EXPECT_FLOAT_EQ(
initial_parent_scale * initial_child_scale,
surface_no_scale->render_surface()->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
initial_parent_scale * initial_child_scale,
surface_no_scale->render_surface()->draw_transform().matrix().get(1, 1));
// The surface_no_scale layer has a fixed contents scale of 1, so it needs to
// be scaled by the device and page scale factors. Its surface is already
// scaled by the transform hierarchy so those don't need to scale the layer's
// drawing.
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor,
surface_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(device_scale_factor * page_scale_factor,
surface_no_scale->draw_transform().matrix().get(1, 1));
// The surface_no_scale_child_scale has its contents scaled by the page and
// device scale factors, but needs to be scaled by the transform hierarchy
// when drawing.
EXPECT_FLOAT_EQ(
initial_child_scale,
surface_no_scale_child_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
initial_child_scale,
surface_no_scale_child_scale->draw_transform().matrix().get(1, 1));
// The surface_no_scale_child_no_scale has a fixed contents scale of 1, so it
// needs to be scaled by the device and page scale factors. It also needs to
// be scaled by any transform heirarchy below its target surface.
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_child_scale,
surface_no_scale_child_no_scale->draw_transform().matrix().get(0, 0));
EXPECT_FLOAT_EQ(
device_scale_factor * page_scale_factor * initial_child_scale,
surface_no_scale_child_no_scale->draw_transform().matrix().get(1, 1));
}
TEST_F(LayerTreeHostCommonTest, ContentsScaleForAnimatingLayer) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
gfx::Transform parent_scale_matrix;
SkMScalar initial_parent_scale = 1.75;
parent_scale_matrix.Scale(initial_parent_scale, initial_parent_scale);
gfx::Transform child_scale_matrix;
SkMScalar initial_child_scale = 1.25;
child_scale_matrix.Scale(initial_child_scale, initial_child_scale);
scoped_refptr<Layer> root = Layer::Create();
root->SetBounds(gfx::Size(100, 100));
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
parent_scale_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
false,
true);
scoped_refptr<ContentLayer> child_scale =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child_scale.get(),
child_scale_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
root->AddChild(parent);
parent->AddChild(child_scale);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// Now put an animating transform on child.
int animation_id = AddAnimatedTransformToController(
child_scale->layer_animation_controller(), 10.0, 30, 0);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(initial_parent_scale, parent);
// The layers with animating transforms should not compute a contents scale
// other than 1 until they finish animating.
EXPECT_CONTENTS_SCALE_EQ(1, child_scale);
}
// Remove the animation, now it can save a raster scale.
child_scale->layer_animation_controller()->RemoveAnimation(animation_id);
{
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_CONTENTS_SCALE_EQ(initial_parent_scale, parent);
// The layers with animating transforms should not compute a contents scale
// other than 1 until they finish animating.
EXPECT_CONTENTS_SCALE_EQ(initial_parent_scale * initial_child_scale,
child_scale);
}
}
TEST_F(LayerTreeHostCommonTest, RenderSurfaceTransformsInHighDPI) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
false,
true);
scoped_refptr<ContentLayer> child = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
gfx::Transform replica_transform;
replica_transform.Scale(1.0, -1.0);
scoped_refptr<ContentLayer> replica = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(replica.get(),
replica_transform,
gfx::PointF(),
gfx::PointF(2.f, 2.f),
gfx::Size(10, 10),
false,
true);
// This layer should end up in the same surface as child, with the same draw
// and screen space transforms.
scoped_refptr<ContentLayer> duplicate_child_non_owner =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(duplicate_child_non_owner.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
false,
true);
parent->AddChild(child);
child->AddChild(duplicate_child_non_owner);
child->SetReplicaLayer(replica.get());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
RenderSurfaceLayerList render_surface_layer_list;
float device_scale_factor = 1.5f;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have two render surfaces. The root's render surface and child's
// render surface (it needs one because it has a replica layer).
EXPECT_EQ(2u, render_surface_layer_list.size());
gfx::Transform expected_parent_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_parent_transform,
parent->draw_transform());
gfx::Transform expected_draw_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_draw_transform,
child->draw_transform());
gfx::Transform expected_screen_space_transform;
expected_screen_space_transform.Translate(
device_scale_factor * child->position().x(),
device_scale_factor * child->position().y());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_screen_space_transform,
child->screen_space_transform());
gfx::Transform expected_duplicate_child_draw_transform =
child->draw_transform();
EXPECT_TRANSFORMATION_MATRIX_EQ(child->draw_transform(),
duplicate_child_non_owner->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
child->screen_space_transform(),
duplicate_child_non_owner->screen_space_transform());
EXPECT_RECT_EQ(child->drawable_content_rect(),
duplicate_child_non_owner->drawable_content_rect());
EXPECT_EQ(child->content_bounds(),
duplicate_child_non_owner->content_bounds());
gfx::Transform expected_render_surface_draw_transform;
expected_render_surface_draw_transform.Translate(
device_scale_factor * child->position().x(),
device_scale_factor * child->position().y());
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_render_surface_draw_transform,
child->render_surface()->draw_transform());
gfx::Transform expected_surface_draw_transform;
expected_surface_draw_transform.Translate(device_scale_factor * 2.f,
device_scale_factor * 2.f);
EXPECT_TRANSFORMATION_MATRIX_EQ(expected_surface_draw_transform,
child->render_surface()->draw_transform());
gfx::Transform expected_surface_screen_space_transform;
expected_surface_screen_space_transform.Translate(device_scale_factor * 2.f,
device_scale_factor * 2.f);
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_surface_screen_space_transform,
child->render_surface()->screen_space_transform());
gfx::Transform expected_replica_draw_transform;
expected_replica_draw_transform.matrix().set(1, 1, -1.0);
expected_replica_draw_transform.matrix().set(0, 3, 6.0);
expected_replica_draw_transform.matrix().set(1, 3, 6.0);
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_replica_draw_transform,
child->render_surface()->replica_draw_transform());
gfx::Transform expected_replica_screen_space_transform;
expected_replica_screen_space_transform.matrix().set(1, 1, -1.0);
expected_replica_screen_space_transform.matrix().set(0, 3, 6.0);
expected_replica_screen_space_transform.matrix().set(1, 3, 6.0);
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_replica_screen_space_transform,
child->render_surface()->replica_screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_replica_screen_space_transform,
child->render_surface()->replica_screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest,
RenderSurfaceTransformsInHighDPIAccurateScaleZeroPosition) {
MockContentLayerClient delegate;
gfx::Transform identity_matrix;
scoped_refptr<ContentLayer> parent = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(33, 31),
false,
true);
scoped_refptr<ContentLayer> child = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(13, 11),
false,
true);
gfx::Transform replica_transform;
replica_transform.Scale(1.0, -1.0);
scoped_refptr<ContentLayer> replica = CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(replica.get(),
replica_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(13, 11),
false,
true);
// This layer should end up in the same surface as child, with the same draw
// and screen space transforms.
scoped_refptr<ContentLayer> duplicate_child_non_owner =
CreateDrawableContentLayer(&delegate);
SetLayerPropertiesForTesting(duplicate_child_non_owner.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(13, 11),
false,
true);
parent->AddChild(child);
child->AddChild(duplicate_child_non_owner);
child->SetReplicaLayer(replica.get());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(parent);
float device_scale_factor = 1.7f;
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
parent.get(), parent->bounds(), &render_surface_layer_list);
inputs.device_scale_factor = device_scale_factor;
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have two render surfaces. The root's render surface and child's
// render surface (it needs one because it has a replica layer).
EXPECT_EQ(2u, render_surface_layer_list.size());
gfx::Transform identity_transform;
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform,
parent->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform, parent->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform, child->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform,
child->screen_space_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform,
duplicate_child_non_owner->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
identity_transform, duplicate_child_non_owner->screen_space_transform());
EXPECT_RECT_EQ(child->drawable_content_rect(),
duplicate_child_non_owner->drawable_content_rect());
EXPECT_EQ(child->content_bounds(),
duplicate_child_non_owner->content_bounds());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform,
child->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(identity_transform,
child->render_surface()->draw_transform());
EXPECT_TRANSFORMATION_MATRIX_EQ(
identity_transform, child->render_surface()->screen_space_transform());
gfx::Transform expected_replica_draw_transform;
expected_replica_draw_transform.matrix().set(1, 1, -1.0);
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_replica_draw_transform,
child->render_surface()->replica_draw_transform());
gfx::Transform expected_replica_screen_space_transform;
expected_replica_screen_space_transform.matrix().set(1, 1, -1.0);
EXPECT_TRANSFORMATION_MATRIX_EQ(
expected_replica_screen_space_transform,
child->render_surface()->replica_screen_space_transform());
}
TEST_F(LayerTreeHostCommonTest, SubtreeSearch) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<Layer> grand_child = Layer::Create();
scoped_refptr<Layer> mask_layer = Layer::Create();
scoped_refptr<Layer> replica_layer = Layer::Create();
grand_child->SetReplicaLayer(replica_layer.get());
child->AddChild(grand_child.get());
child->SetMaskLayer(mask_layer.get());
root->AddChild(child.get());
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
int nonexistent_id = -1;
EXPECT_EQ(root,
LayerTreeHostCommon::FindLayerInSubtree(root.get(), root->id()));
EXPECT_EQ(child,
LayerTreeHostCommon::FindLayerInSubtree(root.get(), child->id()));
EXPECT_EQ(
grand_child,
LayerTreeHostCommon::FindLayerInSubtree(root.get(), grand_child->id()));
EXPECT_EQ(
mask_layer,
LayerTreeHostCommon::FindLayerInSubtree(root.get(), mask_layer->id()));
EXPECT_EQ(
replica_layer,
LayerTreeHostCommon::FindLayerInSubtree(root.get(), replica_layer->id()));
EXPECT_EQ(
0, LayerTreeHostCommon::FindLayerInSubtree(root.get(), nonexistent_id));
}
TEST_F(LayerTreeHostCommonTest, TransparentChildRenderSurfaceCreation) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> grand_child =
make_scoped_refptr(new LayerWithForcedDrawsContent());
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
root->AddChild(child);
child->AddChild(grand_child);
child->SetOpacity(0.5f);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_FALSE(child->render_surface());
}
TEST_F(LayerTreeHostCommonTest, OpacityAnimatingOnPendingTree) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.pending_tree(), 1);
const gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(100, 100),
true,
false);
root->SetDrawsContent(true);
scoped_ptr<LayerImpl> child = LayerImpl::Create(host_impl.pending_tree(), 2);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
child->SetDrawsContent(true);
child->SetOpacity(0.0f);
// Add opacity animation.
AddOpacityTransitionToController(
child->layer_animation_controller(), 10.0, 0.0f, 1.0f, false);
root->AddChild(child.Pass());
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface and two layers. The child
// layer should be included even though it is transparent.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
}
typedef std::tr1::tuple<bool, bool> LCDTextTestParam;
class LCDTextTest
: public LayerTreeHostCommonTestBase,
public testing::TestWithParam<LCDTextTestParam> {
protected:
virtual void SetUp() {
can_use_lcd_text_ = std::tr1::get<0>(GetParam());
root_ = Layer::Create();
child_ = Layer::Create();
grand_child_ = Layer::Create();
child_->AddChild(grand_child_.get());
root_->AddChild(child_.get());
gfx::Transform identity_matrix;
SetLayerPropertiesForTesting(root_.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 1),
true,
false);
SetLayerPropertiesForTesting(child_.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 1),
true,
false);
SetLayerPropertiesForTesting(grand_child_.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(1, 1),
true,
false);
child_->SetForceRenderSurface(std::tr1::get<1>(GetParam()));
host_ = FakeLayerTreeHost::Create();
host_->SetRootLayer(root_);
}
bool can_use_lcd_text_;
scoped_ptr<FakeLayerTreeHost> host_;
scoped_refptr<Layer> root_;
scoped_refptr<Layer> child_;
scoped_refptr<Layer> grand_child_;
};
TEST_P(LCDTextTest, CanUseLCDText) {
// Case 1: Identity transform.
gfx::Transform identity_matrix;
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, child_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, grand_child_->can_use_lcd_text());
// Case 2: Integral translation.
gfx::Transform integral_translation;
integral_translation.Translate(1.0, 2.0);
child_->SetTransform(integral_translation);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, child_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, grand_child_->can_use_lcd_text());
// Case 3: Non-integral translation.
gfx::Transform non_integral_translation;
non_integral_translation.Translate(1.5, 2.5);
child_->SetTransform(non_integral_translation);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_FALSE(child_->can_use_lcd_text());
EXPECT_FALSE(grand_child_->can_use_lcd_text());
// Case 4: Rotation.
gfx::Transform rotation;
rotation.Rotate(10.0);
child_->SetTransform(rotation);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_FALSE(child_->can_use_lcd_text());
EXPECT_FALSE(grand_child_->can_use_lcd_text());
// Case 5: Scale.
gfx::Transform scale;
scale.Scale(2.0, 2.0);
child_->SetTransform(scale);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_FALSE(child_->can_use_lcd_text());
EXPECT_FALSE(grand_child_->can_use_lcd_text());
// Case 6: Skew.
gfx::Transform skew;
skew.SkewX(10.0);
child_->SetTransform(skew);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_FALSE(child_->can_use_lcd_text());
EXPECT_FALSE(grand_child_->can_use_lcd_text());
// Case 7: Translucent.
child_->SetTransform(identity_matrix);
child_->SetOpacity(0.5f);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_FALSE(child_->can_use_lcd_text());
EXPECT_FALSE(grand_child_->can_use_lcd_text());
// Case 8: Sanity check: restore transform and opacity.
child_->SetTransform(identity_matrix);
child_->SetOpacity(1.f);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, child_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, grand_child_->can_use_lcd_text());
}
TEST_P(LCDTextTest, CanUseLCDTextWithAnimation) {
// Sanity check: Make sure can_use_lcd_text_ is set on each node.
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, child_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, grand_child_->can_use_lcd_text());
// Add opacity animation.
child_->SetOpacity(0.9f);
AddOpacityTransitionToController(
child_->layer_animation_controller(), 10.0, 0.9f, 0.1f, false);
ExecuteCalculateDrawProperties(
root_.get(), 1.f, 1.f, NULL, can_use_lcd_text_);
// Text AA should not be adjusted while animation is active.
// Make sure LCD text AA setting remains unchanged.
EXPECT_EQ(can_use_lcd_text_, root_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, child_->can_use_lcd_text());
EXPECT_EQ(can_use_lcd_text_, grand_child_->can_use_lcd_text());
}
INSTANTIATE_TEST_CASE_P(LayerTreeHostCommonTest,
LCDTextTest,
testing::Combine(testing::Bool(), testing::Bool()));
TEST_F(LayerTreeHostCommonTest, SubtreeHidden_SingleLayer) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetIsDrawable(true);
scoped_refptr<Layer> child = Layer::Create();
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
child->SetIsDrawable(true);
scoped_refptr<Layer> grand_child = Layer::Create();
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
grand_child->SetIsDrawable(true);
grand_child->SetHideLayerAndSubtree(true);
child->AddChild(grand_child);
root->AddChild(child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface and two layers. The grand child has
// hidden itself.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
EXPECT_EQ(root->id(), root->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(child->id(), root->render_surface()->layer_list().at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, SubtreeHidden_SingleLayerImpl) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.pending_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetDrawsContent(true);
scoped_ptr<LayerImpl> child = LayerImpl::Create(host_impl.pending_tree(), 2);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
child->SetDrawsContent(true);
scoped_ptr<LayerImpl> grand_child =
LayerImpl::Create(host_impl.pending_tree(), 3);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
grand_child->SetDrawsContent(true);
grand_child->SetHideLayerAndSubtree(true);
child->AddChild(grand_child.Pass());
root->AddChild(child.Pass());
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface and two layers. The grand child has
// hidden itself.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
EXPECT_EQ(1, root->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(2, root->render_surface()->layer_list().at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, SubtreeHidden_TwoLayers) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetIsDrawable(true);
scoped_refptr<Layer> child = Layer::Create();
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
child->SetIsDrawable(true);
child->SetHideLayerAndSubtree(true);
scoped_refptr<Layer> grand_child = Layer::Create();
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
grand_child->SetIsDrawable(true);
child->AddChild(grand_child);
root->AddChild(child);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface and one layers. The child has
// hidden itself and the grand child.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
EXPECT_EQ(root->id(), root->render_surface()->layer_list().at(0)->id());
}
TEST_F(LayerTreeHostCommonTest, SubtreeHidden_TwoLayersImpl) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.pending_tree(), 1);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetDrawsContent(true);
scoped_ptr<LayerImpl> child = LayerImpl::Create(host_impl.pending_tree(), 2);
SetLayerPropertiesForTesting(child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
child->SetDrawsContent(true);
child->SetHideLayerAndSubtree(true);
scoped_ptr<LayerImpl> grand_child =
LayerImpl::Create(host_impl.pending_tree(), 3);
SetLayerPropertiesForTesting(grand_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
grand_child->SetDrawsContent(true);
child->AddChild(grand_child.Pass());
root->AddChild(child.Pass());
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface and one layers. The child has
// hidden itself and the grand child.
ASSERT_EQ(1u, render_surface_layer_list.size());
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
EXPECT_EQ(1, root->render_surface()->layer_list().at(0)->id());
}
void EmptyCopyOutputCallback(scoped_ptr<CopyOutputResult> result) {}
TEST_F(LayerTreeHostCommonTest, SubtreeHiddenWithCopyRequest) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetIsDrawable(true);
scoped_refptr<Layer> copy_grand_parent = Layer::Create();
SetLayerPropertiesForTesting(copy_grand_parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
copy_grand_parent->SetIsDrawable(true);
scoped_refptr<Layer> copy_parent = Layer::Create();
SetLayerPropertiesForTesting(copy_parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
copy_parent->SetIsDrawable(true);
copy_parent->SetForceRenderSurface(true);
scoped_refptr<Layer> copy_layer = Layer::Create();
SetLayerPropertiesForTesting(copy_layer.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
copy_layer->SetIsDrawable(true);
scoped_refptr<Layer> copy_child = Layer::Create();
SetLayerPropertiesForTesting(copy_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
copy_child->SetIsDrawable(true);
scoped_refptr<Layer> copy_grand_parent_sibling_before = Layer::Create();
SetLayerPropertiesForTesting(copy_grand_parent_sibling_before.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
copy_grand_parent_sibling_before->SetIsDrawable(true);
scoped_refptr<Layer> copy_grand_parent_sibling_after = Layer::Create();
SetLayerPropertiesForTesting(copy_grand_parent_sibling_after.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
copy_grand_parent_sibling_after->SetIsDrawable(true);
copy_layer->AddChild(copy_child);
copy_parent->AddChild(copy_layer);
copy_grand_parent->AddChild(copy_parent);
root->AddChild(copy_grand_parent_sibling_before);
root->AddChild(copy_grand_parent);
root->AddChild(copy_grand_parent_sibling_after);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
// Hide the copy_grand_parent and its subtree. But make a copy request in that
// hidden subtree on copy_layer.
copy_grand_parent->SetHideLayerAndSubtree(true);
copy_grand_parent_sibling_before->SetHideLayerAndSubtree(true);
copy_grand_parent_sibling_after->SetHideLayerAndSubtree(true);
copy_layer->RequestCopyOfOutput(CopyOutputRequest::CreateRequest(
base::Bind(&EmptyCopyOutputCallback)));
EXPECT_TRUE(copy_layer->HasCopyRequest());
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRUE(root->draw_properties().layer_or_descendant_has_copy_request);
EXPECT_TRUE(copy_grand_parent->draw_properties().
layer_or_descendant_has_copy_request);
EXPECT_TRUE(copy_parent->draw_properties().
layer_or_descendant_has_copy_request);
EXPECT_TRUE(copy_layer->draw_properties().
layer_or_descendant_has_copy_request);
EXPECT_FALSE(copy_child->draw_properties().
layer_or_descendant_has_copy_request);
EXPECT_FALSE(copy_grand_parent_sibling_before->draw_properties().
layer_or_descendant_has_copy_request);
EXPECT_FALSE(copy_grand_parent_sibling_after->draw_properties().
layer_or_descendant_has_copy_request);
// We should have three render surfaces, one for the root, one for the parent
// since it owns a surface, and one for the copy_layer.
ASSERT_EQ(3u, render_surface_layer_list.size());
EXPECT_EQ(root->id(), render_surface_layer_list.at(0)->id());
EXPECT_EQ(copy_parent->id(), render_surface_layer_list.at(1)->id());
EXPECT_EQ(copy_layer->id(), render_surface_layer_list.at(2)->id());
// The root render surface should have 2 contributing layers. The
// copy_grand_parent is hidden along with its siblings, but the copy_parent
// will appear since something in its subtree needs to be drawn for a copy
// request.
ASSERT_EQ(2u, root->render_surface()->layer_list().size());
EXPECT_EQ(root->id(), root->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(copy_parent->id(),
root->render_surface()->layer_list().at(1)->id());
// Nothing actually draws into the copy parent, so only the copy_layer will
// appear in its list, since it needs to be drawn for the copy request.
ASSERT_EQ(1u, copy_parent->render_surface()->layer_list().size());
EXPECT_EQ(copy_layer->id(),
copy_parent->render_surface()->layer_list().at(0)->id());
// The copy_layer's render surface should have two contributing layers.
ASSERT_EQ(2u, copy_layer->render_surface()->layer_list().size());
EXPECT_EQ(copy_layer->id(),
copy_layer->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(copy_child->id(),
copy_layer->render_surface()->layer_list().at(1)->id());
}
TEST_F(LayerTreeHostCommonTest, ClippedOutCopyRequest) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetIsDrawable(true);
scoped_refptr<Layer> copy_parent = Layer::Create();
SetLayerPropertiesForTesting(copy_parent.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(),
true,
false);
copy_parent->SetIsDrawable(true);
copy_parent->SetMasksToBounds(true);
scoped_refptr<Layer> copy_layer = Layer::Create();
SetLayerPropertiesForTesting(copy_layer.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
copy_layer->SetIsDrawable(true);
scoped_refptr<Layer> copy_child = Layer::Create();
SetLayerPropertiesForTesting(copy_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
copy_child->SetIsDrawable(true);
copy_layer->AddChild(copy_child);
copy_parent->AddChild(copy_layer);
root->AddChild(copy_parent);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
copy_layer->RequestCopyOfOutput(CopyOutputRequest::CreateRequest(
base::Bind(&EmptyCopyOutputCallback)));
EXPECT_TRUE(copy_layer->HasCopyRequest());
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// We should have one render surface, as the others are clipped out.
ASSERT_EQ(1u, render_surface_layer_list.size());
EXPECT_EQ(root->id(), render_surface_layer_list.at(0)->id());
// The root render surface should only have 1 contributing layer, since the
// other layers are empty/clipped away.
ASSERT_EQ(1u, root->render_surface()->layer_list().size());
EXPECT_EQ(root->id(), root->render_surface()->layer_list().at(0)->id());
}
TEST_F(LayerTreeHostCommonTest, VisibleContentRectInsideSurface) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
const gfx::Transform identity_matrix;
scoped_refptr<Layer> root = Layer::Create();
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
root->SetIsDrawable(true);
// The surface is moved slightly outside of the viewport.
scoped_refptr<Layer> surface = Layer::Create();
SetLayerPropertiesForTesting(surface.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(-10, -20),
gfx::Size(),
true,
false);
surface->SetForceRenderSurface(true);
scoped_refptr<Layer> surface_child = Layer::Create();
SetLayerPropertiesForTesting(surface_child.get(),
identity_matrix,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
surface_child->SetIsDrawable(true);
surface->AddChild(surface_child);
root->AddChild(surface);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_adjust_raster_scales = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
// The visible_content_rect for the |surface_child| should not be clipped by
// the viewport.
EXPECT_EQ(gfx::Rect(50, 50).ToString(),
surface_child->visible_content_rect().ToString());
}
TEST_F(LayerTreeHostCommonTest, TransformedClipParent) {
// Ensure that a transform between the layer and its render surface is not a
// problem. Constructs the following layer tree.
//
// root (a render surface)
// + render_surface
// + clip_parent (scaled)
// + intervening_clipping_layer
// + clip_child
//
// The render surface should be resized correctly and the clip child should
// inherit the right clip rect.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface = Layer::Create();
scoped_refptr<Layer> clip_parent = Layer::Create();
scoped_refptr<Layer> intervening = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> clip_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(render_surface);
render_surface->AddChild(clip_parent);
clip_parent->AddChild(intervening);
intervening->AddChild(clip_child);
clip_child->SetClipParent(clip_parent.get());
intervening->SetMasksToBounds(true);
clip_parent->SetMasksToBounds(true);
render_surface->SetForceRenderSurface(true);
gfx::Transform scale_transform;
scale_transform.Scale(2, 2);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(render_surface.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(clip_parent.get(),
scale_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(intervening.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(10, 10),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
ASSERT_TRUE(root->render_surface());
ASSERT_TRUE(render_surface->render_surface());
// Ensure that we've inherited our clip parent's clip and weren't affected
// by the intervening clip layer.
ASSERT_EQ(gfx::Rect(1, 1, 20, 20).ToString(),
clip_parent->clip_rect().ToString());
ASSERT_EQ(clip_parent->clip_rect().ToString(),
clip_child->clip_rect().ToString());
ASSERT_EQ(gfx::Rect(3, 3, 10, 10).ToString(),
intervening->clip_rect().ToString());
// Ensure that the render surface reports a content rect that has been grown
// to accomodate for the clip child.
ASSERT_EQ(gfx::Rect(5, 5, 16, 16).ToString(),
render_surface->render_surface()->content_rect().ToString());
// The above check implies the two below, but they nicely demonstrate that
// we've grown, despite the intervening layer's clip.
ASSERT_TRUE(clip_parent->clip_rect().Contains(
render_surface->render_surface()->content_rect()));
ASSERT_FALSE(intervening->clip_rect().Contains(
render_surface->render_surface()->content_rect()));
}
TEST_F(LayerTreeHostCommonTest, ClipParentWithInterveningRenderSurface) {
// Ensure that intervening render surfaces are not a problem in the basic
// case. In the following tree, both render surfaces should be resized to
// accomodate for the clip child, despite an intervening clip.
//
// root (a render surface)
// + clip_parent (masks to bounds)
// + render_surface1 (sets opacity)
// + intervening (masks to bounds)
// + render_surface2 (also sets opacity)
// + clip_child
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> clip_parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<Layer> intervening = Layer::Create();
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> clip_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(clip_parent);
clip_parent->AddChild(render_surface1);
render_surface1->AddChild(intervening);
intervening->AddChild(render_surface2);
render_surface2->AddChild(clip_child);
clip_child->SetClipParent(clip_parent.get());
intervening->SetMasksToBounds(true);
clip_parent->SetMasksToBounds(true);
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
gfx::Transform translation_transform;
translation_transform.Translate(2, 2);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(clip_parent.get(),
translation_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(intervening.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(-10.f, -10.f),
gfx::Size(60, 60),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_TRUE(render_surface1->render_surface());
EXPECT_TRUE(render_surface2->render_surface());
// Since the render surfaces could have expanded, they should not clip (their
// bounds would no longer be reliable). We should resort to layer clipping
// in this case.
EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(),
render_surface1->render_surface()->clip_rect().ToString());
EXPECT_FALSE(render_surface1->render_surface()->is_clipped());
EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(),
render_surface2->render_surface()->clip_rect().ToString());
EXPECT_FALSE(render_surface2->render_surface()->is_clipped());
// NB: clip rects are in target space.
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
render_surface1->clip_rect().ToString());
EXPECT_TRUE(render_surface1->is_clipped());
// This value is inherited from the clipping ancestor layer, 'intervening'.
EXPECT_EQ(gfx::Rect(0, 0, 5, 5).ToString(),
render_surface2->clip_rect().ToString());
EXPECT_TRUE(render_surface2->is_clipped());
// The content rects of both render surfaces should both have expanded to
// contain the clip child.
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
render_surface1->render_surface()->content_rect().ToString());
EXPECT_EQ(gfx::Rect(-1, -1, 40, 40).ToString(),
render_surface2->render_surface()->content_rect().ToString());
// The clip child should have inherited the clip parent's clip (projected to
// the right space, of course), and should have the correctly sized visible
// content rect.
EXPECT_EQ(gfx::Rect(-1, -1, 40, 40).ToString(),
clip_child->clip_rect().ToString());
EXPECT_EQ(gfx::Rect(9, 9, 40, 40).ToString(),
clip_child->visible_content_rect().ToString());
EXPECT_TRUE(clip_child->is_clipped());
}
TEST_F(LayerTreeHostCommonTest, ClipParentScrolledInterveningLayer) {
// Ensure that intervening render surfaces are not a problem, even if there
// is a scroll involved. Note, we do _not_ have to consider any other sort
// of transform.
//
// root (a render surface)
// + clip_parent (masks to bounds)
// + render_surface1 (sets opacity)
// + intervening (masks to bounds AND scrolls)
// + render_surface2 (also sets opacity)
// + clip_child
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> clip_parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<Layer> intervening = Layer::Create();
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> clip_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(clip_parent);
clip_parent->AddChild(render_surface1);
render_surface1->AddChild(intervening);
intervening->AddChild(render_surface2);
render_surface2->AddChild(clip_child);
clip_child->SetClipParent(clip_parent.get());
intervening->SetMasksToBounds(true);
clip_parent->SetMasksToBounds(true);
intervening->SetScrollClipLayerId(clip_parent->id());
intervening->SetScrollOffset(gfx::Vector2d(3, 3));
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
gfx::Transform translation_transform;
translation_transform.Translate(2, 2);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(clip_parent.get(),
translation_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(intervening.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(1.f, 1.f),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(-10.f, -10.f),
gfx::Size(60, 60),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_TRUE(render_surface1->render_surface());
EXPECT_TRUE(render_surface2->render_surface());
// Since the render surfaces could have expanded, they should not clip (their
// bounds would no longer be reliable). We should resort to layer clipping
// in this case.
EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(),
render_surface1->render_surface()->clip_rect().ToString());
EXPECT_FALSE(render_surface1->render_surface()->is_clipped());
EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(),
render_surface2->render_surface()->clip_rect().ToString());
EXPECT_FALSE(render_surface2->render_surface()->is_clipped());
// NB: clip rects are in target space.
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
render_surface1->clip_rect().ToString());
EXPECT_TRUE(render_surface1->is_clipped());
// This value is inherited from the clipping ancestor layer, 'intervening'.
EXPECT_EQ(gfx::Rect(2, 2, 3, 3).ToString(),
render_surface2->clip_rect().ToString());
EXPECT_TRUE(render_surface2->is_clipped());
// The content rects of both render surfaces should both have expanded to
// contain the clip child.
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
render_surface1->render_surface()->content_rect().ToString());
EXPECT_EQ(gfx::Rect(2, 2, 40, 40).ToString(),
render_surface2->render_surface()->content_rect().ToString());
// The clip child should have inherited the clip parent's clip (projected to
// the right space, of course), and should have the correctly sized visible
// content rect.
EXPECT_EQ(gfx::Rect(2, 2, 40, 40).ToString(),
clip_child->clip_rect().ToString());
EXPECT_EQ(gfx::Rect(12, 12, 40, 40).ToString(),
clip_child->visible_content_rect().ToString());
EXPECT_TRUE(clip_child->is_clipped());
}
TEST_F(LayerTreeHostCommonTest, DescendantsOfClipChildren) {
// Ensures that descendants of the clip child inherit the correct clip.
//
// root (a render surface)
// + clip_parent (masks to bounds)
// + intervening (masks to bounds)
// + clip_child
// + child
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> clip_parent = Layer::Create();
scoped_refptr<Layer> intervening = Layer::Create();
scoped_refptr<Layer> clip_child = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(clip_parent);
clip_parent->AddChild(intervening);
intervening->AddChild(clip_child);
clip_child->AddChild(child);
clip_child->SetClipParent(clip_parent.get());
intervening->SetMasksToBounds(true);
clip_parent->SetMasksToBounds(true);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(clip_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(intervening.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(60, 60),
true,
false);
SetLayerPropertiesForTesting(child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(60, 60),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
// Neither the clip child nor its descendant should have inherited the clip
// from |intervening|.
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
clip_child->clip_rect().ToString());
EXPECT_TRUE(clip_child->is_clipped());
EXPECT_EQ(gfx::Rect(0, 0, 40, 40).ToString(),
child->visible_content_rect().ToString());
EXPECT_TRUE(child->is_clipped());
}
TEST_F(LayerTreeHostCommonTest,
SurfacesShouldBeUnaffectedByNonDescendantClipChildren) {
// Ensures that non-descendant clip children in the tree do not affect
// render surfaces.
//
// root (a render surface)
// + clip_parent (masks to bounds)
// + render_surface1
// + clip_child
// + render_surface2
// + non_clip_child
//
// In this example render_surface2 should be unaffected by clip_child.
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> clip_parent = Layer::Create();
scoped_refptr<Layer> render_surface1 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> clip_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<Layer> render_surface2 = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> non_clip_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(clip_parent);
clip_parent->AddChild(render_surface1);
render_surface1->AddChild(clip_child);
clip_parent->AddChild(render_surface2);
render_surface2->AddChild(non_clip_child);
clip_child->SetClipParent(clip_parent.get());
clip_parent->SetMasksToBounds(true);
render_surface1->SetMasksToBounds(true);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(15, 15),
true,
false);
SetLayerPropertiesForTesting(clip_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(5, 5),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(5, 5),
true,
false);
SetLayerPropertiesForTesting(clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(-1, 1),
gfx::Size(10, 10),
true,
false);
SetLayerPropertiesForTesting(non_clip_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(5, 5),
true,
false);
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_TRUE(render_surface1->render_surface());
EXPECT_TRUE(render_surface2->render_surface());
EXPECT_EQ(gfx::Rect(0, 0, 5, 5).ToString(),
render_surface1->clip_rect().ToString());
EXPECT_TRUE(render_surface1->is_clipped());
// The render surface should not clip (it has unclipped descendants), instead
// it should rely on layer clipping.
EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(),
render_surface1->render_surface()->clip_rect().ToString());
EXPECT_FALSE(render_surface1->render_surface()->is_clipped());
// That said, it should have grown to accomodate the unclipped descendant.
EXPECT_EQ(gfx::Rect(-1, 1, 6, 4).ToString(),
render_surface1->render_surface()->content_rect().ToString());
// This render surface should clip. It has no unclipped descendants.
EXPECT_EQ(gfx::Rect(0, 0, 5, 5).ToString(),
render_surface2->clip_rect().ToString());
EXPECT_TRUE(render_surface2->render_surface()->is_clipped());
// It also shouldn't have grown to accomodate the clip child.
EXPECT_EQ(gfx::Rect(0, 0, 5, 5).ToString(),
render_surface2->render_surface()->content_rect().ToString());
// Sanity check our num_unclipped_descendants values.
EXPECT_EQ(1, render_surface1->num_unclipped_descendants());
EXPECT_EQ(0, render_surface2->num_unclipped_descendants());
}
TEST_F(LayerTreeHostCommonTest, CanRenderToSeparateSurface) {
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl.active_tree(), 12345);
scoped_ptr<LayerImpl> child1 =
LayerImpl::Create(host_impl.active_tree(), 123456);
scoped_ptr<LayerImpl> child2 =
LayerImpl::Create(host_impl.active_tree(), 1234567);
scoped_ptr<LayerImpl> child3 =
LayerImpl::Create(host_impl.active_tree(), 12345678);
gfx::Transform identity_matrix;
gfx::PointF anchor;
gfx::PointF position;
gfx::Size bounds(100, 100);
SetLayerPropertiesForTesting(root.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
root->SetDrawsContent(true);
// This layer structure normally forces render surface due to preserves3d
// behavior.
SetLayerPropertiesForTesting(child1.get(),
identity_matrix,
anchor,
position,
bounds,
false,
true);
child1->SetDrawsContent(true);
SetLayerPropertiesForTesting(child2.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child2->SetDrawsContent(true);
SetLayerPropertiesForTesting(child3.get(),
identity_matrix,
anchor,
position,
bounds,
true,
false);
child3->SetDrawsContent(true);
child2->SetIs3dSorted(true);
child3->SetIs3dSorted(true);
child2->AddChild(child3.Pass());
child1->AddChild(child2.Pass());
root->AddChild(child1.Pass());
{
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_render_to_separate_surface = true;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(2u, render_surface_layer_list.size());
}
{
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
inputs.can_render_to_separate_surface = false;
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_EQ(1u, render_surface_layer_list.size());
}
}
TEST_F(LayerTreeHostCommonTest, DoNotIncludeBackfaceInvisibleSurfaces) {
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> render_surface = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(render_surface);
render_surface->AddChild(child);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(render_surface.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
false,
true);
SetLayerPropertiesForTesting(child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
root->SetShouldFlattenTransform(false);
root->SetIs3dSorted(true);
render_surface->SetDoubleSided(false);
render_surface->SetForceRenderSurface(true);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_EQ(2u, render_surface_layer_list()->size());
EXPECT_EQ(1u,
render_surface_layer_list()->at(0)
->render_surface()->layer_list().size());
EXPECT_EQ(1u,
render_surface_layer_list()->at(1)
->render_surface()->layer_list().size());
gfx::Transform rotation_transform = identity_transform;
rotation_transform.RotateAboutXAxis(180.0);
render_surface->SetTransform(rotation_transform);
ExecuteCalculateDrawProperties(root.get());
EXPECT_EQ(1u, render_surface_layer_list()->size());
EXPECT_EQ(0u,
render_surface_layer_list()->at(0)
->render_surface()->layer_list().size());
}
TEST_F(LayerTreeHostCommonTest, ClippedByScrollParent) {
// Checks that the simple case (being clipped by a scroll parent that would
// have been processed before you anyhow) results in the right clips.
//
// + root
// + scroll_parent_border
// | + scroll_parent_clip
// | + scroll_parent
// + scroll_child
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> scroll_parent_border = Layer::Create();
scoped_refptr<Layer> scroll_parent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_parent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> scroll_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(scroll_child);
root->AddChild(scroll_parent_border);
scroll_parent_border->AddChild(scroll_parent_clip);
scroll_parent_clip->AddChild(scroll_parent);
scroll_parent_clip->SetMasksToBounds(true);
scroll_child->SetScrollParent(scroll_parent.get());
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(scroll_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_EQ(gfx::Rect(0, 0, 30, 30).ToString(),
scroll_child->clip_rect().ToString());
EXPECT_TRUE(scroll_child->is_clipped());
}
TEST_F(LayerTreeHostCommonTest, ClippedByOutOfOrderScrollParent) {
// Checks that clipping by a scroll parent that follows you in paint order
// still results in correct clipping.
//
// + root
// + scroll_child
// + scroll_parent_border
// + scroll_parent_clip
// + scroll_parent
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> scroll_parent_border = Layer::Create();
scoped_refptr<Layer> scroll_parent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_parent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> scroll_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(scroll_parent_border);
scroll_parent_border->AddChild(scroll_parent_clip);
scroll_parent_clip->AddChild(scroll_parent);
root->AddChild(scroll_child);
scroll_parent_clip->SetMasksToBounds(true);
scroll_child->SetScrollParent(scroll_parent.get());
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(scroll_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_EQ(gfx::Rect(0, 0, 30, 30).ToString(),
scroll_child->clip_rect().ToString());
EXPECT_TRUE(scroll_child->is_clipped());
}
TEST_F(LayerTreeHostCommonTest, ClippedByOutOfOrderScrollGrandparent) {
// Checks that clipping by a scroll parent and scroll grandparent that follow
// you in paint order still results in correct clipping.
//
// + root
// + scroll_child
// + scroll_parent_border
// | + scroll_parent_clip
// | + scroll_parent
// + scroll_grandparent_border
// + scroll_grandparent_clip
// + scroll_grandparent
//
scoped_refptr<Layer> root = Layer::Create();
scoped_refptr<Layer> scroll_parent_border = Layer::Create();
scoped_refptr<Layer> scroll_parent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_parent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<Layer> scroll_grandparent_border = Layer::Create();
scoped_refptr<Layer> scroll_grandparent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_grandparent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> scroll_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(scroll_child);
root->AddChild(scroll_parent_border);
scroll_parent_border->AddChild(scroll_parent_clip);
scroll_parent_clip->AddChild(scroll_parent);
root->AddChild(scroll_grandparent_border);
scroll_grandparent_border->AddChild(scroll_grandparent_clip);
scroll_grandparent_clip->AddChild(scroll_grandparent);
scroll_parent_clip->SetMasksToBounds(true);
scroll_grandparent_clip->SetMasksToBounds(true);
scroll_child->SetScrollParent(scroll_parent.get());
scroll_parent_border->SetScrollParent(scroll_grandparent.get());
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(scroll_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
ExecuteCalculateDrawProperties(root.get());
EXPECT_TRUE(root->render_surface());
EXPECT_EQ(gfx::Rect(0, 0, 20, 20).ToString(),
scroll_child->clip_rect().ToString());
EXPECT_TRUE(scroll_child->is_clipped());
// Despite the fact that we visited the above layers out of order to get the
// correct clip, the layer lists should be unaffected.
EXPECT_EQ(3u, root->render_surface()->layer_list().size());
EXPECT_EQ(scroll_child.get(),
root->render_surface()->layer_list().at(0));
EXPECT_EQ(scroll_parent.get(),
root->render_surface()->layer_list().at(1));
EXPECT_EQ(scroll_grandparent.get(),
root->render_surface()->layer_list().at(2));
}
TEST_F(LayerTreeHostCommonTest, OutOfOrderClippingRequiresRSLLSorting) {
// Ensures that even if we visit layers out of order, we still produce a
// correctly ordered render surface layer list.
// + root
// + scroll_child
// + scroll_parent_border
// + scroll_parent_clip
// + scroll_parent
// + render_surface1
// + scroll_grandparent_border
// + scroll_grandparent_clip
// + scroll_grandparent
// + render_surface2
//
scoped_refptr<LayerWithForcedDrawsContent> root =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<Layer> scroll_parent_border = Layer::Create();
scoped_refptr<Layer> scroll_parent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_parent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> render_surface1 =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<Layer> scroll_grandparent_border = Layer::Create();
scoped_refptr<Layer> scroll_grandparent_clip = Layer::Create();
scoped_refptr<LayerWithForcedDrawsContent> scroll_grandparent =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> render_surface2 =
make_scoped_refptr(new LayerWithForcedDrawsContent);
scoped_refptr<LayerWithForcedDrawsContent> scroll_child =
make_scoped_refptr(new LayerWithForcedDrawsContent);
root->AddChild(scroll_child);
root->AddChild(scroll_parent_border);
scroll_parent_border->AddChild(scroll_parent_clip);
scroll_parent_clip->AddChild(scroll_parent);
scroll_parent->AddChild(render_surface2);
root->AddChild(scroll_grandparent_border);
scroll_grandparent_border->AddChild(scroll_grandparent_clip);
scroll_grandparent_clip->AddChild(scroll_grandparent);
scroll_grandparent->AddChild(render_surface1);
scroll_parent_clip->SetMasksToBounds(true);
scroll_grandparent_clip->SetMasksToBounds(true);
scroll_child->SetScrollParent(scroll_parent.get());
scroll_parent_border->SetScrollParent(scroll_grandparent.get());
render_surface1->SetForceRenderSurface(true);
render_surface2->SetForceRenderSurface(true);
gfx::Transform identity_transform;
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(20, 20),
true,
false);
SetLayerPropertiesForTesting(scroll_grandparent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(render_surface1.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(scroll_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(render_surface2.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
scoped_ptr<FakeLayerTreeHost> host = FakeLayerTreeHost::Create();
host->SetRootLayer(root);
RenderSurfaceLayerList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsMainInputsForTesting inputs(
root.get(),
root->bounds(),
identity_transform,
&render_surface_layer_list);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRUE(root->render_surface());
EXPECT_EQ(gfx::Rect(0, 0, 20, 20).ToString(),
scroll_child->clip_rect().ToString());
EXPECT_TRUE(scroll_child->is_clipped());
// Despite the fact that we had to process the layers out of order to get the
// right clip, our render_surface_layer_list's order should be unaffected.
EXPECT_EQ(3u, render_surface_layer_list.size());
EXPECT_EQ(root.get(), render_surface_layer_list.at(0));
EXPECT_EQ(render_surface2.get(), render_surface_layer_list.at(1));
EXPECT_EQ(render_surface1.get(), render_surface_layer_list.at(2));
EXPECT_TRUE(render_surface_layer_list.at(0)->render_surface());
EXPECT_TRUE(render_surface_layer_list.at(1)->render_surface());
EXPECT_TRUE(render_surface_layer_list.at(2)->render_surface());
}
TEST_F(LayerTreeHostCommonTest, DoNotClobberSorting) {
// We rearrange layer list contributions if we have to visit children out of
// order, but it should be a 'stable' rearrangement. That is, the layer list
// additions for a single layer should not be reordered, though their position
// wrt to the contributions due to a sibling may vary.
//
// + root
// + scroll_child
// + top_content
// + bottom_content
// + scroll_parent_border
// + scroll_parent_clip
// + scroll_parent
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
scoped_ptr<LayerImpl> scroll_parent_border =
LayerImpl::Create(host_impl.active_tree(), 2);
scoped_ptr<LayerImpl> scroll_parent_clip =
LayerImpl::Create(host_impl.active_tree(), 3);
scoped_ptr<LayerImpl> scroll_parent =
LayerImpl::Create(host_impl.active_tree(), 4);
scoped_ptr<LayerImpl> scroll_child =
LayerImpl::Create(host_impl.active_tree(), 5);
scoped_ptr<LayerImpl> bottom_content =
LayerImpl::Create(host_impl.active_tree(), 6);
scoped_ptr<LayerImpl> top_content =
LayerImpl::Create(host_impl.active_tree(), 7);
scroll_parent_clip->SetMasksToBounds(true);
scroll_child->SetScrollParent(scroll_parent.get());
scoped_ptr<std::set<LayerImpl*> > scroll_children(new std::set<LayerImpl*>);
scroll_children->insert(scroll_child.get());
scroll_parent->SetScrollChildren(scroll_children.release());
scroll_child->SetDrawsContent(true);
scroll_parent->SetDrawsContent(true);
top_content->SetDrawsContent(true);
bottom_content->SetDrawsContent(true);
gfx::Transform identity_transform;
gfx::Transform top_transform;
top_transform.Translate3d(0.0, 0.0, 5.0);
gfx::Transform bottom_transform;
bottom_transform.Translate3d(0.0, 0.0, 3.0);
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_border.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroll_parent_clip.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(scroll_parent.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(scroll_child.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(top_content.get(),
top_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
false,
true);
SetLayerPropertiesForTesting(bottom_content.get(),
bottom_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
false,
true);
scroll_child->SetShouldFlattenTransform(false);
scroll_child->SetIs3dSorted(true);
scroll_child->AddChild(top_content.Pass());
scroll_child->AddChild(bottom_content.Pass());
root->AddChild(scroll_child.Pass());
scroll_parent_clip->AddChild(scroll_parent.Pass());
scroll_parent_border->AddChild(scroll_parent_clip.Pass());
root->AddChild(scroll_parent_border.Pass());
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRUE(root->render_surface());
// If we don't sort by depth and let the layers get added in the order they
// would normally be visited in, then layers 6 and 7 will be out of order. In
// other words, although we've had to shift 5, 6, and 7 to appear before 4
// in the list (because of the scroll parent relationship), this should not
// have an effect on the the order of 5, 6, and 7 (which had been reordered
// due to layer sorting).
EXPECT_EQ(4u, root->render_surface()->layer_list().size());
EXPECT_EQ(5, root->render_surface()->layer_list().at(0)->id());
EXPECT_EQ(6, root->render_surface()->layer_list().at(1)->id());
EXPECT_EQ(7, root->render_surface()->layer_list().at(2)->id());
EXPECT_EQ(4, root->render_surface()->layer_list().at(3)->id());
}
TEST_F(LayerTreeHostCommonTest, ScrollCompensationWithRounding) {
// This test verifies that a scrolling layer that gets snapped to
// integer coordinates doesn't move a fixed position child.
//
// + root
// + container
// + scroller
// + fixed
//
FakeImplProxy proxy;
FakeLayerTreeHostImpl host_impl(&proxy);
host_impl.CreatePendingTree();
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl.active_tree(), 1);
scoped_ptr<LayerImpl> container =
LayerImpl::Create(host_impl.active_tree(), 2);
LayerImpl* container_layer = container.get();
scoped_ptr<LayerImpl> scroller =
LayerImpl::Create(host_impl.active_tree(), 3);
LayerImpl* scroll_layer = scroller.get();
scoped_ptr<LayerImpl> fixed = LayerImpl::Create(host_impl.active_tree(), 4);
LayerImpl* fixed_layer = fixed.get();
container->SetIsContainerForFixedPositionLayers(true);
LayerPositionConstraint constraint;
constraint.set_is_fixed_position(true);
fixed->SetPositionConstraint(constraint);
scroller->SetScrollClipLayer(container->id());
gfx::Transform identity_transform;
gfx::Transform container_transform;
container_transform.Translate3d(10.0, 20.0, 0.0);
gfx::Vector2dF container_offset = container_transform.To2dTranslation();
SetLayerPropertiesForTesting(root.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
SetLayerPropertiesForTesting(container.get(),
container_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(40, 40),
true,
false);
SetLayerPropertiesForTesting(scroller.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(30, 30),
true,
false);
SetLayerPropertiesForTesting(fixed.get(),
identity_transform,
gfx::PointF(),
gfx::PointF(),
gfx::Size(50, 50),
true,
false);
scroller->AddChild(fixed.Pass());
container->AddChild(scroller.Pass());
root->AddChild(container.Pass());
// Rounded to integers already.
{
gfx::Vector2dF scroll_delta(3.0, 5.0);
scroll_layer->SetScrollDelta(scroll_delta);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRANSFORMATION_MATRIX_EQ(
container_layer->draw_properties().screen_space_transform,
fixed_layer->draw_properties().screen_space_transform);
EXPECT_VECTOR_EQ(
fixed_layer->draw_properties().screen_space_transform.To2dTranslation(),
container_offset);
EXPECT_VECTOR_EQ(scroll_layer->draw_properties()
.screen_space_transform.To2dTranslation(),
container_offset - scroll_delta);
}
// Scroll delta requiring rounding.
{
gfx::Vector2dF scroll_delta(4.1f, 8.1f);
scroll_layer->SetScrollDelta(scroll_delta);
gfx::Vector2dF rounded_scroll_delta(4.f, 8.f);
LayerImplList render_surface_layer_list;
LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting inputs(
root.get(), root->bounds(), &render_surface_layer_list);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
EXPECT_TRANSFORMATION_MATRIX_EQ(
container_layer->draw_properties().screen_space_transform,
fixed_layer->draw_properties().screen_space_transform);
EXPECT_VECTOR_EQ(
fixed_layer->draw_properties().screen_space_transform.To2dTranslation(),
container_offset);
EXPECT_VECTOR_EQ(scroll_layer->draw_properties()
.screen_space_transform.To2dTranslation(),
container_offset - rounded_scroll_delta);
}
}
} // namespace
} // namespace cc
| [
"[email protected]"
] | |
4ecc12b137621e1ccda7d5e17162caa04c542dc2 | 3ac7658c1554f63865eb92a92a9a9b29f462b797 | /EXP/2019-2020(1) EXP/DualStack/DualStack/main.cpp | 6b447dd7b821007fea351a9e5fe08d24af5f6c23 | [] | no_license | yuhuarong/MyCPPExperiment | 9d8f050c616d97f9725fd5809867aedbaddcf637 | 13cac9edb0a1857a456409ba92151c6a90183ac3 | refs/heads/master | 2020-09-22T16:25:04.214263 | 2019-11-26T17:41:52 | 2019-11-26T17:41:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | cpp | #include <iostream>
#include <string>
#include "SeqList.h"
#include "DualStack.h"
using namespace std;
void testSeqList() {
cout << "---------SeqList------------" << endl;
SeqList list;
int r[] = { 0, 2, 4, 53, 3424 };
SeqList list2(r, 5);
list.Insert(0, 5);
list.Insert(0, 2);
list.Insert(0, 3);
list.Insert(2, 6);
list.PrintList();
list.Delete(2);
list.PrintList();
list.Delete(20);
list.PrintList();
list2.PrintList();
list2.Delete(4);
list2.PrintList();
cout << "where is 53: " << list2.Locate(53) << endl;
}
void testDualStack() {
cout << "---------DualStack------------" << endl;
DualStack<string> stack;
stack.push("hello", StackNumber::ONE);
stack.pop(StackNumber::ONE);
}
int main() {
//testSeqList();
testDualStack();
}
| [
"[email protected]"
] | |
862fd3c674c979ff5b01f1ad78b835eedaa035a6 | cf3302a478551167d14c577be171fe0c1b4a3507 | /src/cpp/activemq/activemq-cpp-3.2.5/src/main/activemq/wireformat/openwire/marshal/v1/ResponseMarshaller.cpp | bbdfc3a137a1ead889be21d2d3ee45b219aaaf7f | [
"Apache-2.0"
] | permissive | WilliamDrewAeroNomos/muthur | 7babb320ed3bfb6ed7905a1a943e3d35aa03aedc | 0c66c78af245ef3b06b92172e0df62eb54b3fb84 | refs/heads/master | 2016-09-05T11:15:50.083267 | 2015-07-01T15:49:56 | 2015-07-01T15:49:56 | 38,366,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,236 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <activemq/wireformat/openwire/marshal/v1/ResponseMarshaller.h>
#include <activemq/commands/Response.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Pointer.h>
//
// NOTE!: This file is autogenerated - do not modify!
// if you need to make a change, please see the Java Classes in the
// activemq-core module
//
using namespace std;
using namespace activemq;
using namespace activemq::exceptions;
using namespace activemq::commands;
using namespace activemq::wireformat;
using namespace activemq::wireformat::openwire;
using namespace activemq::wireformat::openwire::marshal;
using namespace activemq::wireformat::openwire::utils;
using namespace activemq::wireformat::openwire::marshal::v1;
using namespace decaf;
using namespace decaf::io;
using namespace decaf::lang;
///////////////////////////////////////////////////////////////////////////////
DataStructure* ResponseMarshaller::createObject() const {
return new Response();
}
///////////////////////////////////////////////////////////////////////////////
unsigned char ResponseMarshaller::getDataStructureType() const {
return Response::ID_RESPONSE;
}
///////////////////////////////////////////////////////////////////////////////
void ResponseMarshaller::tightUnmarshal( OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn, BooleanStream* bs ) throw( decaf::io::IOException ) {
try {
BaseCommandMarshaller::tightUnmarshal( wireFormat, dataStructure, dataIn, bs );
Response* info =
dynamic_cast<Response*>( dataStructure );
info->setCorrelationId( dataIn->readInt() );
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
///////////////////////////////////////////////////////////////////////////////
int ResponseMarshaller::tightMarshal1( OpenWireFormat* wireFormat, DataStructure* dataStructure, BooleanStream* bs ) throw( decaf::io::IOException ) {
try {
int rc = BaseCommandMarshaller::tightMarshal1( wireFormat, dataStructure, bs );
return rc + 4;
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
///////////////////////////////////////////////////////////////////////////////
void ResponseMarshaller::tightMarshal2( OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut, BooleanStream* bs ) throw( decaf::io::IOException ) {
try {
BaseCommandMarshaller::tightMarshal2( wireFormat, dataStructure, dataOut, bs );
Response* info =
dynamic_cast<Response*>( dataStructure );
dataOut->writeInt( info->getCorrelationId() );
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
///////////////////////////////////////////////////////////////////////////////
void ResponseMarshaller::looseUnmarshal( OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn ) throw( decaf::io::IOException ) {
try {
BaseCommandMarshaller::looseUnmarshal( wireFormat, dataStructure, dataIn );
Response* info =
dynamic_cast<Response*>( dataStructure );
info->setCorrelationId( dataIn->readInt() );
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
///////////////////////////////////////////////////////////////////////////////
void ResponseMarshaller::looseMarshal( OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut ) throw( decaf::io::IOException ) {
try {
Response* info =
dynamic_cast<Response*>( dataStructure );
BaseCommandMarshaller::looseMarshal( wireFormat, dataStructure, dataOut );
dataOut->writeInt( info->getCorrelationId() );
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
| [
"[email protected]"
] | |
a43e5a4be36b73b2b9d0f30ce42e2519616e38f1 | 85e69612270607973a84a10dd1dc08db8030dac7 | /Tree/Food Chain.cpp | 85e9128a0925227a2cc4f53fc2de3ed2a5a730d7 | [] | no_license | hellozts4120/data-structure | 22f87a01a49b9e79fd981181ddb35fe619c3d03c | 6c6c42525ef90bdacdd24f3d1f875c27fb14c923 | refs/heads/master | 2021-01-01T06:54:54.273841 | 2015-12-03T05:53:45 | 2015-12-03T05:53:45 | 41,429,073 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,322 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#define MAX 50005
using namespace std;
int n,k;
int father[MAX];
int ranks[MAX];
//father[A]=B,rank[A]=0表示A与B同类;rank[A]=1表示B可以吃A;rank[A]=2 表示A可以吃B
int Find(int x){
if(father[x] == -1){
return x; //此时它的父节点即为它自己
}
int temp = father[x];
father[x] = Find(father[x]); //此时将结点直接挂到root上;
ranks[x] = (ranks[x] + ranks[temp]) % 3;
return father[x];
}
bool Union(int X,int Y, int cases){
int Xfather,Yfather;
Xfather = Find(X);
Yfather = Find(Y);
if(Xfather == Yfather){ //两者的father为同类时,可直接归纳得出结果
if((cases == 1) && (ranks[X] != ranks[Y])){
return true;
}
if((cases == 2) && ((3+ranks[Y]-ranks[X])%3 != 1)){
return true;
}
else return false;
}
else{ //两者的father为不同类时,重要!
father[Yfather] = Xfather;
ranks[Yfather] = (ranks[X] - ranks[Y] + cases + 2) % 3;
}
return false;
}
int main(){
cin >> n >> k;
int wrong = 0;
memset(father,-1,sizeof(father));
memset(ranks,0,sizeof(ranks));
for(int i = 0;i < k;i++){
int cases,X,Y;
cin >> cases >> X >> Y;
if((X>n) || (Y>n) || ((X==Y) && (cases == 2))){
wrong++;
}
else if(Union(X,Y,cases)){
wrong++;
}
}
cout << wrong << endl;
return 0;
} | [
"[email protected]"
] | |
d3b89177b732d6df3fef94f979a8cb94bc8c7a2c | 7ebae5ec0378642a1d2c181184460e76c73debbd | /USACO/censorb/censorb/censorb.cpp | 112da21240d2a14a29d9aecaa6af5ed383880699 | [] | no_license | tonyli00000/Competition-Code | a4352b6b6835819a0f19f7f5cc67e46d2a200906 | 7f5767e3cb997fd15ae6f72145bcb8394f50975f | refs/heads/master | 2020-06-17T23:04:10.367762 | 2019-12-28T22:08:25 | 2019-12-28T22:08:25 | 196,091,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
using namespace std;
int main()
{
string censor, S;
cin >> S >> censor;
string ret;
for (long long i = 0; i < S.size(); i++) {
ret += S[i];
if (ret.size() >= censor.size() && ret.substr(ret.size() - censor.size()) == censor) ret.resize(ret.size() - censor.size());
}
cout << ret << "\n";
return 0;
}
| [
"[email protected]"
] | |
b89a7ccaf67f2a11c18974f682e88fbea827347e | 022ddbfd08623b855f50331861309d5429753d99 | /蓝桥/查找整数/main.cpp | feb710ea2e8b876a39df18d95c998d2879857d66 | [] | no_license | xluos/ACM | 06d6881dac8c12e6e0ded66fc5da43974e3520e7 | e90707178cc203e0e36092dc73bdc807c7daa246 | refs/heads/master | 2020-06-21T07:20:14.584736 | 2018-03-20T13:26:53 | 2018-03-20T13:26:53 | 94,203,765 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | #include <iostream>
using namespace std;
int myfind(int n,int m,int a[])
{
for(int i=0;i<n;i++)
{
if(a[i] == m)
return i+1;
}
return -1;
}
int main()
{
int n,m = -1,a[1005];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>m;
cout<<myfind(n,m,a)<<endl;
return 0;
}
| [
"[email protected]"
] | |
456530a316b04213a37ffee2dd9a01594919aba7 | 3392f4bfd574e4f4c8fb1a16d61531f3dda800d7 | /utils/include/utils/utils.h | 1b1e5d39dc1c7e26af1f7b788d74a59508d34208 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | orsoromeo/cpp_playground | f4e0f90c877e738f2917645e6b09412bdc421f97 | 04fae5ec52aec910becaed56a30366a4e6baa064 | refs/heads/master | 2023-02-18T02:54:18.184191 | 2021-01-18T19:49:31 | 2021-01-18T19:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | #ifndef UTILS_H
#define UTILS_H
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
// GCC specfic method to get a rough representation of the absolute name of the type T
// This is just a helper function for debugging.
template <typename T>
void GetName(const T&)
{
#ifdef __GNUG__
int status;
std::string realname = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
std::cout << realname << std::endl;
#else
#error "Function only implemented for GCC"
#endif
}
#endif /* UTILS_H */
| [
"[email protected]"
] | |
284b76b03fc54fec93931794adbaca3da66ac7a5 | 8f86f0146cdd1202fadae202de160afa8a1c29b3 | /lib/MqttConnector/src/MqttConnector.cpp | 2bde9f3f10f95f9de97063454dffc03fda05ec31 | [
"MIT"
] | permissive | cmmakerclub/cmmc_connector_basic_mqtt_dht11 | 7bfc843fb84555d983b4f194ed22577fc8e25530 | 02d822393c5aa8ebda4e95f3880d9f95be35dc13 | refs/heads/master | 2021-01-15T22:18:57.929941 | 2017-08-16T16:30:38 | 2017-08-16T16:30:38 | 99,896,586 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,030 | cpp | /*
Copyright Nat Weerawan 2015-2016
MIT License
The MIT License (MIT)
Copyright (c) Nat Weerawan <[email protected]> (cmmakerclub.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "MqttConnector.h"
// 192.168.111.111
#define IP_C_STR_SIZE 16
static char *c_ipStr;
static String ipStr;
static String toStringIp(uint32_t ip) {
String res = "";
for (int i = 0; i < 3; i++) {
res += String((ip >> (8 * i)) & 0xFF) + ".";
}
res += String(((ip >> 8 * 3)) & 0xFF);
return res;
}
MqttConnector::MqttConnector(const char* host, uint16_t port)
{
c_ipStr = (char*)malloc(IP_C_STR_SIZE);
ipStr = toStringIp(WiFi.localIP());
strcpy(c_ipStr, ipStr.c_str());
_on_message_arrived = [&](const MQTT::Publish& pub) {
_msg_arrived_ms = millis();
wclient.flush();
if (_user_on_message_arrived) {
_user_on_message_arrived(pub);
}
if (_user_on_after_message_arrived != NULL) {
int prefix_len = _config.channelPrefix.length()+1;
String topic = pub.topic();
String p_topic = topic.substring(prefix_len);
const char *p = p_topic.c_str();
int fc = 0;
while(*p++ != '/') { fc++; }
_user_on_after_message_arrived(p_topic, p_topic.substring(fc+1), pub.payload_string());
}
};
init_config(host, port);
MQTT_DEBUG_PRINTLN("----------- Wrapper CONSTRUCTOR ---------");
MQTT_DEBUG_PRINT(_mqtt_host);
MQTT_DEBUG_PRINT(" - ");
MQTT_DEBUG_PRINT(_mqtt_port);
MQTT_DEBUG_PRINTLN("---------- /Wrapper CONSTRUCTOR ---------");
}
void MqttConnector::init_config(const char* host, uint16_t port)
{
prev_millis = millis();
_mqtt_host = String(host);
_mqtt_port = port;
_config.connOpts = NULL;
_config.client = NULL;
_config.mode = MODE_BOTH;
_subscribe_object = NULL;
_config.enableLastWill = true;
_config.retainPublishMessage = false;
_config.firstCapChannel = false;
JsonObject& r = jsonRootBuffer.createObject();
JsonObject& info = r.createNestedObject("info");
JsonObject& dd = jsonDBuffer.createObject();
this->root = &r;
this->info = &info;
r["info"] = info;
r["d"] = dd;
// this->d = &((JsonObject)r["d"]);
this->d = ⅆ
static struct station_config conf;
wifi_station_get_config(&conf);
const char* ssid = reinterpret_cast<const char*>(conf.ssid);
info["ssid"] = String(ssid);
info["flash_size"] = ESP.getFlashChipSize();
info["flash_id"] = String(ESP.getFlashChipId(), HEX);
info["chip_id"] = String(ESP.getChipId(), HEX);
info["sdk"] = String(system_get_sdk_version());
info["mac"] = WiFi.macAddress();
}
MqttConnector::MqttConnector(const char* host, uint16_t port, cmmc_config_t config_hook)
{
init_config(host, port);
_user_hook_config = config_hook;
}
void MqttConnector::_clear_last_will() {
MQTT_DEBUG_PRINTLN("__CLEAR LASTWILL");
MQTT_DEBUG_PRINT("WILL TOPIC: ");
MQTT_DEBUG_PRINTLN(_config.topicLastWill);
static String willText = String("{\"status\":1,\"id\":\"") + String(_config.clientId) + "\"}";
MQTT::Publish newpub(_config.topicLastWill, (uint8_t*) willText.c_str(), willText.length());
newpub.set_retain(true);
_config.client->publish(newpub);
}
void MqttConnector::on_message(PubSubClient::callback_t callback) {
if (callback != NULL)
{
MQTT_DEBUG_PRINTLN("__USER REGISTER SUBSCRIPTION CALLBACK");
_user_on_message_arrived = callback;
}
else
{
MQTT_DEBUG_PRINTLN("__USER DOES NOT REGISTER SUBSCRIPTION CALLBACk");
}
}
void MqttConnector::on_published(after_publish_hook_t callback) {
on_after_publish(callback);
}
void MqttConnector::on_after_publish(after_publish_hook_t callback) {
if (callback != NULL)
{
MQTT_DEBUG_PRINTLN("__USER REGISTER SUBSCRIPTION CALLBACK");
_user_on_after_publish = callback;
}
else
{
MQTT_DEBUG_PRINTLN("__USER DOES NOT REGISTER SUBSCRIPTION CALLBACk");
}
}
void MqttConnector::connect()
{
MQTT_DEBUG_PRINTLN("BEGIN CMMC_MQTT_CONNECTOR");
_set_default_client_id();
_hook_config();
_hook_after_config();
_connect();
}
void MqttConnector::_hook_config()
{
if (_user_hook_config != NULL)
{
MQTT_DEBUG_PRINTLN("OVERRIDE CONFIG IN _hook_config");
_user_hook_config(&_config);
}
if (_config.clientId == "") {
_config.clientId = String(ESP.getChipId());
}
String commandChannel = "/$/command";
String statusChannel = "/status";
String lwtChannel = "/lwt";
if (_config.firstCapChannel) {
commandChannel = "/$/Command";
statusChannel = "/Status";
lwtChannel = "/Lwt";
}
MQTT_DEBUG_PRINT("TOPIC SUB = ");
MQTT_DEBUG_PRINTLN(_config.topicSub);
MQTT_DEBUG_PRINT("TOPIC PUB = ");
MQTT_DEBUG_PRINTLN(_config.topicPub);
_config.topicSub.trim();
_config.topicPub.trim();
// subscribe
if (_config.topicSub.length() == 0) {
_config.topicSub = String(_config.channelPrefix) +
String(_config.clientId) + commandChannel;
}
// publish
if (_config.topicPub.length() == 0) {
_config.topicPub = String(_config.channelPrefix) +
String(_config.clientId) + statusChannel;
}
MQTT_DEBUG_PRINT("TOPIC SUB = ");
MQTT_DEBUG_PRINTLN(_config.topicSub);
MQTT_DEBUG_PRINT("TOPIC PUB = ");
MQTT_DEBUG_PRINTLN(_config.topicSub);
_config.topicLastWill = String(_config.channelPrefix) +
String(_config.clientId) + lwtChannel;
(*info)["id"] = _config.clientId;
(*info)["client_id"] = _config.clientId;
(*info)["device_id"] = _config.clientId;
(*info)["prefix"] = _config.channelPrefix;
(*info)["ip"] = c_ipStr;
_config.mqttHost = _mqtt_host;
_config.mqttPort = _mqtt_port;
MQTT_DEBUG_PRINT("__PUBLICATION TOPIC -> ");
#ifdef MQTT_DEBUG_LEVEL_VERBOSE
MQTT_DEBUG_PRINTLN(_config.topicPub)
#endif
MQTT_DEBUG_PRINT("__SUBSCRIPTION TOPIC -> ");
#ifdef MQTT_DEBUG_LEVEL_VERBOSE
MQTT_DEBUG_PRINTLN(_config.topicSub);
#endif
_config.connOpts = new MQTT::Connect(_config.clientId);
_config.client = new PubSubClient(wclient);
_config.client->set_server(_mqtt_host, _mqtt_port);
_config.client->set_callback(_on_message_arrived);
_config.username.trim();
_config.password.trim();
// NO-NEED TO SET AUTH;
if(_config.username == "" || _config.password == "") {
MQTT_DEBUG_PRINT("NO-AUTH Connection.");
}
else {
_config.connOpts->set_auth(_config.username, _config.password);
}
_config.connOpts->set_clean_session(true);
if (_config.enableLastWill) {
MQTT_DEBUG_PRINT("ENABLE LAST WILL: ");
// String willText = String("DEAD|") + String(_config.clientId) + "|" + (millis());
static String willText = String("{\"status\":0,\"id\": \"") + String(_config.clientId) + "\"}";
int qos = 1;
int retain = true;
(_config.connOpts)->set_will(_config.topicLastWill, willText, qos, retain);
(_config.connOpts)->set_keepalive(15);
#ifdef MQTT_DEBUG_LEVEL_VERBOSE
MQTT_DEBUG_PRINTLN(_config.topicLastWill);
#endif
}
}
void MqttConnector::_hook_after_config()
{
if (_user_hook_after_config != NULL)
{
MQTT_DEBUG_PRINTLN("OVERRIDE CONFIG IN _hook_config");
_user_hook_after_config(_config);
}
if (_user_on_prepare_data_once) {
_user_on_prepare_data_once();
}
if (_user_on_before_message_arrived_once) {
_user_on_before_message_arrived_once();
}
}
void MqttConnector::sync_pub(String payload)
{
MQTT_DEBUG_PRINT("SYNC PUB.... -> ");
MQTT_DEBUG_PRINTLN(payload.c_str());
MQTT::Publish newpub(_config.topicSub, (uint8_t*)payload.c_str(), payload.length());
newpub.set_retain(true);
_config.client->publish(newpub);
}
void MqttConnector::loop()
{
if (_config.client->connected())
{
_config.client->loop();
if (_config.mode == MODE_SUB_ONLY) {
MQTT_DEBUG_PRINTLN("SUBSCRIBE ONLY MODE..");
}
else {
doPublish();
}
}
else
{
MQTT_DEBUG_PRINTLN("MQTT DISCONNECTED..");
MQTT_DEBUG_PRINTLN("MQTT RECONNECTING..");
_connect();
}
}
void MqttConnector::doPublish(bool force)
{
static long counter = 0;
if (force || _timer_expired(&_publish_timer))
{
if (!_config.client->connected()) return;
unsigned long __dif = (millis() - _msg_arrived_ms);
// MQTT_DEBUG_PRINTf("DIFF == %lu \r\n", __dif);
if (__dif <= 1000) {
// MQTT_DEBUG_PRINTLN("PUBLICATION SKIPPED.");
return;
}
MQTT_DEBUG_PRINTLN("PUBLICATION PASSED.");
_timer_set(&_publish_timer, _publish_interval);
_prepare_data_hook();
(*info)["version"] = _version;
(*d)["heap"] = ESP.getFreeHeap();
(*d)["rssi"] = WiFi.RSSI();
(*d)["counter"] = ++counter;
(*d)["millis"] = millis();
(*d)["subscription"] = _subscription_counter;
_after_prepare_data_hook();
strcpy(jsonStrbuffer, "");
root->printTo(jsonStrbuffer, sizeof(jsonStrbuffer));
// dataPtr = jsonStrbuffer;
prev_millis = millis();
MQTT_DEBUG_PRINTLN("PUBLISH: ");
MQTT_DEBUG_PRINT("______________ TOPIC: -->");
MQTT_DEBUG_PRINT(_config.topicPub);
MQTT_DEBUG_PRINTLN();
MQTT_DEBUG_PRINT("______________ CONTENT: -->");
#ifdef MQTT_DEBUG_LEVEL_VERBOSE
MQTT_DEBUG_PRINT(jsonStrbuffer);
#endif
MQTT_DEBUG_PRINTLN();
MQTT::Publish newpub(_config.topicPub, (uint8_t*)jsonStrbuffer, strlen(jsonStrbuffer));
if (_config.retainPublishMessage) {
newpub.set_retain(true) ;
}
if(!_config.client->publish(newpub)) {
MQTT_DEBUG_PRINTLN();
MQTT_DEBUG_PRINTLN("PUBLISHED FAILED!");
return;
}
else {
MQTT_DEBUG_PRINTLN();
MQTT_DEBUG_PRINTLN("PUBLISHED SUCCEEDED!");
if (_user_on_after_publish) {
_user_on_after_publish(newpub);
}
}
MQTT_DEBUG_PRINTLN("====================================");
MQTT_DEBUG_PRINTLN("====================================");
}
}
void MqttConnector::_connect()
{
// _config.client->set_max_retries(150);
bool flag = true;
uint16_t times = 0;
while(!_config.client->connect(*(_config.connOpts)) && flag)
{
MQTT_DEBUG_PRINTLN("KEEP CONNECTING...");
if (_user_hook_connecting) {
_user_hook_connecting(++times, &flag);
yield();
}
else {
delay(100);
}
}
MQTT_DEBUG_PRINTLN("== Wrapper.connect(); CONNECT WITH OPTIONS = ");
MQTT_DEBUG_PRINTLN("== Wrapper.connect(); CONNECT WITH OPTIONS = ");
MQTT_DEBUG_PRINT("HOST: ");
MQTT_DEBUG_PRINTLN(_mqtt_host);
MQTT_DEBUG_PRINT("PORT: ");
MQTT_DEBUG_PRINTLN(_mqtt_port);
MQTT_DEBUG_PRINT("clientId: ");
MQTT_DEBUG_PRINTLN(_config.clientId);
MQTT_DEBUG_PRINT("USER: ");
MQTT_DEBUG_PRINTLN(_config.username);
MQTT_DEBUG_PRINT("PASS: ");
MQTT_DEBUG_PRINTLN(_config.password);
MQTT_DEBUG_PRINT("clientId: ");
MQTT_DEBUG_PRINTLN(_config.clientId);
MQTT_DEBUG_PRINT("lastWill: ");
MQTT_DEBUG_PRINTLN(_config.enableLastWill);
MQTT_DEBUG_PRINTLN("CONNECTED");
MQTT_DEBUG_PRINTLN("====================================");
MQTT_DEBUG_PRINTLN("====================================");
if (_config.mode == MODE_PUB_ONLY) {
// delete _user_hook_subscribe;
_user_hook_subscribe = NULL;
}
if (_subscribe_object != NULL) {
delete _subscribe_object;
_subscribe_object = NULL;
_subscription_counter=0;
}
_subscribe_object = new MQTT::Subscribe();
/*
* BEGIN SUBSCRIBE LOGIC
*/
if (_user_hook_subscribe != NULL)
{
MQTT_DEBUG_PRINTLN("CALLING HOOK SUBSCRIBING..");
_user_hook_subscribe(_subscribe_object);
MQTT_DEBUG_PRINTLN("CHECK IF __SUBSCRIBING... ->");
_subscribe_object->add_topic(_config.topicSub);
MQTT_DEBUG_PRINTLN("++TRY SUBSCRIBING ++");
if (_config.client->subscribe(*_subscribe_object)) {
_subscription_counter++;
MQTT_DEBUG_PRINT("__SUBSCRIBED TOPICS ___");
// MQTT_DEBUG_PRINTLN(_config.topicSub);
}
else {
// goto loop and recheck connectiviy
return;
}
}
else
{
MQTT_DEBUG_PRINTLN("__ PUBLISH ONLY MODE");
}
if (_config.enableLastWill) {
_clear_last_will();
}
doPublish(true);
}
// HOOKS
// void MqttConnector::connecting_hook(int count, bool *flag) {
// if (_user_hook_connecting != NULL) {
// _user_hook_connecting(count, flag);
// }
// }
void MqttConnector::on_prepare_configuration(cmmc_config_t func)
{
_user_hook_config = func;
}
void MqttConnector::on_after_prepare_configuration(cmmc_after_config_t func)
{
_user_hook_after_config = func;
}
void MqttConnector::on_connecting(connecting_hook_t cb) {
_user_hook_connecting = cb;
}
void MqttConnector::on_prepare_data(prepare_data_hook_t func,
unsigned long publish_interval)
{
_user_hook_prepare_data = func;
_publish_interval = publish_interval;
_timer_set(&_publish_timer, publish_interval);
}
void MqttConnector::on_after_prepare_data(after_prepare_data_hook_t func)
{
_user_hook_after_prepare_data = func;
}
void MqttConnector::on_subscribe(subscribe_hook_t func)
{
_user_hook_subscribe = func;
}
void MqttConnector::_prepare_data_hook()
{
if (_user_on_before_prepare_data != NULL) {
_user_on_before_prepare_data();
}
if (_user_hook_prepare_data != NULL)
{
MQTT_DEBUG_PRINTLN("__user_hook_prepare_data()");
_user_hook_prepare_data(root);
if (_user_hook_after_prepare_data) {
_user_hook_after_prepare_data(root);
}
}
}
void MqttConnector::_after_prepare_data_hook()
{
if (_user_hook_after_prepare_data != NULL)
{
MQTT_DEBUG_PRINTLN("__user_hook_after_prepare_data()");
_user_hook_after_prepare_data(root);
}
// MQTT_DEBUG_PRINTLN("BEFORE PUBLISH");
}
void MqttConnector::_hook_after_publish(char** ptr)
{
// MQTT_DEBUG_PRINTLN("AFTER PUBLISH");
}
void MqttConnector::on_prepare_data_once(before_prepare_data_once_t func) {
_user_on_prepare_data_once = func;
}
void MqttConnector::on_before_prepare_data(before_prepare_data_hook_t func) {
_user_on_before_prepare_data = func;
}
MqttConnector::~MqttConnector()
{
delete _config.connOpts;
delete _config.client;
delete _subscribe_object;
_config.connOpts = NULL;
_config.client = NULL;
_subscribe_object = NULL;
free(c_ipStr);
}
| [
"[email protected]"
] | |
4463cd5f187d4778029d14b56c4ed7c124b01dc6 | 4286765dc67cbd2fe78efed4b91de4432f9adeb3 | /Anferov/Task1_T9/src/T9_translator.cpp | 7045d12a83a0724bf5cf649e01bc90e7d21848bc | [] | no_license | Garanyan/msu_cpp_spring_2017 | 64293be72b3bea7ac6cfcb21ae148053f36bc8df | 9e3df32c0e0b71c15e3995cf2bf731a4f7270e5d | refs/heads/master | 2020-04-01T23:51:17.836329 | 2017-05-21T17:11:01 | 2017-05-21T17:11:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | cpp | #include "stdafx.h"
#include "T9_translator.h"
using namespace std;
key_def T9_translator::letter2digit(int c) {
static const char key[] = {2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};
static const char repeat[] = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,1,2,3,4};
if (c == ' ') return key_def(0,1);
if (c < 'a' || c > 'z') {
throw "Unsupported symbol!";
}
int order = c - int('a');
return key_def(key[order], repeat[order]);
};
string T9_translator::translate(string s) {
char previous_key = 1;
key_def current;
stringstream result;
for (char c: s) {
current = letter2digit(c);
if (previous_key == current.key) {
result << ' ';
}
for (int i=0; i<current.repeat; i++) {
result << char('0'+current.key);
}
previous_key = current.key;
}
return result.str();
};
| [
"[email protected]"
] | |
b80f8bff5808d69a91a1c0ddd0e1eea8fe2455c4 | fa3050f5e5ee850ba39ccb602804c001d9b4dede | /ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.cc | 1ac4395160d1bfc83b5f1497241700115701eb97 | [
"BSD-3-Clause"
] | permissive | wayou/chromium | a64c9df7d9c6190f8f9f730e7f68a998ffcabfc9 | f5f51fc460df28cef915df71b4161aaa6b668004 | refs/heads/main | 2023-06-27T18:09:41.425496 | 2021-09-08T23:02:28 | 2021-09-08T23:02:28 | 404,525,907 | 1 | 0 | BSD-3-Clause | 2021-09-08T23:38:08 | 2021-09-08T23:38:08 | null | UTF-8 | C++ | false | false | 25,587 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h"
#include "base/notreached.h"
#include "chromeos/dbus/rmad/rmad.pb.h"
#include "chromeos/dbus/update_engine/update_engine.pb.h"
#include "mojo/public/cpp/bindings/enum_traits.h"
namespace mojo {
namespace {
using MojomRmaState = ash::shimless_rma::mojom::RmaState;
using ProtoRmadState = rmad::RmadState::StateCase;
using MojomRmadErrorCode = ash::shimless_rma::mojom::RmadErrorCode;
using ProtoRmadErrorCode = rmad::RmadErrorCode;
using MojomOsUpdateOperation = ash::shimless_rma::mojom::OsUpdateOperation;
using ProtoOsUpdateOperation = update_engine::Operation;
using MojomComponentType = ash::shimless_rma::mojom::ComponentType;
using ProtoComponentType = rmad::RmadComponent;
using MojomComponentRepairState =
ash::shimless_rma::mojom::ComponentRepairStatus;
using ProtoComponentRepairState =
rmad::ComponentsRepairState_ComponentRepairStatus_RepairStatus;
using MojomProvisioningStep = ash::shimless_rma::mojom::ProvisioningStep;
using ProtoProvisioningStep = rmad::ProvisionDeviceState::ProvisioningStep;
} // namespace
// static
MojomRmaState EnumTraits<MojomRmaState, ProtoRmadState>::ToMojom(
ProtoRmadState state) {
switch (state) {
case ProtoRmadState::kWelcome:
return MojomRmaState::kWelcomeScreen;
case ProtoRmadState::kComponentsRepair:
return MojomRmaState::kSelectComponents;
case ProtoRmadState::kDeviceDestination:
return MojomRmaState::kChooseDestination;
case ProtoRmadState::kWpDisableMethod:
return MojomRmaState::kChooseWriteProtectDisableMethod;
case ProtoRmadState::kWpDisableRsu:
return MojomRmaState::kEnterRSUWPDisableCode;
case ProtoRmadState::kWpDisablePhysical:
return MojomRmaState::kWaitForManualWPDisable;
case ProtoRmadState::kWpDisableComplete:
return MojomRmaState::kWPDisableComplete;
case ProtoRmadState::kUpdateRoFirmware:
return MojomRmaState::kChooseFirmwareReimageMethod;
case ProtoRmadState::kRestock:
return MojomRmaState::kRestock;
case ProtoRmadState::kUpdateDeviceInfo:
return MojomRmaState::kUpdateDeviceInformation;
case ProtoRmadState::kCheckCalibration:
return MojomRmaState::kCheckCalibration;
case ProtoRmadState::kSetupCalibration:
return MojomRmaState::kSetupCalibration;
case ProtoRmadState::kRunCalibration:
return MojomRmaState::kRunCalibration;
case ProtoRmadState::kProvisionDevice:
return MojomRmaState::kProvisionDevice;
case ProtoRmadState::kWpEnablePhysical:
return MojomRmaState::kWaitForManualWPEnable;
case ProtoRmadState::kFinalize:
return MojomRmaState::kRepairComplete;
case ProtoRmadState::STATE_NOT_SET:
default:
return MojomRmaState::kUnknown;
}
}
// static
MojomRmadErrorCode EnumTraits<MojomRmadErrorCode, ProtoRmadErrorCode>::ToMojom(
ProtoRmadErrorCode error) {
switch (error) {
case ProtoRmadErrorCode::RMAD_ERROR_OK:
return MojomRmadErrorCode::kOk;
case ProtoRmadErrorCode::RMAD_ERROR_WAIT:
return MojomRmadErrorCode::kWait;
case ProtoRmadErrorCode::RMAD_ERROR_EXPECT_REBOOT:
return MojomRmadErrorCode::kExpectReboot;
case ProtoRmadErrorCode::RMAD_ERROR_EXPECT_SHUTDOWN:
return MojomRmadErrorCode::kExpectShutdown;
case ProtoRmadErrorCode::RMAD_ERROR_RMA_NOT_REQUIRED:
return MojomRmadErrorCode::kRmaNotRequired;
case ProtoRmadErrorCode::RMAD_ERROR_STATE_HANDLER_MISSING:
return MojomRmadErrorCode::kStateHandlerMissing;
case ProtoRmadErrorCode::RMAD_ERROR_STATE_HANDLER_INITIALIZATION_FAILED:
return MojomRmadErrorCode::kStateHandlerInitializationFailed;
case ProtoRmadErrorCode::RMAD_ERROR_REQUEST_INVALID:
return MojomRmadErrorCode::kRequestInvalid;
case ProtoRmadErrorCode::RMAD_ERROR_REQUEST_ARGS_MISSING:
return MojomRmadErrorCode::kRequestArgsMissing;
case ProtoRmadErrorCode::RMAD_ERROR_REQUEST_ARGS_VIOLATION:
return MojomRmadErrorCode::kRequestArgsViolation;
case ProtoRmadErrorCode::RMAD_ERROR_TRANSITION_FAILED:
return MojomRmadErrorCode::kTransitionFailed;
case ProtoRmadErrorCode::RMAD_ERROR_ABORT_FAILED:
return MojomRmadErrorCode::kAbortFailed;
case ProtoRmadErrorCode::RMAD_ERROR_MISSING_COMPONENT:
return MojomRmadErrorCode::kMissingComponent;
case ProtoRmadErrorCode::RMAD_ERROR_WRITE_PROTECT_DISABLE_RSU_NO_CHALLENGE:
return MojomRmadErrorCode::kWriteProtectDisableRsuNoChallenge;
case ProtoRmadErrorCode::RMAD_ERROR_WRITE_PROTECT_DISABLE_RSU_CODE_INVALID:
return MojomRmadErrorCode::kWriteProtectDisableRsuCodeInvalid;
case ProtoRmadErrorCode::
RMAD_ERROR_WRITE_PROTECT_DISABLE_BATTERY_NOT_DISCONNECTED:
return MojomRmadErrorCode::kWriteProtectDisableBatteryNotDisconnected;
case ProtoRmadErrorCode::
RMAD_ERROR_WRITE_PROTECT_DISABLE_SIGNAL_NOT_DETECTED:
return MojomRmadErrorCode::kWriteProtectSignalNotDetected;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_NO_NETWORK:
return MojomRmadErrorCode::kReimagingDownloadNoNetwork;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_NETWORK_ERROR:
return MojomRmadErrorCode::kReimagingDownloadNetworkError;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_CANCELLED:
return MojomRmadErrorCode::kReimagingDownloadCancelled;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_NOT_FOUND:
return MojomRmadErrorCode::kReimagingUsbNotFound;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_TOO_MANY_FOUND:
return MojomRmadErrorCode::kReimagingUsbTooManyFound;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_INVALID_IMAGE:
return MojomRmadErrorCode::kReimagingUsbInvalidImage;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_IMAGING_FAILED:
return MojomRmadErrorCode::kReimagingImagingFailed;
case ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_UNKNOWN_FAILURE:
return MojomRmadErrorCode::kReimagingUnknownFailure;
case ProtoRmadErrorCode::RMAD_ERROR_DEVICE_INFO_INVALID:
return MojomRmadErrorCode::kDeviceInfoInvalid;
case ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_COMPONENT_MISSING:
return MojomRmadErrorCode::kCalibrationComponentMissing;
case ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_STATUS_MISSING:
return MojomRmadErrorCode::kCalibrationStatusMissing;
case ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_COMPONENT_INVALID:
return MojomRmadErrorCode::kCalibrationComponentInvalid;
case ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_FAILED:
return MojomRmadErrorCode::kCalibrationFailed;
case ProtoRmadErrorCode::RMAD_ERROR_PROVISIONING_FAILED:
return MojomRmadErrorCode::kProvisioningFailed;
case ProtoRmadErrorCode::RMAD_ERROR_POWERWASH_FAILED:
return MojomRmadErrorCode::kPowerwashFailed;
case ProtoRmadErrorCode::RMAD_ERROR_FINALIZATION_FAILED:
return MojomRmadErrorCode::kFinalizationFailed;
case ProtoRmadErrorCode::RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_CANNOT_CONNECT:
return MojomRmadErrorCode::kLogUploadFtpServerCannotConnect;
case ProtoRmadErrorCode::
RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_CONNECTION_REJECTED:
return MojomRmadErrorCode::kLogUploadFtpServerConnectionRejected;
case ProtoRmadErrorCode::RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_TRANSFER_FAILED:
return MojomRmadErrorCode::kLogUploadFtpServerTransferFailed;
case ProtoRmadErrorCode::RMAD_ERROR_CANNOT_CANCEL_RMA:
return MojomRmadErrorCode::kCannotCancelRma;
case ProtoRmadErrorCode::RMAD_ERROR_CANNOT_GET_LOG:
return MojomRmadErrorCode::kCannotGetLog;
case ProtoRmadErrorCode::RMAD_ERROR_NOT_SET:
default:
NOTREACHED();
return MojomRmadErrorCode::kNotSet;
}
NOTREACHED();
return MojomRmadErrorCode::kNotSet;
}
// static
bool EnumTraits<MojomRmadErrorCode, ProtoRmadErrorCode>::FromMojom(
MojomRmadErrorCode error,
ProtoRmadErrorCode* out) {
switch (error) {
case MojomRmadErrorCode::kOk:
*out = ProtoRmadErrorCode::RMAD_ERROR_OK;
return true;
case MojomRmadErrorCode::kWait:
*out = ProtoRmadErrorCode::RMAD_ERROR_WAIT;
return true;
case MojomRmadErrorCode::kExpectReboot:
*out = ProtoRmadErrorCode::RMAD_ERROR_EXPECT_REBOOT;
return true;
case MojomRmadErrorCode::kExpectShutdown:
*out = ProtoRmadErrorCode::RMAD_ERROR_EXPECT_SHUTDOWN;
return true;
case MojomRmadErrorCode::kRmaNotRequired:
*out = ProtoRmadErrorCode::RMAD_ERROR_RMA_NOT_REQUIRED;
return true;
case MojomRmadErrorCode::kStateHandlerMissing:
*out = ProtoRmadErrorCode::RMAD_ERROR_STATE_HANDLER_MISSING;
return true;
case MojomRmadErrorCode::kStateHandlerInitializationFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_STATE_HANDLER_INITIALIZATION_FAILED;
return true;
case MojomRmadErrorCode::kRequestInvalid:
*out = ProtoRmadErrorCode::RMAD_ERROR_REQUEST_INVALID;
return true;
case MojomRmadErrorCode::kRequestArgsMissing:
*out = ProtoRmadErrorCode::RMAD_ERROR_REQUEST_ARGS_MISSING;
return true;
case MojomRmadErrorCode::kRequestArgsViolation:
*out = ProtoRmadErrorCode::RMAD_ERROR_REQUEST_ARGS_VIOLATION;
return true;
case MojomRmadErrorCode::kTransitionFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_TRANSITION_FAILED;
return true;
case MojomRmadErrorCode::kAbortFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_ABORT_FAILED;
return true;
case MojomRmadErrorCode::kMissingComponent:
*out = ProtoRmadErrorCode::RMAD_ERROR_MISSING_COMPONENT;
return true;
case MojomRmadErrorCode::kWriteProtectDisableRsuNoChallenge:
*out =
ProtoRmadErrorCode::RMAD_ERROR_WRITE_PROTECT_DISABLE_RSU_NO_CHALLENGE;
return true;
case MojomRmadErrorCode::kWriteProtectDisableRsuCodeInvalid:
*out =
ProtoRmadErrorCode::RMAD_ERROR_WRITE_PROTECT_DISABLE_RSU_CODE_INVALID;
return true;
case MojomRmadErrorCode::kWriteProtectDisableBatteryNotDisconnected:
*out = ProtoRmadErrorCode::
RMAD_ERROR_WRITE_PROTECT_DISABLE_BATTERY_NOT_DISCONNECTED;
return true;
case MojomRmadErrorCode::kWriteProtectSignalNotDetected:
*out = ProtoRmadErrorCode::
RMAD_ERROR_WRITE_PROTECT_DISABLE_SIGNAL_NOT_DETECTED;
return true;
case MojomRmadErrorCode::kReimagingDownloadNoNetwork:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_NO_NETWORK;
return true;
case MojomRmadErrorCode::kReimagingDownloadNetworkError:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_NETWORK_ERROR;
return true;
case MojomRmadErrorCode::kReimagingDownloadCancelled:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_DOWNLOAD_CANCELLED;
return true;
case MojomRmadErrorCode::kReimagingUsbNotFound:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_NOT_FOUND;
return true;
case MojomRmadErrorCode::kReimagingUsbTooManyFound:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_TOO_MANY_FOUND;
return true;
case MojomRmadErrorCode::kReimagingUsbInvalidImage:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_USB_INVALID_IMAGE;
return true;
case MojomRmadErrorCode::kReimagingImagingFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_IMAGING_FAILED;
return true;
case MojomRmadErrorCode::kReimagingUnknownFailure:
*out = ProtoRmadErrorCode::RMAD_ERROR_REIMAGING_UNKNOWN_FAILURE;
return true;
case MojomRmadErrorCode::kDeviceInfoInvalid:
*out = ProtoRmadErrorCode::RMAD_ERROR_DEVICE_INFO_INVALID;
return true;
case MojomRmadErrorCode::kCalibrationComponentMissing:
*out = ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_COMPONENT_MISSING;
return true;
case MojomRmadErrorCode::kCalibrationStatusMissing:
*out = ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_STATUS_MISSING;
return true;
case MojomRmadErrorCode::kCalibrationComponentInvalid:
*out = ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_COMPONENT_INVALID;
return true;
case MojomRmadErrorCode::kCalibrationFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_CALIBRATION_FAILED;
return true;
case MojomRmadErrorCode::kProvisioningFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_PROVISIONING_FAILED;
return true;
case MojomRmadErrorCode::kPowerwashFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_POWERWASH_FAILED;
return true;
case MojomRmadErrorCode::kFinalizationFailed:
*out = ProtoRmadErrorCode::RMAD_ERROR_FINALIZATION_FAILED;
return true;
case MojomRmadErrorCode::kLogUploadFtpServerCannotConnect:
*out =
ProtoRmadErrorCode::RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_CANNOT_CONNECT;
return true;
case MojomRmadErrorCode::kLogUploadFtpServerConnectionRejected:
*out = ProtoRmadErrorCode::
RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_CONNECTION_REJECTED;
return true;
case MojomRmadErrorCode::kLogUploadFtpServerTransferFailed:
*out =
ProtoRmadErrorCode::RMAD_ERROR_LOG_UPLOAD_FTP_SERVER_TRANSFER_FAILED;
return true;
case MojomRmadErrorCode::kCannotCancelRma:
*out = ProtoRmadErrorCode::RMAD_ERROR_CANNOT_CANCEL_RMA;
return true;
case MojomRmadErrorCode::kCannotGetLog:
*out = ProtoRmadErrorCode::RMAD_ERROR_CANNOT_GET_LOG;
return true;
case MojomRmadErrorCode::kNotSet:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
MojomOsUpdateOperation
EnumTraits<MojomOsUpdateOperation, ProtoOsUpdateOperation>::ToMojom(
ProtoOsUpdateOperation operation) {
switch (operation) {
case update_engine::IDLE:
return MojomOsUpdateOperation::kIdle;
case update_engine::CHECKING_FOR_UPDATE:
return MojomOsUpdateOperation::kCheckingForUpdate;
case update_engine::UPDATE_AVAILABLE:
return MojomOsUpdateOperation::kUpdateAvailable;
case update_engine::DOWNLOADING:
return MojomOsUpdateOperation::kDownloading;
case update_engine::VERIFYING:
return MojomOsUpdateOperation::kVerifying;
case update_engine::FINALIZING:
return MojomOsUpdateOperation::kFinalizing;
case update_engine::UPDATED_NEED_REBOOT:
return MojomOsUpdateOperation::kUpdatedNeedReboot;
case update_engine::REPORTING_ERROR_EVENT:
return MojomOsUpdateOperation::kReportingErrorEvent;
case update_engine::ATTEMPTING_ROLLBACK:
return MojomOsUpdateOperation::kAttemptingRollback;
case update_engine::DISABLED:
return MojomOsUpdateOperation::kDisabled;
case update_engine::NEED_PERMISSION_TO_UPDATE:
return MojomOsUpdateOperation::kNeedPermissionToUpdate;
case update_engine::ERROR:
case update_engine::Operation_INT_MIN_SENTINEL_DO_NOT_USE_:
case update_engine::Operation_INT_MAX_SENTINEL_DO_NOT_USE_:
NOTREACHED();
return MojomOsUpdateOperation::kIdle;
}
NOTREACHED();
return MojomOsUpdateOperation::kIdle;
}
// static
bool EnumTraits<MojomOsUpdateOperation, ProtoOsUpdateOperation>::FromMojom(
MojomOsUpdateOperation input,
ProtoOsUpdateOperation* out) {
switch (input) {
case MojomOsUpdateOperation::kIdle:
*out = update_engine::IDLE;
return true;
case MojomOsUpdateOperation::kCheckingForUpdate:
*out = update_engine::CHECKING_FOR_UPDATE;
return true;
case MojomOsUpdateOperation::kUpdateAvailable:
*out = update_engine::UPDATE_AVAILABLE;
return true;
case MojomOsUpdateOperation::kDownloading:
*out = update_engine::DOWNLOADING;
return true;
case MojomOsUpdateOperation::kVerifying:
*out = update_engine::VERIFYING;
return true;
case MojomOsUpdateOperation::kFinalizing:
*out = update_engine::FINALIZING;
return true;
case MojomOsUpdateOperation::kUpdatedNeedReboot:
*out = update_engine::UPDATED_NEED_REBOOT;
return true;
case MojomOsUpdateOperation::kReportingErrorEvent:
*out = update_engine::REPORTING_ERROR_EVENT;
return true;
case MojomOsUpdateOperation::kAttemptingRollback:
*out = update_engine::ATTEMPTING_ROLLBACK;
return true;
case MojomOsUpdateOperation::kDisabled:
*out = update_engine::DISABLED;
return true;
case MojomOsUpdateOperation::kNeedPermissionToUpdate:
*out = update_engine::NEED_PERMISSION_TO_UPDATE;
return true;
}
NOTREACHED();
return false;
}
// static
MojomComponentType EnumTraits<MojomComponentType, ProtoComponentType>::ToMojom(
ProtoComponentType component) {
switch (component) {
case rmad::RmadComponent::RMAD_COMPONENT_AUDIO_CODEC:
return MojomComponentType::kAudioCodec;
case rmad::RmadComponent::RMAD_COMPONENT_BATTERY:
return MojomComponentType::kBattery;
case rmad::RmadComponent::RMAD_COMPONENT_STORAGE:
return MojomComponentType::kStorage;
case rmad::RmadComponent::RMAD_COMPONENT_VPD_CACHED:
return MojomComponentType::kVpdCached;
case rmad::RmadComponent::RMAD_COMPONENT_NETWORK: // Obsolete in M91.
return MojomComponentType::kNetwork;
case rmad::RmadComponent::RMAD_COMPONENT_CAMERA:
return MojomComponentType::kCamera;
case rmad::RmadComponent::RMAD_COMPONENT_STYLUS:
return MojomComponentType::kStylus;
case rmad::RmadComponent::RMAD_COMPONENT_TOUCHPAD:
return MojomComponentType::kTouchpad;
case rmad::RmadComponent::RMAD_COMPONENT_TOUCHSCREEN:
return MojomComponentType::kTouchsreen;
case rmad::RmadComponent::RMAD_COMPONENT_DRAM:
return MojomComponentType::kDram;
case rmad::RmadComponent::RMAD_COMPONENT_DISPLAY_PANEL:
return MojomComponentType::kDisplayPanel;
case rmad::RmadComponent::RMAD_COMPONENT_CELLULAR:
return MojomComponentType::kCellular;
case rmad::RmadComponent::RMAD_COMPONENT_ETHERNET:
return MojomComponentType::kEthernet;
case rmad::RmadComponent::RMAD_COMPONENT_WIRELESS:
return MojomComponentType::kWireless;
// Additional rmad components.
case rmad::RmadComponent::RMAD_COMPONENT_SCREEN:
return MojomComponentType::kScreen;
case rmad::RmadComponent::RMAD_COMPONENT_BASE_ACCELEROMETER:
return MojomComponentType::kBaseAccelerometer;
case rmad::RmadComponent::RMAD_COMPONENT_LID_ACCELEROMETER:
return MojomComponentType::kLidAccelerometer;
case rmad::RmadComponent::RMAD_COMPONENT_GYROSCOPE:
return MojomComponentType::kGyroscope;
case rmad::RmadComponent::RMAD_COMPONENT_KEYBOARD:
return MojomComponentType::kKeyboard;
case rmad::RmadComponent::RMAD_COMPONENT_POWER_BUTTON:
return MojomComponentType::kPowerButton;
case rmad::RmadComponent::RMAD_COMPONENT_UNKNOWN:
default:
NOTREACHED();
return MojomComponentType::kComponentUnknown;
}
NOTREACHED();
return MojomComponentType::kComponentUnknown;
}
// static
bool EnumTraits<MojomComponentType, ProtoComponentType>::FromMojom(
MojomComponentType component,
ProtoComponentType* out) {
switch (component) {
case MojomComponentType::kAudioCodec:
*out = rmad::RmadComponent::RMAD_COMPONENT_AUDIO_CODEC;
return true;
case MojomComponentType::kBattery:
*out = rmad::RmadComponent::RMAD_COMPONENT_BATTERY;
return true;
case MojomComponentType::kStorage:
*out = rmad::RmadComponent::RMAD_COMPONENT_STORAGE;
return true;
case MojomComponentType::kVpdCached:
*out = rmad::RmadComponent::RMAD_COMPONENT_VPD_CACHED;
return true;
case MojomComponentType::kNetwork:
*out = rmad::RmadComponent::RMAD_COMPONENT_NETWORK;
return true; // Obsolete in M91.
case MojomComponentType::kCamera:
*out = rmad::RmadComponent::RMAD_COMPONENT_CAMERA;
return true;
case MojomComponentType::kStylus:
*out = rmad::RmadComponent::RMAD_COMPONENT_STYLUS;
return true;
case MojomComponentType::kTouchpad:
*out = rmad::RmadComponent::RMAD_COMPONENT_TOUCHPAD;
return true;
case MojomComponentType::kTouchsreen:
*out = rmad::RmadComponent::RMAD_COMPONENT_TOUCHSCREEN;
return true;
case MojomComponentType::kDram:
*out = rmad::RmadComponent::RMAD_COMPONENT_DRAM;
return true;
case MojomComponentType::kDisplayPanel:
*out = rmad::RmadComponent::RMAD_COMPONENT_DISPLAY_PANEL;
return true;
case MojomComponentType::kCellular:
*out = rmad::RmadComponent::RMAD_COMPONENT_CELLULAR;
return true;
case MojomComponentType::kEthernet:
*out = rmad::RmadComponent::RMAD_COMPONENT_ETHERNET;
return true;
case MojomComponentType::kWireless:
*out = rmad::RmadComponent::RMAD_COMPONENT_WIRELESS;
return true;
// Additional rmad components.
case MojomComponentType::kScreen:
*out = rmad::RmadComponent::RMAD_COMPONENT_SCREEN;
return true;
case MojomComponentType::kBaseAccelerometer:
*out = rmad::RmadComponent::RMAD_COMPONENT_BASE_ACCELEROMETER;
return true;
case MojomComponentType::kLidAccelerometer:
*out = rmad::RmadComponent::RMAD_COMPONENT_LID_ACCELEROMETER;
return true;
case MojomComponentType::kGyroscope:
*out = rmad::RmadComponent::RMAD_COMPONENT_GYROSCOPE;
return true;
case MojomComponentType::kKeyboard:
*out = rmad::RmadComponent::RMAD_COMPONENT_KEYBOARD;
return true;
case MojomComponentType::kPowerButton:
*out = rmad::RmadComponent::RMAD_COMPONENT_POWER_BUTTON;
return true;
case MojomComponentType::kComponentUnknown:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
// static
MojomComponentRepairState
EnumTraits<MojomComponentRepairState, ProtoComponentRepairState>::ToMojom(
ProtoComponentRepairState state) {
switch (state) {
case rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_ORIGINAL:
return MojomComponentRepairState::kOriginal;
case rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_REPLACED:
return MojomComponentRepairState::kReplaced;
case rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_MISSING:
return MojomComponentRepairState::kMissing;
case rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_UNKNOWN:
return MojomComponentRepairState::kRepairUnknown;
default:
NOTREACHED();
return MojomComponentRepairState::kRepairUnknown;
}
NOTREACHED();
return MojomComponentRepairState::kRepairUnknown;
}
// static
bool EnumTraits<MojomComponentRepairState, ProtoComponentRepairState>::
FromMojom(MojomComponentRepairState state, ProtoComponentRepairState* out) {
switch (state) {
case MojomComponentRepairState::kOriginal:
*out = rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_ORIGINAL;
return true;
case MojomComponentRepairState::kReplaced:
*out = rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_REPLACED;
return true;
case MojomComponentRepairState::kMissing:
*out = rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_MISSING;
return true;
case MojomComponentRepairState::kRepairUnknown:
*out = rmad::ComponentsRepairState_ComponentRepairStatus::
RMAD_REPAIR_STATUS_UNKNOWN;
return true;
default:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
// static
MojomProvisioningStep
EnumTraits<MojomProvisioningStep, ProtoProvisioningStep>::ToMojom(
ProtoProvisioningStep step) {
switch (step) {
case rmad::ProvisionDeviceState::RMAD_PROVISIONING_STEP_IN_PROGRESS:
return MojomProvisioningStep::kInProgress;
case rmad::ProvisionDeviceState::RMAD_PROVISIONING_STEP_COMPLETE:
return MojomProvisioningStep::kProvisioningComplete;
case rmad::ProvisionDeviceState::RMAD_PROVISIONING_STEP_UNKNOWN:
default:
NOTREACHED();
return MojomProvisioningStep::kProvisioningUnknown;
}
NOTREACHED();
return MojomProvisioningStep::kProvisioningUnknown;
}
// static
bool EnumTraits<MojomProvisioningStep, ProtoProvisioningStep>::FromMojom(
MojomProvisioningStep step,
ProtoProvisioningStep* out) {
switch (step) {
case MojomProvisioningStep::kInProgress:
*out = rmad::ProvisionDeviceState::RMAD_PROVISIONING_STEP_IN_PROGRESS;
return true;
case MojomProvisioningStep::kProvisioningComplete:
*out = rmad::ProvisionDeviceState::RMAD_PROVISIONING_STEP_COMPLETE;
return true;
case MojomProvisioningStep::kProvisioningUnknown:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
bool StructTraits<ash::shimless_rma::mojom::ComponentDataView,
rmad::ComponentsRepairState_ComponentRepairStatus>::
Read(ash::shimless_rma::mojom::ComponentDataView data,
rmad::ComponentsRepairState_ComponentRepairStatus* out) {
rmad::RmadComponent component;
rmad::ComponentsRepairState_ComponentRepairStatus_RepairStatus repair_status;
if (data.ReadComponent(&component) && data.ReadState(&repair_status)) {
out->set_component(component);
out->set_repair_status(repair_status);
return true;
}
return false;
}
} // namespace mojo
| [
"[email protected]"
] | |
eb47459779968a79851e62d9e0b234094b04ae25 | 852233b7b484943900d8825eef9363f4a3004c66 | /app/src/main/cpp/pb/google/protobuf/stubs/mutex.h | 2c9040643c60f5b12b70e317567e22eb6061fe66 | [] | no_license | zhourui1207/VmSdkDemo_android | 79a54a8a6eeaa4d364395399d11b6a7a69f0c680 | 2ab2807152b7d266da6083f360a67d689ebd75e4 | refs/heads/master | 2021-01-13T09:36:25.735089 | 2017-11-22T13:01:19 | 2017-11-22T13:01:19 | 72,426,136 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,796 | h | // Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_
#define GOOGLE_PROTOBUF_STUBS_MUTEX_H_
#ifdef GOOGLE_PROTOBUF_NO_THREADLOCAL
#include <pthread.h>
#endif
#include <google/protobuf/stubs/macros.h>
// ===================================================================
// emulates google3/base/mutex.h
namespace google {
namespace protobuf {
namespace internal {
// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T
// may hold a mutex at a given time. If T attempts to Lock() the same Mutex
// while holding it, T will deadlock.
class LIBPROTOBUF_EXPORT Mutex {
public:
// Create a Mutex that is not held by anybody.
Mutex();
// Destructor
~Mutex();
// Block if necessary until this Mutex is free, then acquire it exclusively.
void Lock();
// Release this Mutex. Caller must hold it exclusively.
void Unlock();
// Crash if this Mutex is not held exclusively by this thread.
// May fail to crash when it should; will never crash when it should not.
void AssertHeld();
private:
struct Internal;
Internal* mInternal;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex);
};
// Undefine the macros to workaround the conflicts with Google internal
// MutexLock implementation.
// TODO(liujisi): Remove the undef once internal macros are removed.
#undef MutexLock
#undef ReaderMutexLock
#undef WriterMutexLock
#undef MutexLockMaybe
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
class LIBPROTOBUF_EXPORT MutexLock {
public:
explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); }
~MutexLock() { this->mu_->Unlock(); }
private:
Mutex *const mu_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock);
};
// TODO(kenton): Implement these? Hard to implement portably.
typedef MutexLock ReaderMutexLock;
typedef MutexLock WriterMutexLock;
// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL.
class LIBPROTOBUF_EXPORT MutexLockMaybe {
public:
explicit MutexLockMaybe(Mutex *mu) :
mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } }
~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } }
private:
Mutex *const mu_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
};
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
template<typename T>
class ThreadLocalStorage {
public:
ThreadLocalStorage() {
pthread_key_create(&key_, &ThreadLocalStorage::Delete);
}
~ThreadLocalStorage() {
pthread_key_delete(key_);
}
T* Get() {
T* result = static_cast<T*>(pthread_getspecific(key_));
if (result == NULL) {
result = new T();
pthread_setspecific(key_, result);
}
return result;
}
private:
static void Delete(void* value) {
delete static_cast<T*>(value);
}
pthread_key_t key_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadLocalStorage);
};
#endif
} // namespace internal
// We made these internal so that they would show up as such in the docs,
// but we don't want to stick "internal::" in front of them everywhere.
using internal::Mutex;
using internal::MutexLock;
using internal::ReaderMutexLock;
using internal::WriterMutexLock;
using internal::MutexLockMaybe;
} // namespace protobuf
} // namespace pb.google
#endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_
| [
"[email protected]"
] | |
4b8119dd7ee6ed89aabf5b86ed4dcc5e57af6d1d | c709792f1d067dc59ebdf48f2d0c838de101bb2d | /src/f4se/f4se/GameMenus.h | b0c6a36791136bca315fd4d86f5d517ee1d87d0e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | levans88/f4se-mirror | f4122a23582326481614f4b0423a1f5b7f7655ff | 1d8271538faf42388fce245470f41cd83db29616 | refs/heads/master | 2020-09-08T09:05:17.133722 | 2019-06-14T11:52:27 | 2019-06-14T11:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,332 | h | #pragma once
#include "f4se_common/Utilities.h"
#include "f4se_common/Relocation.h"
#include "f4se/GameInput.h"
#include "f4se/GameTypes.h"
#include "f4se/GameUtilities.h"
#include "f4se/ScaleformAPI.h"
#include "f4se/ScaleformCallbacks.h"
#include "f4se/ScaleformValue.h"
typedef GFxValue* (*_GetChildElement)(GFxValue * parent, GFxValue & child, const char * path);
extern RelocAddr<_GetChildElement> GetChildElement;
enum MessageType
{
kMessage_Refresh = 0,
kMessage_Open,
kMessage_Close = 3,
kMessage_Scaleform = 5,//keydown/up
kMessage_Message,
kMessage_Platform = 11
};
class UIMessage
{
public:
virtual ~UIMessage();
BSFixedString name; // 08
UInt32 type; // 10
};
class UIMessageManager
{
public:
MEMBER_FN_PREFIX(UIMessageManager);
DEFINE_MEMBER_FN(SendUIMessage, void, 0x0204CA70, BSFixedString& menuName, UInt32 type);
// 325A22C9C57B8175C01F1E071B4E272401994375+CB
DEFINE_MEMBER_FN(SendUIMessageEx, void, 0x012BA8F0, BSFixedString& menuName, UInt32 type, UIMessage * pExtraData);
};
extern RelocPtr<UIMessageManager*> g_uiMessageManager;
class IMenu :
public SWFToCodeFunctionHandler,
public BSInputEventUser
{
public:
enum
{
//Confirmed
kFlag_PauseGame = 0x01,
kFlag_DoNotDeleteOnClose = 0x02,
kFlag_ShowCursor = 0x04,
kFlag_EnableMenuControl = 0x08, // 1, 2
kFlag_ShaderdWorld = 0x20,
kFlag_Open = 0x40,//set it after open.
kFlag_DoNotPreventGameSave = 0x800,
kFlag_ApplyDropDownFilter = 0x8000, //
kFlag_BlurBackground = 0x400000,
//Unconfirmed
kFlag_Modal = 0x10,
kFlag_PreventGameLoad = 0x80,
kFlag_Unk0100 = 0x100,
kFlag_HideOther = 0x200,
kFlag_DisableInteractive = 0x4000,
kFlag_UpdateCursorOnPlatformChange = 0x400,
kFlag_Unk1000 = 0x1000,
kFlag_ItemMenu = 0x2000,
kFlag_Unk10000 = 0x10000, // mouse cursor
kFlag_Unk800000 = 0x800000
};
virtual UInt32 ProcessMessage(UIMessage * msg) = 0;//???
virtual void DrawNextFrame(float unk0, void * unk1) = 0; //210E8C0
virtual void * Unk_05(void) { return nullptr; }; //return 0;
virtual void * Unk_06(void) { return nullptr; }; //return 0;
virtual bool Unk_07(UInt32 unk0, void * unk1) = 0;
virtual void Unk_08(UInt8 unk0) = 0;
virtual void Unk_09(BSFixedString & menuName, bool unk1) = 0; //UInt64 = 0; //UInt64
virtual void Unk_0A(void) = 0;
virtual void Unk_0B(void) = 0;
virtual void Unk_0C(void) = 0;
virtual bool Unk_0D(bool unk0) = 0;
virtual bool Unk_0E(void) { return false; };
virtual bool CanProcessControl(BSFixedString & controlID) { return false; };
virtual bool Unk_10(void) = 0;
virtual void Unk_11(void) = 0;
virtual void Unk_12(void * unk0) = 0;
GFxValue stage; // 20
GFxMovieView * movie; // 40
BSFixedString unk48; // 48
BSFixedString menuName; // 50
UInt32 flags; // 58
/*
A A A A A A A A B B B B B B B B C C C C C C C C D D D D D D D D
LoadingMenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 1 1 0 0 0 0 0 1 depth: 000E context: 0003
Console 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 1 1 1 depth: 0013 context: 0006
LevelUpMenu 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 1 0 0 0 1 1 1 depth: 0009 context: 0022
FaderMenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 depth: 0006 context: 0022
CursorMenu 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0014 context: 0022
VignetteMenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0003 context: 0022
MessageBoxMenu 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 1 depth: 000A context: 0022
ContainerMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 0 1 0 1 0 1 0 0 1 1 0 1 depth: 0006 context: 0022
ExamineMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 depth: 0009 context: 0022
CookingMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 0 depth: 0009 context: 0022
ExamineConfirmMenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 1 0 1 depth: 0011 context: 0022
RobotModMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 0 depth: 0009 context: 0022
PowerArmorModMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 0 depth: 0009 context: 0022
WorkshopMenu 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 depth: 0006 context: 0010
PromptMenu 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0005 context: 0022
SitWaitMenu 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0006 context: 0012
SleepWaitMenu 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 1 1 0 0 0 1 0 0 1 1 1 0 0 1 1 0 1 depth: 000A context: 0022
DialogueMenu 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0006 context: 0022
BarterMenu 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 1 1 0 1 0 0 1 0 1 0 1 0 0 1 1 0 1 depth: 0006 context: 0022
LockpickingMenu 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 depth: 0006 context: 000C
BookMenu 0 0 0 0 1 0 0 0 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 1 0 1 1 0 1 0 0 1 depth: 0009 context: 0008
SPECIALMenu 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 1 1 0 0 0 0 1 0 0 1 1 1 0 1 1 0 1 depth: 0006 context: 0022
FavoritesMenu 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 depth: 0006 context: 0001
HUDMenu 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0005 context: 0022
PowerArmorHUDMenu 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 depth: 0005 context: 0022
PauseMenu 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 1 1 1 0 0 1 0 1 1 1 0 1 depth: 000B context: 0022
VATSMenu 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 depth: 0006 context: 000D
PipboyMenu 0 0 0 0 0 0 0 0 1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 1 0 1 depth: 0008 context: 0022
PipboyHolotapeMenu 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 depth: 0009 context: 0022
*/
UInt32 unk5C; // 5C
UInt32 unk60; // 60 init'd as DWord then Byte
UInt8 depth; // 64 defalut is 6.
UInt32 context; // 68 init'd in IMenu::IMenu
UInt32 pad6C; // 6C
};
STATIC_ASSERT(offsetof(IMenu, movie) == 0x40);
STATIC_ASSERT(offsetof(IMenu, flags) == 0x58);
// E0
class GameMenuBase : public IMenu
{
public:
GameMenuBase();
virtual ~GameMenuBase();
// BSInputEventUser overrides
virtual void OnButtonEvent(ButtonEvent * inputEvent) override { Impl_OnGameMenuBaseButtonEvent(inputEvent); };
// IMenu overrides
virtual void Invoke(Args * args) override { }
virtual void RegisterFunctions() override { }
virtual UInt32 ProcessMessage(UIMessage * msg) override { return Impl_ProcessMessage(msg); };//???
virtual void DrawNextFrame(float unk0, void * unk1) override { return Impl_DrawNextFrame(unk0, unk1); }; //render,HUD menu uses this function to update its HUD components.
virtual bool Unk_07(UInt32 unk0, void * unk1) override { return Impl_Unk07(unk0, unk1); };
virtual void Unk_08(UInt8 unk0) override { return Impl_Unk08(unk0); };
virtual void Unk_09(BSFixedString & menuName, bool unk1) override { return Impl_Unk09(menuName, unk1); }; //UInt64
virtual void Unk_0A(void) override { return Impl_Unk0A(); };
virtual void Unk_0B(void) override { return Impl_Unk0B(); }
virtual void Unk_0C(void) override { return Impl_Unk0C(); };
virtual bool Unk_0D(bool unk0) override { return Impl_Unk0D(unk0); }
virtual bool Unk_0E(void) override { return false; };
virtual bool CanProcessControl(BSFixedString & controlID) override { return false; };
virtual bool Unk_10(void) override { return Impl_Unk10(); } //90 - E0
virtual void Unk_11(void) override { return Impl_Unk11(); };
virtual void Unk_12(void * unk0) override { return Impl_Unk12(unk0); }
virtual void Unk_13(void * unk0, void * unk1) { return Impl_Unk13(unk0, unk1); }
tArray<BSGFxDisplayObject*> subcomponents; // 70
BSGFxShaderFXTarget * shaderTarget; // 88
void * unk90; // 90
UInt64 unk98[(0xE0 - 0x98) >> 3]; // 98
DEFINE_STATIC_HEAP(ScaleformHeap_Allocate, ScaleformHeap_Free)
private:
DEFINE_MEMBER_FN_0(Impl_ctor, void *, 0x00B323C0);
DEFINE_MEMBER_FN_0(Impl_dtor, void *, 0x00B32480);
DEFINE_MEMBER_FN_2(Impl_DrawNextFrame, void, 0x0210EDB0, float unk0, void * unk1);
DEFINE_MEMBER_FN_1(Impl_ProcessMessage, UInt32, 0x0210ED30, UIMessage * msg);
DEFINE_MEMBER_FN_2(Impl_Unk07, bool, 0x0210F1F0, UInt32 unk0, void * unk1);
DEFINE_MEMBER_FN_1(Impl_Unk08, void, 0x00B32930, UInt8 unk0);
DEFINE_MEMBER_FN_2(Impl_Unk09, void, 0x0210F430, BSFixedString & menuName, bool unk1);
DEFINE_MEMBER_FN_0(Impl_Unk0A, void, 0x00B329A0);
DEFINE_MEMBER_FN_0(Impl_Unk0B, void, 0x00B32A60);
DEFINE_MEMBER_FN_0(Impl_Unk0C, void, 0x00B32AA0)
DEFINE_MEMBER_FN_1(Impl_Unk0D, bool, 0x0210F580, bool unk0);
DEFINE_MEMBER_FN_0(Impl_Unk10, bool, 0x00B32750);
DEFINE_MEMBER_FN_0(Impl_Unk11, void, 0x00B327E0);
DEFINE_MEMBER_FN_1(Impl_Unk12, void, 0x00B32850, void * unk0);
DEFINE_MEMBER_FN_2(Impl_Unk13, void, 0x00B328A0, void * unk0, void * unk1);
};
STATIC_ASSERT(offsetof(GameMenuBase, shaderTarget) == 0x88);
// 218
class LooksMenu : public GameMenuBase
{
public:
BSTEventSink<ChargenCharacterUpdateEvent> eventSink; // E0
UInt64 unkE8; // E8
void * unkF0; // F0 - LooksInputRepeatHandler
UInt64 unkF8[(0x150-0xF8)/8];
UInt32 nextBoneID; // 150
UInt32 currentBoneID; // 154
UInt64 unk158[(0x1E0-0x158)/8];
UInt32 unk1E0; // 1E0
UInt32 unk1E4; // 1E4
UInt64 unk1E8[(0x218-0x1E8)/8];
DEFINE_MEMBER_FN_0(LoadCharacterParameters, void, 0x00B41460); // This function updates all the internals from the current character
// It's followed by a call to onCommitCharacterPresetChange
};
STATIC_ASSERT(offsetof(LooksMenu, nextBoneID) == 0x150);
// 20
template <class T>
class HUDContextArray
{
public:
T * entries; // 00
UInt32 count; // 08
UInt32 unk0C; // 0C
UInt32 flags; // 10
UInt32 unk14; // 14
UInt32 unk18; // 18
bool unk1C; // 1C
};
// F8
class HUDComponentBase : public BSGFxShaderFXTarget
{
public:
HUDComponentBase(GFxValue * parent, const char * componentName, HUDContextArray<BSFixedString> * contextList);
virtual ~HUDComponentBase();
virtual bool Unk_02(void * unk1) { return false; }
virtual void Unk_03() { }
virtual void UpdateComponent() { Impl_UpdateComponent(); } // Does stuff
virtual void UpdateVisibilityContext(void * unk1);
virtual void ColorizeComponent();
virtual bool IsVisible() { return Impl_IsVisible(); }
virtual bool Unk_08() { return contexts.unk1C; }
UInt64 unkB0; // B0
UInt64 unkB8; // B8
UInt64 unkC0; // C0
HUDContextArray<BSFixedString> contexts; // C8
float unkE8; // E8
UInt32 unkEC; // EC
UInt8 unkF0; // F0
UInt8 unkF1; // F1
bool isWarning; // F2 - This chooses the warning color over the default color
UInt8 padF3[5]; // F3
MEMBER_FN_PREFIX(HUDComponentBase);
DEFINE_MEMBER_FN_3(Impl_ctor, HUDComponentBase *, 0x00A22950, GFxValue * parent, const char * componentName, HUDContextArray<BSFixedString> * contextList);
DEFINE_MEMBER_FN_0(Impl_IsVisible, bool, 0x00A22C90);
DEFINE_MEMBER_FN_0(Impl_UpdateComponent, void, 0x00A229F0);
};
STATIC_ASSERT(offsetof(HUDComponentBase, contexts) == 0xC8);
STATIC_ASSERT(offsetof(HUDComponentBase, unkE8) == 0xE8);
STATIC_ASSERT(sizeof(HUDComponentBase) == 0xF8);
typedef bool (* _HasHUDContext)(HUDContextArray<BSFixedString> * contexts, void * unk1);
extern RelocAddr <_HasHUDContext> HasHUDContext;
// 110
class HUDComponents
{
public:
UInt64 unk00; // 00
HUDComponentBase * components[0x1E]; // 08
UInt64 unk98; // 98
UInt64 unk100; // 100
UInt32 numComponents; // 108 - 0x1E
};
// 220
class HUDMenu : public GameMenuBase
{
public:
BSTEventSink<UserEventEnabledEvent> inputEnabledSink; // E0
BSTEventSink<RequestHUDModesEvent> requestHudModesSink; // E8
HUDComponents children; // F0
UInt64 unk200; // 200
UInt64 unk208; // 208
UInt64 unk210; // 210
UInt64 unk218; // 218
};
STATIC_ASSERT(offsetof(HUDMenu, unk200) == 0x200);
// 18
class PipboySubMenu : public BSTEventSink<struct PipboyValueChangedEvent>
{
public:
virtual ~PipboySubMenu();
virtual void Unk02(); // Pure, called by PipboySubMenu::ReceiveEvent
GFxValue *value;
UInt64 unk10;
};
// 18
class PipboyQuestMenu : public PipboySubMenu
{
public:
virtual ~PipboyQuestMenu();
};
// 18
class PipboyValue
{
public:
virtual ~PipboyValue();
virtual void Unk01(); // Sets unk0C to 0
virtual void Unk02(); // pure
virtual void Unk03(void *arg1);
virtual void Unk04(); // pure
UInt32 unk08; // 08 - init'd to incremental variable
UInt8 unk0C; // 0C - init'd to 1
UInt8 unk0D; // 0D - init'd to 1
UInt16 pad0E; // 0E
PipboyValue *unk10; // 10
};
template <class T>
class PipboyPrimitiveValue : public PipboyValue
{
public:
T value; // 18
};
STATIC_ASSERT(offsetof(PipboyPrimitiveValue<bool>, value) == 0x18);
class PipboyObject : public PipboyValue
{
public:
struct PipboyTableItem
{
BSFixedString key;
PipboyValue *value;
bool operator==(const BSFixedString & a_name) const { return key == a_name; }
operator BSFixedString() const { return key; }
static inline UInt32 GetHash(BSFixedString * key)
{
UInt32 hash;
CalculateCRC32_64(&hash, (UInt64)key->data, 0);
return hash;
}
};
virtual ~PipboyObject();
tHashSet<PipboyTableItem, BSFixedString> table; // 18
//...
};
STATIC_ASSERT(offsetof(PipboyObject, table) == 0x18);
// 00C
class MenuTableItem
{
public:
typedef IMenu * (*CallbackType)(void);
BSFixedString name; // 000
IMenu * menuInstance; // 008 0 if the menu is not currently open
CallbackType menuConstructor; // 010
void * unk18; // 018
bool operator==(const MenuTableItem & rhs) const { return name == rhs.name; }
bool operator==(const BSFixedString a_name) const { return name == a_name; }
operator UInt64() const { return (UInt64)name.data->Get<char>(); }
static inline UInt32 GetHash(BSFixedString * key)
{
UInt32 hash;
CalculateCRC32_64(&hash, (UInt64)key->data, 0);
return hash;
}
void Dump(void)
{
_MESSAGE("\t\tname: %s", name.data->Get<char>());
_MESSAGE("\t\tinstance: %08X", menuInstance);
}
};
// 250 ?
class UI
{
public:
virtual ~UI();
virtual void Unk_01(void);
typedef IMenu* (*CreateFunc)(void);
typedef tHashSet<MenuTableItem,BSFixedString> MenuTable;
bool IsMenuOpen(const BSFixedString & menuName);
IMenu * GetMenu(BSFixedString & menuName);
IMenu * GetMenuByMovie(GFxMovieView * movie);
void Register(const char* name, CreateFunc creator)
{
CALL_MEMBER_FN(this, RegisterMenu)(name, creator, 0);
}
bool IsMenuRegistered(BSFixedString & menuName);
template<typename T>
void ForEachMenu(T & menuFunc)
{
g_menuTableLock->LockForReadAndWrite();
menuTable.ForEach(menuFunc);
g_menuTableLock->Release();
}
bool UnregisterMenu(BSFixedString & name, bool force = false);
UInt64 unk08; // 08
UInt64 unk10; // 10
BSTEventDispatcher<MenuOpenCloseEvent> menuOpenCloseEventSource; // 70
UInt64 unk70[(0x190 - 0x70) / 8];
tArray<IMenu*> menuStack; // 190
MenuTable menuTable; // 1A8
UInt64 unk1D8; // 1D8
UInt32 numPauseGame; // 1E0 isInMenuMode
volatile SInt32 numFlag2000; // 1E4
volatile SInt32 numFlag80; // 1E8
UInt32 numFlag20; // 1EC
// ...
protected:
MEMBER_FN_PREFIX(UI);
DEFINE_MEMBER_FN(RegisterMenu, void, 0x02043BD0, const char * name, CreateFunc creator, UInt64 unk1);
DEFINE_MEMBER_FN(IsMenuOpen, bool, 0x02042040, const BSFixedString & name);
};
extern RelocPtr <BSReadWriteLock> g_menuTableLock;
extern RelocPtr <UI*> g_ui;
| [
"[email protected]"
] | |
2fb1e927aed9bb6b73f07fc77b8539c7cb4a335b | c26b7a0948ac4e0d53d15e56fce487e3e681fba6 | /src/bolusGUI/dlgshowdata.h | bf4aac8253909f36e5936b7cf09c023623387399 | [
"Apache-2.0"
] | permissive | dreamshader/bolus | 0a5bfa55436c917808721a0f1aba3c695a2252cc | b63ae2e1821019f920cb8adeff373bafbb5e0008 | refs/heads/master | 2021-07-11T02:28:00.194438 | 2020-07-06T22:21:27 | 2020-07-06T22:21:27 | 138,501,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h | #ifndef DLGSHOWDATA_H
#define DLGSHOWDATA_H
#include <QDialog>
namespace Ui {
class dlgShowData;
}
class dlgShowData : public QDialog
{
Q_OBJECT
public:
explicit dlgShowData(QWidget *parent = nullptr);
~dlgShowData();
void displayDataRecord( void );
private slots:
void on_btnPrevRec_clicked();
void on_btnNextRec_clicked();
private:
Ui::dlgShowData *ui;
QWidget *pParent;
int currRecno;
bool eofReached;
};
#endif // DLGSHOWDATA_H
| [
"[email protected]"
] | |
4aeeb819e321e0abcfdba6aa683fd57b64509ce3 | 4473ae7c91e143f5834f04c2979c17bc80fde4e2 | /srrg2_core/src/srrg_property/property_container_manager.cpp | b27f2a6e6eb21b9a8f52ce398faa2fd4d3682b62 | [
"BSD-3-Clause"
] | permissive | mfkiwl/srrg2_core | b09608b3ba9fad5e48894bf8653cb7909d77ff26 | 2a11c6c65ee08ff681e76482ed8c05e4141909e5 | refs/heads/master | 2022-06-25T14:08:27.003646 | 2020-05-11T13:08:07 | 2020-05-11T13:08:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,002 | cpp | #include <cassert>
#include <dlfcn.h>
#include <gnu/lib-names.h>
#include <iostream>
#include "srrg_boss/deserializer.h"
#include "srrg_boss/json_object_writer.h"
#include "srrg_boss/serializer.h"
#include "srrg_system_utils/env.h"
#include "srrg_system_utils/shell_colors.h"
#include "srrg_system_utils/system_utils.h"
#include "property_container_manager.h"
#include "property_identifiable.h"
#define DEBUG(var) \
if (var) \
std::cerr << #var << ": "
extern char** environ;
namespace srrg2_core {
using namespace std;
void _register_dynamic_loader() __attribute__((constructor));
void _register_dynamic_loader() {
BOSS_REGISTER_CLASS(DynamicLoaderConfig);
}
static const bool module_manager_debug = false;
void DynamicLoaderConfig::deserializeComplete() {
std::vector<std::string> complete_paths;
for (const auto& so_it : so_names.value()) {
bool found = false;
std::string complete_path;
for (const auto& p_it : so_paths.value()) {
complete_path = p_it + "/" + so_it;
// replaces the env vars
replaceEnvTags(complete_path);
cerr << "DynamicLoaderConfig| looking for file [" << complete_path << " ] ";
ifstream is(complete_path);
if (is.good()) {
complete_paths.push_back(complete_path);
found = true;
cerr << "FOUND" << endl;
break;
} else {
cerr << "NOT_FOUND" << endl;
}
}
if (!found) {
std::cerr << "DynamicLoaderConfig| unable to find [" << so_it << "] in paths";
}
}
PropertyContainerManager::initFactory(complete_paths);
}
void PropertyContainerManager::initFactory(const std::string& loader_config_filename) {
Deserializer des;
des.setFilePath(loader_config_filename);
SerializablePtr o = 0;
while ((o = des.readObjectShared())) {
std::shared_ptr<DynamicLoaderConfig> loader_ptr =
std::dynamic_pointer_cast<DynamicLoaderConfig>(o);
if (loader_ptr) {
std::cerr << "loaded config paths from file [" << loader_config_filename << "]"
<< std::endl;
break;
}
}
}
void PropertyContainerManager::makeFactoryStub(const std::string& loader_config_filename) {
Serializer ser;
ser.setFilePath(loader_config_filename);
DynamicLoaderConfig loader;
ser.writeObject(loader);
}
void PropertyContainerManager::initFactory(const std::vector<std::string>& library_paths) {
for (const auto& it : library_paths) {
std::cerr << "opening library [" << FG_YELLOW(it) << "]";
void* handle = dlopen(it.c_str(), RTLD_LAZY);
if (!handle) {
std::cerr << FG_RED("ERROR") << std::endl;
std::cerr << FG_RED(dlerror()) << std::endl;
} else {
std::cerr << FG_GREEN("OK") << std::endl;
}
}
// now we try a cast to initiate the types
std::vector<PropertyContainerIdentifiablePtr> configurables;
std::vector<std::string> class_names = srrg2_core::getClassNames();
for (auto it = class_names.begin(); it != class_names.end(); ++it) {
srrg2_core::Serializable* ser = srrg2_core::Serializable::createInstance(*it);
srrg2_core::PropertyContainerIdentifiable* c =
dynamic_cast<srrg2_core::PropertyContainerIdentifiable*>(ser);
if (c) {
configurables.push_back(PropertyContainerIdentifiablePtr(c));
} else {
delete ser;
}
}
// we recurse in each configuration, and we list the configurable properties
// for each of these properties, we attempt a cast with all instances of the
// existing instances
for (auto c : configurables) {
DEBUG(module_manager_debug) << "name: " << c->className() << std::endl;
for (auto prop_it : c->_properties_identifiable) {
const std::string& prop_name = prop_it->name();
DEBUG(module_manager_debug) << "\tproperty: " << prop_name << std::endl;
PropertyIdentifiablePtrInterfaceBase& prop = *prop_it;
std::vector<std::string>& assignables = prop.assignableTypes();
assignables.clear();
for (auto t : configurables) {
if (prop.canAssign(t)) {
DEBUG(module_manager_debug) << "\t\tcandidate: " << t->className() << std::endl;
assignables.push_back(t->className());
}
}
}
}
}
// lists all possible types of config that can be created
std::vector<std::string> PropertyContainerManager::listTypes() {
// now we try a cast to initiate the types
std::vector<std::string> available;
std::vector<std::string> class_names = srrg2_core::getClassNames();
for (const std::string& name : class_names) {
// DEBUG(module_manager_debug) << *it << " ";
srrg2_core::Serializable* ser = srrg2_core::Serializable::createInstance(name);
srrg2_core::PropertyContainerIdentifiable* c =
dynamic_cast<srrg2_core::PropertyContainerIdentifiable*>(ser);
if (c) {
// DEBUG(module_manager_debug) << "OK" << endl;
available.push_back(name);
}
// else
// DEBUG(module_manager_debug) << "--" << endl;
delete ser;
}
return available;
}
void PropertyContainerManager::read(const std::string& filename) {
_named_instances.clear();
_instances.clear();
_objects.clear();
Deserializer des;
des.setFilePath(filename);
SerializablePtr o = 0;
while ((o = des.readObjectShared())) {
_objects.insert(o);
PropertyContainerIdentifiablePtr c =
std::dynamic_pointer_cast<PropertyContainerIdentifiable>(o);
if (!c) {
continue;
}
_instances.insert(c);
if (!c->name().length()) {
continue;
}
auto it = _named_instances.find(c->name());
if (it != _named_instances.end()) {
DEBUG(module_manager_debug) << "error: a config with the same name: [" << c->name() << "] "
<< " already exists in the system" << endl;
continue;
}
_named_instances.insert(std::make_pair(c->name(), c));
}
}
void PropertyContainerManager::write(const std::string& filename) {
// we need to add to the pool all configurations that
// might be automatically generated on compute
_objects.clear();
// clear all boss IDs
for (auto it : _instances) {
Identifiable* ident = dynamic_cast<Identifiable*>(it.get());
if (ident) {
ident->setId(-1, 0);
}
_objects.insert(it);
}
Serializer ser;
ser.setFilePath(filename);
for (auto it : _objects) {
ser.writeObject(*it);
}
}
// renames a config
void PropertyContainerManager::rename(PropertyContainerIdentifiablePtr conf,
const std::string& name) {
if (conf->name().length()) {
auto it = _named_instances.find(conf->name());
if (it == _named_instances.end()) {
throw("config name mismatch");
}
_named_instances.erase(it);
}
if (name.length()) {
auto it = _named_instances.find(name);
if (it != _named_instances.end()) {
throw("config name already existing");
}
_named_instances.insert(std::make_pair(name, conf));
}
conf->setName(name);
DEBUG(module_manager_debug) << "all right" << endl;
}
// retrieves a configurable whose hame is config_name
PropertyContainerIdentifiablePtr
PropertyContainerManager::getByName(const std::string& config_name) {
auto it = _named_instances.find(config_name);
if (it == _named_instances.end()) {
return PropertyContainerIdentifiablePtr();
}
return it->second;
}
PropertyContainerIdentifiablePtr PropertyContainerManager::create(const std::string& classname,
const std::string& name) {
Serializable* s = Serializable::createInstance(classname);
if (!s) {
return 0;
}
PropertyContainerIdentifiable* c = dynamic_cast<PropertyContainerIdentifiable*>(s);
if (!s) {
return 0;
}
PropertyContainerIdentifiablePtr p(c);
p->setName(name);
if (add(p)) {
return p;
}
return 0;
}
// adds to the managed system a new configurable (and all connected objects)
bool PropertyContainerManager::add(PropertyContainerIdentifiablePtr c) {
std::cerr << "add containers! [" << c->className() << "]" << std::endl;
if (_instances.count(c)) {
return false;
}
_instances.insert(c);
_objects.insert(c);
if (c->name().length()) {
auto it = _named_instances.find(c->name());
if (it != _named_instances.end()) {
return false;
}
_named_instances.insert(std::make_pair(c->name(), c));
}
std::set<PropertyContainerIdentifiablePtr> reachable;
c->getReacheableContainers(reachable);
std::cerr << "containers added! [" << c->className() << "]" << std::endl;
for (PropertyContainerIdentifiablePtr r : reachable) {
std::cerr << "renaming: " << r << " to ''" << std::endl;
r->setName(""); // ds TODO is overwriting the name intended?
_instances.insert(r);
_objects.insert(r);
}
return true;
}
// erases a configurable from the managed system
// detaching it from all connected confs
void PropertyContainerManager::erase(PropertyContainerIdentifiablePtr erased) {
DEBUG(module_manager_debug) << "object " << endl;
auto o_it = _objects.find(erased);
if (o_it == _objects.end()) {
DEBUG(module_manager_debug) << "no object: " << endl;
return;
}
_objects.erase(o_it);
DEBUG(module_manager_debug) << "names" << endl;
if (erased->name().length()) {
_named_instances.erase(erased->name());
}
for (PropertyContainerIdentifiablePtr other : _instances) {
DEBUG(module_manager_debug) << other->className() << endl;
for (auto prop_it : other->_properties_identifiable) {
DEBUG(module_manager_debug) << " " << prop_it->name() << endl;
PropertyIdentifiablePtrVectorInterface* v_prop =
dynamic_cast<PropertyIdentifiablePtrVectorInterface*>(prop_it);
if (v_prop) {
std::vector<IdentifiablePtr> resized_vec;
resized_vec.reserve(v_prop->size());
for (size_t k = 0; k < v_prop->size(); ++k) {
IdentifiablePtr ptr = v_prop->getSharedPtr(k);
if (ptr == erased) {
continue;
// v_prop->assign(k, IdentifiablePtr());
}
resized_vec.emplace_back(ptr);
}
v_prop->assign(resized_vec);
continue;
}
PropertyIdentifiablePtrInterface* prop =
dynamic_cast<PropertyIdentifiablePtrInterface*>(prop_it);
IdentifiablePtr ptr = prop->getSharedPtr();
if (ptr == erased) {
prop->assign(IdentifiablePtr());
}
}
}
_instances.erase(erased);
}
} // namespace srrg2_core
| [
"[email protected]"
] | |
10d728454861e561904dcf0c4d927a946ea41e27 | 6188978ac378e1b84532414de49e8cf32c610104 | /mednafen/video/png.cpp | c49672940c380d4d4dd81f958080ee9a85f4bbf0 | [] | no_license | capnslipp/Mednafen-Core | 22b823f0a49a42b5368a0236aa6f172d48230972 | 66dc9243016db5e162f2bc6b1dd12f6a585806f7 | refs/heads/master | 2021-01-14T11:57:23.505816 | 2015-04-11T00:34:37 | 2015-04-11T00:34:37 | 33,756,804 | 0 | 0 | null | 2015-04-11T00:35:19 | 2015-04-11T00:35:18 | null | UTF-8 | C++ | false | false | 5,683 | cpp | /* Mednafen - Multi-system Emulator
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "video-common.h"
#include <zlib.h>
#include "png.h"
#include "../endian.h"
void PNGWrite::WriteChunk(FileWrapper &pngfile, uint32 size, const char *type, const uint8 *data)
{
uint32 crc;
uint8 tempo[4];
MDFN_en32msb(tempo, size);
pngfile.write(tempo, 4);
pngfile.write(type, 4);
if(size)
pngfile.write(data, size);
crc = crc32(0, (uint8 *)type, 4);
if(size)
crc = crc32(crc,data,size);
MDFN_en32msb(tempo, crc);
pngfile.write(tempo, 4);
}
// int MDFN_SavePNGSnapshot(const char *fname, const MDFN_Surface *src, const MDFN_Rect *rect, const MDFN_Rect *LineWidths)
PNGWrite::~PNGWrite()
{
}
PNGWrite::PNGWrite(const char *path, const MDFN_Surface *src, const MDFN_Rect &rect, const MDFN_Rect *LineWidths) : ownfile(path, FileWrapper::MODE_WRITE_SAFE)
{
WriteIt(ownfile, src, rect, LineWidths);
}
#if 0
PNGWrite::PNGWrite(FileWrapper &pngfile, const MDFN_Surface *src, const MDFN_Rect &rect, const MDFN_Rect *LineWidths)
{
WriteIt(pngfile, src, rect, LineWidths);
}
#endif
INLINE void PNGWrite::EncodeImage(const MDFN_Surface *src, const MDFN_PixelFormat &format, const MDFN_Rect &rect, const MDFN_Rect *LineWidths, const int png_width)
{
const int32 pitchinpix = src->pitchinpix;
uint8 *tmp_inc;
tmp_buffer.resize((png_width * ((format.bpp == 8) ? 1 : 3) + 1) * rect.h);
tmp_inc = &tmp_buffer[0];
for(int y = 0; y < rect.h; y++)
{
*tmp_inc = 0;
tmp_inc++;
int line_width = rect.w;
int x_base = rect.x;
if(LineWidths && LineWidths[0].w != ~0)
{
line_width = LineWidths[y + rect.y].w;
x_base = LineWidths[y + rect.y].x;
}
for(int x = 0; MDFN_LIKELY(x < line_width); x++)
{
int r, g, b;
if(format.bpp == 8)
{
tmp_inc[0] = src->pixels8[(y + rect.y) * pitchinpix + (x + x_base)];
tmp_inc++;
}
else
{
if(format.bpp == 16)
format.DecodeColor(src->pixels16[(y + rect.y) * pitchinpix + (x + x_base)], r, g, b);
else
format.DecodeColor(src->pixels[(y + rect.y) * pitchinpix + (x + x_base)], r, g, b);
tmp_inc[0] = r;
tmp_inc[1] = g;
tmp_inc[2] = b;
tmp_inc += 3;
}
}
for(int x = line_width; x < png_width; x++)
{
if(format.bpp == 8)
{
tmp_inc[0] = 0;
tmp_inc++;
}
else
{
tmp_inc[0] = tmp_inc[1] = tmp_inc[2] = 0;
tmp_inc += 3;
}
}
}
}
void PNGWrite::WriteIt(FileWrapper &pngfile, const MDFN_Surface *src, const MDFN_Rect &rect_in, const MDFN_Rect *LineWidths)
{
uLongf compmemsize;
int png_width;
const MDFN_PixelFormat format = src->format;
const MDFN_Rect rect = rect_in;
if(LineWidths && LineWidths[0].w != ~0)
{
png_width = 0;
for(int y = 0; y < rect.h; y++)
{
if(LineWidths[rect.y + y].w > png_width)
png_width = LineWidths[rect.y + y].w;
}
}
else
png_width = rect.w;
if(!rect.h)
throw(MDFN_Error(0, "Refusing to save a zero-height PNG."));
if(!png_width)
throw(MDFN_Error(0, "Refusing to save a zero-width PNG."));
compmemsize = (uLongf)( (rect.h * (png_width + 1) * 3 * 1.001 + 1) + 12 );
compmem.resize(compmemsize);
{
static uint8 header[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
pngfile.write(header, 8);
}
{
uint8 chunko[13];
MDFN_en32msb(&chunko[0], png_width); // Width
MDFN_en32msb(&chunko[4], rect.h); // Height
chunko[8]=8; // Bit depth
if(format.bpp == 8)
chunko[9]=3; // Color type; palette index
else
chunko[9]=2; // Color type; RGB triplet
chunko[10]=0; // compression: deflate
chunko[11]=0; // Basic adaptive filter set(though none are used).
chunko[12]=0; // No interlace.
WriteChunk(pngfile, 13, "IHDR", chunko);
}
if(format.bpp == 8)
{
uint8 chunko[256 * 3];
for(int i = 0; i < 256; i++)
{
chunko[(i * 3) + 0] = src->palette[i].r;
chunko[(i * 3) + 1] = src->palette[i].g;
chunko[(i * 3) + 2] = src->palette[i].b;
}
WriteChunk(pngfile, 256 * 3, "PLTE", chunko);
}
// pHYs chunk
#if 0
{
uint8 chunko[9];
uint32 ppx, ppy;
//ppx = png_width / MDFNGameInfo->nominal_width;
//ppy = 1; //rect->h / rect->h
ppx = png_width;
ppy = MDFNGameInfo->nominal_width;
MDFN_en32msb(&chunko[0], ppx);
MDFN_en32msb(&chunko[4], ppy);
//printf("%08x %08x, %04x %04x\n", ppx, ppy, *(uint32 *)&chunko[0], *(uint32 *)&chunko[4]);
chunko[8] = 0;
WriteChunk(pngfile, 9, "pHYs", chunko);
}
#endif
// IDAT chunk
{
//uint32 st = MDFND_GetTime();
if(MDFN_LIKELY(format.colorspace == MDFN_COLORSPACE_RGB && format.bpp == 32))
EncodeImage(src, format, rect, LineWidths, png_width);
else
EncodeImage(src, format, rect, LineWidths, png_width);
//printf("%u\n", MDFND_GetTime() - st);
if(compress(&compmem[0], &compmemsize, &tmp_buffer[0], rect.h * (png_width * ((format.bpp == 8) ? 1 : 3) + 1)) != Z_OK)
{
throw(MDFN_Error(0, "zlib error")); // TODO: verbosify
}
WriteChunk(pngfile, compmemsize, "IDAT", &compmem[0]);
}
//
//
//
WriteChunk(pngfile, 0, "IEND", 0);
}
| [
"[email protected]"
] | |
69a077430677acdac67dd6cfe65e4ab8ac35dda5 | 23ce9939fddf910c090bda03618023f74a7337de | /GameOfLife/src/OpenCLMode.h | c13f87553d9b2db1077aa8150bdda0f194f900a7 | [] | no_license | schwittlick/ParallelOptimization | 4f21d88ab9d703b8f179e661488257a3fa3eb59a | b2160c4781aec83103eab249f361a5462501e2ae | refs/heads/master | 2021-05-27T19:26:08.065894 | 2013-09-27T10:22:38 | 2013-09-27T10:22:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | h | #pragma once
#include "ofxState.h"
#include "SharedData.h"
#include "Colony.h"
#include "ofxUI.h"
#include "Timer.h"
#include <string>
#include <CL\opencl.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "Cell.h"
class OpenCLMode : public itg::ofxState<SharedData>
{
public:
OpenCLMode(void);
~OpenCLMode(void);
void stateEnter(void);
void stateExit(void);
void update(void);
void draw(void);
void keyPressed(int key);
void mousePressed(int x, int y, int button);
string getName(void); // returns the name of the class. important for switching between states
private:
void initOpenCLBoolStuff();
void updateOpenCLBoolStuff(cl_device_id device_id);
cl_context context;
cl_program program;
cl_command_queue commandQueue;
size_t roundUp( int groupSize, int globalSize);
ofxUICanvas *gui; // the graphical user interface
gol::Colony* colony; // the game of life colony
bool running; // determining if the animation is running
int dimension; // determining the size of the colony. neccessary for the reinitialization.
Timer *drawTimer; // timer timing the elapsed time during drawing the game of life.
Timer * calculationTimer;
void restart(void); // restarts the entire animation
void clean(void); // cleans some objects
void guiEvent(ofxUIEventArgs &e); // callback method for gui events
void startDeviceSelector( void );
size_t choosenPlatform;
cl_platform_id* platformIds;
void createContext();
cl_device_id createCommandQueue();
void createKernel( cl_device_id device, cl_context _context );
cl_kernel createKernelFromSource( cl_device_id device, cl_context context, const char * source, const char * name );
void fail( std::string errorMsg );
cl_sampler sampler;
cl_kernel kernel;
_Bool * board;//[ 32*32];
cl_mem input;
cl_mem output;
cl_device_id device_id;
void printBoard();
float elapsedTimeSinceLastReset;
ofFile file;
int elapsedFrames;
};
| [
"[email protected]"
] | |
c5a2a5d407e27b109c93201c2aaa7a0923de114f | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/new_hunk_7113.cpp | 1653395a134cc1ebf24c230f92db7149b85ab636 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | cpp | if (show_all) {
printf("usage: %s\n\n", git_usage_string);
list_commands();
printf("%s\n", git_more_info_string);
return 0;
}
if (!argv[0]) {
printf("usage: %s\n\n", git_usage_string);
list_common_cmds_help();
printf("\n%s\n", git_more_info_string);
return 0;
}
| [
"[email protected]"
] | |
f685f4691954c89b047046fcb5c36645a14efdcb | 18146d0b9af100224ccc9fa994529e66aab64944 | /src/net.cpp | dde17ee8d43b9f8dbb3d609c7323ca7a359031a6 | [
"MIT"
] | permissive | proffilit/selitcoin | 587e9c3c9ed4183226cd7efa4e6c9a46927f34b6 | 4caaf7f463b60bf1360b4cca6613bc3ff9bc89e2 | refs/heads/master | 2021-01-17T06:48:13.434377 | 2016-06-29T17:10:17 | 2016-06-29T17:10:17 | 56,967,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,007 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fClient = false;
bool fDiscover = true;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64 nLocalHostNonce = 0;
array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
Sleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore;
info.nPort = addr.GetPort() + (fAlready ? 1 : 0);
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their webserver that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to nonblocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
vRecv.clear();
}
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: local node %s misbehaving\n", addrName.c_str());
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior);
return true;
}
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nReleaseTime);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
void ThreadSocketHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
// Make this thread recognisable as the networking thread
RenameThread("bitcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (hSocketMax != INVALID_SOCKET)
{
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
Sleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("warning: unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", WSAGetLastError());
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
pnode->nLastSend = GetTime();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Inactivity checking
//
if (pnode->vSend.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
Sleep(10);
}
}
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"andarazoroflove", "andarazoroflove.org"},
};
void ThreadDNSAddressSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
// Make this thread recognisable as the DNS seeding thread
RenameThread("bitcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (GetNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0x2EFDCB71, 0xCC1B3AD6, 0xADA77149,
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
Sleep(100000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg));
// Make this thread recognisable as the address dumping thread
RenameThread("bitcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect"))
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
Sleep(500);
if (fShutdown)
return;
}
}
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
Sleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
nTries++;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (GetNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
Sleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
loop
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
Sleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if succesful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
// Make this thread recognisable as the message handling thread
RenameThread("bitcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
// Receive messages
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
ProcessMessages(pnode);
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
Sleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to nonblocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. SelitCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host ip
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
CreateThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("bitcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!CreateThread(ThreadDNSAddressSeed, NULL))
printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
// Get addresses from IRC and advertise ours
if (!CreateThread(ThreadIRCSeed, NULL))
printf("Error: CreateThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!CreateThread(ThreadSocketHandler, NULL))
printf("Error: CreateThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!CreateThread(ThreadOpenAddedConnections, NULL))
printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!CreateThread(ThreadOpenConnections, NULL))
printf("Error: CreateThread(ThreadOpenConnections) failed\n");
// Process messages
if (!CreateThread(ThreadMessageHandler, NULL))
printf("Error: CreateThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!CreateThread(ThreadDumpAddress, NULL))
printf("Error; CreateThread(ThreadDumpAddress) failed\n");
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64 nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
Sleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
Sleep(20);
Sleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
| [
"[email protected]"
] | |
fa40e12662faafacd90650aa9eda7c9cde678f0e | 9acc7813bb1e46bda24811e7942bad7f194329ed | /assignment 1/all root.cpp | 73e9b399c2f9ac06c6c9b22ffd77defb72c4adc2 | [] | no_license | KaziShoaib/NumericalMethods-IIUC | 7c4e56a53af16fd16c4d82f91aff122f4ff00737 | e575e23d630f30ae6f2aa3488d67c4627dd30432 | refs/heads/master | 2022-08-09T20:08:33.744452 | 2019-02-08T14:15:15 | 2019-02-08T14:15:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | cpp | #include<iostream>
#include<cmath>
#define E .0005
using namespace std;
int n, deg, counter, iteration;
double co[100], dco[100], x1, x0, roots[100];
void input(void)
{
int i;
cout<<"input degree of equation : ";
cin>>n;
deg=n;
for(i=n;i>=0;i--)
{
cout<<"input co-efficient of x^"<<i<<" : ";
cin>>co[i];
}
cout<<endl<<endl;
}
void find_der(void)
{
int i;
for(i=n;i>0;i--)
dco[i-1]=co[i]*i;
}
double val(double x)
{
int i;
double r=0;
for(i=n;i>=0;i--)
r+=co[i]*pow(x,i);
//cout<<"f of "<<x<<" is "<<r<<endl;
return r;
}
double dval(double x)
{
int i;
double r=0;
for(i=n-1;i>=0;i--)
r+=dco[i]*pow(x,i);
//cout<<"f prime of "<<x<<" is "<<r<<endl;
return r;
}
void synthetic(double xr)
{
double b[100];
int i;
b[n]=0;
for(i=n;i>0;i--)
b[i-1]=co[i]+xr*b[i];
n--;
for(i=n;i>=0;i--)
co[i]=b[i];
}
void nr(void)
{
find_der();
while(true)
{
cout<<"input first approximation : ";
cin>>x0;
if(dval(x0)>0||dval(x0)<0)
break;
}
counter=n;
while(counter>1)
{
//find_der();
iteration=0;
while(true)
{
iteration++;
x1 = x0 - val(x0)/dval(x0);
cout<<"iteration "<<iteration<<endl;
cout<<" x0 : "<<x0<<endl<<" x1 : "<<x1<<endl;
if(fabs(x1-x0)<E)
break;
x0 = x1;
}
roots[counter]=x1;
synthetic(x1);
cout<<"root "<<counter<<" : "<<roots[counter]<<endl<<endl;
counter--;
x0=x1;
find_der();
}
roots[1]=-co[0]/co[1];
cout<<"root "<<counter<<" : "<<roots[1]<<endl<<endl;
//return x1;
}
int main()
{
input();
nr();
int i;
cout<<endl<<endl<<endl;
cout<<"roots are : "<<endl;
for(i=deg;i>0;i--)
{
cout<<roots[i]<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
47c49d30c2c0b331e1ccadfcdc92ebfb9d8dbc13 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/KDCIssuesKerberosTicket/UNIX_KDCIssuesKerberosTicket_ZOS.hxx | 108d0612b625ecf8d7dacbdc15f95f92024d35ca | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 140 | hxx | #ifdef PEGASUS_OS_ZOS
#ifndef __UNIX_KDCISSUESKERBEROSTICKET_PRIVATE_H
#define __UNIX_KDCISSUESKERBEROSTICKET_PRIVATE_H
#endif
#endif
| [
"[email protected]"
] | |
82f443b500f3dda2c74bf0def68b97b70b795919 | b4377eb1749729819d9affa3b290425082501aa9 | /firsttest-master/class.h | abe0e9300fce13515fb1a322f74b3742cc2cf7c8 | [] | no_license | dawendiguo/myc- | bccd7e146e9030558a1a526c8d3c97a2b33160cb | 692a84efd541fdad6885c1da7d782d5809cdf08c | refs/heads/master | 2021-01-18T19:28:49.359429 | 2019-09-08T15:02:21 | 2019-09-08T15:02:21 | 59,921,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | h | #include<iostream>
#include<string.h>
using namespace std;
class Student
{
public:
Student(int i,char na[20],char s)
{num=i;
strcpy(name,na);
sex=s;
}
void display()
{cout>>"num:">>num>>endl;
cout>>"name">>name>>endl;
cout>>"sex">>sex>>endl;
}
pvivate:
int num;
char name[20];
char sex;
};
| [
"[email protected]"
] | |
cf56047af82bbba0bb05097b2b8ac79ef7d59b8d | 8d229d2e04abaf35da511ab39301f0a8723ab0f2 | /tt.h | 23e94559ef61d68c891e95664ec5b5c951f634bc | [] | no_license | Suhanip/School-Management-System | 49d88e59c2637b34d58d380994ba8352a50dd46c | 001013166c70de7dc0b543de9b4b2306e766a11f | refs/heads/master | 2022-11-10T21:29:10.162265 | 2020-06-08T13:29:21 | 2020-06-08T13:29:21 | 270,570,758 | 1 | 0 | null | 2020-06-08T07:26:54 | 2020-06-08T07:22:17 | null | UTF-8 | C++ | false | false | 4,147 | h | #include <bits/stdc++.h>
#include <iostream>
#include <iterator>
#include<fstream>
#include <map>
using namespace std;
class attendance{
public:
int mathat;
int chemat;
int phyat;
int cseat;
int show()
{
cout<<mathat<<setw(16)<<chemat<<setw(16)<<phyat<<setw(16)<<cseat<<endl;
}
};
struct batch{
map <int, string> batch;
} b [3];
int allotment(){
attendance at;
/*
maths teacher can teach cse as well
chem teacher can teach PHY as well
phy teacher can teach CHEM as well
cse teacher can teach maths as well
*/
map <int, string> subject;
subject.insert(pair<int,string>(0,"MATH"));
subject.insert(pair<int,string>(1,"CHEM"));
subject.insert(pair<int,string>(2,"PHY"));
subject.insert(pair<int,string>(3,"CSE"));
map <int, string>::iterator it0, it1, it2, temp;
//predefine schedule of batch 0,1,2 on each day, schedule for a particular batch remain same on each day only changes in absence of teacher
b [0].batch.insert (pair<int, string> (0, "MATH"));
b [0].batch.insert (pair<int, string> (1, "CHEM"));
b [0].batch.insert (pair<int, string> (2, "PHY"));
b [0].batch.insert (pair<int, string> (3, "CSE"));
b [1].batch.insert (pair<int, string> (0, "CSE"));
b [1].batch.insert (pair<int, string> (1, "PHY"));
b [1].batch.insert (pair<int, string> (2, "CHEM"));
b [1].batch.insert (pair<int, string> (3, "MATH"));
b [2].batch.insert (pair<int, string> (0, "CHEM"));
b [2].batch.insert (pair<int, string> (1, "MATH"));
b [2].batch.insert (pair<int, string> (2, "CSE"));
b [2].batch.insert (pair<int, string> (3, "PHY"));
int a [4], i;
cout << "give attendance for 4 teachers,for present enter 1 and for absent 0" << endl;
for (int i = 0; i < 4; i++)
{
cout<<subject[i]<<" TEACHER : "<<endl;
cin>>a[i];
}
fstream file;
file.open("attend.dat",ios::in|ios::out|ios::app|ios::binary);
at.mathat=a[0];
at.chemat=a[1];
at.phyat=a[2];
at.cseat=a[3];
file.write((char *) &at, sizeof(at));
file.close();
int br, j;
int s, v;
//manager has choice to select two batches who will have class on a particular day
cout << "allot classes to batches, choose from batch 0,batch 1,batch 2" << endl;
cin >> s >> v;
int count=0;
int check=1;
int stop=1;
int l = min (s,v);
int u = max (s,v);
for(i = min (s,v); i <= max (s,v); i = max (s,v))
{
br = 0;
if (l == i)
it1 = b [max (s,v)].batch.begin ();
else
it1 = b [min (s, v)].batch.begin ();
temp = b [i].batch.end ();
temp--;
for (j = 0, it0 = b[i].batch.begin (); it0 != b[i].batch.end () && j < 4; j++, ++it0) {
string s1 = temp->second;
string s2 = it1->second;
if (a[j] || ((a[3-j] && s1 != s2)&&(stop==1)))//((3-(it0->first))!=(it1->first)))
cout << "Batch" << i << " period " << j << "is" << it0->second << endl;
else if(a[3-j]&&stop>1)
cout << "Batch" << i << " period " << j << "is" << it0->second << endl;
else
{ if (br <= 1)
{
cout << "Batch" << i << " period " << j << "is free" << endl;
br++;
}
else
cout << "Batch" << i << " period " << j << "is lab" << endl;
}
stop++;
++it1;
temp--;
}
if (i == max (s,v))
break;
}
}
int show_attendance()
{
int a=0;
int b=0;
int c=0;
int d=0;
fstream file;
attendance at;
file.open("attend.dat",ios::in|ios::binary);
file.seekg(0);
//cout<<"0";
cout<<"\n";
cout<<"maths"<<setw(15)<<"chem"<<setw(15)<<"phy"<<setw(15)<<"cse"<<endl;
while(file.read((char*)&at,sizeof(at))){
at.show();
a=a+at.mathat;
b=b+at.chemat;
c=c+at.phyat;
d=d+at.cseat;
}
cout<<setw(40)<<"THE MOST COMMITED TEACHER IS WITH HIGHEST NUMBER OF CLASSES"<<endl;
cout<<a<<setw(16)<<b<<setw(16)<<c<<setw(16)<<d<<endl;
file.close();
}
| [
"[email protected]"
] | |
427c5cb5db665ceef8565f1665dfd77b1a4e7d22 | c91d781eeea756b186b98bce035db2d979c2ac06 | /lib/sparkbox/filesystem/public/sparkbox/filesystem/filesystem_manager.h | d35e12c728a8eb605b4a7385a77fadc6103141eb | [] | no_license | patrick24r/sparkboxHD | 77c8113e197d03162e9ea6df25d529505f560fb3 | 08537b3eb9c5d17168409269550efd165d03ad39 | refs/heads/master | 2023-09-01T11:18:28.176934 | 2023-08-30T03:26:18 | 2023-08-30T03:26:18 | 204,087,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | h | #pragma once
#include "sparkbox/filesystem/filesystem_driver.h"
namespace sparkbox::filesystem {
class FilesystemManager {
public:
FilesystemManager(FilesystemDriver& driver) :
driver_(driver) {
driver_.Init();
}
void RunTest();
void RunDirectoryTest();
private:
FilesystemDriver& driver_;
};
} // namespace sparkbox::filesystem | [
"[email protected]"
] | |
2b7c580692d940688682e125106d6d19d6f8f914 | 806754d57c15d8b9b18119e4cc70e860907b7f2e | /EmbSysLib/Lib/Example/Hardware/Common/cHwEncoder.cpp | 714510c1d12480b6e34d7a2dfa79a8034b1efb94 | [
"MIT"
] | permissive | NXTRobot2k17/Orgel | 9fa26825e4a622b7bd8416c69c685e2b95ba070d | a31b1457d85159bd432f58498bc090ab51c87359 | refs/heads/master | 2021-01-23T05:08:54.323535 | 2017-07-10T15:36:50 | 2017-07-10T15:36:50 | 92,952,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | cpp | //*******************************************************************
/*!
\file cHwEncoder.cpp
\author Thomas Breuer
\date 30.03.2015
\brief Sample of using hardware related classes
*/
//*******************************************************************
#include <stdio.h>
//*******************************************************************
char str[40];
int speed = 0;
int pos = 0;
//*******************************************************************
int main(void)
{
uart.set( "\r\n\ncHwEncoder,"__DATE__ ","__TIME__"\r\n\n" );
while( 1 )
{
char str[40];
speed = enc.get();
pos += speed;
sprintf( str, "speed: %5d, pos: %5d\r", speed, pos );
uart.set( str );
}
}
| [
"[email protected]"
] | |
4f445065ef75df727036ee21642a3e653291d979 | 7abcadaefba80b3f16e18960a216c97dfc47e3d2 | /cx_src/anim/player_rock_x.hpp | c7433f75daa301359fd8510bc6acbcc9578ab050 | [] | no_license | rufaswan/CX | ce9e5545860fc56c216f986b4564bb66f253ab70 | 1f491208ca9cacfa6ff4c651db54039a329e3dbb | refs/heads/master | 2021-09-28T18:26:08.840540 | 2018-11-19T11:29:56 | 2018-11-19T11:29:56 | 9,579,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,742 | hpp | class RockX : public EntityData {
private:
bool m_jumped;
bool m_jump_hold;
int m_jump_cnt;
int m_jump_max;
int m_noshot;
protected:
public:
enum STATE {
STAND = 0,
SHOT = 49,
STD_W = 30,
WALK = 3,
JUMP = 23,
FALL = 26,
LAND = 28,
DASH = 54,
WALL = 39,
CLMB = 42,
WALK_SHOT = 13,
JUMP_SHOT = 32,
FALL_SHOT = 35,
LAND_SHOT = 37,
DASH_SHOT = 57,
WALL_SHOT = 44,
CLMB_SHOT = 47,
TELE = 60,
TELE_IN = 61,
TELE_OUT = 62,
VICTORY = 80
};
bool m_act_fin;
void pl_up( int st, int st_sh, int mv )
{
if ( m_state == st || m_state == st_sh )
switch_state( st );
else
change_state( st );
up( mv, m_dir );
}
void pl_down( int st, int st_sh, int mv )
{
if ( m_state == st || m_state == st_sh )
switch_state( st );
else
change_state( st );
down( mv, m_dir );
}
void pl_left( int st, int st_sh, int mv )
{
if ( m_state == st || m_state == st_sh )
switch_state( st );
else
change_state( st );
left( mv );
}
void pl_right( int st, int st_sh, int mv )
{
if ( m_state == st || m_state == st_sh )
switch_state( st );
else
change_state( st );
right( mv );
}
void act_shot()
{
switch ( m_state )
{
case STAND: change_state( SHOT ); break;
case STD_W: change_state( SHOT ); break;
case WALK: switch_state( WALK_SHOT ); break;
case JUMP: switch_state( JUMP_SHOT ); break;
case FALL: switch_state( FALL_SHOT ); break;
case LAND: switch_state( LAND_SHOT ); break;
case DASH: switch_state( DASH_SHOT ); break;
case WALL: switch_state( WALL_SHOT ); break;
case CLMB: switch_state( CLMB_SHOT ); break;
}
if ( m_noshot > 0 )
return;
int px = ( m_state == SHOT ) ? 0 : 8;
int py = m_pos_y - 16;
if ( m_dir == 'l' )
{
PLAYER_BULLET.push_back( new XBuster );
PLAYER_BULLET.back()->m_id = -1;
PLAYER_BULLET.back()->m_ref_map = m_ref_map;
PLAYER_BULLET.back()->m_ref_tile = m_ref_tile;
PLAYER_BULLET.back()->set( m_rect_x1 - px, py, 'l' );
}
if ( m_dir == 'r' )
{
PLAYER_BULLET.push_back( new XBuster );
PLAYER_BULLET.back()->m_id = -1;
PLAYER_BULLET.back()->m_ref_map = m_ref_map;
PLAYER_BULLET.back()->m_ref_tile = m_ref_tile;
PLAYER_BULLET.back()->set( m_rect_x2 + px, py, 'r' );
}
m_noshot = 4;
}
void act_victory()
{
m_act_fin = false;
if ( is_anim_done() )
m_act_fin = true;
}
void act_tele_in()
{
m_act_fin = false;
if ( m_state == TELE_IN )
{
if ( is_anim_done() )
m_act_fin = true;
}
else
{
// out of map , no wall , seg.fault
if ( m_rect_y1 > 0 )
{
aware_nearby_walls();
pl_down( TELE, TELE, m_vel_y );
if ( m_is_wall_down )
change_state( TELE_IN );
}
else
{
change_state( TELE );
move( 0, m_vel_y, m_dir );
}
}
}
void act_fall( gamesys* sys )
{
m_jumped = true;
m_jump_cnt = 0;
pl_down( FALL, FALL_SHOT, m_vel_y );
if ( sys->m_Dleft ) left ( m_vel_x );
else if ( sys->m_Dright ) right( m_vel_x );
}
void act_jump( gamesys* sys )
{
if ( m_jumped )
{
if ( m_jump_cnt > 0 )
{
m_jump_cnt -= 10;
if ( m_is_wall_up )
m_jump_cnt = 0;
}
}
else // first press
{
m_jumped = true;
m_jump_cnt = m_jump_max;
}
int acce_y = (m_vel_y * m_jump_cnt) / m_jump_max;
pl_up( JUMP, JUMP_SHOT, acce_y );
if ( sys->m_Dleft ) left ( m_vel_x );
else if ( sys->m_Dright ) right( m_vel_x );
}
void act_stand()
{
change_state( STAND );
}
void ai_update()
{
aware_nearby_walls();
if ( m_is_wall_down )
{
m_jumped = false;
m_jump_cnt = 0;
change_state( STAND );
}
else
{
pl_down( FALL, FALL_SHOT, m_vel_y );
}
}
void pl_update( gamesys* sys )
{
aware_nearby_walls();
if ( m_noshot > 0 ) m_noshot--;
// ground control
if ( m_is_wall_down )
{
m_jumped = false;
m_jump_cnt = 0;
if ( sys->m_Dup )
act_jump( sys );
if ( sys->m_Dleft )
pl_left ( WALK, WALK_SHOT, m_vel_x );
else if ( sys->m_Dright )
pl_right( WALK, WALK_SHOT, m_vel_x );
else
change_state( STAND );
}
// air control
else
{
if ( m_jump_cnt > 0 )
act_jump( sys );
else
act_fall( sys );
}
if ( sys->m_Ddown )
act_shot();
}
RockX()
{
m_class_name = "RockX";
m_anim.load_def("cx_data/anim/player_rock_x/rock.def");
m_vel_x = 4;
m_vel_y = 12;
m_jumped = true;
m_jump_cnt = 0;
m_jump_max = 100;
m_noshot = 0;
m_act_fin = false;
}
}; // class RockX
| [
"[email protected]"
] | |
4c4b7cbb51a3ee9aadd00263bf729af4b7da3d6b | 31d2ff5b2d70ad6afc047c31339875b4ab4e4975 | /chrome/browser/vr/ui_input_manager.cc | fd571342cc33a8979ee5a34f8fe1007eba4da9a4 | [
"BSD-3-Clause"
] | permissive | DalavanCloud/chromium | 3d0934237ac6604158ed8db649d5e08d95e6c702 | 6a4703692d4e6f1480cc9d32a8677ff8c2a51c16 | refs/heads/master | 2023-01-01T17:13:36.512656 | 2018-07-13T14:37:55 | 2018-07-13T14:37:55 | 140,859,288 | 1 | 0 | null | 2018-07-13T14:48:30 | 2018-07-13T14:48:30 | null | UTF-8 | C++ | false | false | 17,403 | 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 "chrome/browser/vr/ui_input_manager.h"
#include <algorithm>
#include "base/containers/adapters.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "chrome/browser/vr/elements/ui_element.h"
#include "chrome/browser/vr/input_event.h"
#include "chrome/browser/vr/model/controller_model.h"
#include "chrome/browser/vr/model/reticle_model.h"
#include "chrome/browser/vr/model/text_input_info.h"
#include "chrome/browser/vr/ui_renderer.h"
#include "chrome/browser/vr/ui_scene.h"
namespace vr {
namespace {
constexpr gfx::PointF kInvalidTargetPoint =
gfx::PointF(std::numeric_limits<float>::max(),
std::numeric_limits<float>::max());
constexpr float kControllerQuiescenceAngularThresholdDegrees = 3.5f;
constexpr float kControllerQuiescenceTemporalThresholdSeconds = 1.2f;
constexpr float kControllerFocusThresholdSeconds = 1.0f;
bool IsCentroidInViewport(const gfx::Transform& view_proj_matrix,
const gfx::Transform& world_matrix) {
if (world_matrix.IsIdentity()) {
// Uninitialized matrices are considered out of the viewport.
return false;
}
gfx::Transform m = view_proj_matrix * world_matrix;
gfx::Point3F o;
m.TransformPoint(&o);
return o.x() > -1.0f && o.x() < 1.0f && o.y() > -1.0f && o.y() < 1.0f;
}
bool IsScrollOrFling(const InputEventList& list) {
if (list.empty()) {
return false;
}
// We assume that we only need to consider the first gesture in the list.
auto type = list.front()->type();
return InputEvent::IsScrollEventType(type) ||
type == InputEvent::kFlingCancel;
}
void HitTestElements(UiScene* scene,
ReticleModel* reticle_model,
HitTestRequest* request) {
std::vector<const UiElement*> elements = scene->GetElementsToHitTest();
std::vector<const UiElement*> sorted =
UiRenderer::GetElementsInDrawOrder(elements);
for (const auto* element : base::Reversed(sorted)) {
DCHECK(element->IsHitTestable());
HitTestResult result;
element->HitTest(*request, &result);
if (result.type != HitTestResult::Type::kHits) {
continue;
}
reticle_model->target_element_id = element->id();
reticle_model->target_local_point = result.local_hit_point;
reticle_model->target_point = result.hit_point;
reticle_model->cursor_type = element->cursor_type();
break;
}
}
} // namespace
UiInputManager::UiInputManager(UiScene* scene) : scene_(scene) {}
UiInputManager::~UiInputManager() {}
void UiInputManager::HandleInput(base::TimeTicks current_time,
const RenderInfo& render_info,
const ControllerModel& controller_model,
ReticleModel* reticle_model,
InputEventList* input_event_list) {
UpdateQuiescenceState(current_time, controller_model);
UpdateControllerFocusState(current_time, render_info, controller_model);
reticle_model->target_element_id = 0;
reticle_model->target_local_point = kInvalidTargetPoint;
UiElement* target_element =
GetTargetElement(controller_model, reticle_model, *input_event_list);
auto element_local_point = reticle_model->target_local_point;
if (input_capture_element_id_)
element_local_point =
GetCapturedElementHitPoint(reticle_model->target_point);
// Sending end and cancel events.
SendFlingCancel(input_event_list, element_local_point);
SendScrollEnd(input_event_list, element_local_point,
controller_model.touchpad_button_state);
SendButtonUp(element_local_point, controller_model.touchpad_button_state,
controller_model.last_button_timestamp);
SendHoverLeave(target_element, controller_model.last_orientation_timestamp);
// Sending update events.
if (in_scroll_) {
SendScrollUpdate(input_event_list, element_local_point);
} else if (in_click_) {
SendTouchMove(element_local_point,
controller_model.last_orientation_timestamp);
} else {
SendHoverMove(target_element, reticle_model->target_local_point,
controller_model.last_orientation_timestamp);
}
// Sending begin events.
SendHoverEnter(target_element, reticle_model->target_local_point,
controller_model.last_orientation_timestamp);
SendScrollBegin(target_element, input_event_list, element_local_point);
SendButtonDown(target_element, reticle_model->target_local_point,
controller_model.touchpad_button_state,
controller_model.last_button_timestamp);
previous_button_state_ = controller_model.touchpad_button_state;
}
void UiInputManager::OnPause() {
if (hover_target_id_) {
UiElement* prev_hovered = scene_->GetUiElementById(hover_target_id_);
if (prev_hovered)
prev_hovered->OnHoverLeave(base::TimeTicks::Now());
hover_target_id_ = 0;
}
}
void UiInputManager::SendFlingCancel(InputEventList* input_event_list,
const gfx::PointF& target_point) {
if (!fling_target_id_) {
return;
}
if (input_event_list->empty() ||
(input_event_list->front()->type() != InputEvent::kFlingCancel)) {
return;
}
// Scrolling currently only supported on content window.
UiElement* element = scene_->GetUiElementById(fling_target_id_);
if (element) {
DCHECK(element->scrollable());
element->OnFlingCancel(std::move(input_event_list->front()), target_point);
}
input_event_list->erase(input_event_list->begin());
fling_target_id_ = 0;
}
void UiInputManager::SendScrollEnd(InputEventList* input_event_list,
const gfx::PointF& target_point,
ButtonState button_state) {
if (!in_scroll_) {
return;
}
DCHECK_GT(input_capture_element_id_, 0);
UiElement* element = scene_->GetUiElementById(input_capture_element_id_);
if (previous_button_state_ != button_state &&
button_state == ButtonState::DOWN) {
DCHECK_GT(input_event_list->size(), 0LU);
DCHECK_EQ(input_event_list->front()->type(), InputEvent::kScrollEnd);
}
DCHECK(!element || element->scrollable());
if (input_event_list->empty() ||
input_event_list->front()->type() != InputEvent::kScrollEnd) {
return;
}
DCHECK_LE(input_event_list->size(), 1LU);
fling_target_id_ = input_capture_element_id_;
element->OnScrollEnd(std::move(input_event_list->front()), target_point);
input_event_list->erase(input_event_list->begin());
input_capture_element_id_ = 0;
in_scroll_ = false;
}
void UiInputManager::SendScrollBegin(UiElement* target,
InputEventList* input_event_list,
const gfx::PointF& target_point) {
if (in_scroll_ || !target || !target->scrollable())
return;
if (input_event_list->empty() ||
input_event_list->front()->type() != InputEvent::kScrollBegin) {
return;
}
input_capture_element_id_ = target->id();
in_scroll_ = true;
target->OnScrollBegin(std::move(input_event_list->front()), target_point);
input_event_list->erase(input_event_list->begin());
}
void UiInputManager::SendScrollUpdate(InputEventList* input_event_list,
const gfx::PointF& target_point) {
DCHECK(input_capture_element_id_);
if (input_event_list->empty() ||
(input_event_list->front()->type() != InputEvent::kScrollUpdate)) {
return;
}
// Scrolling currently only supported on content window.
UiElement* element = scene_->GetUiElementById(input_capture_element_id_);
if (element) {
DCHECK(element->scrollable());
element->OnScrollUpdate(std::move(input_event_list->front()), target_point);
}
input_event_list->erase(input_event_list->begin());
}
void UiInputManager::SendHoverLeave(UiElement* current_target,
base::TimeTicks timestamp) {
if (hover_target_id_ &&
(!current_target || current_target->id() != hover_target_id_)) {
UiElement* prev_hovered = scene_->GetUiElementById(hover_target_id_);
if (prev_hovered)
prev_hovered->OnHoverLeave(timestamp);
hover_target_id_ = 0;
}
}
void UiInputManager::SendHoverEnter(UiElement* target,
const gfx::PointF& target_point,
base::TimeTicks timestamp) {
if (!target || target->id() == hover_target_id_)
return;
if ((in_click_ || in_scroll_) && target->id() != input_capture_element_id_)
return;
target->OnHoverEnter(target_point, timestamp);
hover_target_id_ = target->id();
}
void UiInputManager::SendHoverMove(UiElement* target,
const gfx::PointF& target_point,
base::TimeTicks timestamp) {
if (target && target->id() == hover_target_id_)
target->OnHoverMove(target_point, timestamp);
}
void UiInputManager::SendButtonUp(const gfx::PointF& target_point,
ButtonState button_state,
base::TimeTicks timestamp) {
if (!in_click_ || previous_button_state_ == button_state ||
button_state != ButtonState::UP) {
return;
}
in_click_ = false;
if (!input_capture_element_id_)
return;
UiElement* element = scene_->GetUiElementById(input_capture_element_id_);
if (element) {
element->OnButtonUp(target_point, timestamp);
// Clicking outside of the focused element causes it to lose focus.
if (element->id() != focused_element_id_ && element->focusable())
UnfocusFocusedElement();
}
input_capture_element_id_ = 0;
}
void UiInputManager::SendButtonDown(UiElement* target,
const gfx::PointF& target_point,
ButtonState button_state,
base::TimeTicks timestamp) {
if (previous_button_state_ == button_state ||
button_state != ButtonState::DOWN) {
return;
}
in_click_ = true;
if (target) {
target->OnButtonDown(target_point, timestamp);
input_capture_element_id_ = target->id();
} else {
input_capture_element_id_ = 0;
}
}
void UiInputManager::SendTouchMove(const gfx::PointF& target_point,
base::TimeTicks timestamp) {
if (!input_capture_element_id_)
return;
UiElement* element = scene_->GetUiElementById(input_capture_element_id_);
if (element)
element->OnTouchMove(target_point, timestamp);
}
UiElement* UiInputManager::GetTargetElement(
const ControllerModel& controller_model,
ReticleModel* reticle_model,
const InputEventList& input_event_list) const {
// If we place the reticle based on elements intersecting the controller beam,
// we can end up with the reticle hiding behind elements, or jumping laterally
// in the field of view. This is physically correct, but hard to use. For
// usability, do the following instead:
//
// - Project the controller laser onto a distance-limiting sphere.
// - Create a vector between the eyes and the point on the sphere.
// - If any UI elements intersect this vector, and are within the bounding
// sphere, choose the element that is last in scene draw order (which is
// typically the closest to the eye).
// Compute the distance from the eyes to the distance limiting sphere. Note
// that the sphere is centered at the controller, rather than the eye, for
// simplicity.
float distance = scene_->background_distance();
reticle_model->target_point =
controller_model.laser_origin +
gfx::ScaleVector3d(controller_model.laser_direction, distance);
// Determine which UI element (if any) intersects the line between the ray
// origin and the controller target position. The ray origin will typically be
// the world origin (roughly the eye) to make targeting with a real controller
// more intuitive. For testing, however, we occasionally hit test along the
// laser precisely since this geometric accuracy is important and we are not
// dealing with a physical controller.
gfx::Point3F ray_origin;
if (hit_test_strategy_ == HitTestStrategy::PROJECT_TO_LASER_ORIGIN_FOR_TEST) {
ray_origin = controller_model.laser_origin;
}
float distance_limit = (reticle_model->target_point - ray_origin).Length();
HitTestRequest request;
request.ray_origin = ray_origin;
request.ray_target = reticle_model->target_point;
request.max_distance_to_plane = distance_limit;
HitTestElements(scene_, reticle_model, &request);
// TODO(vollick): support multiple dispatch. We may want to, for example,
// dispatch raw events to several elements we hit (imagine nested horizontal
// and vertical scrollers). Currently, we only dispatch to one "winner".
UiElement* target_element =
scene_->GetUiElementById(reticle_model->target_element_id);
if (target_element) {
if (IsScrollOrFling(input_event_list) && !input_capture_element_id_) {
DCHECK(!in_scroll_ && !in_click_);
UiElement* ancestor = target_element;
while (!ancestor->scrollable() && ancestor->parent())
ancestor = ancestor->parent();
if (ancestor->scrollable())
target_element = ancestor;
}
}
return target_element;
}
void UiInputManager::UpdateQuiescenceState(
base::TimeTicks current_time,
const ControllerModel& controller_model) {
// Update quiescence state.
gfx::Point3F old_position;
gfx::Point3F old_forward_position(0, 0, -1);
last_significant_controller_transform_.TransformPoint(&old_position);
last_significant_controller_transform_.TransformPoint(&old_forward_position);
gfx::Vector3dF old_forward = old_forward_position - old_position;
old_forward.GetNormalized(&old_forward);
gfx::Point3F new_position;
gfx::Point3F new_forward_position(0, 0, -1);
controller_model.transform.TransformPoint(&new_position);
controller_model.transform.TransformPoint(&new_forward_position);
gfx::Vector3dF new_forward = new_forward_position - new_position;
new_forward.GetNormalized(&new_forward);
float angle = AngleBetweenVectorsInDegrees(old_forward, new_forward);
if (angle > kControllerQuiescenceAngularThresholdDegrees || in_click_ ||
in_scroll_) {
controller_quiescent_ = false;
last_significant_controller_transform_ = controller_model.transform;
last_significant_controller_update_time_ = current_time;
} else if ((current_time - last_significant_controller_update_time_)
.InSecondsF() >
kControllerQuiescenceTemporalThresholdSeconds) {
controller_quiescent_ = true;
}
}
void UiInputManager::UpdateControllerFocusState(
base::TimeTicks current_time,
const RenderInfo& render_info,
const ControllerModel& controller_model) {
if (!IsCentroidInViewport(render_info.left_eye_model.view_proj_matrix,
controller_model.transform) &&
!IsCentroidInViewport(render_info.right_eye_model.view_proj_matrix,
controller_model.transform)) {
last_controller_outside_viewport_time_ = current_time;
controller_resting_in_viewport_ = false;
return;
}
controller_resting_in_viewport_ =
(current_time - last_controller_outside_viewport_time_).InSecondsF() >
kControllerFocusThresholdSeconds;
}
void UiInputManager::UnfocusFocusedElement() {
if (!focused_element_id_)
return;
UiElement* focused = scene_->GetUiElementById(focused_element_id_);
if (focused && focused->focusable()) {
focused->OnFocusChanged(false);
}
focused_element_id_ = 0;
}
void UiInputManager::RequestFocus(int element_id) {
if (element_id == focused_element_id_)
return;
UnfocusFocusedElement();
UiElement* focused = scene_->GetUiElementById(element_id);
if (!focused || !focused->focusable())
return;
focused_element_id_ = element_id;
focused->OnFocusChanged(true);
}
void UiInputManager::RequestUnfocus(int element_id) {
if (element_id != focused_element_id_)
return;
UnfocusFocusedElement();
}
void UiInputManager::OnInputEdited(const EditedText& info) {
UiElement* focused = scene_->GetUiElementById(focused_element_id_);
if (!focused)
return;
DCHECK(focused->focusable());
focused->OnInputEdited(info);
}
void UiInputManager::OnInputCommitted(const EditedText& info) {
UiElement* focused = scene_->GetUiElementById(focused_element_id_);
if (!focused || !focused->focusable())
return;
DCHECK(focused->focusable());
focused->OnInputCommitted(info);
}
void UiInputManager::OnKeyboardHidden() {
UnfocusFocusedElement();
}
gfx::PointF UiInputManager::GetCapturedElementHitPoint(
const gfx::Point3F& target_point) const {
UiElement* captured_element =
scene_->GetUiElementById(input_capture_element_id_);
if (captured_element && captured_element->IsVisible()) {
HitTestRequest request;
request.ray_target = target_point;
request.max_distance_to_plane = 2 * scene_->background_distance();
HitTestResult result;
captured_element->HitTest(request, &result);
if (result.type != HitTestResult::Type::kNone)
return result.local_hit_point;
}
return kInvalidTargetPoint;
}
} // namespace vr
| [
"[email protected]"
] | |
dbf6b548c9dbd976c15a3d0f095d03b972c33499 | 112f8258e211e7c565ae6daebe297ee78ff1722e | /Chapter 03/Ex3_12.cpp | 2790ba3e68b5ba8bc74fe997c69918cf6692eed0 | [] | no_license | vukhuyen/CPlusPlus | c4a39356eaa6310ad7abb5baa824c833ab26dfdc | 28949fff0033c4f34e84c4853879c30da8eda3e8 | refs/heads/master | 2021-06-05T21:09:27.412519 | 2017-12-14T00:54:23 | 2017-12-14T00:54:23 | 11,208,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | // Ex3_12.cpp
// Using a while loop to compute an average
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
double value {}; // Value entered stored here
double sum {}; // Total of values accumulated here
int i {}; // Count of number of values
char indicator { 'y' }; // Continue or not?
while('y' == indicator) // Loop as long as y is entered
{
cout << endl
<< "Enter a value: ";
cin >> value; // Read a value
++i; // Increment count
sum += value; // Add current input to total
cout << endl
<< "Do you want to enter another value (enter y or n)? ";
cin >> indicator; // Read indicator
}
cout << endl
<< "The average of the " << i
<< " values you entered is " << sum/i << "."
<< endl;
return 0;
}
| [
"[email protected]"
] | |
5bcdbf5c0391795126f2168147285418785b7d6f | b0dc293c331c50b9082b1c1af037b07b7d8d4bc4 | /rkdnseprmfwk.cpp | fe5c8bda6fc0f9398f746e400aa7724eb708ae31 | [] | no_license | Ironee1617/Programmers | 477c7f686dbe158223346743a47cb0dfc0b28d37 | 335367e20f600f7b3bdbf6d4ddf52a17412ea321 | refs/heads/main | 2023-05-29T02:59:35.296512 | 2021-06-02T15:08:38 | 2021-06-02T15:08:38 | 359,445,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include <string>
#include <vector>
using namespace std;
string solution(string s) {
string answer = "";
int a = s.size();
if (a % 2 == 0) {
a /= 2;
answer = s.substr(a - 1, 2);
}
else {
a /= 2;
answer = s.at(a);
}
return answer;
} | [
"[email protected]"
] | |
5fc3251f9062ec640dac4e1baffa921f77cbc29e | 264198f21472fae6d78aedcaf39295cc2d5a5865 | /Source/MyActionRPG/Struct/ItemInfo/ItemInfo.h | 9cea643eb070603c24335cbb5ef4c4eccf4495f8 | [] | no_license | Phudal/MyActionRPG | 271f76b589dd35ddc33702677559ac40987e0722 | 0b1fb98de3f00a1a400951712db9442eecc37330 | refs/heads/main | 2023-07-13T03:14:07.321020 | 2021-08-06T11:36:48 | 2021-08-06T11:36:48 | 384,091,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,482 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataTable.h"
#include "Enum/ItemType.h"
#include "ItemInfo.generated.h"
USTRUCT()
struct MYACTIONRPG_API FItemInfo : public FTableRowBase
{
GENERATED_USTRUCT_BODY()
public:
// 아이템 코드
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FName ItemCode;
// 아이템 타입
// 기타, 소비, 장비
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
EItemType ItemType;
// 아이템 이름
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FText ItemName;
// 아이템 설명
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FText ItemDescription;
// 아이템 이미지 경로
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FSoftObjectPath ItemImagePath;
// 슬롯 최대 개수
/// - 슬롯에 담을 수 있는 최대 개수를 나타냄
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
int32 MaxSlotCount;
// 아이템 판매 가격
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
int32 Price;
public:
FORCEINLINE bool IsEmpty() const
{
return ItemCode.IsNone();
}
FORCEINLINE bool operator==(FItemInfo& itemInfo)
{
return (this->ItemCode == itemInfo.ItemCode);
}
FORCEINLINE bool operator!=(FItemInfo& itemInfo)
{
return (this->ItemCode != itemInfo.ItemCode);
}
};
| [
"[email protected]"
] | |
222022400b69bbf3a3cbfde1f90bcf9384c80f4e | 8fb3a7a95985e7d61aec85b201a96265e599d44c | /IR_Led.ino | e76880b22669cac92483b33876ed02fad85477f7 | [
"Apache-2.0"
] | permissive | aksharsramesh/Amaze2019 | a2f596939d2ccb821e449de71dd7facbe00337af | 80e2c05e169d6d3042dc06cf9dbd02d074e11479 | refs/heads/master | 2020-04-25T00:13:32.319638 | 2019-03-21T11:12:46 | 2019-03-21T11:12:46 | 172,371,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | ino | int ir = 13, led = 10, a;
void setup() {
pinMode(ir,INPUT);
pinMode(led,OUTPUT);
Serial.begin(9600);
}
void loop() {
a= digitalRead(ir);
Serial.println(a);
if(a==1)
{
digitalWrite(led,HIGH);
}
else
{
digitalWrite(led,LOW);
}
}
| [
"[email protected]"
] | |
e31b879618f3750c5aaf1fa60d3f9a6d1fed0672 | ef66dadf885506c94897f7c6727c35a6b5d9b7d3 | /art-extension/compiler/optimizing/extensions/passes/peeling.cc | f8549e1f95dd77e2839523f7398aabf5e275c740 | [
"Apache-2.0",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pramulkant/https-github.com-android-art-intel-marshmallow | aef8d075498f3c19712403c271b55ea457e053ec | 87e8c22f248164780b92aaa0cdea14bf6cda3859 | refs/heads/master | 2021-01-12T05:00:35.783906 | 2016-11-07T08:34:41 | 2016-11-07T08:34:41 | 77,827,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,470 | cc | /*
* Copyright (C) 2015 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 "ext_utility.h"
#include "graph_x86.h"
#include "loop_iterators.h"
#include "peeling.h"
namespace art {
static constexpr size_t kLeastRequiredCandidateCount = 1u;
bool HLoopPeeling::ShouldPeel(HLoopInformation_X86* loop) {
DCHECK(loop->IsInner());
size_t num_candidate_instr = 0u;
if (loop->GetBlocks().NumSetBits() <= 2u) {
// Check to see if peeling may be worth it - these are cases where GVN may do a better job
// by eliminating throwers/getters inside of a loop.
for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
HBasicBlock* block = it_loop.Current();
for (HInstruction* instruction = block->GetFirstInstruction();
instruction != nullptr;
instruction = instruction->GetNext()) {
// Check if thrower or heap mutator/reader first.
// We also handle LoadString and LoadClass specially because they may not fall
// in either category but in reality are useful to hoist since they have no
// IR inputs and will reload same thing over and over.
if (instruction->CanThrow() || instruction->HasSideEffects() ||
instruction->GetSideEffects().HasDependencies() ||
instruction->IsLoadClass() || instruction->IsLoadString()) {
bool all_inputs_from_outside = true;
// Now check that all inputs are from outside.
for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
HInstruction* input = instruction->InputAt(i);
if (loop->Contains(*input->GetBlock())) {
all_inputs_from_outside = false;
break;
}
}
// If all inputs from outside, count that we found a candidate which makes
// peeling worth it.
if (all_inputs_from_outside) {
num_candidate_instr++;
if (num_candidate_instr >= kLeastRequiredCandidateCount) {
return true;
}
}
}
}
}
}
return false;
}
void HLoopPeeling::Run() {
HOnlyInnerLoopIterator inner_iter(GRAPH_TO_GRAPH_X86(graph_)->GetLoopInformation());
PRINT_PASS_OSTREAM_MESSAGE(this, "Start " << GetMethodName(graph_));
while (!inner_iter.Done()) {
HLoopInformation_X86* inner_loop = inner_iter.Current();
// If the loop should be peeled, make an attempt to do it.
if (ShouldPeel(inner_loop)) {
if (inner_loop->IsPeelable(this)) {
inner_loop->PeelHead(this);
MaybeRecordStat(MethodCompilationStat::kIntelLoopPeeled);
PRINT_PASS_OSTREAM_MESSAGE(this, "Successfully peeled loop with header block " <<
inner_loop->GetHeader()->GetBlockId() << '.');
}
}
inner_iter.Advance();
}
PRINT_PASS_OSTREAM_MESSAGE(this, "End " << GetMethodName(graph_));
}
} // namespace art
| [
"[email protected]"
] | |
ba4c4a5cf2659eff99f4c358cae8eaf06a262255 | f6c14d0a503f3145e6d84c400e8b91418b626afc | /projetoPONG.ino | f50cb1d9e58368eba0dd5a9349c41a453caf2039 | [] | no_license | VinniciusL/POO | ec79683cb1e0597ea667d91850d3b42ddf01a0c2 | e80f255267ed8754d5af11d3d9ebbf2d124e932f | refs/heads/master | 2020-06-27T04:27:43.679367 | 2019-11-22T11:13:51 | 2019-11-22T11:13:51 | 199,844,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,959 | ino |
// =============================================================================================================
// --- Declaração dos Caracteres Customizados ---
// =============================================================================================================
// -- Caracteres para a Parede --
byte wallA[8] = {
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011
};
byte wallB[8] = {
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011,
0b00011
};
// =============================================================================================================
// -- Caracteres para o Jogador --
byte paddle1[8] = {
0b10000,
0b10000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte paddle2[8] = {
0b00000,
0b10000,
0b10000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte paddle3[8] = {
0b00000,
0b00000,
0b10000,
0b10000,
0b10000,
0b00000,
0b00000,
0b00000
};
byte paddle4[8] = {
0b00000,
0b00000,
0b00000,
0b10000,
0b10000,
0b10000,
0b00000,
0b00000
};
byte paddle5[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b10000,
0b10000,
0b00000
};
byte paddle6[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b10000,
0b10000
};
byte paddle7a[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b10000
};
byte paddle7b[8] = {
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte paddle8a[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000
};
byte paddle8b[8] = {
0b10000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
// =============================================================================================================
// -- Caracteres para a Bola --
// Row 1, Each Column
byte ball00[8] = {
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball01[8] = {
0b01000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball02[8] = {
0b00100,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball03[8] = {
0b00010,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball04[8] = {
0b00001,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
// Row 2, Each Column
byte ball10[8] = {
0b00000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball11[8] = {
0b00000,
0b01000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball12[8] = {
0b00000,
0b00100,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball13[8] = {
0b00000,
0b00010,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball14[8] = {
0b00000,
0b00001,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
// Row 3, Each Column
byte ball20[8] = {
0b00000,
0b00000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball21[8] = {
0b00000,
0b00000,
0b01000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball22[8] = {
0b00000,
0b00000,
0b00100,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball23[8] = {
0b00000,
0b00000,
0b00010,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball24[8] = {
0b00000,
0b00000,
0b00001,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
// Row 4, Each Column
byte ball30[8] = {
0b00000,
0b00000,
0b00000,
0b10000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball31[8] = {
0b00000,
0b00000,
0b00000,
0b01000,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball32[8] = {
0b00000,
0b00000,
0b00000,
0b00100,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball33[8] = {
0b00000,
0b00000,
0b00000,
0b00010,
0b00000,
0b00000,
0b00000,
0b00000
};
byte ball34[8] = {
0b00000,
0b00000,
0b00000,
0b00001,
0b00000,
0b00000,
0b00000,
0b00000
};
// Row 5, Each Column
byte ball40[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b00000,
0b00000,
0b00000
};
byte ball41[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b01000,
0b00000,
0b00000,
0b00000
};
byte ball42[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00100,
0b00000,
0b00000,
0b00000
};
byte ball43[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00010,
0b00000,
0b00000,
0b00000
};
byte ball44[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00001,
0b00000,
0b00000,
0b00000
};
// Row 6, Each Column
byte ball50[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b00000,
0b00000
};
byte ball51[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b01000,
0b00000,
0b00000
};
byte ball52[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00100,
0b00000,
0b00000
};
byte ball53[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00010,
0b00000,
0b00000
};
byte ball54[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00001,
0b00000,
0b00000
};
// Row 7, Each Column
byte ball60[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000,
0b00000
};
byte ball61[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b01000,
0b00000
};
byte ball62[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00100,
0b00000
};
byte ball63[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00010,
0b00000
};
byte ball64[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00001,
0b00000
};
// Row 8, Each Column
byte ball70[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b10000
};
byte ball71[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b01000
};
byte ball72[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00100
};
byte ball73[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00010
};
byte ball74[8] = {
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
0b00001
};
// =============================================================================================================
// --- Bibliotecas Auxiliares ---
#include <Wire.h> //INCLUSÃO DE BIBLIOTECA
#include <LiquidCrystal_I2C.h> //INCLUSÃO DE BIBLIOTECA DO MODULOI2C
// =============================================================================================================
// --- Hardware do LCD ---
// --- Utilização do MODULOI2C para mostrar o jogo --- #1 Mudança
LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
// Arduino Pins
const int compPoint1 = 5; // LED1 pin
const int compPoint2 = 6; // LED2 pin
const int compPoint3 = 7; // LED3 pin
const int button = 9; // Push button (pulled low)
// Globals
int upDownDir; // Up/Down State of the Ball
int leftRightDir; // Left/Right State of the Ball
int angle; // Angle with respect to the horizontal (X) axis the ball is travelling
int pontuacao = 0x00;
float azimuth; // Clockwise angle from the Vertical (Y) axis the ball is travelling
boolean gameStarted; // Game State
int paddlePos; // Position of the player's paddle (14 possible positions)
int ballPos[2]; // X, Y coordinates of the bal
int points; // Keeps track of how many balls have passed the players boundary (game is to 3)
float distance; // Distance between successive positions of the ball
float totalDistance; // Total distance from the ball's last boundary deflection (control) point, this is used to properly calculate the ball's trajectory
// Game Control Variables (CHANGE TO SUIT YOUR DESIRE)
float speedIncreasePercent = 20; // Speed increase percentage when the player successfully bounces the ball off their paddle
int gameAngleMin = 10; // Min trajectory angle for the ball
int gameAngleMax = 50; // Max trajectory angle for the ball
float initialDist = 1.0; // Initial Distance value that is used at the start of a game (pick a bigger number for the ball to travel faster at the start)
void setup() {
gameStarted = false;
// set up the lcd's number of columns and rows:
lcd.begin(16, 2);
// set LED pins as output and turned them off
pinMode(compPoint1, OUTPUT);
pinMode(compPoint2, OUTPUT);
pinMode(compPoint3, OUTPUT);
digitalWrite(compPoint1, LOW);
digitalWrite(compPoint2, LOW);
digitalWrite(compPoint3, LOW);
// set button pin as input
pinMode(button, INPUT_PULLUP);
// calculate an initial trajectory angle for the ball
calcInitialDir();
// set the ball's initial position to centre screen
ballPos[0] = 39;
ballPos[1] = 7;
// initialize control variables to default values
distance = initialDist;
totalDistance = distance;
points = 0;
// display message for player to press the button to start the game
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Aperte o botao ");
lcd.setCursor(0,1);
lcd.print("para iniciar!!! ");
}
void loop() {
// check the game state
if (gameStarted == true) // Game is started
{
ballUpdate(); // Update the ball's position
// Check if game to 3 has ended
if (gameStarted == true) {
playerPaddleUpdate(); // Update the player's paddle position
// Check for button press to reset the game
if (digitalRead(button) == LOW) {
delay(250);
setup();
}
}
delay(100);
}
else // Game has not started
{
// Check for button press
if (digitalRead(button) == LOW)
{
// Start a game (toggle game state) and initialize the game board
gameStarted = true;
drawInitial();
}
}
}
// Function for drawing the initial state of the game board
void drawInitial() {
lcd.clear();
// Draw the pong Wall chars
lcd.createChar(0, wallA);
lcd.setCursor(0,0);
lcd.write((byte)0);
lcd.createChar(1, wallB);
lcd.setCursor(0,1);
lcd.write(1);
// Draw the ball in it's default starting position
lcd.createChar(2, ball04);
lcd.setCursor(7,1);
lcd.write(2);
delay(250);
}
// Function for determining the ball's trajectory angle
void calcInitialDir() {
// randomly get a 1 or -1 for the up/down and left/right directions and the ball's angle of travel from the X axis
upDownDir = 0;
leftRightDir = 0;
while (upDownDir == 0) {
upDownDir = random(-1,2);
}
while (leftRightDir == 0) {
leftRightDir = random(-1,2);
}
// Randomly grab a game angle between Min and Max values
randomSeed(analogRead(1));
angle = random(gameAngleMin,gameAngleMax + 1);
}
// Function for updating the player's paddle position based on the potentiometer's value
void playerPaddleUpdate() {
// read the pot on A0 for paddle position
int potReading = analogRead(A0);
// map and constrain the pot's value to represent one of the 14 possible paddle positions
paddlePos = constrain(map(potReading, 0, 950, 1, 14), 1, 14);
//clear the paddle
lcd.setCursor(15,0);
lcd.print(" ");
lcd.setCursor(15,1);
lcd.print(" ");
//draw new paddle position using the correct custom LCD character(s)
if (paddlePos == 1)
{
lcd.createChar(6, paddle6);
lcd.setCursor(15,1);
lcd.write(6);
}
else if (paddlePos == 2)
{
lcd.createChar(7, paddle5);
lcd.setCursor(15,1);
lcd.write(7);
}
else if (paddlePos == 3)
{
lcd.createChar(6, paddle4);
lcd.setCursor(15,1);
lcd.write(6);
}
else if (paddlePos == 4)
{
lcd.createChar(7, paddle3);
lcd.setCursor(15,1);
lcd.write(7);
}
else if (paddlePos == 5)
{
lcd.createChar(6, paddle2);
lcd.setCursor(15,1);
lcd.write(6);
}
else if (paddlePos == 6)
{
lcd.createChar(7, paddle1);
lcd.setCursor(15,1);
lcd.write(7);
}
else if (paddlePos == 7)
{
lcd.createChar(6, paddle8a);
lcd.setCursor(15,0);
lcd.write(6);
lcd.createChar(7, paddle8b);
lcd.setCursor(15,1);
lcd.write(7);
}
else if (paddlePos == 8)
{
lcd.createChar(6, paddle7a);
lcd.setCursor(15,0);
lcd.write(6);
lcd.createChar(7, paddle7b);
lcd.setCursor(15,1);
lcd.write(7);
}
else if (paddlePos == 9)
{
lcd.createChar(6, paddle6);
lcd.setCursor(15,0);
lcd.write(6);
}
else if (paddlePos == 10)
{
lcd.createChar(7, paddle5);
lcd.setCursor(15,0);
lcd.write(7);
}
else if (paddlePos == 11)
{
lcd.createChar(6, paddle4);
lcd.setCursor(15,0);
lcd.write(6);
}
else if (paddlePos == 12)
{
lcd.createChar(7, paddle3);
lcd.setCursor(15,0);
lcd.write(7);
}
else if (paddlePos == 13)
{
lcd.createChar(6, paddle2);
lcd.setCursor(15,0);
lcd.write(6);
}
else if (paddlePos == 14)
{
lcd.createChar(7, paddle1);
lcd.setCursor(15,0);
lcd.write(7);
}
}
// Function for updating the ball's position on the LCD screen using one of 40 possible custom characters
void ballUpdate() {
// Calculate the azimuth of the ball's game angle (trajectory angle)
if (upDownDir == 1 && leftRightDir == -1)
{
azimuth = 90 - angle;
}
else if (upDownDir == -1 && leftRightDir == -1)
{
azimuth = 90 + angle;
}
else if (upDownDir == -1 && leftRightDir == 1)
{
azimuth = 270 - angle;
}
else
{
azimuth = 270 + angle;
}
// Convert degrees to radians
azimuth = azimuth * PI / 180.0;
// Solve for the ball's new position (uses the ball's last deflection point along with total distance to better display the true game angle)
int newX = sin(azimuth) * totalDistance + (float)ballPos[0];
int newY = cos(azimuth) * totalDistance + (float)ballPos[1];
// Constrain the ball's position to be on the game board
newX = constrain(newX, 5, 75);
newY = constrain(newY, 0, 15);
// Update the total distance between the ball and it's last deflection (bounce) point within the game
totalDistance = totalDistance + distance;
// Check if the ball has hit a top/bottom boundary and if so update it's Up/Down state value
if (newY == 0) // Hit the Bottom
{
upDownDir = 1;
totalDistance = distance;
ballPos[0] = newX;
ballPos[1] = newY + 1;
}
else if (newY == 15) // Hit the Top
{
upDownDir = -1;
totalDistance = distance;
ballPos[0] = newX;
ballPos[1] = newY - 1;
}
// Check if the ball has hit a left/right boundary and if so update it's Left/Right state value
if (newX == 5) // Hit the Wall
{
pontuacao++;
leftRightDir = -1;
totalDistance = distance;
ballPos[0] = newX + 1;
ballPos[1] = newY;
}
else if (newX == 75) // Hit the player's boundary
{
// Speed up the ball each time it hit's the player's paddle
distance = (1.0 + speedIncreasePercent / 100.0) * distance;
// Check to see if the player's paddle was in the correct paddle position to bounce the ball
if (newY == 0 && (paddlePos == 1 || paddlePos == 2)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 1 && (paddlePos == 1 || paddlePos == 2 || paddlePos == 3)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 2 && (paddlePos == 1 || paddlePos == 2 || paddlePos == 3 || paddlePos == 4)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 3 && (paddlePos == 1 || paddlePos == 2 || paddlePos == 3 || paddlePos == 4 || paddlePos == 5)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 4 && (paddlePos == 2 || paddlePos == 3 || paddlePos == 4 || paddlePos == 5 || paddlePos == 6)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 5 && (paddlePos == 3 || paddlePos == 4 || paddlePos == 5 || paddlePos == 6 || paddlePos == 7)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 6 && (paddlePos == 4 || paddlePos == 5 || paddlePos == 6 || paddlePos == 7 || paddlePos == 8)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 7 && (paddlePos == 5 || paddlePos == 6 || paddlePos == 7 || paddlePos == 8 || paddlePos == 9)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 8 && (paddlePos == 6 || paddlePos == 7 || paddlePos == 8 || paddlePos == 9 || paddlePos == 10)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 9 && (paddlePos == 7 || paddlePos == 8 || paddlePos == 9 || paddlePos == 10 || paddlePos == 11)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 10 && (paddlePos == 8 || paddlePos == 9 || paddlePos == 10 || paddlePos == 11 || paddlePos == 12)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 11 && (paddlePos == 9 || paddlePos == 10 || paddlePos == 11 || paddlePos == 12 || paddlePos == 13)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 12 && (paddlePos == 10 || paddlePos == 11 || paddlePos == 12 || paddlePos == 13 || paddlePos == 14)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 13 && (paddlePos == 11 || paddlePos == 12 || paddlePos == 13 || paddlePos == 14)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 14 && (paddlePos == 12 || paddlePos == 13 || paddlePos == 14)) {
hitPaddleUpdate(newX, newY);
}
else if (newY == 15 && (paddlePos == 13 || paddlePos == 14)) {
hitPaddleUpdate(newX, newY);
}
// The ball has crossed the player's boundary
else {
//Reset the ball's position and control variables for the next point
ballPos[0] = 39;
ballPos[1] = 7;
totalDistance = distance;
drawInitial();
// Determine a new game angle for this point
calcInitialDir();
points++;
// A point has been scored (by the computer), flash the LED(s)
if (points == 1) {
for (int i = 0; i < 5; i++) {
digitalWrite(compPoint1, HIGH);
delay(250);
digitalWrite(compPoint1, LOW);
delay(250);
}
digitalWrite(compPoint1, HIGH);
}
else if (points == 2) {
for (int i = 0; i < 5; i++) {
digitalWrite(compPoint2, HIGH);
delay(250);
digitalWrite(compPoint2, LOW);
delay(250);
}
digitalWrite(compPoint2, HIGH);
}
// Game is over, 3 points have been scored by the computer, reset the LCD to display the Start Game message
else if (points == 3) {
gameStarted = false;
// Display Game Over Message
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" GAME ");
lcd.setCursor(0,1);
lcd.print(" OVER ");
delay(2000);
lcd.clear();
delay(50);
lcd.setCursor(0,0);
lcd.print("Numero de pontos");
lcd.setCursor(4,1);
lcd.print(pontuacao);
for (int i = 0; i < 5; i++) {
digitalWrite(compPoint1, HIGH);
digitalWrite(compPoint2, HIGH);
digitalWrite(compPoint3, HIGH);
delay(250);
digitalWrite(compPoint1, LOW);
digitalWrite(compPoint2, LOW);
digitalWrite(compPoint3, LOW);
delay(250);
}
digitalWrite(compPoint1, HIGH);
digitalWrite(compPoint2, HIGH);
digitalWrite(compPoint3, HIGH);
pontuacao = 0x00;
delay(250);
// Call setup to start the game over
setup();
}
}
}
// Check to make sure the Game is NOT over and then update the ball's LCD character
if (gameStarted == true) {
drawChars(newX, newY);
}
}
// Function to perform necessary updates/events when the ball hits the player's paddle
void hitPaddleUpdate(int X, int Y) {
leftRightDir = 1;
totalDistance = distance;
ballPos[0] = X - 1;
ballPos[1] = Y;
}
// Function to determine which one of the 40 possible custom LCD characters should be drawn (and where) on the LCD
void drawChars(int X, int Y) {
int LCDrow;
int LCDcol;
// Determine which row of the LCD the ball's character is on
if (Y <= 7) {
LCDrow = 1;
}
else {
LCDrow = 0;
}
//Determine which column of the LCD the ball's character is on
if (X <= 4) {
LCDcol = 0;
}
else if (X <= 9) {
LCDcol = 1;
}
else if (X <= 14) {
LCDcol = 2;
}
else if (X <= 19) {
LCDcol = 3;
}
else if (X <= 24) {
LCDcol = 4;
}
else if (X <= 29) {
LCDcol = 5;
}
else if (X <= 34) {
LCDcol = 6;
}
else if (X <= 39) {
LCDcol = 7;
}
else if (X <= 44) {
LCDcol = 8;
}
else if (X <= 49) {
LCDcol = 9;
}
else if (X <= 54) {
LCDcol = 10;
}
else if (X <= 59) {
LCDcol = 11;
}
else if (X <= 64) {
LCDcol = 12;
}
else if (X <= 69) {
LCDcol = 13;
}
else if (X <= 74) {
LCDcol = 14;
}
else {
LCDcol = 15;
}
// Clear the LCD of the previous ball (but not the Wall and the player's paddle)
lcd.setCursor(1,0);
// 14 empty characters printed inbetween the Wall and the player's paddle
lcd.print(" ");
lcd.setCursor(1,1);
lcd.print(" ");
// Determine the ball's position (single pixel) within a single LCD character (i.e. within the 8x5 pixels that make up a single LCD character)
int dx = X - 5 * LCDcol; // Column position within the LCD character
int dy;
// Row position within the LCD character
if (Y == 0 || Y == 8) {
dy = 0;
}
else if (Y == 1 || Y == 9) {
dy = 1;
}
else if (Y == 2 || Y == 10) {
dy = 2;
}
else if (Y == 3 || Y == 11) {
dy = 3;
}
else if (Y == 4 || Y == 12) {
dy = 4;
}
else if (Y == 5 || Y == 13) {
dy = 5;
}
else if (Y == 6 || Y == 14) {
dy = 6;
}
else if (Y == 7 || Y == 15) {
dy = 7;
}
// Select the correct custom character, of the 40 possible, and display it (in it's correct LCD column, row position)
// Alternate assigning the custom characters to LCD custom character bytes 1,2,3,4,5
if (dx == 0 && dy == 0) {
lcd.createChar(2, ball70);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 1 && dy == 0) {
lcd.createChar(2, ball71);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 2 && dy == 0) {
lcd.createChar(2, ball72);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 3 && dy == 0) {
lcd.createChar(2, ball73);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 4 && dy == 0) {
lcd.createChar(2, ball74);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 0 && dy == 1) {
lcd.createChar(3, ball60);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 1 && dy == 1) {
lcd.createChar(3, ball61);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 2 && dy == 1) {
lcd.createChar(3, ball62);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 3 && dy == 1) {
lcd.createChar(3, ball63);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 4 && dy == 1) {
lcd.createChar(3, ball64);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 0 && dy == 2) {
lcd.createChar(4, ball50);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 1 && dy == 2) {
lcd.createChar(4, ball51);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 2 && dy == 2) {
lcd.createChar(4, ball52);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 3 && dy == 2) {
lcd.createChar(4, ball53);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 4 && dy == 2) {
lcd.createChar(4, ball54);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 0 && dy == 3) {
lcd.createChar(5, ball40);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 1 && dy == 3) {
lcd.createChar(5, ball41);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 2 && dy == 3) {
lcd.createChar(5, ball42);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 3 && dy == 3) {
lcd.createChar(5, ball43);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 4 && dy == 3) {
lcd.createChar(5, ball44);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 0 && dy == 4) {
lcd.createChar(2, ball30);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 1 && dy == 4) {
lcd.createChar(2, ball31);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 2 && dy == 4) {
lcd.createChar(2, ball32);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 3 && dy == 4) {
lcd.createChar(2, ball33);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 4 && dy == 4) {
lcd.createChar(2, ball34);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(2);
}
else if (dx == 0 && dy == 5) {
lcd.createChar(3, ball20);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 1 && dy == 5) {
lcd.createChar(3, ball21);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 2 && dy == 5) {
lcd.createChar(3, ball22);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 3 && dy == 5) {
lcd.createChar(3, ball23);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 4 && dy == 5) {
lcd.createChar(3, ball24);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(3);
}
else if (dx == 0 && dy == 6) {
lcd.createChar(4, ball10);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 1 && dy == 6) {
lcd.createChar(4, ball11);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 2 && dy == 6) {
lcd.createChar(4, ball12);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 3 && dy == 6) {
lcd.createChar(4, ball13);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 4 && dy == 6) {
lcd.createChar(4, ball14);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(4);
}
else if (dx == 0 && dy == 7) {
lcd.createChar(5, ball00);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 1 && dy == 7) {
lcd.createChar(5, ball01);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 2 && dy == 7) {
lcd.createChar(5, ball02);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 3 && dy == 7) {
lcd.createChar(5, ball03);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
else if (dx == 4 && dy == 7) {
lcd.createChar(5, ball04);
lcd.setCursor(LCDcol, LCDrow);
lcd.write(5);
}
}
| [
"[email protected]"
] | |
229f6b3f816e35fd7b3cca96037f2cbec84a4cd5 | a3c83318e5adc064816b7411e6c4b82a40833477 | /rclcpp/executors/cbg_executor/src/examples_rclcpp_cbg_executor/ping_node.cpp | 4b65cb7336f7250093f3303e8511999744b17604 | [
"Apache-2.0"
] | permissive | ros2/examples | ffce506f1aed06e1d9cb3c4c7647f5796763de0d | 1d97c4fc7445554f6f85f63305d424fc017212a0 | refs/heads/rolling | 2023-08-22T18:27:34.258624 | 2023-07-11T20:10:08 | 2023-07-11T20:10:08 | 21,909,749 | 560 | 328 | Apache-2.0 | 2023-06-20T11:42:06 | 2014-07-16T17:11:20 | C++ | UTF-8 | C++ | false | false | 4,067 | cpp | // Copyright (c) 2020 Robert Bosch GmbH
//
// 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 "examples_rclcpp_cbg_executor/ping_node.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>
#include "./utilities.hpp"
namespace examples_rclcpp_cbg_executor
{
PingNode::PingNode()
: rclcpp::Node("ping_node")
{
using std::placeholders::_1;
using std_msgs::msg::Int32;
this->declare_parameter<double>("ping_period", 0.01);
std::chrono::nanoseconds ping_period = get_nanos_from_secs_parameter(this, "ping_period");
ping_timer_ = this->create_wall_timer(ping_period, std::bind(&PingNode::send_ping, this));
high_ping_publisher_ = this->create_publisher<Int32>("high_ping", rclcpp::SensorDataQoS());
low_ping_publisher_ = this->create_publisher<Int32>("low_ping", rclcpp::SensorDataQoS());
high_pong_subscription_ = this->create_subscription<Int32>(
"high_pong", rclcpp::SensorDataQoS(), std::bind(&PingNode::high_pong_received, this, _1));
low_pong_subscription_ = this->create_subscription<Int32>(
"low_pong", rclcpp::SensorDataQoS(), std::bind(&PingNode::low_pong_received, this, _1));
}
void PingNode::send_ping()
{
std_msgs::msg::Int32 msg;
msg.data = static_cast<int32_t>(rtt_data_.size());
rtt_data_.push_back(RTTData(now()));
high_ping_publisher_->publish(msg);
low_ping_publisher_->publish(msg);
}
void PingNode::high_pong_received(const std_msgs::msg::Int32::ConstSharedPtr msg)
{
rtt_data_[msg->data].high_received_ = now();
}
void PingNode::low_pong_received(const std_msgs::msg::Int32::ConstSharedPtr msg)
{
rtt_data_[msg->data].low_received_ = now();
}
void PingNode::print_statistics(std::chrono::seconds experiment_duration) const
{
size_t ping_count = rtt_data_.size();
std::vector<double> high_rtts;
std::vector<double> low_rtts;
for (const auto & entry : rtt_data_) {
if (entry.high_received_.nanoseconds() >= entry.sent_.nanoseconds()) {
high_rtts.push_back((entry.high_received_ - entry.sent_).seconds());
}
if (entry.low_received_.nanoseconds() >= entry.sent_.nanoseconds()) {
low_rtts.push_back((entry.low_received_ - entry.sent_).seconds());
}
}
std::chrono::nanoseconds ping_period = get_nanos_from_secs_parameter(this, "ping_period");
size_t ideal_ping_count = experiment_duration / ping_period;
RCLCPP_INFO(
get_logger(), "Both paths: Sent out %zu of configured %ld pings, i.e. %zu%%.",
ping_count, ideal_ping_count, 100 * ping_count / ideal_ping_count);
RCLCPP_INFO(
get_logger(), "High prio path: Received %zu pongs, i.e. for %zu%% of the pings.",
high_rtts.size(), 100 * high_rtts.size() / ping_count);
if (!high_rtts.empty()) {
double high_rtt_avg = calc_average(high_rtts) * 1000.0;
RCLCPP_INFO(get_logger(), "High prio path: Average RTT is %3.1fms.", high_rtt_avg);
double high_rtt_jitter = calc_std_deviation(high_rtts) * 1000.0;
RCLCPP_INFO(get_logger(), "High prio path: Jitter of RTT is %5.3fms.", high_rtt_jitter);
}
RCLCPP_INFO(
get_logger(), "Low prio path: Received %zu pongs, i.e. for %zu%% of the pings.",
low_rtts.size(), 100 * low_rtts.size() / ping_count);
if (!low_rtts.empty()) {
double low_rtt_avg = calc_average(low_rtts) * 1000.0;
RCLCPP_INFO(get_logger(), "Low prio path: Average RTT is %3.1fms.", low_rtt_avg);
double low_rtt_jitter = calc_std_deviation(low_rtts) * 1000.0;
RCLCPP_INFO(get_logger(), "Low prio path: Jitter of RTT is %5.3fms.", low_rtt_jitter);
}
}
} // namespace examples_rclcpp_cbg_executor
| [
"[email protected]"
] | |
2cee294c0e4a2b6ce2e4c111ebb7aaddf4644de6 | add6d8eea5c2ea65bed56bf6939b5185b9ee14a5 | /stack/stack.h | 732916549568980ff9a415cd53087ce6ed25551a | [] | no_license | bcbcarl/data-structures | 0e70e2c9b4c9d6ffa045d07609aab5c4abe4efd0 | 60faca522938568064c4cc9ab52f71123a04230b | refs/heads/master | 2021-01-19T07:13:23.586774 | 2017-04-11T17:32:00 | 2017-04-11T17:32:00 | 87,529,100 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | #ifndef CARL_STACK_H
#define CARL_STACK_H
#include <list>
namespace carl {
template <typename T>
class Stack {
public:
bool empty() const noexcept {
return stack_.empty();
}
size_t size() const noexcept {
return stack_.size();
}
const T& top() const {
return stack_.back();
}
void push(const T& val) {
stack_.push_back(val);
}
void pop() {
stack_.pop_back();
}
private:
std::list<T> stack_;
};
}
#endif // CARL_STACK_H
| [
"[email protected]"
] | |
d6e5e9386372935e8281385affa92c3eb1ba77ea | 177a619d09dc04cfa1ad11700fe5c10683555702 | /16-1hangman.cpp | f2aa74a93e6c8127bd33e9855cd40a262f2e275d | [] | no_license | Hanaydn/LearningCpp | 4b1ddaea300c169c1c00eaca397d0c58d3bb382a | 62f852c2d68fb195708f2bb0d0f1e948aadfde11 | refs/heads/master | 2020-03-22T05:02:05.307573 | 2018-07-27T03:59:17 | 2018-07-27T03:59:17 | 139,537,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | cpp | #include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<cctype>
using namespace std;
const int NUM = 26;
const string wordlist[NUM] = {"apiary", "beetle", "cereal", "danger", "ensign", "florid", "garage", "health", "insult", "jackal", "keeper", "loaner", "manage", "nonce", "onset", "plaid", "quilt", "remote", "stolid", "train", "useful", "valid", "whence", "xenon", "yearn", "zippy"};
int main(int argc_, char* argv_[]){
srand(time(0));
char play;
cout << "Will you play a word game? <y/n>";
cin >> play;
play = tolower(play);
while(play == 'y'){
string target = wordlist[rand() % NUM];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "Guess my secret word. It has " << length << " letters, and you guess\n" << "one letter at a time. You get " << guesses << " wrong guesses.\n";
}
cout << "Your word: " << attempt << endl;
while (guesses > 0 && attempt != target){
char letter;
cout << "Guess a letter: ";
cin >> letter;
if(badchars.find(letter) != npos || attempt.find(letter) != npos){
cout << "You already guessed that. Try again.\n";
continue;
}
int loc = target.find(letter);
if (loc == npos){
cout << "Oh, bad guess!\n";
--guesses;
badchars += letter;
}else{
cout << "Good guess!\n";
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
while(loc != npos){
attempt[loc] = letter;
loc = target,find(letter, loc + 1);
}
}
cout << "Your word: " << attempt << endl;
if(attempt != target){
if(badchars.length() > 0){
cout << "Bad choices: " << badchars << endl;
}
cout << guessed << " bad guessed left\n";
}
}
if(guesses > 0){
cout << "That's right!\n";
}else{
cout << "Sorry, the word is " << target << ".\n";
cout << "Will you play another? <y/n>";
cin >> play;
play = tolower(play);
}
cout << "Bye\n";
return 0;
}
| [
"[email protected]"
] | |
d0653249cb2089e89f4423eae4f118998fe8c072 | 0c87193ec953a53d6f25d3d7ed6a6d7492fe65af | /CannyStill1.cpp | e936e910aef06be1ca0d41315434a7dc4dd6aa6e | [] | no_license | Louieboy246/Thesis | 19df3913b55afb4a245746172bddb10dd532fb5e | 80dfc1a762ec8bc8b47c2724ab25159a1c7336d3 | refs/heads/master | 2021-01-12T00:13:48.227933 | 2017-01-12T00:15:29 | 2017-01-12T00:15:29 | 78,691,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | cpp | // CannyStill.cpp
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
///////////////////////////////////////////////////////////////////////////////////////////////////
int main() {
cv::Mat matOriginal; // input image
cv::Mat matGrayscale; // grayscale of input image
cv::Mat matBlurred; // intermediate blured image
cv::Mat matCanny; // Canny edge image
matOriginal = cv::imread("2016-1-27-22-41-1-300k.jpg"); // open image
if (matOriginal.empty()) { // if unable to open image
std::cout << "error: image not read from file\n\n"; // show error message on command line
return(0); // and exit program
}
cv::cvtColor(matOriginal, matGrayscale, CV_BGR2GRAY); // convert to grayscale
cv::GaussianBlur(matGrayscale, // input image
matBlurred, // output image
cv::Size(5, 5), // smoothing window width and height in pixels
1.5); // sigma value, determines how much the image will be blurred
cv::Canny(matBlurred, // input image
matCanny, // output image
100, // low threshold
200); // high threshold
// declare windows
cv::namedWindow("Original", CV_WINDOW_AUTOSIZE); // note: you can use CV_WINDOW_NORMAL which allows resizing the window
cv::namedWindow("Canny", CV_WINDOW_AUTOSIZE); // or CV_WINDOW_AUTOSIZE for a fixed size window matching the resolution of the image
// CV_WINDOW_AUTOSIZE is the default
cv::imshow("Original", matOriginal); // show windows
cv::imshow("Canny", matCanny);
cv::waitKey(0); // hold windows open until user presses a key
return(0);
}
| [
"[email protected]"
] | |
9b942c87c9c880a662400b0aaa6d8417f9ac769d | 6e09d72177402b133921a0cc611d4fbeabcf3aed | /Cpp/VS2005/book/book/二维数组找最大值.cpp | 8da0c724e1b34bf015533b6110f9027b221bb3c1 | [] | no_license | aravinda-kumar/Code | 4f91617c79569cccb7bbf517a3699d16fa7e1377 | eccdee6fe73237e2982b128a04813c854e4cfd4d | refs/heads/master | 2020-05-01T10:31:20.940519 | 2019-03-24T05:09:01 | 2019-03-24T05:09:01 | 177,422,267 | 1 | 0 | null | 2019-03-24T13:59:14 | 2019-03-24T13:59:14 | null | UTF-8 | C++ | false | false | 724 | cpp | //#include <iostream>
//using namespace std;
//
//int max_value(int i_a[][4]);
//
//int main()
//{
// int i_a[3][4]={5,12,23,56,19,28,37,46,-12,-34,6,8};
// cout << "The biggest number is:" << max_value(i_a) << endl;
// cout << "It is in NO." << i_row+1 << " row, and NO." << i_colum+1 << " colum." << endl;
// system("pause");
// return 0;
//}
//
//int max_value(int i_a[3][4])
//{
// int i_countx,i_county,i_row,i_colum,i_max;
// i_max = i_a[0][0];
// for (i_countx=0;i_countx<3;i_countx++)
// {
// for (i_county=0;i_county<4;i_county++)
// {
// if(i_max < i_a[i_countx][i_county])
// {
// i_max = i_a[i_countx][i_county];
// i_row = i_countx;
// i_colum = i_county;
// }
// }
// }
// return i_max;
//} | [
"[email protected]"
] | |
133fe8ff0e0a0e31e74e158400b496bbc38f09bd | 8042163dbac5ddf47f078b4d14f4eb6fe1da030d | /tensorflow/lite/micro/kernels/svdf.cc | ba7cb05da57aa403e758ce64df3a1348996f07d0 | [
"Apache-2.0"
] | permissive | AITutorials/tensorflow | 4513de8db4e9bb74b784f5ba865ef8a573b9efc1 | 6bee0d45f8228f2498f53bd6dec0a691f53b3c7b | refs/heads/master | 2022-07-29T13:37:23.749388 | 2020-06-11T17:47:26 | 2020-06-11T17:57:06 | 271,615,051 | 3 | 0 | Apache-2.0 | 2020-06-11T18:07:11 | 2020-06-11T18:07:10 | null | UTF-8 | C++ | false | false | 21,074 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <math.h>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/op_macros.h"
#include "tensorflow/lite/micro/kernels/activation_utils.h"
#include "tensorflow/lite/micro/micro_utils.h"
namespace tflite {
namespace ops {
namespace micro {
namespace svdf {
namespace {
struct OpData {
int32 effective_scale_1_a;
int32 effective_scale_2_a;
// b versions of each scale are kept at int since the numbers are just the
// shift value - typically between [-32, 32].
int effective_scale_1_b;
int effective_scale_2_b;
int scratch_tensor_index;
int scratch_output_tensor_index;
};
/**
* This version of SVDF is specific to TFLite Micro. It contains the following
* differences between the TFLite version:
*
* 1.) Scratch tensor allocation - scratch tensors must be known ahead of time
* for the Micro interpreter.
* 2.) Output dimensions - the TFLite version determines output size and runtime
* and resizes the output tensor. Micro runtime does not support tensor
* resizing.
*/
static inline void ApplyTimeWeightsBiasAndActivation(
int batch_size, int memory_size, int num_filters, int num_units, int rank,
const float* const __restrict__ weights_time_ptr,
const float* const __restrict__ bias_ptr, TfLiteFusedActivation activation,
float* const __restrict__ state_ptr, float* const __restrict__ scratch_ptr,
float* const __restrict__ output_ptr) {
// Compute matmul(activation_state, weights_time).
for (int b = 0; b < batch_size; ++b) {
// Perform batched vector dot product:
float* scratch_ptr_batch = scratch_ptr + b * num_filters;
const float* vector1_ptr = weights_time_ptr;
const float* vector2_ptr = state_ptr + b * memory_size * num_filters;
for (int i = 0; i < num_filters; ++i) {
*scratch_ptr_batch = 0.f;
for (int j = 0; j < memory_size; ++j) {
*scratch_ptr_batch += *vector1_ptr++ * *vector2_ptr++;
}
scratch_ptr_batch++;
}
}
// Initialize output with bias if provided.
if (bias_ptr) {
// VectorBatchVectorAssign
for (int i = 0; i < batch_size; ++i) {
float* output_data = output_ptr + i * num_units;
const float* bias_data = bias_ptr;
for (int j = 0; j < num_units; ++j) {
*output_data++ = *bias_data++;
}
}
} else {
float* output_data = output_ptr;
for (int i = 0; i < batch_size * num_units; ++i) {
*output_data++ = 0.0f;
}
}
// Reduction sum.
for (int b = 0; b < batch_size; ++b) {
float* output_ptr_batch = output_ptr + b * num_units;
float* scratch_ptr_batch = scratch_ptr + b * num_filters;
// Reduction sum vector
for (int i = 0; i < num_units; ++i) {
for (int j = 0; j < rank; j++) {
output_ptr_batch[i] += *scratch_ptr_batch++;
}
}
}
// Apply activation.
for (int b = 0; b < batch_size; ++b) {
float* output_ptr_batch = output_ptr + b * num_units;
for (int i = 0; i < num_units; ++i) {
*output_ptr_batch = ActivationValFloat(activation, *output_ptr_batch);
++output_ptr_batch;
}
}
}
inline void EvalFloatSVDF(
TfLiteContext* context, TfLiteNode* node, const TfLiteTensor* input,
const TfLiteTensor* weights_feature, const TfLiteTensor* weights_time,
const TfLiteTensor* bias, const TfLiteSVDFParams* params,
int scratch_tensor_index, TfLiteTensor* activation_state,
TfLiteTensor* output) {
const int rank = params->rank;
const int batch_size = input->dims->data[0];
const int input_size = input->dims->data[1];
const int num_filters = weights_feature->dims->data[0];
const int num_units = num_filters / rank;
const int memory_size = weights_time->dims->data[1];
const float* weights_feature_ptr = GetTensorData<float>(weights_feature);
const float* weights_time_ptr = GetTensorData<float>(weights_time);
const float* bias_ptr = GetTensorData<float>(bias);
const float* input_ptr = GetTensorData<float>(input);
float* state_ptr = GetTensorData<float>(activation_state);
TFLITE_DCHECK(context != nullptr);
TFLITE_DCHECK(context->GetScratchBuffer != nullptr);
float* scratch_ptr = static_cast<float*>(
context->GetScratchBuffer(context, scratch_tensor_index));
float* output_ptr = GetTensorData<float>(output);
// Left shift the activation_state.
{
float* new_state_start = state_ptr;
const float* old_state_start = state_ptr + 1;
const float* old_state_end =
state_ptr + batch_size * num_filters * memory_size;
while (old_state_start != old_state_end) {
*new_state_start++ = *old_state_start++;
}
}
// Note: no need to clear the latest activation, matmul is not accumulative.
// Compute conv1d(inputs, weights_feature).
// The activation_state's rightmost column is used to save current cycle
// activation. This is achieved by starting at state_ptr[memory_size - 1] and
// having the stride equal to memory_size.
// Perform batched matrix vector multiply operation:
{
const float* matrix = weights_feature_ptr;
const float* vector = input_ptr;
float* result = &state_ptr[memory_size - 1];
float* result_in_batch = result;
for (int i = 0; i < batch_size; ++i) {
const float* matrix_ptr = matrix;
for (int j = 0; j < num_filters; ++j) {
float dot_prod = 0.0f;
const float* vector_in_batch = vector + i * input_size;
for (int k = 0; k < input_size; ++k) {
dot_prod += *matrix_ptr++ * *vector_in_batch++;
}
*result_in_batch = dot_prod;
result_in_batch += memory_size;
}
}
}
ApplyTimeWeightsBiasAndActivation(
batch_size, memory_size, num_filters, num_units, rank, weights_time_ptr,
bias_ptr, params->activation, state_ptr, scratch_ptr, output_ptr);
}
void EvalIntegerSVDF(TfLiteContext* context, TfLiteNode* node,
const TfLiteTensor* input_tensor,
const TfLiteTensor* weights_feature_tensor,
const TfLiteTensor* weights_time_tensor,
const TfLiteTensor* bias_tensor,
const TfLiteSVDFParams* params,
TfLiteTensor* activation_state_tensor,
TfLiteTensor* output_tensor, const OpData& data,
int32_t input_zp, int32_t output_zp) {
const int n_rank = params->rank;
const int n_batch = input_tensor->dims->data[0];
const int n_input = input_tensor->dims->data[1];
const int n_filter = weights_feature_tensor->dims->data[0];
const int n_unit = n_filter / n_rank;
const int n_memory = weights_time_tensor->dims->data[1];
TFLITE_DCHECK(context != nullptr);
TFLITE_DCHECK(context->GetScratchBuffer != nullptr);
int32_t* scratch_tensor = static_cast<int32_t*>(
context->GetScratchBuffer(context, data.scratch_tensor_index));
int32_t* scratch_output_tensor = static_cast<int32_t*>(
context->GetScratchBuffer(context, data.scratch_output_tensor_index));
// Shift states.
int16_t* const state_ptr = GetTensorData<int16_t>(activation_state_tensor);
// Left shift the activation_state.
{
int16_t* new_state_start = state_ptr;
const int16_t* old_state_start = state_ptr + 1;
const int16_t* old_state_end = state_ptr + n_batch * n_filter * n_memory;
while (old_state_start != old_state_end) {
*new_state_start++ = *old_state_start++;
}
}
// Note: no need to clear the latest activation, matmul is not accumulative.
// Feature matmul.
{
int16_t* state = GetTensorData<int16_t>(activation_state_tensor);
const int8_t* input = GetTensorData<int8_t>(input_tensor);
const int8_t* weight_feature =
GetTensorData<int8_t>(weights_feature_tensor);
const int32_t output_max = std::numeric_limits<int16_t>::max();
const int32_t output_min = std::numeric_limits<int16_t>::min();
int16_t* result_in_batch = state + (n_memory - 1);
for (int b = 0; b < n_batch; b++) {
const int8_t* matrix_ptr = weight_feature;
for (int r = 0; r < n_filter; r++) {
int32_t dot_prod = 0;
const int8_t* vector_in_batch = input + b * n_input;
for (int c = 0; c < n_input; c++) {
dot_prod += *matrix_ptr++ * (*vector_in_batch++ - input_zp);
}
dot_prod = MultiplyByQuantizedMultiplier(
dot_prod, data.effective_scale_1_a, data.effective_scale_1_b);
dot_prod = std::min(std::max(output_min, dot_prod), output_max);
// This assumes state is symmetrically quantized. Otherwise last bit of
// state should be initialized to its zero point and accumulate the
// dot_prod.
// Equivalent as the following:
// result_in_batch = zero point, which happens to be zero.
// result_in_batch += dot_prod_56.
*result_in_batch = dot_prod;
result_in_batch += n_memory;
}
}
}
// Time.
{
for (int b = 0; b < n_batch; ++b) {
int32_t* scratch_ptr_batch = scratch_tensor + b * n_filter;
// Perform batched vector dot product:
const int16_t* vector1_ptr = GetTensorData<int16_t>(weights_time_tensor);
const int16_t* vector2_ptr =
GetTensorData<int16_t>(activation_state_tensor) +
b * n_memory * n_filter;
for (int i = 0; i < n_filter; i++) {
*scratch_ptr_batch = 0;
for (int j = 0; j < n_memory; j++) {
*scratch_ptr_batch += *vector1_ptr++ * *vector2_ptr++;
}
scratch_ptr_batch++;
}
}
}
// Reduce, add bias, rescale, activation.
{
// Add bias.
if (bias_tensor) {
// Vector batch assign:
const int32_t* bias_data = GetTensorData<int32_t>(bias_tensor);
for (int i = 0; i < n_batch; ++i) {
int32_t* output_ptr = scratch_output_tensor + i * n_unit;
const int32_t* bias_ptr = bias_data;
for (int j = 0; j < n_unit; ++j) {
*output_ptr++ = *bias_ptr++;
}
}
} else {
int32_t* output_ptr = scratch_output_tensor;
for (int i = 0; i < n_batch * n_unit; ++i) {
*output_ptr++ = 0;
}
}
// Reduce.
for (int b = 0; b < n_batch; ++b) {
int32_t* output_temp_ptr = scratch_output_tensor + b * n_unit;
int32_t* scratch_ptr_batch = scratch_tensor + b * n_filter;
// Reduction sum vector
for (int i = 0; i < n_unit; ++i) {
for (int j = 0; j < n_rank; ++j) {
output_temp_ptr[i] += *scratch_ptr_batch++;
}
}
}
// Rescale.
const int32_t output_max = std::numeric_limits<int8_t>::max();
const int32_t output_min = std::numeric_limits<int8_t>::min();
for (int i = 0; i < n_batch * n_unit; ++i) {
int32_t x1 = scratch_output_tensor[i];
int32_t x2 = MultiplyByQuantizedMultiplier(x1, data.effective_scale_2_a,
data.effective_scale_2_b);
int32_t x3 = x2 + output_zp;
int32_t x4 = std::min(std::max(output_min, x3), output_max);
GetTensorData<int8_t>(output_tensor)[i] = static_cast<int8_t>(x4);
}
}
}
} // namespace
// Input tensors.
constexpr int kInputTensor = 0;
constexpr int kWeightsFeatureTensor = 1;
constexpr int kWeightsTimeTensor = 2;
constexpr int kBiasTensor = 3;
// This is a variable tensor, and will be modified by this op.
constexpr int kInputActivationStateTensor = 4;
// Output tensor.
constexpr int kOutputTensor = 0;
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
void* data = nullptr;
if (context->AllocatePersistentBuffer(context, sizeof(OpData), &data) ==
kTfLiteError) {
return nullptr;
}
return data;
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->builtin_data != nullptr);
const auto* params = static_cast<const TfLiteSVDFParams*>(node->builtin_data);
// Validate Tensor Inputs (dtype depends on quantization):
// [0] = Input, {2, batch_size, input_size}
// [1] = Weights Feature, {2, num_filters, input_size}
// [2] = Weights Time, {2, num_filters, memory_size}
// [3] = Bias (optional), {1, num_units}
// [4] = Activation State (variable),
// {2, batch_size, memory_size * num_filters}
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* weights_feature =
GetInput(context, node, kWeightsFeatureTensor);
const TfLiteTensor* weights_time =
GetInput(context, node, kWeightsTimeTensor);
const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
const TfLiteTensor* activation_state =
GetInput(context, node, kInputActivationStateTensor);
// Define input constants based on input tensor definition above:
const int rank = params->rank;
const int input_size = input->dims->data[1];
const int batch_size = input->dims->data[0];
const int num_filters = weights_feature->dims->data[0];
TF_LITE_ENSURE_EQ(context, num_filters % rank, 0);
const int num_units = num_filters / rank;
const int memory_size = weights_time->dims->data[1];
// Validate Input Tensor:
TF_LITE_ENSURE(context,
input->type == kTfLiteFloat32 || input->type == kTfLiteInt8);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 2);
// Validate Tensor Output:
// [0] = float/int8, {2, batch_size, num_units}
TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(output), 2);
TF_LITE_ENSURE_EQ(context, output->dims->data[0], batch_size);
TF_LITE_ENSURE_EQ(context, output->dims->data[1], num_units);
// Validate Weights Feature Input Tensor:
TF_LITE_ENSURE_EQ(context, NumDimensions(weights_feature), 2);
TF_LITE_ENSURE_EQ(context, weights_feature->dims->data[1], input_size);
// Validate Weights Time Input Tensor:
TF_LITE_ENSURE_EQ(context, NumDimensions(weights_time), 2);
TF_LITE_ENSURE_EQ(context, weights_time->dims->data[0], num_filters);
TF_LITE_ENSURE_EQ(context, weights_time->dims->data[1], memory_size);
// Validate Optional Bias Input Tensor:
if (bias != nullptr) {
TF_LITE_ENSURE_EQ(context, bias->dims->data[0], num_units);
}
// Validate Activation State Input Tensor:
TF_LITE_ENSURE_EQ(context, NumDimensions(activation_state), 2);
TF_LITE_ENSURE_EQ(context, activation_state->dims->data[0], batch_size);
TF_LITE_ENSURE_EQ(context, activation_state->dims->data[1],
memory_size * num_filters);
TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);
if (input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, weights_feature->type, kTfLiteInt8);
TF_LITE_ENSURE_EQ(context, weights_time->type, kTfLiteInt16);
TF_LITE_ENSURE_EQ(context, activation_state->type, kTfLiteInt16);
if (bias != nullptr) {
TF_LITE_ENSURE_EQ(context, bias->type, kTfLiteInt32);
}
TF_LITE_ENSURE_EQ(context, output->type, kTfLiteInt8);
const auto* input_params =
reinterpret_cast<TfLiteAffineQuantization*>(input->quantization.params);
const auto* weights_feature_params =
static_cast<const TfLiteAffineQuantization*>(
weights_feature->quantization.params);
const auto* state_params = static_cast<const TfLiteAffineQuantization*>(
activation_state->quantization.params);
const auto* weight_time_params =
static_cast<const TfLiteAffineQuantization*>(
weights_time->quantization.params);
const auto* output_params = static_cast<const TfLiteAffineQuantization*>(
output->quantization.params);
const double effective_scale_1 = static_cast<double>(
input_params->scale->data[0] * weights_feature_params->scale->data[0] /
state_params->scale->data[0]);
const double effective_scale_2 = static_cast<double>(
state_params->scale->data[0] * weight_time_params->scale->data[0] /
output_params->scale->data[0]);
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
QuantizeMultiplier(effective_scale_1, &(data->effective_scale_1_a),
&(data->effective_scale_1_b));
QuantizeMultiplier(effective_scale_2, &(data->effective_scale_2_a),
&(data->effective_scale_2_b));
TFLITE_DCHECK(context->RequestScratchBufferInArena != nullptr);
const TfLiteStatus scratch_status = context->RequestScratchBufferInArena(
context, batch_size * num_filters * sizeof(int32_t),
&(data->scratch_tensor_index));
TF_LITE_ENSURE_OK(context, scratch_status);
const TfLiteStatus scratch_output_status =
context->RequestScratchBufferInArena(
context, batch_size * num_units * sizeof(int32_t),
&(data->scratch_output_tensor_index));
TF_LITE_ENSURE_OK(context, scratch_output_status);
} else {
TF_LITE_ENSURE_EQ(context, weights_feature->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, weights_time->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, activation_state->type, kTfLiteFloat32);
if (bias != nullptr) {
TF_LITE_ENSURE_EQ(context, bias->type, kTfLiteFloat32);
}
TF_LITE_ENSURE_EQ(context, output->type, kTfLiteFloat32);
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
TFLITE_DCHECK(context->RequestScratchBufferInArena != nullptr);
const TfLiteStatus scratch_status = context->RequestScratchBufferInArena(
context, batch_size * num_filters * sizeof(float),
&(data->scratch_tensor_index));
TF_LITE_ENSURE_OK(context, scratch_status);
}
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSVDFParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* weights_feature =
GetInput(context, node, kWeightsFeatureTensor);
const TfLiteTensor* weights_time =
GetInput(context, node, kWeightsTimeTensor);
const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
TfLiteTensor* activation_state =
GetVariableInput(context, node, kInputActivationStateTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TFLITE_DCHECK(node->user_data != nullptr);
const OpData& data = *(static_cast<const OpData*>(node->user_data));
switch (weights_feature->type) {
case kTfLiteFloat32: {
EvalFloatSVDF(context, node, input, weights_feature, weights_time, bias,
params, data.scratch_tensor_index, activation_state,
output);
return kTfLiteOk;
break;
}
case kTfLiteInt8: {
TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActRelu);
EvalIntegerSVDF(context, node, input, weights_feature, weights_time, bias,
params, activation_state, output, data,
input->params.zero_point, output->params.zero_point);
return kTfLiteOk;
break;
}
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(weights_feature->type));
return kTfLiteError;
}
return kTfLiteOk;
}
} // namespace svdf
TfLiteRegistration* Register_SVDF() {
// TODO(b/149408647): Once we remove AddBuiltin from MicroOpResolver and
// completely switch to the templated AddBuiltin from MicroMutableOpResolver,
// this struct no longer needs to be static and can be returned by value.
static TfLiteRegistration r = {/*init=*/svdf::Init,
/*free=*/nullptr,
/*prepare=*/svdf::Prepare,
/*invoke=*/svdf::Eval,
/*profiling_string=*/nullptr,
/*builtin_code=*/0,
/*custom_name=*/nullptr,
/*version=*/0};
return &r;
}
} // namespace micro
} // namespace ops
} // namespace tflite
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.